Improve customize type of org-agenda-custom-commands.
[org-mode.git] / org.el
blob3baab04d02aa2bb9b8bee14de9069149d2a5c494
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 ; (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
359 ; " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
360 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\(\\+[0-9]+[dwmy]\\)"
361 "Regular expression for specifying repeated events.
362 After a match, group 1 contains the repeat expression.")
364 (defgroup org-structure nil
365 "Options concerning the general structure of Org-mode files."
366 :tag "Org Structure"
367 :group 'org)
369 (defgroup org-reveal-location nil
370 "Options about how to make context of a location visible."
371 :tag "Org Reveal Location"
372 :group 'org-structure)
374 (defconst org-context-choice
375 '(choice
376 (const :tag "Always" t)
377 (const :tag "Never" nil)
378 (repeat :greedy t :tag "Individual contexts"
379 (cons
380 (choice :tag "Context"
381 (const agenda)
382 (const org-goto)
383 (const occur-tree)
384 (const tags-tree)
385 (const link-search)
386 (const mark-goto)
387 (const bookmark-jump)
388 (const isearch)
389 (const default))
390 (boolean))))
391 "Contexts for the reveal options.")
393 (defcustom org-show-hierarchy-above '((default . t))
394 "Non-nil means, show full hierarchy when revealing a location.
395 Org-mode often shows locations in an org-mode file which might have
396 been invisible before. When this is set, the hierarchy of headings
397 above the exposed location is shown.
398 Turning this off for example for sparse trees makes them very compact.
399 Instead of t, this can also be an alist specifying this option for different
400 contexts. Valid contexts are
401 agenda when exposing an entry from the agenda
402 org-goto when using the command `org-goto' on key C-c C-j
403 occur-tree when using the command `org-occur' on key C-c /
404 tags-tree when constructing a sparse tree based on tags matches
405 link-search when exposing search matches associated with a link
406 mark-goto when exposing the jump goal of a mark
407 bookmark-jump when exposing a bookmark location
408 isearch when exiting from an incremental search
409 default default for all contexts not set explicitly"
410 :group 'org-reveal-location
411 :type org-context-choice)
413 (defcustom org-show-following-heading '((default . nil))
414 "Non-nil means, show following heading when revealing a location.
415 Org-mode often shows locations in an org-mode file which might have
416 been invisible before. When this is set, the heading following the
417 match is shown.
418 Turning this off for example for sparse trees makes them very compact,
419 but makes it harder to edit the location of the match. In such a case,
420 use the command \\[org-reveal] to show more context.
421 Instead of t, this can also be an alist specifying this option for different
422 contexts. See `org-show-hierarchy-above' for valid contexts."
423 :group 'org-reveal-location
424 :type org-context-choice)
426 (defcustom org-show-siblings '((default . nil) (isearch t))
427 "Non-nil means, show all sibling heading when revealing a location.
428 Org-mode often shows locations in an org-mode file which might have
429 been invisible before. When this is set, the sibling of the current entry
430 heading are all made visible. If `org-show-hierarchy-above' is t,
431 the same happens on each level of the hierarchy above the current entry.
433 By default this is on for the isearch context, off for all other contexts.
434 Turning this off for example for sparse trees makes them very compact,
435 but makes it harder to edit the location of the match. In such a case,
436 use the command \\[org-reveal] to show more context.
437 Instead of t, this can also be an alist specifying this option for different
438 contexts. See `org-show-hierarchy-above' for valid contexts."
439 :group 'org-reveal-location
440 :type org-context-choice)
442 (defcustom org-show-entry-below '((default . nil))
443 "Non-nil means, show the entry below a headline when revealing a location.
444 Org-mode often shows locations in an org-mode file which might have
445 been invisible before. When this is set, the text below the headline that is
446 exposed is also shown.
448 By default this is off for all contexts.
449 Instead of t, this can also be an alist specifying this option for different
450 contexts. See `org-show-hierarchy-above' for valid contexts."
451 :group 'org-reveal-location
452 :type org-context-choice)
454 (defgroup org-cycle nil
455 "Options concerning visibility cycling in Org-mode."
456 :tag "Org Cycle"
457 :group 'org-structure)
459 (defcustom org-drawers '("PROPERTIES" "CLOCK")
460 "Names of drawers. Drawers are not opened by cycling on the headline above.
461 Drawers only open with a TAB on the drawer line itself. A drawer looks like
462 this:
463 :DRAWERNAME:
464 .....
465 :END:
466 The drawer \"PROPERTIES\" is special for capturing properties through
467 the property API.
469 Drawers can be defined on the per-file basis with a line like:
471 #+DRAWERS: HIDDEN STATE PROPERTIES"
472 :group 'org-structure
473 :type '(repeat (string :tag "Drawer Name")))
475 (defcustom org-cycle-global-at-bob nil
476 "Cycle globally if cursor is at beginning of buffer and not at a headline.
477 This makes it possible to do global cycling without having to use S-TAB or
478 C-u TAB. For this special case to work, the first line of the buffer
479 must not be a headline - it may be empty ot some other text. When used in
480 this way, `org-cycle-hook' is disables temporarily, to make sure the
481 cursor stays at the beginning of the buffer.
482 When this option is nil, don't do anything special at the beginning
483 of the buffer."
484 :group 'org-cycle
485 :type 'boolean)
487 (defcustom org-cycle-emulate-tab t
488 "Where should `org-cycle' emulate TAB.
489 nil Never
490 white Only in completely white lines
491 whitestart Only at the beginning of lines, before the first non-white char
492 t Everywhere except in headlines
493 exc-hl-bol Everywhere except at the start of a headline
494 If TAB is used in a place where it does not emulate TAB, the current subtree
495 visibility is cycled."
496 :group 'org-cycle
497 :type '(choice (const :tag "Never" nil)
498 (const :tag "Only in completely white lines" white)
499 (const :tag "Before first char in a line" whitestart)
500 (const :tag "Everywhere except in headlines" t)
501 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
504 (defcustom org-cycle-separator-lines 2
505 "Number of empty lines needed to keep an empty line between collapsed trees.
506 If you leave an empty line between the end of a subtree and the following
507 headline, this empty line is hidden when the subtree is folded.
508 Org-mode will leave (exactly) one empty line visible if the number of
509 empty lines is equal or larger to the number given in this variable.
510 So the default 2 means, at least 2 empty lines after the end of a subtree
511 are needed to produce free space between a collapsed subtree and the
512 following headline.
514 Special case: when 0, never leave empty lines in collapsed view."
515 :group 'org-cycle
516 :type 'integer)
518 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
519 org-cycle-hide-drawers
520 org-cycle-show-empty-lines
521 org-optimize-window-after-visibility-change)
522 "Hook that is run after `org-cycle' has changed the buffer visibility.
523 The function(s) in this hook must accept a single argument which indicates
524 the new state that was set by the most recent `org-cycle' command. The
525 argument is a symbol. After a global state change, it can have the values
526 `overview', `content', or `all'. After a local state change, it can have
527 the values `folded', `children', or `subtree'."
528 :group 'org-cycle
529 :type 'hook)
531 (defgroup org-edit-structure nil
532 "Options concerning structure editing in Org-mode."
533 :tag "Org Edit Structure"
534 :group 'org-structure)
536 (defcustom org-odd-levels-only nil
537 "Non-nil means, skip even levels and only use odd levels for the outline.
538 This has the effect that two stars are being added/taken away in
539 promotion/demotion commands. It also influences how levels are
540 handled by the exporters.
541 Changing it requires restart of `font-lock-mode' to become effective
542 for fontification also in regions already fontified.
543 You may also set this on a per-file basis by adding one of the following
544 lines to the buffer:
546 #+STARTUP: odd
547 #+STARTUP: oddeven"
548 :group 'org-edit-structure
549 :group 'org-font-lock
550 :type 'boolean)
552 (defcustom org-adapt-indentation t
553 "Non-nil means, adapt indentation when promoting and demoting.
554 When this is set and the *entire* text in an entry is indented, the
555 indentation is increased by one space in a demotion command, and
556 decreased by one in a promotion command. If any line in the entry
557 body starts at column 0, indentation is not changed at all."
558 :group 'org-edit-structure
559 :type 'boolean)
561 (defcustom org-special-ctrl-a/e nil
562 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
563 When t, `C-a' will bring back the cursor to the beginning of the
564 headline text, i.e. after the stars and after a possible TODO keyword.
565 In an item, this will be the position after the bullet.
566 When the cursor is already at that position, another `C-a' will bring
567 it to the beginning of the line.
568 `C-e' will jump to the end of the headline, ignoring the presence of tags
569 in the headline. A second `C-e' will then jump to the true end of the
570 line, after any tags.
571 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
572 and only a directly following, identical keypress will bring the cursor
573 to the special positions."
574 :group 'org-edit-structure
575 :type '(choice
576 (const :tag "off" nil)
577 (const :tag "after bullet first" t)
578 (const :tag "border first" reversed)))
580 (if (fboundp 'defvaralias)
581 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
583 (defcustom org-special-ctrl-k nil
584 "Non-nil means `C-k' will behave specially in headlines.
585 When nil, `C-k' will call the default `kill-line' command.
586 When t, the following will happen while the cursor is in the headline:
588 - When the cursor is at the beginning of a headline, kill the entire
589 line and possible the folded subtree below the line.
590 - When in the middle of the headline text, kill the headline up to the tags.
591 - When after the headline text, kill the tags."
592 :group 'org-edit-structure
593 :type 'boolean)
595 (defcustom org-M-RET-may-split-line '((default . t))
596 "Non-nil means, M-RET will split the line at the cursor position.
597 When nil, it will go to the end of the line before making a
598 new line.
599 You may also set this option in a different way for different
600 contexts. Valid contexts are:
602 headline when creating a new headline
603 item when creating a new item
604 table in a table field
605 default the value to be used for all contexts not explicitly
606 customized"
607 :group 'org-structure
608 :group 'org-table
609 :type '(choice
610 (const :tag "Always" t)
611 (const :tag "Never" nil)
612 (repeat :greedy t :tag "Individual contexts"
613 (cons
614 (choice :tag "Context"
615 (const headline)
616 (const item)
617 (const table)
618 (const default))
619 (boolean)))))
622 (defcustom org-blank-before-new-entry '((heading . nil)
623 (plain-list-item . nil))
624 "Should `org-insert-heading' leave a blank line before new heading/item?
625 The value is an alist, with `heading' and `plain-list-item' as car,
626 and a boolean flag as cdr."
627 :group 'org-edit-structure
628 :type '(list
629 (cons (const heading) (boolean))
630 (cons (const plain-list-item) (boolean))))
632 (defcustom org-insert-heading-hook nil
633 "Hook being run after inserting a new heading."
634 :group 'org-edit-structure
635 :type 'hook)
637 (defcustom org-enable-fixed-width-editor t
638 "Non-nil means, lines starting with \":\" are treated as fixed-width.
639 This currently only means, they are never auto-wrapped.
640 When nil, such lines will be treated like ordinary lines.
641 See also the QUOTE keyword."
642 :group 'org-edit-structure
643 :type 'boolean)
645 (defcustom org-goto-auto-isearch t
646 "Non-nil means, typing characters in org-goto starts incremental search."
647 :group 'org-edit-structure
648 :type 'boolean)
650 (defgroup org-sparse-trees nil
651 "Options concerning sparse trees in Org-mode."
652 :tag "Org Sparse Trees"
653 :group 'org-structure)
655 (defcustom org-highlight-sparse-tree-matches t
656 "Non-nil means, highlight all matches that define a sparse tree.
657 The highlights will automatically disappear the next time the buffer is
658 changed by an edit command."
659 :group 'org-sparse-trees
660 :type 'boolean)
662 (defcustom org-remove-highlights-with-change t
663 "Non-nil means, any change to the buffer will remove temporary highlights.
664 Such highlights are created by `org-occur' and `org-clock-display'.
665 When nil, `C-c C-c needs to be used to get rid of the highlights.
666 The highlights created by `org-preview-latex-fragment' always need
667 `C-c C-c' to be removed."
668 :group 'org-sparse-trees
669 :group 'org-time
670 :type 'boolean)
673 (defcustom org-occur-hook '(org-first-headline-recenter)
674 "Hook that is run after `org-occur' has constructed a sparse tree.
675 This can be used to recenter the window to show as much of the structure
676 as possible."
677 :group 'org-sparse-trees
678 :type 'hook)
680 (defgroup org-plain-lists nil
681 "Options concerning plain lists in Org-mode."
682 :tag "Org Plain lists"
683 :group 'org-structure)
685 (defcustom org-cycle-include-plain-lists nil
686 "Non-nil means, include plain lists into visibility cycling.
687 This means that during cycling, plain list items will *temporarily* be
688 interpreted as outline headlines with a level given by 1000+i where i is the
689 indentation of the bullet. In all other operations, plain list items are
690 not seen as headlines. For example, you cannot assign a TODO keyword to
691 such an item."
692 :group 'org-plain-lists
693 :type 'boolean)
695 (defcustom org-plain-list-ordered-item-terminator t
696 "The character that makes a line with leading number an ordered list item.
697 Valid values are ?. and ?\). To get both terminators, use t. While
698 ?. may look nicer, it creates the danger that a line with leading
699 number may be incorrectly interpreted as an item. ?\) therefore is
700 the safe choice."
701 :group 'org-plain-lists
702 :type '(choice (const :tag "dot like in \"2.\"" ?.)
703 (const :tag "paren like in \"2)\"" ?\))
704 (const :tab "both" t)))
706 (defcustom org-auto-renumber-ordered-lists t
707 "Non-nil means, automatically renumber ordered plain lists.
708 Renumbering happens when the sequence have been changed with
709 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
710 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
711 :group 'org-plain-lists
712 :type 'boolean)
714 (defcustom org-provide-checkbox-statistics t
715 "Non-nil means, update checkbox statistics after insert and toggle.
716 When this is set, checkbox statistics is updated each time you either insert
717 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
718 with \\[org-ctrl-c-ctrl-c\\]."
719 :group 'org-plain-lists
720 :type 'boolean)
722 (defgroup org-archive nil
723 "Options concerning archiving in Org-mode."
724 :tag "Org Archive"
725 :group 'org-structure)
727 (defcustom org-archive-tag "ARCHIVE"
728 "The tag that marks a subtree as archived.
729 An archived subtree does not open during visibility cycling, and does
730 not contribute to the agenda listings.
731 After changing this, font-lock must be restarted in the relevant buffers to
732 get the proper fontification."
733 :group 'org-archive
734 :group 'org-keywords
735 :type 'string)
737 (defcustom org-agenda-skip-archived-trees t
738 "Non-nil means, the agenda will skip any items located in archived trees.
739 An archived tree is a tree marked with the tag ARCHIVE."
740 :group 'org-archive
741 :group 'org-agenda-skip
742 :type 'boolean)
744 (defcustom org-cycle-open-archived-trees nil
745 "Non-nil means, `org-cycle' will open archived trees.
746 An archived tree is a tree marked with the tag ARCHIVE.
747 When nil, archived trees will stay folded. You can still open them with
748 normal outline commands like `show-all', but not with the cycling commands."
749 :group 'org-archive
750 :group 'org-cycle
751 :type 'boolean)
753 (defcustom org-sparse-tree-open-archived-trees nil
754 "Non-nil means sparse tree construction shows matches in archived trees.
755 When nil, matches in these trees are highlighted, but the trees are kept in
756 collapsed state."
757 :group 'org-archive
758 :group 'org-sparse-trees
759 :type 'boolean)
761 (defcustom org-archive-location "%s_archive::"
762 "The location where subtrees should be archived.
763 This string consists of two parts, separated by a double-colon.
765 The first part is a file name - when omitted, archiving happens in the same
766 file. %s will be replaced by the current file name (without directory part).
767 Archiving to a different file is useful to keep archived entries from
768 contributing to the Org-mode Agenda.
770 The part after the double colon is a headline. The archived entries will be
771 filed under that headline. When omitted, the subtrees are simply filed away
772 at the end of the file, as top-level entries.
774 Here are a few examples:
775 \"%s_archive::\"
776 If the current file is Projects.org, archive in file
777 Projects.org_archive, as top-level trees. This is the default.
779 \"::* Archived Tasks\"
780 Archive in the current file, under the top-level headline
781 \"* Archived Tasks\".
783 \"~/org/archive.org::\"
784 Archive in file ~/org/archive.org (absolute path), as top-level trees.
786 \"basement::** Finished Tasks\"
787 Archive in file ./basement (relative path), as level 3 trees
788 below the level 2 heading \"** Finished Tasks\".
790 You may set this option on a per-file basis by adding to the buffer a
791 line like
793 #+ARCHIVE: basement::** Finished Tasks"
794 :group 'org-archive
795 :type 'string)
797 (defcustom org-archive-mark-done t
798 "Non-nil means, mark entries as DONE when they are moved to the archive file.
799 This can be a string to set the keyword to use. When t, Org-mode will
800 use the first keyword in its list that means done."
801 :group 'org-archive
802 :type '(choice
803 (const :tag "No" nil)
804 (const :tag "Yes" t)
805 (string :tag "Use this keyword")))
807 (defcustom org-archive-stamp-time t
808 "Non-nil means, add a time stamp to entries moved to an archive file.
809 This variable is obsolete and has no effect anymore, instead add ot remove
810 `time' from the variablle `org-archive-save-context-info'."
811 :group 'org-archive
812 :type 'boolean)
814 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
815 "Parts of context info that should be stored as properties when archiving.
816 When a subtree is moved to an archive file, it looses information given by
817 context, like inherited tags, the category, and possibly also the TODO
818 state (depending on the variable `org-archive-mark-done').
819 This variable can be a list of any of the following symbols:
821 time The time of archiving.
822 file The file where the entry originates.
823 itags The local tags, in the headline of the subtree.
824 ltags The tags the subtree inherits from further up the hierarchy.
825 todo The pre-archive TODO state.
826 category The category, taken from file name or #+CATEGORY lines.
827 olpath The outline path to the item. These are all headlines above
828 the current item, separated by /, like a file path.
830 For each symbol present in the list, a property will be created in
831 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
832 information."
833 :group 'org-archive
834 :type '(set :greedy t
835 (const :tag "Time" time)
836 (const :tag "File" file)
837 (const :tag "Category" category)
838 (const :tag "TODO state" todo)
839 (const :tag "TODO state" priority)
840 (const :tag "Inherited tags" itags)
841 (const :tag "Outline path" olpath)
842 (const :tag "Local tags" ltags)))
844 (defgroup org-imenu-and-speedbar nil
845 "Options concerning imenu and speedbar in Org-mode."
846 :tag "Org Imenu and Speedbar"
847 :group 'org-structure)
849 (defcustom org-imenu-depth 2
850 "The maximum level for Imenu access to Org-mode headlines.
851 This also applied for speedbar access."
852 :group 'org-imenu-and-speedbar
853 :type 'number)
855 (defgroup org-table nil
856 "Options concerning tables in Org-mode."
857 :tag "Org Table"
858 :group 'org)
860 (defcustom org-enable-table-editor 'optimized
861 "Non-nil means, lines starting with \"|\" are handled by the table editor.
862 When nil, such lines will be treated like ordinary lines.
864 When equal to the symbol `optimized', the table editor will be optimized to
865 do the following:
866 - Automatic overwrite mode in front of whitespace in table fields.
867 This makes the structure of the table stay in tact as long as the edited
868 field does not exceed the column width.
869 - Minimize the number of realigns. Normally, the table is aligned each time
870 TAB or RET are pressed to move to another field. With optimization this
871 happens only if changes to a field might have changed the column width.
872 Optimization requires replacing the functions `self-insert-command',
873 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
874 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
875 very good at guessing when a re-align will be necessary, but you can always
876 force one with \\[org-ctrl-c-ctrl-c].
878 If you would like to use the optimized version in Org-mode, but the
879 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
881 This variable can be used to turn on and off the table editor during a session,
882 but in order to toggle optimization, a restart is required.
884 See also the variable `org-table-auto-blank-field'."
885 :group 'org-table
886 :type '(choice
887 (const :tag "off" nil)
888 (const :tag "on" t)
889 (const :tag "on, optimized" optimized)))
891 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
892 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
893 In the optimized version, the table editor takes over all simple keys that
894 normally just insert a character. In tables, the characters are inserted
895 in a way to minimize disturbing the table structure (i.e. in overwrite mode
896 for empty fields). Outside tables, the correct binding of the keys is
897 restored.
899 The default for this option is t if the optimized version is also used in
900 Org-mode. See the variable `org-enable-table-editor' for details. Changing
901 this variable requires a restart of Emacs to become effective."
902 :group 'org-table
903 :type 'boolean)
905 (defcustom orgtbl-radio-table-templates
906 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
907 % END RECEIVE ORGTBL %n
908 \\begin{comment}
909 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
910 | | |
911 \\end{comment}\n")
912 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
913 @c END RECEIVE ORGTBL %n
914 @ignore
915 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
916 | | |
917 @end ignore\n")
918 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
919 <!-- END RECEIVE ORGTBL %n -->
920 <!--
921 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
922 | | |
923 -->\n"))
924 "Templates for radio tables in different major modes.
925 All occurrences of %n in a template will be replaced with the name of the
926 table, obtained by prompting the user."
927 :group 'org-table
928 :type '(repeat
929 (list (symbol :tag "Major mode")
930 (string :tag "Format"))))
932 (defgroup org-table-settings nil
933 "Settings for tables in Org-mode."
934 :tag "Org Table Settings"
935 :group 'org-table)
937 (defcustom org-table-default-size "5x2"
938 "The default size for newly created tables, Columns x Rows."
939 :group 'org-table-settings
940 :type 'string)
942 (defcustom org-table-number-regexp
943 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
944 "Regular expression for recognizing numbers in table columns.
945 If a table column contains mostly numbers, it will be aligned to the
946 right. If not, it will be aligned to the left.
948 The default value of this option is a regular expression which allows
949 anything which looks remotely like a number as used in scientific
950 context. For example, all of the following will be considered a
951 number:
952 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
954 Other options offered by the customize interface are more restrictive."
955 :group 'org-table-settings
956 :type '(choice
957 (const :tag "Positive Integers"
958 "^[0-9]+$")
959 (const :tag "Integers"
960 "^[-+]?[0-9]+$")
961 (const :tag "Floating Point Numbers"
962 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
963 (const :tag "Floating Point Number or Integer"
964 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
965 (const :tag "Exponential, Floating point, Integer"
966 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
967 (const :tag "Very General Number-Like, including hex"
968 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
969 (string :tag "Regexp:")))
971 (defcustom org-table-number-fraction 0.5
972 "Fraction of numbers in a column required to make the column align right.
973 In a column all non-white fields are considered. If at least this
974 fraction of fields is matched by `org-table-number-fraction',
975 alignment to the right border applies."
976 :group 'org-table-settings
977 :type 'number)
979 (defgroup org-table-editing nil
980 "Behavior of tables during editing in Org-mode."
981 :tag "Org Table Editing"
982 :group 'org-table)
984 (defcustom org-table-automatic-realign t
985 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
986 When nil, aligning is only done with \\[org-table-align], or after column
987 removal/insertion."
988 :group 'org-table-editing
989 :type 'boolean)
991 (defcustom org-table-auto-blank-field t
992 "Non-nil means, automatically blank table field when starting to type into it.
993 This only happens when typing immediately after a field motion
994 command (TAB, S-TAB or RET).
995 Only relevant when `org-enable-table-editor' is equal to `optimized'."
996 :group 'org-table-editing
997 :type 'boolean)
999 (defcustom org-table-tab-jumps-over-hlines t
1000 "Non-nil means, tab in the last column of a table with jump over a hline.
1001 If a horizontal separator line is following the current line,
1002 `org-table-next-field' can either create a new row before that line, or jump
1003 over the line. When this option is nil, a new line will be created before
1004 this line."
1005 :group 'org-table-editing
1006 :type 'boolean)
1008 (defcustom org-table-tab-recognizes-table.el t
1009 "Non-nil means, TAB will automatically notice a table.el table.
1010 When it sees such a table, it moves point into it and - if necessary -
1011 calls `table-recognize-table'."
1012 :group 'org-table-editing
1013 :type 'boolean)
1015 (defgroup org-table-calculation nil
1016 "Options concerning tables in Org-mode."
1017 :tag "Org Table Calculation"
1018 :group 'org-table)
1020 (defcustom org-table-use-standard-references t
1021 "Should org-mode work with table refrences like B3 instead of @3$2?
1022 Possible values are:
1023 nil never use them
1024 from accept as input, do not present for editing
1025 t: accept as input and present for editing"
1026 :group 'org-table-calculation
1027 :type '(choice
1028 (const :tag "Never, don't even check unser input for them" nil)
1029 (const :tag "Always, both as user input, and when editing" t)
1030 (const :tag "Convert user input, don't offer during editing" 'from)))
1032 (defcustom org-table-copy-increment t
1033 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1034 :group 'org-table-calculation
1035 :type 'boolean)
1037 (defcustom org-calc-default-modes
1038 '(calc-internal-prec 12
1039 calc-float-format (float 5)
1040 calc-angle-mode deg
1041 calc-prefer-frac nil
1042 calc-symbolic-mode nil
1043 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1044 calc-display-working-message t
1046 "List with Calc mode settings for use in calc-eval for table formulas.
1047 The list must contain alternating symbols (Calc modes variables and values).
1048 Don't remove any of the default settings, just change the values. Org-mode
1049 relies on the variables to be present in the list."
1050 :group 'org-table-calculation
1051 :type 'plist)
1053 (defcustom org-table-formula-evaluate-inline t
1054 "Non-nil means, TAB and RET evaluate a formula in current table field.
1055 If the current field starts with an equal sign, it is assumed to be a formula
1056 which should be evaluated as described in the manual and in the documentation
1057 string of the command `org-table-eval-formula'. This feature requires the
1058 Emacs calc package.
1059 When this variable is nil, formula calculation is only available through
1060 the command \\[org-table-eval-formula]."
1061 :group 'org-table-calculation
1062 :type 'boolean)
1064 (defcustom org-table-formula-use-constants t
1065 "Non-nil means, interpret constants in formulas in tables.
1066 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1067 by the value given in `org-table-formula-constants', or by a value obtained
1068 from the `constants.el' package."
1069 :group 'org-table-calculation
1070 :type 'boolean)
1072 (defcustom org-table-formula-constants nil
1073 "Alist with constant names and values, for use in table formulas.
1074 The car of each element is a name of a constant, without the `$' before it.
1075 The cdr is the value as a string. For example, if you'd like to use the
1076 speed of light in a formula, you would configure
1078 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1080 and then use it in an equation like `$1*$c'.
1082 Constants can also be defined on a per-file basis using a line like
1084 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1085 :group 'org-table-calculation
1086 :type '(repeat
1087 (cons (string :tag "name")
1088 (string :tag "value"))))
1090 (defvar org-table-formula-constants-local nil
1091 "Local version of `org-table-formula-constants'.")
1092 (make-variable-buffer-local 'org-table-formula-constants-local)
1094 (defcustom org-table-allow-automatic-line-recalculation t
1095 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1096 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1097 :group 'org-table-calculation
1098 :type 'boolean)
1100 (defgroup org-link nil
1101 "Options concerning links in Org-mode."
1102 :tag "Org Link"
1103 :group 'org)
1105 (defvar org-link-abbrev-alist-local nil
1106 "Buffer-local version of `org-link-abbrev-alist', which see.
1107 The value of this is taken from the #+LINK lines.")
1108 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1110 (defcustom org-link-abbrev-alist nil
1111 "Alist of link abbreviations.
1112 The car of each element is a string, to be replaced at the start of a link.
1113 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1114 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1116 [[linkkey:tag][description]]
1118 If REPLACE is a string, the tag will simply be appended to create the link.
1119 If the string contains \"%s\", the tag will be inserted there.
1121 REPLACE may also be a function that will be called with the tag as the
1122 only argument to create the link, which should be returned as a string.
1124 See the manual for examples."
1125 :group 'org-link
1126 :type 'alist)
1128 (defcustom org-descriptive-links t
1129 "Non-nil means, hide link part and only show description of bracket links.
1130 Bracket links are like [[link][descritpion]]. This variable sets the initial
1131 state in new org-mode buffers. The setting can then be toggled on a
1132 per-buffer basis from the Org->Hyperlinks menu."
1133 :group 'org-link
1134 :type 'boolean)
1136 (defcustom org-link-file-path-type 'adaptive
1137 "How the path name in file links should be stored.
1138 Valid values are:
1140 relative Relative to the current directory, i.e. the directory of the file
1141 into which the link is being inserted.
1142 absolute Absolute path, if possible with ~ for home directory.
1143 noabbrev Absolute path, no abbreviation of home directory.
1144 adaptive Use relative path for files in the current directory and sub-
1145 directories of it. For other files, use an absolute path."
1146 :group 'org-link
1147 :type '(choice
1148 (const relative)
1149 (const absolute)
1150 (const noabbrev)
1151 (const adaptive)))
1153 (defcustom org-activate-links '(bracket angle plain radio tag date)
1154 "Types of links that should be activated in Org-mode files.
1155 This is a list of symbols, each leading to the activation of a certain link
1156 type. In principle, it does not hurt to turn on most link types - there may
1157 be a small gain when turning off unused link types. The types are:
1159 bracket The recommended [[link][description]] or [[link]] links with hiding.
1160 angular Links in angular brackes that may contain whitespace like
1161 <bbdb:Carsten Dominik>.
1162 plain Plain links in normal text, no whitespace, like http://google.com.
1163 radio Text that is matched by a radio target, see manual for details.
1164 tag Tag settings in a headline (link to tag search).
1165 date Time stamps (link to calendar).
1167 Changing this variable requires a restart of Emacs to become effective."
1168 :group 'org-link
1169 :type '(set (const :tag "Double bracket links (new style)" bracket)
1170 (const :tag "Angular bracket links (old style)" angular)
1171 (const :tag "Plain text links" plain)
1172 (const :tag "Radio target matches" radio)
1173 (const :tag "Tags" tag)
1174 (const :tag "Timestamps" date)))
1176 (defgroup org-link-store nil
1177 "Options concerning storing links in Org-mode"
1178 :tag "Org Store Link"
1179 :group 'org-link)
1181 (defcustom org-email-link-description-format "Email %c: %.30s"
1182 "Format of the description part of a link to an email or usenet message.
1183 The following %-excapes will be replaced by corresponding information:
1185 %F full \"From\" field
1186 %f name, taken from \"From\" field, address if no name
1187 %T full \"To\" field
1188 %t first name in \"To\" field, address if no name
1189 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1190 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1191 %s subject
1192 %m message-id.
1194 You may use normal field width specification between the % and the letter.
1195 This is for example useful to limit the length of the subject.
1197 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1198 :group 'org-link-store
1199 :type 'string)
1201 (defcustom org-from-is-user-regexp
1202 (let (r1 r2)
1203 (when (and user-mail-address (not (string= user-mail-address "")))
1204 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1205 (when (and user-full-name (not (string= user-full-name "")))
1206 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1207 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1208 "Regexp mached against the \"From:\" header of an email or usenet message.
1209 It should match if the message is from the user him/herself."
1210 :group 'org-link-store
1211 :type 'regexp)
1213 (defcustom org-context-in-file-links t
1214 "Non-nil means, file links from `org-store-link' contain context.
1215 A search string will be added to the file name with :: as separator and
1216 used to find the context when the link is activated by the command
1217 `org-open-at-point'.
1218 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1219 negates this setting for the duration of the command."
1220 :group 'org-link-store
1221 :type 'boolean)
1223 (defcustom org-keep-stored-link-after-insertion nil
1224 "Non-nil means, keep link in list for entire session.
1226 The command `org-store-link' adds a link pointing to the current
1227 location to an internal list. These links accumulate during a session.
1228 The command `org-insert-link' can be used to insert links into any
1229 Org-mode file (offering completion for all stored links). When this
1230 option is nil, every link which has been inserted once using \\[org-insert-link]
1231 will be removed from the list, to make completing the unused links
1232 more efficient."
1233 :group 'org-link-store
1234 :type 'boolean)
1236 (defcustom org-usenet-links-prefer-google nil
1237 "Non-nil means, `org-store-link' will create web links to Google groups.
1238 When nil, Gnus will be used for such links.
1239 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1240 negates this setting for the duration of the command."
1241 :group 'org-link-store
1242 :type 'boolean)
1244 (defgroup org-link-follow nil
1245 "Options concerning following links in Org-mode"
1246 :tag "Org Follow Link"
1247 :group 'org-link)
1249 (defcustom org-follow-link-hook nil
1250 "Hook that is run after a link has been followed."
1251 :group 'org-link-follow
1252 :type 'hook)
1254 (defcustom org-tab-follows-link nil
1255 "Non-nil means, on links TAB will follow the link.
1256 Needs to be set before org.el is loaded."
1257 :group 'org-link-follow
1258 :type 'boolean)
1260 (defcustom org-return-follows-link nil
1261 "Non-nil means, on links RET will follow the link.
1262 Needs to be set before org.el is loaded."
1263 :group 'org-link-follow
1264 :type 'boolean)
1266 (defcustom org-mouse-1-follows-link
1267 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1268 "Non-nil means, mouse-1 on a link will follow the link.
1269 A longer mouse click will still set point. Does not work on XEmacs.
1270 Needs to be set before org.el is loaded."
1271 :group 'org-link-follow
1272 :type 'boolean)
1274 (defcustom org-mark-ring-length 4
1275 "Number of different positions to be recorded in the ring
1276 Changing this requires a restart of Emacs to work correctly."
1277 :group 'org-link-follow
1278 :type 'interger)
1280 (defcustom org-link-frame-setup
1281 '((vm . vm-visit-folder-other-frame)
1282 (gnus . gnus-other-frame)
1283 (file . find-file-other-window))
1284 "Setup the frame configuration for following links.
1285 When following a link with Emacs, it may often be useful to display
1286 this link in another window or frame. This variable can be used to
1287 set this up for the different types of links.
1288 For VM, use any of
1289 `vm-visit-folder'
1290 `vm-visit-folder-other-frame'
1291 For Gnus, use any of
1292 `gnus'
1293 `gnus-other-frame'
1294 For FILE, use any of
1295 `find-file'
1296 `find-file-other-window'
1297 `find-file-other-frame'
1298 For the calendar, use the variable `calendar-setup'.
1299 For BBDB, it is currently only possible to display the matches in
1300 another window."
1301 :group 'org-link-follow
1302 :type '(list
1303 (cons (const vm)
1304 (choice
1305 (const vm-visit-folder)
1306 (const vm-visit-folder-other-window)
1307 (const vm-visit-folder-other-frame)))
1308 (cons (const gnus)
1309 (choice
1310 (const gnus)
1311 (const gnus-other-frame)))
1312 (cons (const file)
1313 (choice
1314 (const find-file)
1315 (const find-file-other-window)
1316 (const find-file-other-frame)))))
1318 (defcustom org-display-internal-link-with-indirect-buffer nil
1319 "Non-nil means, use indirect buffer to display infile links.
1320 Activating internal links (from one location in a file to another location
1321 in the same file) normally just jumps to the location. When the link is
1322 activated with a C-u prefix (or with mouse-3), the link is displayed in
1323 another window. When this option is set, the other window actually displays
1324 an indirect buffer clone of the current buffer, to avoid any visibility
1325 changes to the current buffer."
1326 :group 'org-link-follow
1327 :type 'boolean)
1329 (defcustom org-open-non-existing-files nil
1330 "Non-nil means, `org-open-file' will open non-existing files.
1331 When nil, an error will be generated."
1332 :group 'org-link-follow
1333 :type 'boolean)
1335 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1336 "Function and arguments to call for following mailto links.
1337 This is a list with the first element being a lisp function, and the
1338 remaining elements being arguments to the function. In string arguments,
1339 %a will be replaced by the address, and %s will be replaced by the subject
1340 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1341 :group 'org-link-follow
1342 :type '(choice
1343 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1344 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1345 (const :tag "message-mail" (message-mail "%a" "%s"))
1346 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1348 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1349 "Non-nil means, ask for confirmation before executing shell links.
1350 Shell links can be dangerous: just think about a link
1352 [[shell:rm -rf ~/*][Google Search]]
1354 This link would show up in your Org-mode document as \"Google Search\",
1355 but really it would remove your entire home directory.
1356 Therefore we advise against setting this variable to nil.
1357 Just change it to `y-or-n-p' of you want to confirm with a
1358 single keystroke rather than having to type \"yes\"."
1359 :group 'org-link-follow
1360 :type '(choice
1361 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1362 (const :tag "with y-or-n (faster)" y-or-n-p)
1363 (const :tag "no confirmation (dangerous)" nil)))
1365 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1366 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1367 Elisp links can be dangerous: just think about a link
1369 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1371 This link would show up in your Org-mode document as \"Google Search\",
1372 but really it would remove your entire home directory.
1373 Therefore we advise against setting this variable to nil.
1374 Just change it to `y-or-n-p' of you want to confirm with a
1375 single keystroke rather than having to type \"yes\"."
1376 :group 'org-link-follow
1377 :type '(choice
1378 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1379 (const :tag "with y-or-n (faster)" y-or-n-p)
1380 (const :tag "no confirmation (dangerous)" nil)))
1382 (defconst org-file-apps-defaults-gnu
1383 '((remote . emacs)
1384 (t . mailcap))
1385 "Default file applications on a UNIX or GNU/Linux system.
1386 See `org-file-apps'.")
1388 (defconst org-file-apps-defaults-macosx
1389 '((remote . emacs)
1390 (t . "open %s")
1391 ("ps" . "gv %s")
1392 ("ps.gz" . "gv %s")
1393 ("eps" . "gv %s")
1394 ("eps.gz" . "gv %s")
1395 ("dvi" . "xdvi %s")
1396 ("fig" . "xfig %s"))
1397 "Default file applications on a MacOS X system.
1398 The system \"open\" is known as a default, but we use X11 applications
1399 for some files for which the OS does not have a good default.
1400 See `org-file-apps'.")
1402 (defconst org-file-apps-defaults-windowsnt
1403 (list
1404 '(remote . emacs)
1405 (cons t
1406 (list (if (featurep 'xemacs)
1407 'mswindows-shell-execute
1408 'w32-shell-execute)
1409 "open" 'file)))
1410 "Default file applications on a Windows NT system.
1411 The system \"open\" is used for most files.
1412 See `org-file-apps'.")
1414 (defcustom org-file-apps
1416 ("txt" . emacs)
1417 ("tex" . emacs)
1418 ("ltx" . emacs)
1419 ("org" . emacs)
1420 ("el" . emacs)
1421 ("bib" . emacs)
1423 "External applications for opening `file:path' items in a document.
1424 Org-mode uses system defaults for different file types, but
1425 you can use this variable to set the application for a given file
1426 extension. The entries in this list are cons cells where the car identifies
1427 files and the cdr the corresponding command. Possible values for the
1428 file identifier are
1429 \"ext\" A string identifying an extension
1430 `directory' Matches a directory
1431 `remote' Matches a remote file, accessible through tramp or efs.
1432 Remote files most likely should be visited through Emacs
1433 because external applications cannot handle such paths.
1434 t Default for all remaining files
1436 Possible values for the command are:
1437 `emacs' The file will be visited by the current Emacs process.
1438 `default' Use the default application for this file type.
1439 string A command to be executed by a shell; %s will be replaced
1440 by the path to the file.
1441 sexp A Lisp form which will be evaluated. The file path will
1442 be available in the Lisp variable `file'.
1443 For more examples, see the system specific constants
1444 `org-file-apps-defaults-macosx'
1445 `org-file-apps-defaults-windowsnt'
1446 `org-file-apps-defaults-gnu'."
1447 :group 'org-link-follow
1448 :type '(repeat
1449 (cons (choice :value ""
1450 (string :tag "Extension")
1451 (const :tag "Default for unrecognized files" t)
1452 (const :tag "Remote file" remote)
1453 (const :tag "Links to a directory" directory))
1454 (choice :value ""
1455 (const :tag "Visit with Emacs" emacs)
1456 (const :tag "Use system default" default)
1457 (string :tag "Command")
1458 (sexp :tag "Lisp form")))))
1460 (defcustom org-mhe-search-all-folders nil
1461 "Non-nil means, that the search for the mh-message will be extended to
1462 all folders if the message cannot be found in the folder given in the link.
1463 Searching all folders is very efficient with one of the search engines
1464 supported by MH-E, but will be slow with pick."
1465 :group 'org-link-follow
1466 :type 'boolean)
1468 (defgroup org-remember nil
1469 "Options concerning interaction with remember.el."
1470 :tag "Org Remember"
1471 :group 'org)
1473 (defcustom org-directory "~/org"
1474 "Directory with org files.
1475 This directory will be used as default to prompt for org files.
1476 Used by the hooks for remember.el."
1477 :group 'org-remember
1478 :type 'directory)
1480 (defcustom org-default-notes-file "~/.notes"
1481 "Default target for storing notes.
1482 Used by the hooks for remember.el. This can be a string, or nil to mean
1483 the value of `remember-data-file'.
1484 You can set this on a per-template basis with the variable
1485 `org-remember-templates'."
1486 :group 'org-remember
1487 :type '(choice
1488 (const :tag "Default from remember-data-file" nil)
1489 file))
1491 (defcustom org-remember-store-without-prompt t
1492 "Non-nil means, `C-c C-c' stores remember note without further promts.
1493 In this case, you need `C-u C-c C-c' to get the prompts for
1494 note file and headline.
1495 When this variable is nil, `C-c C-c' give you the prompts, and
1496 `C-u C-c C-c' trigger the fasttrack."
1497 :group 'org-remember
1498 :type 'boolean)
1500 (defcustom org-remember-interactive-interface 'refile
1501 "The interface to be used for interactive filing of remember notes.
1502 This is only used when the interactive mode for selecting a filing
1503 location is used (see the variable `org-remember-store-without-prompt').
1504 Allowed vaues are:
1505 outline The interface shows an outline of the relevant file
1506 and the correct heading is found by moving through
1507 the outline or by searching with incremental search.
1508 outline-path-completion Headlines in the current buffer are offered via
1509 completion.
1510 refile Use the refile interface, and offer headlines,
1511 possibly from different buffers."
1512 :group 'org-remember
1513 :type '(choice
1514 (const :tag "Refile" refile)
1515 (const :tag "Outline" outline)
1516 (const :tag "Outline-path-completion" outline-path-completion)))
1518 (defcustom org-goto-interface 'outline
1519 "The default interface to be used for `org-goto'.
1520 Allowed vaues are:
1521 outline The interface shows an outline of the relevant file
1522 and the correct heading is found by moving through
1523 the outline or by searching with incremental search.
1524 outline-path-completion Headlines in the current buffer are offered via
1525 completion."
1526 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1527 :type '(choice
1528 (const :tag "Outline" outline)
1529 (const :tag "Outline-path-completion" outline-path-completion)))
1531 (defcustom org-remember-default-headline ""
1532 "The headline that should be the default location in the notes file.
1533 When filing remember notes, the cursor will start at that position.
1534 You can set this on a per-template basis with the variable
1535 `org-remember-templates'."
1536 :group 'org-remember
1537 :type 'string)
1539 (defcustom org-remember-templates nil
1540 "Templates for the creation of remember buffers.
1541 When nil, just let remember make the buffer.
1542 When not nil, this is a list of 5-element lists. In each entry, the first
1543 element is the name of the template, which should be a single short word.
1544 The second element is a character, a unique key to select this template.
1545 The third element is the template. The fourth element is optional and can
1546 specify a destination file for remember items created with this template.
1547 The default file is given by `org-default-notes-file'. An optional fifth
1548 element can specify the headline in that file that should be offered
1549 first when the user is asked to file the entry. The default headline is
1550 given in the variable `org-remember-default-headline'.
1552 An optional sixth element can specify the context in which the user should
1553 be able to select this template. If this element is a list of major modes,
1554 the template will only be available while invoking `org-remember' from a
1555 buffer in one of these modes. If it is a function, the template will only
1556 be selected if the function returns `t'. A value of `t' means select
1557 this template in any context. When the element is `nil', the template
1558 will be selected by default, i.e. when all contextual checks failed.
1560 The template specifies the structure of the remember buffer. It should have
1561 a first line starting with a star, to act as the org-mode headline.
1562 Furthermore, the following %-escapes will be replaced with content:
1564 %^{prompt} Prompt the user for a string and replace this sequence with it.
1565 A default value and a completion table ca be specified like this:
1566 %^{prompt|default|completion2|completion3|...}
1567 %t time stamp, date only
1568 %T time stamp with date and time
1569 %u, %U like the above, but inactive time stamps
1570 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1571 You may define a prompt like %^{Please specify birthday}t
1572 %n user name (taken from `user-full-name')
1573 %a annotation, normally the link created with org-store-link
1574 %i initial content, the region active. If %i is indented,
1575 the entire inserted text will be indented as well.
1576 %c content of the clipboard, or current kill ring head
1577 %^g prompt for tags, with completion on tags in target file
1578 %^G prompt for tags, with completion all tags in all agenda files
1579 %:keyword specific information for certain link types, see below
1580 %[pathname] insert the contents of the file given by `pathname'
1581 %(sexp) evaluate elisp `(sexp)' and replace with the result
1582 %! Store this note immediately after filling the template
1584 %? After completing the template, position cursor here.
1586 Apart from these general escapes, you can access information specific to the
1587 link type that is created. For example, calling `remember' in emails or gnus
1588 will record the author and the subject of the message, which you can access
1589 with %:author and %:subject, respectively. Here is a complete list of what
1590 is recorded for each link type.
1592 Link type | Available information
1593 -------------------+------------------------------------------------------
1594 bbdb | %:type %:name %:company
1595 vm, wl, mh, rmail | %:type %:subject %:message-id
1596 | %:from %:fromname %:fromaddress
1597 | %:to %:toname %:toaddress
1598 | %:fromto (either \"to NAME\" or \"from NAME\")
1599 gnus | %:group, for messages also all email fields
1600 w3, w3m | %:type %:url
1601 info | %:type %:file %:node
1602 calendar | %:type %:date"
1603 :group 'org-remember
1604 :get (lambda (var) ; Make sure all entries have at least 5 elements
1605 (mapcar (lambda (x)
1606 (if (not (stringp (car x))) (setq x (cons "" x)))
1607 (cond ((= (length x) 4) (append x '("")))
1608 ((= (length x) 3) (append x '("" "")))
1609 (t x)))
1610 (default-value var)))
1611 :type '(repeat
1612 :tag "enabled"
1613 (list :value ("" ?a "\n" nil nil nil)
1614 (string :tag "Name")
1615 (character :tag "Selection Key")
1616 (string :tag "Template")
1617 (choice
1618 (file :tag "Destination file")
1619 (const :tag "Prompt for file" nil))
1620 (choice
1621 (string :tag "Destination headline")
1622 (const :tag "Selection interface for heading"))
1623 (choice
1624 (const :tag "Use by default" nil)
1625 (const :tag "Use in all contexts" t)
1626 (repeat :tag "Use only if in major mode"
1627 (symbol :tag "Major mode"))
1628 (function :tag "Perform a check against function")))))
1630 (defcustom org-reverse-note-order nil
1631 "Non-nil means, store new notes at the beginning of a file or entry.
1632 When nil, new notes will be filed to the end of a file or entry.
1633 This can also be a list with cons cells of regular expressions that
1634 are matched against file names, and values."
1635 :group 'org-remember
1636 :type '(choice
1637 (const :tag "Reverse always" t)
1638 (const :tag "Reverse never" nil)
1639 (repeat :tag "By file name regexp"
1640 (cons regexp boolean))))
1642 (defcustom org-refile-targets nil
1643 "Targets for refiling entries with \\[org-refile].
1644 This is list of cons cells. Each cell contains:
1645 - a specification of the files to be considered, either a list of files,
1646 or a symbol whose function or value fields will be used to retrieve
1647 a file name or a list of file names. Nil means, refile to a different
1648 heading in the current buffer.
1649 - A specification of how to find candidate refile targets. This may be
1650 any of
1651 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1652 This tag has to be present in all target headlines, inheritance will
1653 not be considered.
1654 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1655 todo keyword.
1656 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1657 headlines that are refiling targets.
1658 - a cons cell (:level . N). Any headline of level N is considered a target.
1659 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1660 ;; FIXME: what if there are a var and func with same name???
1661 :group 'org-remember
1662 :type '(repeat
1663 (cons
1664 (choice :value org-agenda-files
1665 (const :tag "All agenda files" org-agenda-files)
1666 (const :tag "Current buffer" nil)
1667 (function) (variable) (file))
1668 (choice :tag "Identify target headline by"
1669 (cons :tag "Specific tag" (const :tag) (string))
1670 (cons :tag "TODO keyword" (const :todo) (string))
1671 (cons :tag "Regular expression" (const :regexp) (regexp))
1672 (cons :tag "Level number" (const :level) (integer))
1673 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1675 (defcustom org-refile-use-outline-path nil
1676 "Non-nil means, provide refile targets as paths.
1677 So a level 3 headline will be available as level1/level2/level3.
1678 When the value is `file', also include the file name (without directory)
1679 into the path. When `full-file-path', include the full file path."
1680 :group 'org-remember
1681 :type '(choice
1682 (const :tag "Not" nil)
1683 (const :tag "Yes" t)
1684 (const :tag "Start with file name" file)
1685 (const :tag "Start with full file path" full-file-path)))
1687 (defgroup org-todo nil
1688 "Options concerning TODO items in Org-mode."
1689 :tag "Org TODO"
1690 :group 'org)
1692 (defgroup org-progress nil
1693 "Options concerning Progress logging in Org-mode."
1694 :tag "Org Progress"
1695 :group 'org-time)
1697 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1698 "List of TODO entry keyword sequences and their interpretation.
1699 \\<org-mode-map>This is a list of sequences.
1701 Each sequence starts with a symbol, either `sequence' or `type',
1702 indicating if the keywords should be interpreted as a sequence of
1703 action steps, or as different types of TODO items. The first
1704 keywords are states requiring action - these states will select a headline
1705 for inclusion into the global TODO list Org-mode produces. If one of
1706 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1707 signify that no further action is necessary. If \"|\" is not found,
1708 the last keyword is treated as the only DONE state of the sequence.
1710 The command \\[org-todo] cycles an entry through these states, and one
1711 additional state where no keyword is present. For details about this
1712 cycling, see the manual.
1714 TODO keywords and interpretation can also be set on a per-file basis with
1715 the special #+SEQ_TODO and #+TYP_TODO lines.
1717 Each keyword can optionally specify a character for fast state selection
1718 \(in combination with the variable `org-use-fast-todo-selection')
1719 and specifiers for state change logging, using the same syntax
1720 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1721 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1722 indicates to record a time stamp each time this state is selected.
1724 Each keyword may also specify if a timestamp or a note should be
1725 recorded when entering or leaving the state, by adding additional
1726 characters in the parenthesis after the keyword. This looks like this:
1727 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1728 record only the time of the state change. With X and Y being either
1729 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1730 Y when leaving the state if and only if the *target* state does not
1731 define X. You may omit any of the fast-selection key or X or /Y,
1732 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1734 For backward compatibility, this variable may also be just a list
1735 of keywords - in this case the interptetation (sequence or type) will be
1736 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1737 :group 'org-todo
1738 :group 'org-keywords
1739 :type '(choice
1740 (repeat :tag "Old syntax, just keywords"
1741 (string :tag "Keyword"))
1742 (repeat :tag "New syntax"
1743 (cons
1744 (choice
1745 :tag "Interpretation"
1746 (const :tag "Sequence (cycling hits every state)" sequence)
1747 (const :tag "Type (cycling directly to DONE)" type))
1748 (repeat
1749 (string :tag "Keyword"))))))
1751 (defvar org-todo-keywords-1 nil
1752 "All TODO and DONE keywords active in a buffer.")
1753 (make-variable-buffer-local 'org-todo-keywords-1)
1754 (defvar org-todo-keywords-for-agenda nil)
1755 (defvar org-done-keywords-for-agenda nil)
1756 (defvar org-not-done-keywords nil)
1757 (make-variable-buffer-local 'org-not-done-keywords)
1758 (defvar org-done-keywords nil)
1759 (make-variable-buffer-local 'org-done-keywords)
1760 (defvar org-todo-heads nil)
1761 (make-variable-buffer-local 'org-todo-heads)
1762 (defvar org-todo-sets nil)
1763 (make-variable-buffer-local 'org-todo-sets)
1764 (defvar org-todo-log-states nil)
1765 (make-variable-buffer-local 'org-todo-log-states)
1766 (defvar org-todo-kwd-alist nil)
1767 (make-variable-buffer-local 'org-todo-kwd-alist)
1768 (defvar org-todo-key-alist nil)
1769 (make-variable-buffer-local 'org-todo-key-alist)
1770 (defvar org-todo-key-trigger nil)
1771 (make-variable-buffer-local 'org-todo-key-trigger)
1773 (defcustom org-todo-interpretation 'sequence
1774 "Controls how TODO keywords are interpreted.
1775 This variable is in principle obsolete and is only used for
1776 backward compatibility, if the interpretation of todo keywords is
1777 not given already in `org-todo-keywords'. See that variable for
1778 more information."
1779 :group 'org-todo
1780 :group 'org-keywords
1781 :type '(choice (const sequence)
1782 (const type)))
1784 (defcustom org-use-fast-todo-selection 'prefix
1785 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1786 This variable describes if and under what circumstances the cycling
1787 mechanism for TODO keywords will be replaced by a single-key, direct
1788 selection scheme.
1790 When nil, fast selection is never used.
1792 When the symbol `prefix', it will be used when `org-todo' is called with
1793 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1794 in an agenda buffer.
1796 When t, fast selection is used by default. In this case, the prefix
1797 argument forces cycling instead.
1799 In all cases, the special interface is only used if access keys have actually
1800 been assigned by the user, i.e. if keywords in the configuration are followed
1801 by a letter in parenthesis, like TODO(t)."
1802 :group 'org-todo
1803 :type '(choice
1804 (const :tag "Never" nil)
1805 (const :tag "By default" t)
1806 (const :tag "Only with C-u C-c C-t" prefix)))
1808 (defcustom org-after-todo-state-change-hook nil
1809 "Hook which is run after the state of a TODO item was changed.
1810 The new state (a string with a TODO keyword, or nil) is available in the
1811 Lisp variable `state'."
1812 :group 'org-todo
1813 :type 'hook)
1815 (defcustom org-log-done nil
1816 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1817 When equal to the list (done), also prompt for a closing note.
1818 This can also be configured on a per-file basis by adding one of
1819 the following lines anywhere in the buffer:
1821 #+STARTUP: logdone
1822 #+STARTUP: lognotedone
1823 #+STARTUP: nologdone"
1824 :group 'org-todo
1825 :group 'org-progress
1826 :type '(choice
1827 (const :tag "No logging" nil)
1828 (const :tag "Record CLOSED timestamp" time)
1829 (const :tag "Record CLOSED timestamp with closing note." note)))
1831 ;; Normalize old uses of org-log-done.
1832 (cond
1833 ((eq org-log-done t) (setq org-log-done 'time))
1834 ((and (listp org-log-done) (memq 'done org-log-done))
1835 (setq org-log-done 'note)))
1837 ;; FIXME: document
1838 (defcustom org-log-note-clock-out nil
1839 "Non-nil means, recored a note when clocking out of an item.
1840 This can also be configured on a per-file basis by adding one of
1841 the following lines anywhere in the buffer:
1843 #+STARTUP: lognoteclock-out
1844 #+STARTUP: nolognoteclock-out"
1845 :group 'org-todo
1846 :group 'org-progress
1847 :type 'boolean)
1849 (defcustom org-log-done-with-time t
1850 "Non-nil means, the CLOSED time stamp will contain date and time.
1851 When nil, only the date will be recorded."
1852 :group 'org-progress
1853 :type 'boolean)
1855 (defcustom org-log-note-headings
1856 '((done . "CLOSING NOTE %t")
1857 (state . "State %-12s %t")
1858 (clock-out . ""))
1859 "Headings for notes added when clocking out or closing TODO items.
1860 The value is an alist, with the car being a symbol indicating the note
1861 context, and the cdr is the heading to be used. The heading may also be the
1862 empty string.
1863 %t in the heading will be replaced by a time stamp.
1864 %s will be replaced by the new TODO state, in double quotes.
1865 %u will be replaced by the user name.
1866 %U will be replaced by the full user name."
1867 :group 'org-todo
1868 :group 'org-progress
1869 :type '(list :greedy t
1870 (cons (const :tag "Heading when closing an item" done) string)
1871 (cons (const :tag
1872 "Heading when changing todo state (todo sequence only)"
1873 state) string)
1874 (cons (const :tag "Heading when clocking out" clock-out) string)))
1876 (defcustom org-log-states-order-reversed t
1877 "Non-nil means, the latest state change note will be directly after heading.
1878 When nil, the notes will be orderer according to time."
1879 :group 'org-todo
1880 :group 'org-progress
1881 :type 'boolean)
1883 (defcustom org-log-repeat 'time
1884 "Non-nil means, record moving through the DONE state when triggering repeat.
1885 An auto-repeating tasks is immediately switched back to TODO when marked
1886 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1887 the TODO keyword definition, or recording a cloing note by setting
1888 `org-log-done', there will be no record of the task moving trhough DONE.
1889 This variable forces taking a note anyway. Possible values are:
1891 nil Don't force a record
1892 time Record a time stamp
1893 note Record a note
1895 This option can also be set with on a per-file-basis with
1897 #+STARTUP: logrepeat
1898 #+STARTUP: lognoterepeat
1899 #+STARTUP: nologrepeat
1901 You can have local logging settings for a subtree by setting the LOGGING
1902 property to one or more of these keywords."
1903 :group 'org-todo
1904 :group 'org-progress
1905 :type '(choice
1906 (const :tag "Don't force a record" nil)
1907 (const :tag "Force recording the DONE state" time)
1908 (const :tag "Force recording a note with the DONE state" note)))
1910 (defcustom org-clock-into-drawer 2
1911 "Should clocking info be wrapped into a drawer?
1912 When t, clocking info will always be inserted into a :CLOCK: drawer.
1913 If necessary, the drawer will be created.
1914 When nil, the drawer will not be created, but used when present.
1915 When an integer and the number of clocking entries in an item
1916 reaches or exceeds this number, a drawer will be created."
1917 :group 'org-todo
1918 :group 'org-progress
1919 :type '(choice
1920 (const :tag "Always" t)
1921 (const :tag "Only when drawer exists" nil)
1922 (integer :tag "When at least N clock entries")))
1924 (defcustom org-clock-out-when-done t
1925 "When t, the clock will be stopped when the relevant entry is marked DONE.
1926 Nil means, clock will keep running until stopped explicitly with
1927 `C-c C-x C-o', or until the clock is started in a different item."
1928 :group 'org-progress
1929 :type 'boolean)
1931 (defcustom org-clock-in-switch-to-state nil
1932 "Set task to a special todo state while clocking it.
1933 The value should be the state to which the entry should be switched."
1934 :group 'org-progress
1935 :group 'org-todo
1936 :type '(choice
1937 (const :tag "Don't force a state" nil)
1938 (string :tag "State")))
1940 (defgroup org-priorities nil
1941 "Priorities in Org-mode."
1942 :tag "Org Priorities"
1943 :group 'org-todo)
1945 (defcustom org-highest-priority ?A
1946 "The highest priority of TODO items. A character like ?A, ?B etc.
1947 Must have a smaller ASCII number than `org-lowest-priority'."
1948 :group 'org-priorities
1949 :type 'character)
1951 (defcustom org-lowest-priority ?C
1952 "The lowest priority of TODO items. A character like ?A, ?B etc.
1953 Must have a larger ASCII number than `org-highest-priority'."
1954 :group 'org-priorities
1955 :type 'character)
1957 (defcustom org-default-priority ?B
1958 "The default priority of TODO items.
1959 This is the priority an item get if no explicit priority is given."
1960 :group 'org-priorities
1961 :type 'character)
1963 (defcustom org-priority-start-cycle-with-default t
1964 "Non-nil means, start with default priority when starting to cycle.
1965 When this is nil, the first step in the cycle will be (depending on the
1966 command used) one higher or lower that the default priority."
1967 :group 'org-priorities
1968 :type 'boolean)
1970 (defgroup org-time nil
1971 "Options concerning time stamps and deadlines in Org-mode."
1972 :tag "Org Time"
1973 :group 'org)
1975 (defcustom org-insert-labeled-timestamps-at-point nil
1976 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1977 When nil, these labeled time stamps are forces into the second line of an
1978 entry, just after the headline. When scheduling from the global TODO list,
1979 the time stamp will always be forced into the second line."
1980 :group 'org-time
1981 :type 'boolean)
1983 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1984 "Formats for `format-time-string' which are used for time stamps.
1985 It is not recommended to change this constant.")
1987 (defcustom org-time-stamp-rounding-minutes '(0 5)
1988 "Number of minutes to round time stamps to.
1989 These are two values, the first applies when first creating a time stamp.
1990 The second applies when changing it with the commands `S-up' and `S-down'.
1991 When changing the time stamp, this means that it will change in steps
1992 of N minues, as given by the second value.
1994 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1995 numbers should be factors of 60, so for example 5, 10, 15.
1997 When this is larger than 1, you can still force an exact time-stamp by using
1998 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1999 and by using a prefix arg to `S-up/down' to specify the exact number
2000 of minutes to shift."
2001 :group 'org-time
2002 :get '(lambda (var) ; Make sure all entries have 5 elements
2003 (if (integerp (default-value var))
2004 (list (default-value var) 5)
2005 (default-value var)))
2006 :type '(list
2007 (integer :tag "when inserting times")
2008 (integer :tag "when modifying times")))
2010 (defcustom org-display-custom-times nil
2011 "Non-nil means, overlay custom formats over all time stamps.
2012 The formats are defined through the variable `org-time-stamp-custom-formats'.
2013 To turn this on on a per-file basis, insert anywhere in the file:
2014 #+STARTUP: customtime"
2015 :group 'org-time
2016 :set 'set-default
2017 :type 'sexp)
2018 (make-variable-buffer-local 'org-display-custom-times)
2020 (defcustom org-time-stamp-custom-formats
2021 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2022 "Custom formats for time stamps. See `format-time-string' for the syntax.
2023 These are overlayed over the default ISO format if the variable
2024 `org-display-custom-times' is set. Time like %H:%M should be at the
2025 end of the second format."
2026 :group 'org-time
2027 :type 'sexp)
2029 (defun org-time-stamp-format (&optional long inactive)
2030 "Get the right format for a time string."
2031 (let ((f (if long (cdr org-time-stamp-formats)
2032 (car org-time-stamp-formats))))
2033 (if inactive
2034 (concat "[" (substring f 1 -1) "]")
2035 f)))
2037 (defcustom org-read-date-prefer-future t
2038 "Non-nil means, assume future for incomplete date input from user.
2039 This affects the following situations:
2040 1. The user gives a day, but no month.
2041 For example, if today is the 15th, and you enter \"3\", Org-mode will
2042 read this as the third of *next* month. However, if you enter \"17\",
2043 it will be considered as *this* month.
2044 2. The user gives a month but not a year.
2045 For example, if it is april and you enter \"feb 2\", this will be read
2046 as feb 2, *next* year. \"May 5\", however, will be this year.
2048 When this option is nil, the current month and year will always be used
2049 as defaults."
2050 :group 'org-time
2051 :type 'boolean)
2053 (defcustom org-read-date-display-live t
2054 "Non-nil means, display current interpretation of date prompt live.
2055 This display will be in an overlay, in the minibuffer."
2056 :group 'org-time
2057 :type 'boolean)
2059 (defcustom org-read-date-popup-calendar t
2060 "Non-nil means, pop up a calendar when prompting for a date.
2061 In the calendar, the date can be selected with mouse-1. However, the
2062 minibuffer will also be active, and you can simply enter the date as well.
2063 When nil, only the minibuffer will be available."
2064 :group 'org-time
2065 :type 'boolean)
2066 (if (fboundp 'defvaralias)
2067 (defvaralias 'org-popup-calendar-for-date-prompt
2068 'org-read-date-popup-calendar))
2070 (defcustom org-extend-today-until 0
2071 "The hour when your day really ends.
2072 This has influence for the following applications:
2073 - When switching the agenda to \"today\". It it is still earlier than
2074 the time given here, the day recognized as TODAY is actually yesterday.
2075 - When a date is read from the user and it is still before the time given
2076 here, the current date and time will be assumed to be yesterday, 23:59.
2078 FIXME:
2079 IMPORTANT: This is still a very experimental feature, it may disappear
2080 again or it may be extended to mean more things."
2081 :group 'org-time
2082 :type 'number)
2084 (defcustom org-edit-timestamp-down-means-later nil
2085 "Non-nil means, S-down will increase the time in a time stamp.
2086 When nil, S-up will increase."
2087 :group 'org-time
2088 :type 'boolean)
2090 (defcustom org-calendar-follow-timestamp-change t
2091 "Non-nil means, make the calendar window follow timestamp changes.
2092 When a timestamp is modified and the calendar window is visible, it will be
2093 moved to the new date."
2094 :group 'org-time
2095 :type 'boolean)
2097 (defcustom org-clock-heading-function nil
2098 "When non-nil, should be a function to create `org-clock-heading'.
2099 This is the string shown in the mode line when a clock is running.
2100 The function is called with point at the beginning of the headline."
2101 :group 'org-time ; FIXME: Should we have a separate group????
2102 :type 'function)
2104 (defgroup org-tags nil
2105 "Options concerning tags in Org-mode."
2106 :tag "Org Tags"
2107 :group 'org)
2109 (defcustom org-tag-alist nil
2110 "List of tags allowed in Org-mode files.
2111 When this list is nil, Org-mode will base TAG input on what is already in the
2112 buffer.
2113 The value of this variable is an alist, the car of each entry must be a
2114 keyword as a string, the cdr may be a character that is used to select
2115 that tag through the fast-tag-selection interface.
2116 See the manual for details."
2117 :group 'org-tags
2118 :type '(repeat
2119 (choice
2120 (cons (string :tag "Tag name")
2121 (character :tag "Access char"))
2122 (const :tag "Start radio group" (:startgroup))
2123 (const :tag "End radio group" (:endgroup)))))
2125 (defcustom org-use-fast-tag-selection 'auto
2126 "Non-nil means, use fast tag selection scheme.
2127 This is a special interface to select and deselect tags with single keys.
2128 When nil, fast selection is never used.
2129 When the symbol `auto', fast selection is used if and only if selection
2130 characters for tags have been configured, either through the variable
2131 `org-tag-alist' or through a #+TAGS line in the buffer.
2132 When t, fast selection is always used and selection keys are assigned
2133 automatically if necessary."
2134 :group 'org-tags
2135 :type '(choice
2136 (const :tag "Always" t)
2137 (const :tag "Never" nil)
2138 (const :tag "When selection characters are configured" 'auto)))
2140 (defcustom org-fast-tag-selection-single-key nil
2141 "Non-nil means, fast tag selection exits after first change.
2142 When nil, you have to press RET to exit it.
2143 During fast tag selection, you can toggle this flag with `C-c'.
2144 This variable can also have the value `expert'. In this case, the window
2145 displaying the tags menu is not even shown, until you press C-c again."
2146 :group 'org-tags
2147 :type '(choice
2148 (const :tag "No" nil)
2149 (const :tag "Yes" t)
2150 (const :tag "Expert" expert)))
2152 (defvar org-fast-tag-selection-include-todo nil
2153 "Non-nil means, fast tags selection interface will also offer TODO states.
2154 This is an undocumented feature, you should not rely on it.")
2156 (defcustom org-tags-column -80
2157 "The column to which tags should be indented in a headline.
2158 If this number is positive, it specifies the column. If it is negative,
2159 it means that the tags should be flushright to that column. For example,
2160 -80 works well for a normal 80 character screen."
2161 :group 'org-tags
2162 :type 'integer)
2164 (defcustom org-auto-align-tags t
2165 "Non-nil means, realign tags after pro/demotion of TODO state change.
2166 These operations change the length of a headline and therefore shift
2167 the tags around. With this options turned on, after each such operation
2168 the tags are again aligned to `org-tags-column'."
2169 :group 'org-tags
2170 :type 'boolean)
2172 (defcustom org-use-tag-inheritance t
2173 "Non-nil means, tags in levels apply also for sublevels.
2174 When nil, only the tags directly given in a specific line apply there.
2175 If you turn off this option, you very likely want to turn on the
2176 companion option `org-tags-match-list-sublevels'."
2177 :group 'org-tags
2178 :type 'boolean)
2180 (defcustom org-tags-match-list-sublevels nil
2181 "Non-nil means list also sublevels of headlines matching tag search.
2182 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2183 the sublevels of a headline matching a tag search often also match
2184 the same search. Listing all of them can create very long lists.
2185 Setting this variable to nil causes subtrees of a match to be skipped.
2186 This option is off by default, because inheritance in on. If you turn
2187 inheritance off, you very likely want to turn this option on.
2189 As a special case, if the tag search is restricted to TODO items, the
2190 value of this variable is ignored and sublevels are always checked, to
2191 make sure all corresponding TODO items find their way into the list."
2192 :group 'org-tags
2193 :type 'boolean)
2195 (defvar org-tags-history nil
2196 "History of minibuffer reads for tags.")
2197 (defvar org-last-tags-completion-table nil
2198 "The last used completion table for tags.")
2199 (defvar org-after-tags-change-hook nil
2200 "Hook that is run after the tags in a line have changed.")
2202 (defgroup org-properties nil
2203 "Options concerning properties in Org-mode."
2204 :tag "Org Properties"
2205 :group 'org)
2207 (defcustom org-property-format "%-10s %s"
2208 "How property key/value pairs should be formatted by `indent-line'.
2209 When `indent-line' hits a property definition, it will format the line
2210 according to this format, mainly to make sure that the values are
2211 lined-up with respect to each other."
2212 :group 'org-properties
2213 :type 'string)
2215 (defcustom org-use-property-inheritance nil
2216 "Non-nil means, properties apply also for sublevels.
2217 This setting is only relevant during property searches, not when querying
2218 an entry with `org-entry-get'. To retrieve a property with inheritance,
2219 you need to call `org-entry-get' with the inheritance flag.
2220 Turning this on can cause significant overhead when doing a search, so
2221 this is turned off by default.
2222 When nil, only the properties directly given in the current entry count.
2223 The value may also be a list of properties that shouldhave inheritance.
2225 However, note that some special properties use inheritance under special
2226 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2227 and the properties ending in \"_ALL\" when they are used as descriptor
2228 for valid values of a property."
2229 :group 'org-properties
2230 :type '(choice
2231 (const :tag "Not" nil)
2232 (const :tag "Always" nil)
2233 (repeat :tag "Specific properties" (string :tag "Property"))))
2235 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2236 "The default column format, if no other format has been defined.
2237 This variable can be set on the per-file basis by inserting a line
2239 #+COLUMNS: %25ITEM ....."
2240 :group 'org-properties
2241 :type 'string)
2243 (defcustom org-global-properties nil
2244 "List of property/value pairs that can be inherited by any entry.
2245 You can set buffer-local values for this by adding lines like
2247 #+PROPERTY: NAME VALUE"
2248 :group 'org-properties
2249 :type '(repeat
2250 (cons (string :tag "Property")
2251 (string :tag "Value"))))
2253 (defvar org-local-properties nil
2254 "List of property/value pairs that can be inherited by any entry.
2255 Valid for the current buffer.
2256 This variable is populated from #+PROPERTY lines.")
2258 (defgroup org-agenda nil
2259 "Options concerning agenda views in Org-mode."
2260 :tag "Org Agenda"
2261 :group 'org)
2263 (defvar org-category nil
2264 "Variable used by org files to set a category for agenda display.
2265 Such files should use a file variable to set it, for example
2267 # -*- mode: org; org-category: \"ELisp\"
2269 or contain a special line
2271 #+CATEGORY: ELisp
2273 If the file does not specify a category, then file's base name
2274 is used instead.")
2275 (make-variable-buffer-local 'org-category)
2277 (defcustom org-agenda-files nil
2278 "The files to be used for agenda display.
2279 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2280 \\[org-remove-file]. You can also use customize to edit the list.
2282 If an entry is a directory, all files in that directory that are matched by
2283 `org-agenda-file-regexp' will be part of the file list.
2285 If the value of the variable is not a list but a single file name, then
2286 the list of agenda files is actually stored and maintained in that file, one
2287 agenda file per line."
2288 :group 'org-agenda
2289 :type '(choice
2290 (repeat :tag "List of files and directories" file)
2291 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2293 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2294 "Regular expression to match files for `org-agenda-files'.
2295 If any element in the list in that variable contains a directory instead
2296 of a normal file, all files in that directory that are matched by this
2297 regular expression will be included."
2298 :group 'org-agenda
2299 :type 'regexp)
2301 (defcustom org-agenda-skip-unavailable-files nil
2302 "t means to just skip non-reachable files in `org-agenda-files'.
2303 Nil means to remove them, after a query, from the list."
2304 :group 'org-agenda
2305 :type 'boolean)
2307 (defcustom org-agenda-text-search-extra-files nil
2308 "List of extra files to be searched by text search commands.
2309 These files will be search in addition to the agenda files bu the
2310 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2311 Note that these files will only be searched for text search commands,
2312 not for the other agenda views like todo lists, tag earches or the weekly
2313 agenda. This variable is intended to list notes and possibly archive files
2314 that should also be searched by these two commands."
2315 :group 'org-agenda
2316 :type '(repeat file))
2318 (if (fboundp 'defvaralias)
2319 (defvaralias 'org-agenda-multi-occur-extra-files
2320 'org-agenda-text-search-extra-files))
2322 (defcustom org-agenda-confirm-kill 1
2323 "When set, remote killing from the agenda buffer needs confirmation.
2324 When t, a confirmation is always needed. When a number N, confirmation is
2325 only needed when the text to be killed contains more than N non-white lines."
2326 :group 'org-agenda
2327 :type '(choice
2328 (const :tag "Never" nil)
2329 (const :tag "Always" t)
2330 (number :tag "When more than N lines")))
2332 (defcustom org-calendar-to-agenda-key [?c]
2333 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2334 The command `org-calendar-goto-agenda' will be bound to this key. The
2335 default is the character `c' because then `c' can be used to switch back and
2336 forth between agenda and calendar."
2337 :group 'org-agenda
2338 :type 'sexp)
2340 (defcustom org-agenda-compact-blocks nil
2341 "Non-nil means, make the block agenda more compact.
2342 This is done by leaving out unnecessary lines."
2343 :group 'org-agenda
2344 :type nil)
2346 (defgroup org-agenda-export nil
2347 "Options concerning exporting agenda views in Org-mode."
2348 :tag "Org Agenda Export"
2349 :group 'org-agenda)
2351 (defcustom org-agenda-with-colors t
2352 "Non-nil means, use colors in agenda views."
2353 :group 'org-agenda-export
2354 :type 'boolean)
2356 (defcustom org-agenda-exporter-settings nil
2357 "Alist of variable/value pairs that should be active during agenda export.
2358 This is a good place to set uptions for ps-print and for htmlize."
2359 :group 'org-agenda-export
2360 :type '(repeat
2361 (list
2362 (variable)
2363 (sexp :tag "Value"))))
2365 (defcustom org-agenda-export-html-style ""
2366 "The style specification for exported HTML Agenda files.
2367 If this variable contains a string, it will replace the default <style>
2368 section as produced by `htmlize'.
2369 Since there are different ways of setting style information, this variable
2370 needs to contain the full HTML structure to provide a style, including the
2371 surrounding HTML tags. The style specifications should include definitions
2372 the fonts used by the agenda, here is an example:
2374 <style type=\"text/css\">
2375 p { font-weight: normal; color: gray; }
2376 .org-agenda-structure {
2377 font-size: 110%;
2378 color: #003399;
2379 font-weight: 600;
2381 .org-todo {
2382 color: #cc6666;Week-agenda:
2383 font-weight: bold;
2385 .org-done {
2386 color: #339933;
2388 .title { text-align: center; }
2389 .todo, .deadline { color: red; }
2390 .done { color: green; }
2391 </style>
2393 or, if you want to keep the style in a file,
2395 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2397 As the value of this option simply gets inserted into the HTML <head> header,
2398 you can \"misuse\" it to also add other text to the header. However,
2399 <style>...</style> is required, if not present the variable will be ignored."
2400 :group 'org-agenda-export
2401 :group 'org-export-html
2402 :type 'string)
2404 (defgroup org-agenda-custom-commands nil
2405 "Options concerning agenda views in Org-mode."
2406 :tag "Org Agenda Custom Commands"
2407 :group 'org-agenda)
2409 (defconst org-sorting-choice
2410 '(choice
2411 (const time-up) (const time-down)
2412 (const category-keep) (const category-up) (const category-down)
2413 (const tag-down) (const tag-up)
2414 (const priority-up) (const priority-down))
2415 "Sorting choices.")
2417 (defconst org-agenda-custom-commands-local-options
2418 `(repeat :tag "Local settings for this command. Remember to quote values"
2419 (choice :tag "Setting"
2420 (list :tag "Any variable"
2421 (variable :tag "Variable")
2422 (sexp :tag "Value"))
2423 (list :tag "Files to be searched"
2424 (const org-agenda-files)
2425 (list
2426 (const :format "" quote)
2427 (repeat
2428 (file))))
2429 (list :tag "Sorting strategy"
2430 (const org-agenda-sorting-strategy)
2431 (list
2432 (const :format "" quote)
2433 (repeat
2434 ,org-sorting-choice)))
2435 (list :tag "Prefix format"
2436 (const org-agenda-prefix-format :value " %-12:c%?-12t% s")
2437 (string))
2438 (list :tag "Number of days in agenda"
2439 (const org-agenda-ndays)
2440 (integer :value 1))
2441 (list :tag "Fixed starting date"
2442 (const org-agenda-start-day)
2443 (string :value "2007-11-01"))
2444 (list :tag "Start on day of week"
2445 (const org-agenda-start-on-weekday)
2446 (choice :value 1
2447 (const :tag "Today" nil)
2448 (number :tag "Weekday No.")))
2449 (list :tag "Include data from diary"
2450 (const org-agenda-include-diary)
2451 (boolean))
2452 (list :tag "Deadline Warning days"
2453 (const org-deadline-warning-days)
2454 (integer :value 1))
2455 (list :tag "Standard skipping condition"
2456 :value (org-agenda-skip-function '(org-agenda-skip-entry-if))
2457 (const org-agenda-skip-function)
2458 (list
2459 (const :format "" quote)
2460 (list
2461 (choice
2462 :tag "Skiping range"
2463 (const :tag "Skip entry" org-agenda-skip-entry-if)
2464 (const :tag "Skip subtree" org-agenda-skip-subtree-if))
2465 (repeat :inline t :tag "Conditions for skipping"
2466 (choice
2467 :tag "Condition type"
2468 (list :tag "Regexp matches" :inline t (const :format "" 'regexp) (regexp))
2469 (list :tag "Regexp does not match" :inline t (const :format "" 'notregexp) (regexp))
2470 (const :tag "scheduled" 'scheduled)
2471 (const :tag "not scheduled" 'notscheduled)
2472 (const :tag "deadline" 'deadline)
2473 (const :tag "no deadline" 'notdeadline))))))
2474 (list :tag "Non-standard skipping condition"
2475 :value (org-agenda-skip-function)
2476 (list
2477 (const org-agenda-skip-function)
2478 (sexp :tag "Function or form (quoted!)")))))
2479 "Selection of examples for agenda command settings.
2480 This will be spliced into the custom type of
2481 `org-agenda-custom-commands'.")
2484 (defcustom org-agenda-custom-commands nil
2485 "Custom commands for the agenda.
2486 These commands will be offered on the splash screen displayed by the
2487 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2489 (key desc type match settings files)
2491 key The key (one or more characters as a string) to be associated
2492 with the command.
2493 desc A description of the command, when omitted or nil, a default
2494 description is built using MATCH.
2495 type The command type, any of the following symbols:
2496 agenda The daily/weekly agenda.
2497 todo Entries with a specific TODO keyword, in all agenda files.
2498 search Entries containing search words entry or headline.
2499 tags Tags/Property/TODO match in all agenda files.
2500 tags-todo Tags/P/T match in all agenda files, TODO entries only.
2501 todo-tree Sparse tree of specific TODO keyword in *current* file.
2502 tags-tree Sparse tree with all tags matches in *current* file.
2503 occur-tree Occur sparse tree for *current* file.
2504 ... A user-defined function.
2505 match What to search for:
2506 - a single keyword for TODO keyword searches
2507 - a tags match expression for tags searches
2508 - a word search expression for text searches.
2509 - a regular expression for occur searches
2510 For all other commands, this should be the empty string.
2511 settings A list of option settings, similar to that in a let form, so like
2512 this: ((opt1 val1) (opt2 val2) ...). The values will be
2513 evaluated at the moment of execution, so quote them when needed.
2514 files A list of files file to write the produced agenda buffer to
2515 with the command `org-store-agenda-views'.
2516 If a file name ends in \".html\", an HTML version of the buffer
2517 is written out. If it ends in \".ps\", a postscript version is
2518 produced. Otherwide, only the plain text is written to the file.
2520 You can also define a set of commands, to create a composite agenda buffer.
2521 In this case, an entry looks like this:
2523 (key desc (cmd1 cmd2 ...) general-settings-for-whole-set files)
2525 where
2527 desc A description string to be displayed in the dispatcher menu.
2528 cmd An agenda command, similar to the above. However, tree commands
2529 are no allowed, but instead you can get agenda and global todo list.
2530 So valid commands for a set are:
2531 (agenda \"\" settings)
2532 (alltodo \"\" settings)
2533 (stuck \"\" settings)
2534 (todo \"match\" settings files)
2535 (search \"match\" settings files)
2536 (tags \"match\" settings files)
2537 (tags-todo \"match\" settings files)
2539 Each command can carry a list of options, and another set of options can be
2540 given for the whole set of commands. Individual command options take
2541 precedence over the general options.
2543 When using several characters as key to a command, the first characters
2544 are prefix commands. For the dispatcher to display useful information, you
2545 should provide a description for the prefix, like
2547 (setq org-agenda-custom-commands
2548 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2549 (\"hl\" tags \"+HOME+Lisa\")
2550 (\"hp\" tags \"+HOME+Peter\")
2551 (\"hk\" tags \"+HOME+Kim\")))"
2552 :group 'org-agenda-custom-commands
2553 :type `(repeat
2554 (choice :value ("x" "Describe command here" tags "" nil)
2555 (list :tag "Single command"
2556 (string :tag "Access Key(s) ")
2557 (option (string :tag "Description"))
2558 (choice
2559 (const :tag "Agenda" agenda)
2560 (const :tag "TODO list" alltodo)
2561 (const :tag "Search words" search)
2562 (const :tag "Stuck projects" stuck)
2563 (const :tag "Tags search (all agenda files)" tags)
2564 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2565 (const :tag "TODO keyword search (all agenda files)" todo)
2566 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2567 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2568 (const :tag "Occur tree (current buffer)" occur-tree)
2569 (sexp :tag "Other, user-defined function"))
2570 (string :tag "Match (only for some commands)")
2571 ,org-agenda-custom-commands-local-options
2572 (option (repeat :tag "Export" (file :tag "Export to"))))
2573 (list :tag "Command series, all agenda files"
2574 (string :tag "Access Key(s)")
2575 (string :tag "Description ")
2576 (repeat :tag "Component"
2577 (choice
2578 (list :tag "Agenda"
2579 (const :format "" agenda)
2580 (const :tag "" :format "" "")
2581 ,org-agenda-custom-commands-local-options)
2582 (list :tag "TODO list (all keywords)"
2583 (const :format "" alltodo)
2584 (const :tag "" :format "" "")
2585 ,org-agenda-custom-commands-local-options)
2586 (list :tag "Search words"
2587 (const :format "" search)
2588 (string :tag "Match")
2589 ,org-agenda-custom-commands-local-options)
2590 (list :tag "Stuck projects"
2591 (const :format "" stuck)
2592 (const :tag "" :format "" "")
2593 ,org-agenda-custom-commands-local-options)
2594 (list :tag "Tags search"
2595 (const :format "" tags)
2596 (string :tag "Match")
2597 ,org-agenda-custom-commands-local-options)
2598 (list :tag "Tags search, TODO entries only"
2599 (const :format "" tags-todo)
2600 (string :tag "Match")
2601 ,org-agenda-custom-commands-local-options)
2602 (list :tag "TODO keyword search"
2603 (const :format "" todo)
2604 (string :tag "Match")
2605 ,org-agenda-custom-commands-local-options)
2606 (list :tag "Other, user-defined function"
2607 (symbol :tag "function")
2608 (string :tag "Match")
2609 ,org-agenda-custom-commands-local-options)))
2611 (repeat :tag "Settings for entire command set"
2612 (list (variable :tag "Any variable")
2613 (sexp :tag "Value")))
2614 (option (repeat :tag "Export" (file :tag "Export to"))))
2615 (cons :tag "Prefix key documentation"
2616 (string :tag "Access Key(s)")
2617 (string :tag "Description ")))))
2619 (defcustom org-agenda-query-register ?o
2620 "The register holding the current query string.
2621 The prupose of this is that if you construct a query string interactively,
2622 you can then use it to define a custom command."
2623 :group 'org-agenda-custom-commands
2624 :type 'character)
2626 (defcustom org-stuck-projects
2627 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2628 "How to identify stuck projects.
2629 This is a list of four items:
2630 1. A tags/todo matcher string that is used to identify a project.
2631 The entire tree below a headline matched by this is considered one project.
2632 2. A list of TODO keywords identifying non-stuck projects.
2633 If the project subtree contains any headline with one of these todo
2634 keywords, the project is considered to be not stuck. If you specify
2635 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2636 3. A list of tags identifying non-stuck projects.
2637 If the project subtree contains any headline with one of these tags,
2638 the project is considered to be not stuck. If you specify \"*\" as
2639 a tag, any tag will mark the project unstuck.
2640 4. An arbitrary regular expression matching non-stuck projects.
2642 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2643 or `C-c a #' to produce the list."
2644 :group 'org-agenda-custom-commands
2645 :type '(list
2646 (string :tag "Tags/TODO match to identify a project")
2647 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2648 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2649 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2652 (defgroup org-agenda-skip nil
2653 "Options concerning skipping parts of agenda files."
2654 :tag "Org Agenda Skip"
2655 :group 'org-agenda)
2657 (defcustom org-agenda-todo-list-sublevels t
2658 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2659 When nil, the sublevels of a TODO entry are not checked, resulting in
2660 potentially much shorter TODO lists."
2661 :group 'org-agenda-skip
2662 :group 'org-todo
2663 :type 'boolean)
2665 (defcustom org-agenda-todo-ignore-with-date nil
2666 "Non-nil means, don't show entries with a date in the global todo list.
2667 You can use this if you prefer to mark mere appointments with a TODO keyword,
2668 but don't want them to show up in the TODO list.
2669 When this is set, it also covers deadlines and scheduled items, the settings
2670 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2671 will be ignored."
2672 :group 'org-agenda-skip
2673 :group 'org-todo
2674 :type 'boolean)
2676 (defcustom org-agenda-todo-ignore-scheduled nil
2677 "Non-nil means, don't show scheduled entries in the global todo list.
2678 The idea behind this is that by scheduling it, you have already taken care
2679 of this item.
2680 See also `org-agenda-todo-ignore-with-date'."
2681 :group 'org-agenda-skip
2682 :group 'org-todo
2683 :type 'boolean)
2685 (defcustom org-agenda-todo-ignore-deadlines nil
2686 "Non-nil means, don't show near deadline entries in the global todo list.
2687 Near means closer than `org-deadline-warning-days' days.
2688 The idea behind this is that such items will appear in the agenda anyway.
2689 See also `org-agenda-todo-ignore-with-date'."
2690 :group 'org-agenda-skip
2691 :group 'org-todo
2692 :type 'boolean)
2694 (defcustom org-agenda-skip-scheduled-if-done nil
2695 "Non-nil means don't show scheduled items in agenda when they are done.
2696 This is relevant for the daily/weekly agenda, not for the TODO list. And
2697 it applies only to the actual date of the scheduling. Warnings about
2698 an item with a past scheduling dates are always turned off when the item
2699 is DONE."
2700 :group 'org-agenda-skip
2701 :type 'boolean)
2703 (defcustom org-agenda-skip-deadline-if-done nil
2704 "Non-nil means don't show deadines when the corresponding item is done.
2705 When nil, the deadline is still shown and should give you a happy feeling.
2706 This is relevant for the daily/weekly agenda. And it applied only to the
2707 actualy date of the deadline. Warnings about approching and past-due
2708 deadlines are always turned off when the item is DONE."
2709 :group 'org-agenda-skip
2710 :type 'boolean)
2712 (defcustom org-agenda-skip-timestamp-if-done nil
2713 "Non-nil means don't select item by timestamp or -range if it is DONE."
2714 :group 'org-agenda-skip
2715 :type 'boolean)
2717 (defcustom org-timeline-show-empty-dates 3
2718 "Non-nil means, `org-timeline' also shows dates without an entry.
2719 When nil, only the days which actually have entries are shown.
2720 When t, all days between the first and the last date are shown.
2721 When an integer, show also empty dates, but if there is a gap of more than
2722 N days, just insert a special line indicating the size of the gap."
2723 :group 'org-agenda-skip
2724 :type '(choice
2725 (const :tag "None" nil)
2726 (const :tag "All" t)
2727 (number :tag "at most")))
2730 (defgroup org-agenda-startup nil
2731 "Options concerning initial settings in the Agenda in Org Mode."
2732 :tag "Org Agenda Startup"
2733 :group 'org-agenda)
2735 (defcustom org-finalize-agenda-hook nil
2736 "Hook run just before displaying an agenda buffer."
2737 :group 'org-agenda-startup
2738 :type 'hook)
2740 (defcustom org-agenda-mouse-1-follows-link nil
2741 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2742 A longer mouse click will still set point. Does not work on XEmacs.
2743 Needs to be set before org.el is loaded."
2744 :group 'org-agenda-startup
2745 :type 'boolean)
2747 (defcustom org-agenda-start-with-follow-mode nil
2748 "The initial value of follow-mode in a newly created agenda window."
2749 :group 'org-agenda-startup
2750 :type 'boolean)
2752 (defgroup org-agenda-windows nil
2753 "Options concerning the windows used by the Agenda in Org Mode."
2754 :tag "Org Agenda Windows"
2755 :group 'org-agenda)
2757 (defcustom org-agenda-window-setup 'reorganize-frame
2758 "How the agenda buffer should be displayed.
2759 Possible values for this option are:
2761 current-window Show agenda in the current window, keeping all other windows.
2762 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2763 other-window Use `switch-to-buffer-other-window' to display agenda.
2764 reorganize-frame Show only two windows on the current frame, the current
2765 window and the agenda.
2766 See also the variable `org-agenda-restore-windows-after-quit'."
2767 :group 'org-agenda-windows
2768 :type '(choice
2769 (const current-window)
2770 (const other-frame)
2771 (const other-window)
2772 (const reorganize-frame)))
2774 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2775 "The min and max height of the agenda window as a fraction of frame height.
2776 The value of the variable is a cons cell with two numbers between 0 and 1.
2777 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2778 :group 'org-agenda-windows
2779 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2781 (defcustom org-agenda-restore-windows-after-quit nil
2782 "Non-nil means, restore window configuration open exiting agenda.
2783 Before the window configuration is changed for displaying the agenda,
2784 the current status is recorded. When the agenda is exited with
2785 `q' or `x' and this option is set, the old state is restored. If
2786 `org-agenda-window-setup' is `other-frame', the value of this
2787 option will be ignored.."
2788 :group 'org-agenda-windows
2789 :type 'boolean)
2791 (defcustom org-indirect-buffer-display 'other-window
2792 "How should indirect tree buffers be displayed?
2793 This applies to indirect buffers created with the commands
2794 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2795 Valid values are:
2796 current-window Display in the current window
2797 other-window Just display in another window.
2798 dedicated-frame Create one new frame, and re-use it each time.
2799 new-frame Make a new frame each time. Note that in this case
2800 previously-made indirect buffers are kept, and you need to
2801 kill these buffers yourself."
2802 :group 'org-structure
2803 :group 'org-agenda-windows
2804 :type '(choice
2805 (const :tag "In current window" current-window)
2806 (const :tag "In current frame, other window" other-window)
2807 (const :tag "Each time a new frame" new-frame)
2808 (const :tag "One dedicated frame" dedicated-frame)))
2810 (defgroup org-agenda-daily/weekly nil
2811 "Options concerning the daily/weekly agenda."
2812 :tag "Org Agenda Daily/Weekly"
2813 :group 'org-agenda)
2815 (defcustom org-agenda-ndays 7
2816 "Number of days to include in overview display.
2817 Should be 1 or 7."
2818 :group 'org-agenda-daily/weekly
2819 :type 'number)
2821 (defcustom org-agenda-start-on-weekday 1
2822 "Non-nil means, start the overview always on the specified weekday.
2823 0 denotes Sunday, 1 denotes Monday etc.
2824 When nil, always start on the current day."
2825 :group 'org-agenda-daily/weekly
2826 :type '(choice (const :tag "Today" nil)
2827 (number :tag "Weekday No.")))
2829 (defcustom org-agenda-show-all-dates t
2830 "Non-nil means, `org-agenda' shows every day in the selected range.
2831 When nil, only the days which actually have entries are shown."
2832 :group 'org-agenda-daily/weekly
2833 :type 'boolean)
2835 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2836 "Format string for displaying dates in the agenda.
2837 Used by the daily/weekly agenda and by the timeline. This should be
2838 a format string understood by `format-time-string', or a function returning
2839 the formatted date as a string. The function must take a single argument,
2840 a calendar-style date list like (month day year)."
2841 :group 'org-agenda-daily/weekly
2842 :type '(choice
2843 (string :tag "Format string")
2844 (function :tag "Function")))
2846 (defun org-agenda-format-date-aligned (date)
2847 "Format a date string for display in the daily/weekly agenda, or timeline.
2848 This function makes sure that dates are aligned for easy reading."
2849 (format "%-9s %2d %s %4d"
2850 (calendar-day-name date)
2851 (extract-calendar-day date)
2852 (calendar-month-name (extract-calendar-month date))
2853 (extract-calendar-year date)))
2855 (defcustom org-agenda-include-diary nil
2856 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2857 :group 'org-agenda-daily/weekly
2858 :type 'boolean)
2860 (defcustom org-agenda-include-all-todo nil
2861 "Set means weekly/daily agenda will always contain all TODO entries.
2862 The TODO entries will be listed at the top of the agenda, before
2863 the entries for specific days."
2864 :group 'org-agenda-daily/weekly
2865 :type 'boolean)
2867 (defcustom org-agenda-repeating-timestamp-show-all t
2868 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2869 When nil, only one occurence is shown, either today or the
2870 nearest into the future."
2871 :group 'org-agenda-daily/weekly
2872 :type 'boolean)
2874 (defcustom org-deadline-warning-days 14
2875 "No. of days before expiration during which a deadline becomes active.
2876 This variable governs the display in sparse trees and in the agenda.
2877 When 0 or negative, it means use this number (the absolute value of it)
2878 even if a deadline has a different individual lead time specified."
2879 :group 'org-time
2880 :group 'org-agenda-daily/weekly
2881 :type 'number)
2883 (defcustom org-scheduled-past-days 10000
2884 "No. of days to continue listing scheduled items that are not marked DONE.
2885 When an item is scheduled on a date, it shows up in the agenda on this
2886 day and will be listed until it is marked done for the number of days
2887 given here."
2888 :group 'org-agenda-daily/weekly
2889 :type 'number)
2891 (defgroup org-agenda-time-grid nil
2892 "Options concerning the time grid in the Org-mode Agenda."
2893 :tag "Org Agenda Time Grid"
2894 :group 'org-agenda)
2896 (defcustom org-agenda-use-time-grid t
2897 "Non-nil means, show a time grid in the agenda schedule.
2898 A time grid is a set of lines for specific times (like every two hours between
2899 8:00 and 20:00). The items scheduled for a day at specific times are
2900 sorted in between these lines.
2901 For details about when the grid will be shown, and what it will look like, see
2902 the variable `org-agenda-time-grid'."
2903 :group 'org-agenda-time-grid
2904 :type 'boolean)
2906 (defcustom org-agenda-time-grid
2907 '((daily today require-timed)
2908 "----------------"
2909 (800 1000 1200 1400 1600 1800 2000))
2911 "The settings for time grid for agenda display.
2912 This is a list of three items. The first item is again a list. It contains
2913 symbols specifying conditions when the grid should be displayed:
2915 daily if the agenda shows a single day
2916 weekly if the agenda shows an entire week
2917 today show grid on current date, independent of daily/weekly display
2918 require-timed show grid only if at least one item has a time specification
2920 The second item is a string which will be places behing the grid time.
2922 The third item is a list of integers, indicating the times that should have
2923 a grid line."
2924 :group 'org-agenda-time-grid
2925 :type
2926 '(list
2927 (set :greedy t :tag "Grid Display Options"
2928 (const :tag "Show grid in single day agenda display" daily)
2929 (const :tag "Show grid in weekly agenda display" weekly)
2930 (const :tag "Always show grid for today" today)
2931 (const :tag "Show grid only if any timed entries are present"
2932 require-timed)
2933 (const :tag "Skip grid times already present in an entry"
2934 remove-match))
2935 (string :tag "Grid String")
2936 (repeat :tag "Grid Times" (integer :tag "Time"))))
2938 (defgroup org-agenda-sorting nil
2939 "Options concerning sorting in the Org-mode Agenda."
2940 :tag "Org Agenda Sorting"
2941 :group 'org-agenda)
2943 (defcustom org-agenda-sorting-strategy
2944 '((agenda time-up category-keep priority-down)
2945 (todo category-keep priority-down)
2946 (tags category-keep priority-down)
2947 (search category-keep))
2948 "Sorting structure for the agenda items of a single day.
2949 This is a list of symbols which will be used in sequence to determine
2950 if an entry should be listed before another entry. The following
2951 symbols are recognized:
2953 time-up Put entries with time-of-day indications first, early first
2954 time-down Put entries with time-of-day indications first, late first
2955 category-keep Keep the default order of categories, corresponding to the
2956 sequence in `org-agenda-files'.
2957 category-up Sort alphabetically by category, A-Z.
2958 category-down Sort alphabetically by category, Z-A.
2959 tag-up Sort alphabetically by last tag, A-Z.
2960 tag-down Sort alphabetically by last tag, Z-A.
2961 priority-up Sort numerically by priority, high priority last.
2962 priority-down Sort numerically by priority, high priority first.
2964 The different possibilities will be tried in sequence, and testing stops
2965 if one comparison returns a \"not-equal\". For example, the default
2966 '(time-up category-keep priority-down)
2967 means: Pull out all entries having a specified time of day and sort them,
2968 in order to make a time schedule for the current day the first thing in the
2969 agenda listing for the day. Of the entries without a time indication, keep
2970 the grouped in categories, don't sort the categories, but keep them in
2971 the sequence given in `org-agenda-files'. Within each category sort by
2972 priority.
2974 Leaving out `category-keep' would mean that items will be sorted across
2975 categories by priority.
2977 Instead of a single list, this can also be a set of list for specific
2978 contents, with a context symbol in the car of the list, any of
2979 `agenda', `todo', `tags' for the corresponding agenda views."
2980 :group 'org-agenda-sorting
2981 :type `(choice
2982 (repeat :tag "General" ,org-sorting-choice)
2983 (list :tag "Individually"
2984 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2985 (repeat ,org-sorting-choice))
2986 (cons (const :tag "Strategy for TODO lists" todo)
2987 (repeat ,org-sorting-choice))
2988 (cons (const :tag "Strategy for Tags matches" tags)
2989 (repeat ,org-sorting-choice)))))
2991 (defcustom org-sort-agenda-notime-is-late t
2992 "Non-nil means, items without time are considered late.
2993 This is only relevant for sorting. When t, items which have no explicit
2994 time like 15:30 will be considered as 99:01, i.e. later than any items which
2995 do have a time. When nil, the default time is before 0:00. You can use this
2996 option to decide if the schedule for today should come before or after timeless
2997 agenda entries."
2998 :group 'org-agenda-sorting
2999 :type 'boolean)
3001 (defgroup org-agenda-line-format nil
3002 "Options concerning the entry prefix in the Org-mode agenda display."
3003 :tag "Org Agenda Line Format"
3004 :group 'org-agenda)
3006 (defcustom org-agenda-prefix-format
3007 '((agenda . " %-12:c%?-12t% s")
3008 (timeline . " % s")
3009 (todo . " %-12:c")
3010 (tags . " %-12:c")
3011 (search . " %-12:c"))
3012 "Format specifications for the prefix of items in the agenda views.
3013 An alist with four entries, for the different agenda types. The keys to the
3014 sublists are `agenda', `timeline', `todo', and `tags'. The values
3015 are format strings.
3016 This format works similar to a printf format, with the following meaning:
3018 %c the category of the item, \"Diary\" for entries from the diary, or
3019 as given by the CATEGORY keyword or derived from the file name.
3020 %T the *last* tag of the item. Last because inherited tags come
3021 first in the list.
3022 %t the time-of-day specification if one applies to the entry, in the
3023 format HH:MM
3024 %s Scheduling/Deadline information, a short string
3026 All specifiers work basically like the standard `%s' of printf, but may
3027 contain two additional characters: A question mark just after the `%' and
3028 a whitespace/punctuation character just before the final letter.
3030 If the first character after `%' is a question mark, the entire field
3031 will only be included if the corresponding value applies to the
3032 current entry. This is useful for fields which should have fixed
3033 width when present, but zero width when absent. For example,
3034 \"%?-12t\" will result in a 12 character time field if a time of the
3035 day is specified, but will completely disappear in entries which do
3036 not contain a time.
3038 If there is punctuation or whitespace character just before the final
3039 format letter, this character will be appended to the field value if
3040 the value is not empty. For example, the format \"%-12:c\" leads to
3041 \"Diary: \" if the category is \"Diary\". If the category were be
3042 empty, no additional colon would be interted.
3044 The default value of this option is \" %-12:c%?-12t% s\", meaning:
3045 - Indent the line with two space characters
3046 - Give the category in a 12 chars wide field, padded with whitespace on
3047 the right (because of `-'). Append a colon if there is a category
3048 (because of `:').
3049 - If there is a time-of-day, put it into a 12 chars wide field. If no
3050 time, don't put in an empty field, just skip it (because of '?').
3051 - Finally, put the scheduling information and append a whitespace.
3053 As another example, if you don't want the time-of-day of entries in
3054 the prefix, you could use:
3056 (setq org-agenda-prefix-format \" %-11:c% s\")
3058 See also the variables `org-agenda-remove-times-when-in-prefix' and
3059 `org-agenda-remove-tags'."
3060 :type '(choice
3061 (string :tag "General format")
3062 (list :greedy t :tag "View dependent"
3063 (cons (const agenda) (string :tag "Format"))
3064 (cons (const timeline) (string :tag "Format"))
3065 (cons (const todo) (string :tag "Format"))
3066 (cons (const tags) (string :tag "Format"))
3067 (cons (const search) (string :tag "Format"))))
3068 :group 'org-agenda-line-format)
3070 (defvar org-prefix-format-compiled nil
3071 "The compiled version of the most recently used prefix format.
3072 See the variable `org-agenda-prefix-format'.")
3074 (defcustom org-agenda-todo-keyword-format "%-1s"
3075 "Format for the TODO keyword in agenda lines.
3076 Set this to something like \"%-12s\" if you want all TODO keywords
3077 to occupy a fixed space in the agenda display."
3078 :group 'org-agenda-line-format
3079 :type 'string)
3081 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
3082 "Text preceeding scheduled items in the agenda view.
3083 This is a list with two strings. The first applies when the item is
3084 scheduled on the current day. The second applies when it has been scheduled
3085 previously, it may contain a %d to capture how many days ago the item was
3086 scheduled."
3087 :group 'org-agenda-line-format
3088 :type '(list
3089 (string :tag "Scheduled today ")
3090 (string :tag "Scheduled previously")))
3092 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
3093 "Text preceeding deadline items in the agenda view.
3094 This is a list with two strings. The first applies when the item has its
3095 deadline on the current day. The second applies when it is in the past or
3096 in the future, it may contain %d to capture how many days away the deadline
3097 is (was)."
3098 :group 'org-agenda-line-format
3099 :type '(list
3100 (string :tag "Deadline today ")
3101 (string :tag "Deadline relative")))
3103 (defcustom org-agenda-remove-times-when-in-prefix t
3104 "Non-nil means, remove duplicate time specifications in agenda items.
3105 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
3106 time-of-day specification in a headline or diary entry is extracted and
3107 placed into the prefix. If this option is non-nil, the original specification
3108 \(a timestamp or -range, or just a plain time(range) specification like
3109 11:30-4pm) will be removed for agenda display. This makes the agenda less
3110 cluttered.
3111 The option can be t or nil. It may also be the symbol `beg', indicating
3112 that the time should only be removed what it is located at the beginning of
3113 the headline/diary entry."
3114 :group 'org-agenda-line-format
3115 :type '(choice
3116 (const :tag "Always" t)
3117 (const :tag "Never" nil)
3118 (const :tag "When at beginning of entry" beg)))
3121 (defcustom org-agenda-default-appointment-duration nil
3122 "Default duration for appointments that only have a starting time.
3123 When nil, no duration is specified in such cases.
3124 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
3125 :group 'org-agenda-line-format
3126 :type '(choice
3127 (integer :tag "Minutes")
3128 (const :tag "No default duration")))
3131 (defcustom org-agenda-remove-tags nil
3132 "Non-nil means, remove the tags from the headline copy in the agenda.
3133 When this is the symbol `prefix', only remove tags when
3134 `org-agenda-prefix-format' contains a `%T' specifier."
3135 :group 'org-agenda-line-format
3136 :type '(choice
3137 (const :tag "Always" t)
3138 (const :tag "Never" nil)
3139 (const :tag "When prefix format contains %T" prefix)))
3141 (if (fboundp 'defvaralias)
3142 (defvaralias 'org-agenda-remove-tags-when-in-prefix
3143 'org-agenda-remove-tags))
3145 (defcustom org-agenda-tags-column -80
3146 "Shift tags in agenda items to this column.
3147 If this number is positive, it specifies the column. If it is negative,
3148 it means that the tags should be flushright to that column. For example,
3149 -80 works well for a normal 80 character screen."
3150 :group 'org-agenda-line-format
3151 :type 'integer)
3153 (if (fboundp 'defvaralias)
3154 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
3156 (defcustom org-agenda-fontify-priorities t
3157 "Non-nil means, highlight low and high priorities in agenda.
3158 When t, the highest priority entries are bold, lowest priority italic.
3159 This may also be an association list of priority faces. The face may be
3160 a names face, or a list like `(:background \"Red\")'."
3161 :group 'org-agenda-line-format
3162 :type '(choice
3163 (const :tag "Never" nil)
3164 (const :tag "Defaults" t)
3165 (repeat :tag "Specify"
3166 (list (character :tag "Priority" :value ?A)
3167 (sexp :tag "face")))))
3169 (defgroup org-latex nil
3170 "Options for embedding LaTeX code into Org-mode"
3171 :tag "Org LaTeX"
3172 :group 'org)
3174 (defcustom org-format-latex-options
3175 '(:foreground default :background default :scale 1.0
3176 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3177 :matchers ("begin" "$" "$$" "\\(" "\\["))
3178 "Options for creating images from LaTeX fragments.
3179 This is a property list with the following properties:
3180 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
3181 `default' means use the forground of the default face.
3182 :background the background color, or \"Transparent\".
3183 `default' means use the background of the default face.
3184 :scale a scaling factor for the size of the images
3185 :html-foreground, :html-background, :html-scale
3186 The same numbers for HTML export.
3187 :matchers a list indicating which matchers should be used to
3188 find LaTeX fragments. Valid members of this list are:
3189 \"begin\" find environments
3190 \"$\" find math expressions surrounded by $...$
3191 \"$$\" find math expressions surrounded by $$....$$
3192 \"\\(\" find math expressions surrounded by \\(...\\)
3193 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3194 :group 'org-latex
3195 :type 'plist)
3197 (defcustom org-format-latex-header "\\documentclass{article}
3198 \\usepackage{fullpage} % do not remove
3199 \\usepackage{amssymb}
3200 \\usepackage[usenames]{color}
3201 \\usepackage{amsmath}
3202 \\usepackage{latexsym}
3203 \\usepackage[mathscr]{eucal}
3204 \\pagestyle{empty} % do not remove"
3205 "The document header used for processing LaTeX fragments."
3206 :group 'org-latex
3207 :type 'string)
3209 (defgroup org-export nil
3210 "Options for exporting org-listings."
3211 :tag "Org Export"
3212 :group 'org)
3214 (defgroup org-export-general nil
3215 "General options for exporting Org-mode files."
3216 :tag "Org Export General"
3217 :group 'org-export)
3219 ;; FIXME
3220 (defvar org-export-publishing-directory nil)
3222 (defcustom org-export-with-special-strings t
3223 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3224 When this option is turned on, these strings will be exported as:
3226 Org HTML LaTeX
3227 -----+----------+--------
3228 \\- &shy; \\-
3229 -- &ndash; --
3230 --- &mdash; ---
3231 ... &hellip; \ldots
3233 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3234 :group 'org-export-translation
3235 :type 'boolean)
3237 (defcustom org-export-language-setup
3238 '(("en" "Author" "Date" "Table of Contents")
3239 ("cs" "Autor" "Datum" "Obsah")
3240 ("da" "Ophavsmand" "Dato" "Indhold")
3241 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3242 ("es" "Autor" "Fecha" "\xcdndice")
3243 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3244 ("it" "Autore" "Data" "Indice")
3245 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3246 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3247 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3248 "Terms used in export text, translated to different languages.
3249 Use the variable `org-export-default-language' to set the language,
3250 or use the +OPTION lines for a per-file setting."
3251 :group 'org-export-general
3252 :type '(repeat
3253 (list
3254 (string :tag "HTML language tag")
3255 (string :tag "Author")
3256 (string :tag "Date")
3257 (string :tag "Table of Contents"))))
3259 (defcustom org-export-default-language "en"
3260 "The default language of HTML export, as a string.
3261 This should have an association in `org-export-language-setup'."
3262 :group 'org-export-general
3263 :type 'string)
3265 (defcustom org-export-skip-text-before-1st-heading t
3266 "Non-nil means, skip all text before the first headline when exporting.
3267 When nil, that text is exported as well."
3268 :group 'org-export-general
3269 :type 'boolean)
3271 (defcustom org-export-headline-levels 3
3272 "The last level which is still exported as a headline.
3273 Inferior levels will produce itemize lists when exported.
3274 Note that a numeric prefix argument to an exporter function overrides
3275 this setting.
3277 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3278 :group 'org-export-general
3279 :type 'number)
3281 (defcustom org-export-with-section-numbers t
3282 "Non-nil means, add section numbers to headlines when exporting.
3284 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3285 :group 'org-export-general
3286 :type 'boolean)
3288 (defcustom org-export-with-toc t
3289 "Non-nil means, create a table of contents in exported files.
3290 The TOC contains headlines with levels up to`org-export-headline-levels'.
3291 When an integer, include levels up to N in the toc, this may then be
3292 different from `org-export-headline-levels', but it will not be allowed
3293 to be larger than the number of headline levels.
3294 When nil, no table of contents is made.
3296 Headlines which contain any TODO items will be marked with \"(*)\" in
3297 ASCII export, and with red color in HTML output, if the option
3298 `org-export-mark-todo-in-toc' is set.
3300 In HTML output, the TOC will be clickable.
3302 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3303 or \"toc:3\"."
3304 :group 'org-export-general
3305 :type '(choice
3306 (const :tag "No Table of Contents" nil)
3307 (const :tag "Full Table of Contents" t)
3308 (integer :tag "TOC to level")))
3310 (defcustom org-export-mark-todo-in-toc nil
3311 "Non-nil means, mark TOC lines that contain any open TODO items."
3312 :group 'org-export-general
3313 :type 'boolean)
3315 (defcustom org-export-preserve-breaks nil
3316 "Non-nil means, preserve all line breaks when exporting.
3317 Normally, in HTML output paragraphs will be reformatted. In ASCII
3318 export, line breaks will always be preserved, regardless of this variable.
3320 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3321 :group 'org-export-general
3322 :type 'boolean)
3324 (defcustom org-export-with-archived-trees 'headline
3325 "Whether subtrees with the ARCHIVE tag should be exported.
3326 This can have three different values
3327 nil Do not export, pretend this tree is not present
3328 t Do export the entire tree
3329 headline Only export the headline, but skip the tree below it."
3330 :group 'org-export-general
3331 :group 'org-archive
3332 :type '(choice
3333 (const :tag "not at all" nil)
3334 (const :tag "headline only" 'headline)
3335 (const :tag "entirely" t)))
3337 (defcustom org-export-author-info t
3338 "Non-nil means, insert author name and email into the exported file.
3340 This option can also be set with the +OPTIONS line,
3341 e.g. \"author-info:nil\"."
3342 :group 'org-export-general
3343 :type 'boolean)
3345 (defcustom org-export-time-stamp-file t
3346 "Non-nil means, insert a time stamp into the exported file.
3347 The time stamp shows when the file was created.
3349 This option can also be set with the +OPTIONS line,
3350 e.g. \"timestamp:nil\"."
3351 :group 'org-export-general
3352 :type 'boolean)
3354 (defcustom org-export-with-timestamps t
3355 "If nil, do not export time stamps and associated keywords."
3356 :group 'org-export-general
3357 :type 'boolean)
3359 (defcustom org-export-remove-timestamps-from-toc t
3360 "If nil, remove timestamps from the table of contents entries."
3361 :group 'org-export-general
3362 :type 'boolean)
3364 (defcustom org-export-with-tags 'not-in-toc
3365 "If nil, do not export tags, just remove them from headlines.
3366 If this is the symbol `not-in-toc', tags will be removed from table of
3367 contents entries, but still be shown in the headlines of the document.
3369 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3370 :group 'org-export-general
3371 :type '(choice
3372 (const :tag "Off" nil)
3373 (const :tag "Not in TOC" not-in-toc)
3374 (const :tag "On" t)))
3376 (defcustom org-export-with-drawers nil
3377 "Non-nil means, export with drawers like the property drawer.
3378 When t, all drawers are exported. This may also be a list of
3379 drawer names to export."
3380 :group 'org-export-general
3381 :type '(choice
3382 (const :tag "All drawers" t)
3383 (const :tag "None" nil)
3384 (repeat :tag "Selected drawers"
3385 (string :tag "Drawer name"))))
3387 (defgroup org-export-translation nil
3388 "Options for translating special ascii sequences for the export backends."
3389 :tag "Org Export Translation"
3390 :group 'org-export)
3392 (defcustom org-export-with-emphasize t
3393 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3394 If the export target supports emphasizing text, the word will be
3395 typeset in bold, italic, or underlined, respectively. Works only for
3396 single words, but you can say: I *really* *mean* *this*.
3397 Not all export backends support this.
3399 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3400 :group 'org-export-translation
3401 :type 'boolean)
3403 (defcustom org-export-with-footnotes t
3404 "If nil, export [1] as a footnote marker.
3405 Lines starting with [1] will be formatted as footnotes.
3407 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3408 :group 'org-export-translation
3409 :type 'boolean)
3411 (defcustom org-export-with-sub-superscripts t
3412 "Non-nil means, interpret \"_\" and \"^\" for export.
3413 When this option is turned on, you can use TeX-like syntax for sub- and
3414 superscripts. Several characters after \"_\" or \"^\" will be
3415 considered as a single item - so grouping with {} is normally not
3416 needed. For example, the following things will be parsed as single
3417 sub- or superscripts.
3419 10^24 or 10^tau several digits will be considered 1 item.
3420 10^-12 or 10^-tau a leading sign with digits or a word
3421 x^2-y^3 will be read as x^2 - y^3, because items are
3422 terminated by almost any nonword/nondigit char.
3423 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3425 Still, ambiguity is possible - so when in doubt use {} to enclose the
3426 sub/superscript. If you set this variable to the symbol `{}',
3427 the braces are *required* in order to trigger interpretations as
3428 sub/superscript. This can be helpful in documents that need \"_\"
3429 frequently in plain text.
3431 Not all export backends support this, but HTML does.
3433 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3434 :group 'org-export-translation
3435 :type '(choice
3436 (const :tag "Always interpret" t)
3437 (const :tag "Only with braces" {})
3438 (const :tag "Never interpret" nil)))
3440 (defcustom org-export-with-special-strings t
3441 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3442 When this option is turned on, these strings will be exported as:
3444 \\- : &shy;
3445 -- : &ndash;
3446 --- : &mdash;
3448 Not all export backends support this, but HTML does.
3450 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3451 :group 'org-export-translation
3452 :type 'boolean)
3454 (defcustom org-export-with-TeX-macros t
3455 "Non-nil means, interpret simple TeX-like macros when exporting.
3456 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3457 No only real TeX macros will work here, but the standard HTML entities
3458 for math can be used as macro names as well. For a list of supported
3459 names in HTML export, see the constant `org-html-entities'.
3460 Not all export backends support this.
3462 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3463 :group 'org-export-translation
3464 :group 'org-export-latex
3465 :type 'boolean)
3467 (defcustom org-export-with-LaTeX-fragments nil
3468 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3469 When set, the exporter will find LaTeX environments if the \\begin line is
3470 the first non-white thing on a line. It will also find the math delimiters
3471 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3472 display math.
3474 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3475 :group 'org-export-translation
3476 :group 'org-export-latex
3477 :type 'boolean)
3479 (defcustom org-export-with-fixed-width t
3480 "Non-nil means, lines starting with \":\" will be in fixed width font.
3481 This can be used to have pre-formatted text, fragments of code etc. For
3482 example:
3483 : ;; Some Lisp examples
3484 : (while (defc cnt)
3485 : (ding))
3486 will be looking just like this in also HTML. See also the QUOTE keyword.
3487 Not all export backends support this.
3489 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3490 :group 'org-export-translation
3491 :type 'boolean)
3493 (defcustom org-match-sexp-depth 3
3494 "Number of stacked braces for sub/superscript matching.
3495 This has to be set before loading org.el to be effective."
3496 :group 'org-export-translation
3497 :type 'integer)
3499 (defgroup org-export-tables nil
3500 "Options for exporting tables in Org-mode."
3501 :tag "Org Export Tables"
3502 :group 'org-export)
3504 (defcustom org-export-with-tables t
3505 "If non-nil, lines starting with \"|\" define a table.
3506 For example:
3508 | Name | Address | Birthday |
3509 |-------------+----------+-----------|
3510 | Arthur Dent | England | 29.2.2100 |
3512 Not all export backends support this.
3514 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3515 :group 'org-export-tables
3516 :type 'boolean)
3518 (defcustom org-export-highlight-first-table-line t
3519 "Non-nil means, highlight the first table line.
3520 In HTML export, this means use <th> instead of <td>.
3521 In tables created with table.el, this applies to the first table line.
3522 In Org-mode tables, all lines before the first horizontal separator
3523 line will be formatted with <th> tags."
3524 :group 'org-export-tables
3525 :type 'boolean)
3527 (defcustom org-export-table-remove-special-lines t
3528 "Remove special lines and marking characters in calculating tables.
3529 This removes the special marking character column from tables that are set
3530 up for spreadsheet calculations. It also removes the entire lines
3531 marked with `!', `_', or `^'. The lines with `$' are kept, because
3532 the values of constants may be useful to have."
3533 :group 'org-export-tables
3534 :type 'boolean)
3536 (defcustom org-export-prefer-native-exporter-for-tables nil
3537 "Non-nil means, always export tables created with table.el natively.
3538 Natively means, use the HTML code generator in table.el.
3539 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3540 the table does not use row- or column-spanning). This has the
3541 advantage, that the automatic HTML conversions for math symbols and
3542 sub/superscripts can be applied. Org-mode's HTML generator is also
3543 much faster."
3544 :group 'org-export-tables
3545 :type 'boolean)
3547 (defgroup org-export-ascii nil
3548 "Options specific for ASCII export of Org-mode files."
3549 :tag "Org Export ASCII"
3550 :group 'org-export)
3552 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3553 "Characters for underlining headings in ASCII export.
3554 In the given sequence, these characters will be used for level 1, 2, ..."
3555 :group 'org-export-ascii
3556 :type '(repeat character))
3558 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3559 "Bullet characters for headlines converted to lists in ASCII export.
3560 The first character is used for the first lest level generated in this
3561 way, and so on. If there are more levels than characters given here,
3562 the list will be repeated.
3563 Note that plain lists will keep the same bullets as the have in the
3564 Org-mode file."
3565 :group 'org-export-ascii
3566 :type '(repeat character))
3568 (defgroup org-export-xml nil
3569 "Options specific for XML export of Org-mode files."
3570 :tag "Org Export XML"
3571 :group 'org-export)
3573 (defgroup org-export-html nil
3574 "Options specific for HTML export of Org-mode files."
3575 :tag "Org Export HTML"
3576 :group 'org-export)
3578 (defcustom org-export-html-coding-system nil
3580 :group 'org-export-html
3581 :type 'coding-system)
3583 (defcustom org-export-html-extension "html"
3584 "The extension for exported HTML files."
3585 :group 'org-export-html
3586 :type 'string)
3588 (defcustom org-export-html-style
3589 "<style type=\"text/css\">
3590 html {
3591 font-family: Times, serif;
3592 font-size: 12pt;
3594 .title { text-align: center; }
3595 .todo { color: red; }
3596 .done { color: green; }
3597 .timestamp { color: grey }
3598 .timestamp-kwd { color: CadetBlue }
3599 .tag { background-color:lightblue; font-weight:normal }
3600 .target { background-color: lavender; }
3601 pre {
3602 border: 1pt solid #AEBDCC;
3603 background-color: #F3F5F7;
3604 padding: 5pt;
3605 font-family: courier, monospace;
3607 table { border-collapse: collapse; }
3608 td, th {
3609 vertical-align: top;
3610 <!--border: 1pt solid #ADB9CC;-->
3612 </style>"
3613 "The default style specification for exported HTML files.
3614 Since there are different ways of setting style information, this variable
3615 needs to contain the full HTML structure to provide a style, including the
3616 surrounding HTML tags. The style specifications should include definitions
3617 for new classes todo, done, title, and deadline. For example, legal values
3618 would be:
3620 <style type=\"text/css\">
3621 p { font-weight: normal; color: gray; }
3622 h1 { color: black; }
3623 .title { text-align: center; }
3624 .todo, .deadline { color: red; }
3625 .done { color: green; }
3626 </style>
3628 or, if you want to keep the style in a file,
3630 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3632 As the value of this option simply gets inserted into the HTML <head> header,
3633 you can \"misuse\" it to add arbitrary text to the header."
3634 :group 'org-export-html
3635 :type 'string)
3638 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3639 "Format for typesetting the document title in HTML export."
3640 :group 'org-export-html
3641 :type 'string)
3643 (defcustom org-export-html-toplevel-hlevel 2
3644 "The <H> level for level 1 headings in HTML export."
3645 :group 'org-export-html
3646 :type 'string)
3648 (defcustom org-export-html-link-org-files-as-html t
3649 "Non-nil means, make file links to `file.org' point to `file.html'.
3650 When org-mode is exporting an org-mode file to HTML, links to
3651 non-html files are directly put into a href tag in HTML.
3652 However, links to other Org-mode files (recognized by the
3653 extension `.org.) should become links to the corresponding html
3654 file, assuming that the linked org-mode file will also be
3655 converted to HTML.
3656 When nil, the links still point to the plain `.org' file."
3657 :group 'org-export-html
3658 :type 'boolean)
3660 (defcustom org-export-html-inline-images 'maybe
3661 "Non-nil means, inline images into exported HTML pages.
3662 This is done using an <img> tag. When nil, an anchor with href is used to
3663 link to the image. If this option is `maybe', then images in links with
3664 an empty description will be inlined, while images with a description will
3665 be linked only."
3666 :group 'org-export-html
3667 :type '(choice (const :tag "Never" nil)
3668 (const :tag "Always" t)
3669 (const :tag "When there is no description" maybe)))
3671 ;; FIXME: rename
3672 (defcustom org-export-html-expand t
3673 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3674 When nil, these tags will be exported as plain text and therefore
3675 not be interpreted by a browser.
3677 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3678 :group 'org-export-html
3679 :type 'boolean)
3681 (defcustom org-export-html-table-tag
3682 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3683 "The HTML tag that is used to start a table.
3684 This must be a <table> tag, but you may change the options like
3685 borders and spacing."
3686 :group 'org-export-html
3687 :type 'string)
3689 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3690 "The opening tag for table header fields.
3691 This is customizable so that alignment options can be specified."
3692 :group 'org-export-tables
3693 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3695 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3696 "The opening tag for table data fields.
3697 This is customizable so that alignment options can be specified."
3698 :group 'org-export-tables
3699 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3701 (defcustom org-export-html-with-timestamp nil
3702 "If non-nil, write `org-export-html-html-helper-timestamp'
3703 into the exported HTML text. Otherwise, the buffer will just be saved
3704 to a file."
3705 :group 'org-export-html
3706 :type 'boolean)
3708 (defcustom org-export-html-html-helper-timestamp
3709 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3710 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3711 :group 'org-export-html
3712 :type 'string)
3714 (defgroup org-export-icalendar nil
3715 "Options specific for iCalendar export of Org-mode files."
3716 :tag "Org Export iCalendar"
3717 :group 'org-export)
3719 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3720 "The file name for the iCalendar file covering all agenda files.
3721 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3722 The file name should be absolute, the file will be overwritten without warning."
3723 :group 'org-export-icalendar
3724 :type 'file)
3726 (defcustom org-icalendar-include-todo nil
3727 "Non-nil means, export to iCalendar files should also cover TODO items."
3728 :group 'org-export-icalendar
3729 :type '(choice
3730 (const :tag "None" nil)
3731 (const :tag "Unfinished" t)
3732 (const :tag "All" all)))
3734 (defcustom org-icalendar-include-sexps t
3735 "Non-nil means, export to iCalendar files should also cover sexp entries.
3736 These are entries like in the diary, but directly in an Org-mode file."
3737 :group 'org-export-icalendar
3738 :type 'boolean)
3740 (defcustom org-icalendar-include-body 100
3741 "Amount of text below headline to be included in iCalendar export.
3742 This is a number of characters that should maximally be included.
3743 Properties, scheduling and clocking lines will always be removed.
3744 The text will be inserted into the DESCRIPTION field."
3745 :group 'org-export-icalendar
3746 :type '(choice
3747 (const :tag "Nothing" nil)
3748 (const :tag "Everything" t)
3749 (integer :tag "Max characters")))
3751 (defcustom org-icalendar-combined-name "OrgMode"
3752 "Calendar name for the combined iCalendar representing all agenda files."
3753 :group 'org-export-icalendar
3754 :type 'string)
3756 (defgroup org-font-lock nil
3757 "Font-lock settings for highlighting in Org-mode."
3758 :tag "Org Font Lock"
3759 :group 'org)
3761 (defcustom org-level-color-stars-only nil
3762 "Non-nil means fontify only the stars in each headline.
3763 When nil, the entire headline is fontified.
3764 Changing it requires restart of `font-lock-mode' to become effective
3765 also in regions already fontified."
3766 :group 'org-font-lock
3767 :type 'boolean)
3769 (defcustom org-hide-leading-stars nil
3770 "Non-nil means, hide the first N-1 stars in a headline.
3771 This works by using the face `org-hide' for these stars. This
3772 face is white for a light background, and black for a dark
3773 background. You may have to customize the face `org-hide' to
3774 make this work.
3775 Changing it requires restart of `font-lock-mode' to become effective
3776 also in regions already fontified.
3777 You may also set this on a per-file basis by adding one of the following
3778 lines to the buffer:
3780 #+STARTUP: hidestars
3781 #+STARTUP: showstars"
3782 :group 'org-font-lock
3783 :type 'boolean)
3785 (defcustom org-fontify-done-headline nil
3786 "Non-nil means, change the face of a headline if it is marked DONE.
3787 Normally, only the TODO/DONE keyword indicates the state of a headline.
3788 When this is non-nil, the headline after the keyword is set to the
3789 `org-headline-done' as an additional indication."
3790 :group 'org-font-lock
3791 :type 'boolean)
3793 (defcustom org-fontify-emphasized-text t
3794 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3795 Changing this variable requires a restart of Emacs to take effect."
3796 :group 'org-font-lock
3797 :type 'boolean)
3799 (defcustom org-highlight-latex-fragments-and-specials nil
3800 "Non-nil means, fontify what is treated specially by the exporters."
3801 :group 'org-font-lock
3802 :type 'boolean)
3804 (defcustom org-hide-emphasis-markers nil
3805 "Non-nil mean font-lock should hide the emphasis marker characters."
3806 :group 'org-font-lock
3807 :type 'boolean)
3809 (defvar org-emph-re nil
3810 "Regular expression for matching emphasis.")
3811 (defvar org-verbatim-re nil
3812 "Regular expression for matching verbatim text.")
3813 (defvar org-emphasis-regexp-components) ; defined just below
3814 (defvar org-emphasis-alist) ; defined just below
3815 (defun org-set-emph-re (var val)
3816 "Set variable and compute the emphasis regular expression."
3817 (set var val)
3818 (when (and (boundp 'org-emphasis-alist)
3819 (boundp 'org-emphasis-regexp-components)
3820 org-emphasis-alist org-emphasis-regexp-components)
3821 (let* ((e org-emphasis-regexp-components)
3822 (pre (car e))
3823 (post (nth 1 e))
3824 (border (nth 2 e))
3825 (body (nth 3 e))
3826 (nl (nth 4 e))
3827 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3828 (body1 (concat body "*?"))
3829 (markers (mapconcat 'car org-emphasis-alist ""))
3830 (vmarkers (mapconcat
3831 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3832 org-emphasis-alist "")))
3833 ;; make sure special characters appear at the right position in the class
3834 (if (string-match "\\^" markers)
3835 (setq markers (concat (replace-match "" t t markers) "^")))
3836 (if (string-match "-" markers)
3837 (setq markers (concat (replace-match "" t t markers) "-")))
3838 (if (string-match "\\^" vmarkers)
3839 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3840 (if (string-match "-" vmarkers)
3841 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3842 (if (> nl 0)
3843 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3844 (int-to-string nl) "\\}")))
3845 ;; Make the regexp
3846 (setq org-emph-re
3847 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3848 "\\("
3849 "\\([" markers "]\\)"
3850 "\\("
3851 "[^" border "]\\|"
3852 "[^" border (if (and nil stacked) markers) "]"
3853 body1
3854 "[^" border (if (and nil stacked) markers) "]"
3855 "\\)"
3856 "\\3\\)"
3857 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3858 (setq org-verbatim-re
3859 (concat "\\([" pre "]\\|^\\)"
3860 "\\("
3861 "\\([" vmarkers "]\\)"
3862 "\\("
3863 "[^" border "]\\|"
3864 "[^" border "]"
3865 body1
3866 "[^" border "]"
3867 "\\)"
3868 "\\3\\)"
3869 "\\([" post "]\\|$\\)")))))
3871 (defcustom org-emphasis-regexp-components
3872 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3873 "Components used to build the regular expression for emphasis.
3874 This is a list with 6 entries. Terminology: In an emphasis string
3875 like \" *strong word* \", we call the initial space PREMATCH, the final
3876 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3877 and \"trong wor\" is the body. The different components in this variable
3878 specify what is allowed/forbidden in each part:
3880 pre Chars allowed as prematch. Beginning of line will be allowed too.
3881 post Chars allowed as postmatch. End of line will be allowed too.
3882 border The chars *forbidden* as border characters.
3883 body-regexp A regexp like \".\" to match a body character. Don't use
3884 non-shy groups here, and don't allow newline here.
3885 newline The maximum number of newlines allowed in an emphasis exp.
3887 Use customize to modify this, or restart Emacs after changing it."
3888 :group 'org-font-lock
3889 :set 'org-set-emph-re
3890 :type '(list
3891 (sexp :tag "Allowed chars in pre ")
3892 (sexp :tag "Allowed chars in post ")
3893 (sexp :tag "Forbidden chars in border ")
3894 (sexp :tag "Regexp for body ")
3895 (integer :tag "number of newlines allowed")
3896 (option (boolean :tag "Stacking (DISABLED) "))))
3898 (defcustom org-emphasis-alist
3899 '(("*" bold "<b>" "</b>")
3900 ("/" italic "<i>" "</i>")
3901 ("_" underline "<u>" "</u>")
3902 ("=" org-code "<code>" "</code>" verbatim)
3903 ("~" org-verbatim "" "" verbatim)
3904 ("+" (:strike-through t) "<del>" "</del>")
3906 "Special syntax for emphasized text.
3907 Text starting and ending with a special character will be emphasized, for
3908 example *bold*, _underlined_ and /italic/. This variable sets the marker
3909 characters, the face to be used by font-lock for highlighting in Org-mode
3910 Emacs buffers, and the HTML tags to be used for this.
3911 Use customize to modify this, or restart Emacs after changing it."
3912 :group 'org-font-lock
3913 :set 'org-set-emph-re
3914 :type '(repeat
3915 (list
3916 (string :tag "Marker character")
3917 (choice
3918 (face :tag "Font-lock-face")
3919 (plist :tag "Face property list"))
3920 (string :tag "HTML start tag")
3921 (string :tag "HTML end tag")
3922 (option (const verbatim)))))
3924 ;;; The faces
3926 (defgroup org-faces nil
3927 "Faces in Org-mode."
3928 :tag "Org Faces"
3929 :group 'org-font-lock)
3931 (defun org-compatible-face (inherits specs)
3932 "Make a compatible face specification.
3933 If INHERITS is an existing face and if the Emacs version supports it,
3934 just inherit the face. If not, use SPECS to define the face.
3935 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3936 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3937 to the top of the list. The `min-colors' attribute will be removed from
3938 any other entries, and any resulting duplicates will be removed entirely."
3939 (cond
3940 ((and inherits (facep inherits)
3941 (not (featurep 'xemacs)) (> emacs-major-version 22))
3942 ;; In Emacs 23, we use inheritance where possible.
3943 ;; We only do this in Emacs 23, because only there the outline
3944 ;; faces have been changed to the original org-mode-level-faces.
3945 (list (list t :inherit inherits)))
3946 ((or (featurep 'xemacs) (< emacs-major-version 22))
3947 ;; These do not understand the `min-colors' attribute.
3948 (let (r e a)
3949 (while (setq e (pop specs))
3950 (cond
3951 ((memq (car e) '(t default)) (push e r))
3952 ((setq a (member '(min-colors 8) (car e)))
3953 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3954 (cdr e)))))
3955 ((setq a (assq 'min-colors (car e)))
3956 (setq e (cons (delq a (car e)) (cdr e)))
3957 (or (assoc (car e) r) (push e r)))
3958 (t (or (assoc (car e) r) (push e r)))))
3959 (nreverse r)))
3960 (t specs)))
3961 (put 'org-compatible-face 'lisp-indent-function 1)
3963 (defface org-hide
3964 '((((background light)) (:foreground "white"))
3965 (((background dark)) (:foreground "black")))
3966 "Face used to hide leading stars in headlines.
3967 The forground color of this face should be equal to the background
3968 color of the frame."
3969 :group 'org-faces)
3971 (defface org-level-1 ;; font-lock-function-name-face
3972 (org-compatible-face 'outline-1
3973 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3974 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3975 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3976 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3977 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3978 (t (:bold t))))
3979 "Face used for level 1 headlines."
3980 :group 'org-faces)
3982 (defface org-level-2 ;; font-lock-variable-name-face
3983 (org-compatible-face 'outline-2
3984 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3985 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3986 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3987 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3988 (t (:bold t))))
3989 "Face used for level 2 headlines."
3990 :group 'org-faces)
3992 (defface org-level-3 ;; font-lock-keyword-face
3993 (org-compatible-face 'outline-3
3994 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3995 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3996 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3997 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3998 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3999 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
4000 (t (:bold t))))
4001 "Face used for level 3 headlines."
4002 :group 'org-faces)
4004 (defface org-level-4 ;; font-lock-comment-face
4005 (org-compatible-face 'outline-4
4006 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4007 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4008 (((class color) (min-colors 16) (background light)) (:foreground "red"))
4009 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
4010 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4011 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4012 (t (:bold t))))
4013 "Face used for level 4 headlines."
4014 :group 'org-faces)
4016 (defface org-level-5 ;; font-lock-type-face
4017 (org-compatible-face 'outline-5
4018 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
4019 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
4020 (((class color) (min-colors 8)) (:foreground "green"))))
4021 "Face used for level 5 headlines."
4022 :group 'org-faces)
4024 (defface org-level-6 ;; font-lock-constant-face
4025 (org-compatible-face 'outline-6
4026 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
4027 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
4028 (((class color) (min-colors 8)) (:foreground "magenta"))))
4029 "Face used for level 6 headlines."
4030 :group 'org-faces)
4032 (defface org-level-7 ;; font-lock-builtin-face
4033 (org-compatible-face 'outline-7
4034 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
4035 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
4036 (((class color) (min-colors 8)) (:foreground "blue"))))
4037 "Face used for level 7 headlines."
4038 :group 'org-faces)
4040 (defface org-level-8 ;; font-lock-string-face
4041 (org-compatible-face 'outline-8
4042 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4043 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4044 (((class color) (min-colors 8)) (:foreground "green"))))
4045 "Face used for level 8 headlines."
4046 :group 'org-faces)
4048 (defface org-special-keyword ;; font-lock-string-face
4049 (org-compatible-face nil
4050 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4051 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4052 (t (:italic t))))
4053 "Face used for special keywords."
4054 :group 'org-faces)
4056 (defface org-drawer ;; font-lock-function-name-face
4057 (org-compatible-face nil
4058 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4059 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4060 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4061 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4062 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4063 (t (:bold t))))
4064 "Face used for drawers."
4065 :group 'org-faces)
4067 (defface org-property-value nil
4068 "Face used for the value of a property."
4069 :group 'org-faces)
4071 (defface org-column
4072 (org-compatible-face nil
4073 '((((class color) (min-colors 16) (background light))
4074 (:background "grey90"))
4075 (((class color) (min-colors 16) (background dark))
4076 (:background "grey30"))
4077 (((class color) (min-colors 8))
4078 (:background "cyan" :foreground "black"))
4079 (t (:inverse-video t))))
4080 "Face for column display of entry properties."
4081 :group 'org-faces)
4083 (when (fboundp 'set-face-attribute)
4084 ;; Make sure that a fixed-width face is used when we have a column table.
4085 (set-face-attribute 'org-column nil
4086 :height (face-attribute 'default :height)
4087 :family (face-attribute 'default :family)))
4089 (defface org-warning
4090 (org-compatible-face 'font-lock-warning-face
4091 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4092 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4093 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4094 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4095 (t (:bold t))))
4096 "Face for deadlines and TODO keywords."
4097 :group 'org-faces)
4099 (defface org-archived ; similar to shadow
4100 (org-compatible-face 'shadow
4101 '((((class color grayscale) (min-colors 88) (background light))
4102 (:foreground "grey50"))
4103 (((class color grayscale) (min-colors 88) (background dark))
4104 (:foreground "grey70"))
4105 (((class color) (min-colors 8) (background light))
4106 (:foreground "green"))
4107 (((class color) (min-colors 8) (background dark))
4108 (:foreground "yellow"))))
4109 "Face for headline with the ARCHIVE tag."
4110 :group 'org-faces)
4112 (defface org-link
4113 '((((class color) (background light)) (:foreground "Purple" :underline t))
4114 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4115 (t (:underline t)))
4116 "Face for links."
4117 :group 'org-faces)
4119 (defface org-ellipsis
4120 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
4121 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
4122 (t (:strike-through t)))
4123 "Face for the ellipsis in folded text."
4124 :group 'org-faces)
4126 (defface org-target
4127 '((((class color) (background light)) (:underline t))
4128 (((class color) (background dark)) (:underline t))
4129 (t (:underline t)))
4130 "Face for links."
4131 :group 'org-faces)
4133 (defface org-date
4134 '((((class color) (background light)) (:foreground "Purple" :underline t))
4135 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4136 (t (:underline t)))
4137 "Face for links."
4138 :group 'org-faces)
4140 (defface org-sexp-date
4141 '((((class color) (background light)) (:foreground "Purple"))
4142 (((class color) (background dark)) (:foreground "Cyan"))
4143 (t (:underline t)))
4144 "Face for links."
4145 :group 'org-faces)
4147 (defface org-tag
4148 '((t (:bold t)))
4149 "Face for tags."
4150 :group 'org-faces)
4152 (defface org-todo ; font-lock-warning-face
4153 (org-compatible-face nil
4154 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4155 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4156 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4157 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4158 (t (:inverse-video t :bold t))))
4159 "Face for TODO keywords."
4160 :group 'org-faces)
4162 (defface org-done ;; font-lock-type-face
4163 (org-compatible-face nil
4164 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
4165 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
4166 (((class color) (min-colors 8)) (:foreground "green"))
4167 (t (:bold t))))
4168 "Face used for todo keywords that indicate DONE items."
4169 :group 'org-faces)
4171 (defface org-headline-done ;; font-lock-string-face
4172 (org-compatible-face nil
4173 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4174 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4175 (((class color) (min-colors 8) (background light)) (:bold nil))))
4176 "Face used to indicate that a headline is DONE.
4177 This face is only used if `org-fontify-done-headline' is set. If applies
4178 to the part of the headline after the DONE keyword."
4179 :group 'org-faces)
4181 (defcustom org-todo-keyword-faces nil
4182 "Faces for specific TODO keywords.
4183 This is a list of cons cells, with TODO keywords in the car
4184 and faces in the cdr. The face can be a symbol, or a property
4185 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
4186 :group 'org-faces
4187 :group 'org-todo
4188 :type '(repeat
4189 (cons
4190 (string :tag "keyword")
4191 (sexp :tag "face"))))
4193 (defface org-table ;; font-lock-function-name-face
4194 (org-compatible-face nil
4195 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4196 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4197 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4198 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4199 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4200 (((class color) (min-colors 8) (background dark)))))
4201 "Face used for tables."
4202 :group 'org-faces)
4204 (defface org-formula
4205 (org-compatible-face nil
4206 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4207 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4208 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4209 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4210 (t (:bold t :italic t))))
4211 "Face for formulas."
4212 :group 'org-faces)
4214 (defface org-code
4215 (org-compatible-face nil
4216 '((((class color grayscale) (min-colors 88) (background light))
4217 (:foreground "grey50"))
4218 (((class color grayscale) (min-colors 88) (background dark))
4219 (:foreground "grey70"))
4220 (((class color) (min-colors 8) (background light))
4221 (:foreground "green"))
4222 (((class color) (min-colors 8) (background dark))
4223 (:foreground "yellow"))))
4224 "Face for fixed-with text like code snippets."
4225 :group 'org-faces
4226 :version "22.1")
4228 (defface org-verbatim
4229 (org-compatible-face nil
4230 '((((class color grayscale) (min-colors 88) (background light))
4231 (:foreground "grey50" :underline t))
4232 (((class color grayscale) (min-colors 88) (background dark))
4233 (:foreground "grey70" :underline t))
4234 (((class color) (min-colors 8) (background light))
4235 (:foreground "green" :underline t))
4236 (((class color) (min-colors 8) (background dark))
4237 (:foreground "yellow" :underline t))))
4238 "Face for fixed-with text like code snippets."
4239 :group 'org-faces
4240 :version "22.1")
4242 (defface org-agenda-structure ;; font-lock-function-name-face
4243 (org-compatible-face nil
4244 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4245 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4246 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4247 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4248 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4249 (t (:bold t))))
4250 "Face used in agenda for captions and dates."
4251 :group 'org-faces)
4253 (defface org-scheduled-today
4254 (org-compatible-face nil
4255 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4256 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4257 (((class color) (min-colors 8)) (:foreground "green"))
4258 (t (:bold t :italic t))))
4259 "Face for items scheduled for a certain day."
4260 :group 'org-faces)
4262 (defface org-scheduled-previously
4263 (org-compatible-face nil
4264 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4265 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4266 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4267 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4268 (t (:bold t))))
4269 "Face for items scheduled previously, and not yet done."
4270 :group 'org-faces)
4272 (defface org-upcoming-deadline
4273 (org-compatible-face nil
4274 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4275 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4276 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4277 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4278 (t (:bold t))))
4279 "Face for items scheduled previously, and not yet done."
4280 :group 'org-faces)
4282 (defcustom org-agenda-deadline-faces
4283 '((1.0 . org-warning)
4284 (0.5 . org-upcoming-deadline)
4285 (0.0 . default))
4286 "Faces for showing deadlines in the agenda.
4287 This is a list of cons cells. The cdr of each cell is a face to be used,
4288 and it can also just be like '(:foreground \"yellow\").
4289 Each car is a fraction of the head-warning time that must have passed for
4290 this the face in the cdr to be used for display. The numbers must be
4291 given in descending order. The head-warning time is normally taken
4292 from `org-deadline-warning-days', but can also be specified in the deadline
4293 timestamp itself, like this:
4295 DEADLINE: <2007-08-13 Mon -8d>
4297 You may use d for days, w for weeks, m for months and y for years. Months
4298 and years will only be treated in an approximate fashion (30.4 days for a
4299 month and 365.24 days for a year)."
4300 :group 'org-faces
4301 :group 'org-agenda-daily/weekly
4302 :type '(repeat
4303 (cons
4304 (number :tag "Fraction of head-warning time passed")
4305 (sexp :tag "Face"))))
4307 ;; FIXME: this is not a good face yet.
4308 (defface org-agenda-restriction-lock
4309 (org-compatible-face nil
4310 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4311 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4312 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4313 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4314 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4315 (t (:inverse-video t))))
4316 "Face for showing the agenda restriction lock."
4317 :group 'org-faces)
4319 (defface org-time-grid ;; font-lock-variable-name-face
4320 (org-compatible-face nil
4321 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4322 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4323 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4324 "Face used for time grids."
4325 :group 'org-faces)
4327 (defconst org-level-faces
4328 '(org-level-1 org-level-2 org-level-3 org-level-4
4329 org-level-5 org-level-6 org-level-7 org-level-8
4332 (defcustom org-n-level-faces (length org-level-faces)
4333 "The number of different faces to be used for headlines.
4334 Org-mode defines 8 different headline faces, so this can be at most 8.
4335 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4336 :type 'number
4337 :group 'org-faces)
4339 ;;; Functions and variables from ther packages
4340 ;; Declared here to avoid compiler warnings
4342 (eval-and-compile
4343 (unless (fboundp 'declare-function)
4344 (defmacro declare-function (fn file &optional arglist fileonly))))
4346 ;; XEmacs only
4347 (defvar outline-mode-menu-heading)
4348 (defvar outline-mode-menu-show)
4349 (defvar outline-mode-menu-hide)
4350 (defvar zmacs-regions) ; XEmacs regions
4352 ;; Emacs only
4353 (defvar mark-active)
4355 ;; Various packages
4356 ;; FIXME: get the argument lists for the UNKNOWN stuff
4357 (declare-function add-to-diary-list "diary-lib"
4358 (date string specifier &optional marker globcolor literal))
4359 (declare-function table--at-cell-p "table" (position &optional object at-column))
4360 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4361 (declare-function bbdb "ext:bbdb-com" (string elidep))
4362 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4363 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4364 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4365 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4366 (declare-function bbdb-record-name "ext:bbdb" (record))
4367 (declare-function bibtex-beginning-of-entry "bibtex" ())
4368 (declare-function bibtex-generate-autokey "bibtex" ())
4369 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4370 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4371 (defvar calc-embedded-close-formula)
4372 (defvar calc-embedded-open-formula)
4373 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4374 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4375 (declare-function calendar-check-holidays "holidays" (date))
4376 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4377 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4378 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4379 (declare-function calendar-forward-day "cal-move" (arg))
4380 (declare-function calendar-french-date-string "cal-french" (&optional date))
4381 (declare-function calendar-goto-date "cal-move" (date))
4382 (declare-function calendar-goto-today "cal-move" ())
4383 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4384 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4385 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4386 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4387 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4388 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4389 (defvar calendar-mode-map)
4390 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4391 (declare-function cdlatex-tab "ext:cdlatex" ())
4392 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4393 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4394 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4395 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4396 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4397 (defvar font-lock-unfontify-region-function)
4398 (declare-function gnus-article-show-summary "gnus-art" ())
4399 (declare-function gnus-summary-last-subject "gnus-sum" ())
4400 (defvar gnus-other-frame-object)
4401 (defvar gnus-group-name)
4402 (defvar gnus-article-current)
4403 (defvar Info-current-file)
4404 (defvar Info-current-node)
4405 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4406 (declare-function mh-find-path "mh-utils" ())
4407 (declare-function mh-get-header-field "mh-utils" (field))
4408 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4409 (declare-function mh-header-display "mh-show" ())
4410 (declare-function mh-index-previous-folder "mh-search" ())
4411 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4412 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4413 (declare-function mh-search-choose "mh-search" (&optional searcher))
4414 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4415 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4416 (declare-function mh-show-header-display "mh-show" t t)
4417 (declare-function mh-show-msg "mh-show" (msg))
4418 (declare-function mh-show-show "mh-show" t t)
4419 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4420 (defvar mh-progs)
4421 (defvar mh-current-folder)
4422 (defvar mh-show-folder-buffer)
4423 (defvar mh-index-folder)
4424 (defvar mh-searcher)
4425 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4426 (declare-function parse-time-string "parse-time" (string))
4427 (declare-function remember "remember" (&optional initial))
4428 (declare-function remember-buffer-desc "remember" ())
4429 (declare-function remember-finalize "remember" ())
4430 (defvar remember-save-after-remembering)
4431 (defvar remember-data-file)
4432 (defvar remember-register)
4433 (defvar remember-buffer)
4434 (defvar remember-handler-functions)
4435 (defvar remember-annotation-functions)
4436 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4437 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4438 (declare-function rmail-what-message "rmail" ())
4439 (defvar rmail-current-message)
4440 (defvar texmathp-why)
4441 (declare-function vm-beginning-of-message "ext:vm-page" ())
4442 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4443 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4444 (declare-function vm-isearch-narrow "ext:vm-search" ())
4445 (declare-function vm-isearch-update "ext:vm-search" ())
4446 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4447 (declare-function vm-su-message-id "ext:vm-summary" (m))
4448 (declare-function vm-su-subject "ext:vm-summary" (m))
4449 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4450 (defvar vm-message-pointer)
4451 (defvar vm-folder-directory)
4452 (defvar w3m-current-url)
4453 (defvar w3m-current-title)
4454 ;; backward compatibility to old version of wl
4455 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4456 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4457 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4458 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4459 (declare-function wl-summary-line-from "ext:wl-summary" ())
4460 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4461 (declare-function wl-summary-message-number "ext:wl-summary" ())
4462 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4463 (defvar wl-summary-buffer-elmo-folder)
4464 (defvar wl-summary-buffer-folder-name)
4465 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4467 (defvar org-latex-regexps)
4468 (defvar constants-unit-system)
4470 ;;; Variables for pre-computed regular expressions, all buffer local
4472 (defvar org-drawer-regexp nil
4473 "Matches first line of a hidden block.")
4474 (make-variable-buffer-local 'org-drawer-regexp)
4475 (defvar org-todo-regexp nil
4476 "Matches any of the TODO state keywords.")
4477 (make-variable-buffer-local 'org-todo-regexp)
4478 (defvar org-not-done-regexp nil
4479 "Matches any of the TODO state keywords except the last one.")
4480 (make-variable-buffer-local 'org-not-done-regexp)
4481 (defvar org-todo-line-regexp nil
4482 "Matches a headline and puts TODO state into group 2 if present.")
4483 (make-variable-buffer-local 'org-todo-line-regexp)
4484 (defvar org-complex-heading-regexp nil
4485 "Matches a headline and puts everything into groups:
4486 group 1: the stars
4487 group 2: The todo keyword, maybe
4488 group 3: Priority cookie
4489 group 4: True headline
4490 group 5: Tags")
4491 (make-variable-buffer-local 'org-complex-heading-regexp)
4492 (defvar org-todo-line-tags-regexp nil
4493 "Matches a headline and puts TODO state into group 2 if present.
4494 Also put tags into group 4 if tags are present.")
4495 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4496 (defvar org-nl-done-regexp nil
4497 "Matches newline followed by a headline with the DONE keyword.")
4498 (make-variable-buffer-local 'org-nl-done-regexp)
4499 (defvar org-looking-at-done-regexp nil
4500 "Matches the DONE keyword a point.")
4501 (make-variable-buffer-local 'org-looking-at-done-regexp)
4502 (defvar org-ds-keyword-length 12
4503 "Maximum length of the Deadline and SCHEDULED keywords.")
4504 (make-variable-buffer-local 'org-ds-keyword-length)
4505 (defvar org-deadline-regexp nil
4506 "Matches the DEADLINE keyword.")
4507 (make-variable-buffer-local 'org-deadline-regexp)
4508 (defvar org-deadline-time-regexp nil
4509 "Matches the DEADLINE keyword together with a time stamp.")
4510 (make-variable-buffer-local 'org-deadline-time-regexp)
4511 (defvar org-deadline-line-regexp nil
4512 "Matches the DEADLINE keyword and the rest of the line.")
4513 (make-variable-buffer-local 'org-deadline-line-regexp)
4514 (defvar org-scheduled-regexp nil
4515 "Matches the SCHEDULED keyword.")
4516 (make-variable-buffer-local 'org-scheduled-regexp)
4517 (defvar org-scheduled-time-regexp nil
4518 "Matches the SCHEDULED keyword together with a time stamp.")
4519 (make-variable-buffer-local 'org-scheduled-time-regexp)
4520 (defvar org-closed-time-regexp nil
4521 "Matches the CLOSED keyword together with a time stamp.")
4522 (make-variable-buffer-local 'org-closed-time-regexp)
4524 (defvar org-keyword-time-regexp nil
4525 "Matches any of the 4 keywords, together with the time stamp.")
4526 (make-variable-buffer-local 'org-keyword-time-regexp)
4527 (defvar org-keyword-time-not-clock-regexp nil
4528 "Matches any of the 3 keywords, together with the time stamp.")
4529 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4530 (defvar org-maybe-keyword-time-regexp nil
4531 "Matches a timestamp, possibly preceeded by a keyword.")
4532 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4533 (defvar org-planning-or-clock-line-re nil
4534 "Matches a line with planning or clock info.")
4535 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4537 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4538 rear-nonsticky t mouse-map t fontified t)
4539 "Properties to remove when a string without properties is wanted.")
4541 (defsubst org-match-string-no-properties (num &optional string)
4542 (if (featurep 'xemacs)
4543 (let ((s (match-string num string)))
4544 (remove-text-properties 0 (length s) org-rm-props s)
4546 (match-string-no-properties num string)))
4548 (defsubst org-no-properties (s)
4549 (if (fboundp 'set-text-properties)
4550 (set-text-properties 0 (length s) nil s)
4551 (remove-text-properties 0 (length s) org-rm-props s))
4554 (defsubst org-get-alist-option (option key)
4555 (cond ((eq key t) t)
4556 ((eq option t) t)
4557 ((assoc key option) (cdr (assoc key option)))
4558 (t (cdr (assq 'default option)))))
4560 (defsubst org-inhibit-invisibility ()
4561 "Modified `buffer-invisibility-spec' for Emacs 21.
4562 Some ops with invisible text do not work correctly on Emacs 21. For these
4563 we turn off invisibility temporarily. Use this in a `let' form."
4564 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4566 (defsubst org-set-local (var value)
4567 "Make VAR local in current buffer and set it to VALUE."
4568 (set (make-variable-buffer-local var) value))
4570 (defsubst org-mode-p ()
4571 "Check if the current buffer is in Org-mode."
4572 (eq major-mode 'org-mode))
4574 (defsubst org-last (list)
4575 "Return the last element of LIST."
4576 (car (last list)))
4578 (defun org-let (list &rest body)
4579 (eval (cons 'let (cons list body))))
4580 (put 'org-let 'lisp-indent-function 1)
4582 (defun org-let2 (list1 list2 &rest body)
4583 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4584 (put 'org-let2 'lisp-indent-function 2)
4585 (defconst org-startup-options
4586 '(("fold" org-startup-folded t)
4587 ("overview" org-startup-folded t)
4588 ("nofold" org-startup-folded nil)
4589 ("showall" org-startup-folded nil)
4590 ("content" org-startup-folded content)
4591 ("hidestars" org-hide-leading-stars t)
4592 ("showstars" org-hide-leading-stars nil)
4593 ("odd" org-odd-levels-only t)
4594 ("oddeven" org-odd-levels-only nil)
4595 ("align" org-startup-align-all-tables t)
4596 ("noalign" org-startup-align-all-tables nil)
4597 ("customtime" org-display-custom-times t)
4598 ("logdone" org-log-done time)
4599 ("lognotedone" org-log-done note)
4600 ("nologdone" org-log-done nil)
4601 ("lognoteclock-out" org-log-note-clock-out t)
4602 ("nolognoteclock-out" org-log-note-clock-out nil)
4603 ("logrepeat" org-log-repeat state)
4604 ("lognoterepeat" org-log-repeat note)
4605 ("nologrepeat" org-log-repeat nil)
4606 ("constcgs" constants-unit-system cgs)
4607 ("constSI" constants-unit-system SI))
4608 "Variable associated with STARTUP options for org-mode.
4609 Each element is a list of three items: The startup options as written
4610 in the #+STARTUP line, the corresponding variable, and the value to
4611 set this variable to if the option is found. An optional forth element PUSH
4612 means to push this value onto the list in the variable.")
4614 (defun org-set-regexps-and-options ()
4615 "Precompute regular expressions for current buffer."
4616 (when (org-mode-p)
4617 (org-set-local 'org-todo-kwd-alist nil)
4618 (org-set-local 'org-todo-key-alist nil)
4619 (org-set-local 'org-todo-key-trigger nil)
4620 (org-set-local 'org-todo-keywords-1 nil)
4621 (org-set-local 'org-done-keywords nil)
4622 (org-set-local 'org-todo-heads nil)
4623 (org-set-local 'org-todo-sets nil)
4624 (org-set-local 'org-todo-log-states nil)
4625 (let ((re (org-make-options-regexp
4626 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4627 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4628 "CONSTANTS" "PROPERTY" "DRAWERS")))
4629 (splitre "[ \t]+")
4630 kwds kws0 kwsa key log value cat arch tags const links hw dws
4631 tail sep kws1 prio props drawers)
4632 (save-excursion
4633 (save-restriction
4634 (widen)
4635 (goto-char (point-min))
4636 (while (re-search-forward re nil t)
4637 (setq key (match-string 1) value (org-match-string-no-properties 2))
4638 (cond
4639 ((equal key "CATEGORY")
4640 (if (string-match "[ \t]+$" value)
4641 (setq value (replace-match "" t t value)))
4642 (setq cat value))
4643 ((member key '("SEQ_TODO" "TODO"))
4644 (push (cons 'sequence (org-split-string value splitre)) kwds))
4645 ((equal key "TYP_TODO")
4646 (push (cons 'type (org-split-string value splitre)) kwds))
4647 ((equal key "TAGS")
4648 (setq tags (append tags (org-split-string value splitre))))
4649 ((equal key "COLUMNS")
4650 (org-set-local 'org-columns-default-format value))
4651 ((equal key "LINK")
4652 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4653 (push (cons (match-string 1 value)
4654 (org-trim (match-string 2 value)))
4655 links)))
4656 ((equal key "PRIORITIES")
4657 (setq prio (org-split-string value " +")))
4658 ((equal key "PROPERTY")
4659 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4660 (push (cons (match-string 1 value) (match-string 2 value))
4661 props)))
4662 ((equal key "DRAWERS")
4663 (setq drawers (org-split-string value splitre)))
4664 ((equal key "CONSTANTS")
4665 (setq const (append const (org-split-string value splitre))))
4666 ((equal key "STARTUP")
4667 (let ((opts (org-split-string value splitre))
4668 l var val)
4669 (while (setq l (pop opts))
4670 (when (setq l (assoc l org-startup-options))
4671 (setq var (nth 1 l) val (nth 2 l))
4672 (if (not (nth 3 l))
4673 (set (make-local-variable var) val)
4674 (if (not (listp (symbol-value var)))
4675 (set (make-local-variable var) nil))
4676 (set (make-local-variable var) (symbol-value var))
4677 (add-to-list var val))))))
4678 ((equal key "ARCHIVE")
4679 (string-match " *$" value)
4680 (setq arch (replace-match "" t t value))
4681 (remove-text-properties 0 (length arch)
4682 '(face t fontified t) arch)))
4684 (when cat
4685 (org-set-local 'org-category (intern cat))
4686 (push (cons "CATEGORY" cat) props))
4687 (when prio
4688 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4689 (setq prio (mapcar 'string-to-char prio))
4690 (org-set-local 'org-highest-priority (nth 0 prio))
4691 (org-set-local 'org-lowest-priority (nth 1 prio))
4692 (org-set-local 'org-default-priority (nth 2 prio)))
4693 (and props (org-set-local 'org-local-properties (nreverse props)))
4694 (and drawers (org-set-local 'org-drawers drawers))
4695 (and arch (org-set-local 'org-archive-location arch))
4696 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4697 ;; Process the TODO keywords
4698 (unless kwds
4699 ;; Use the global values as if they had been given locally.
4700 (setq kwds (default-value 'org-todo-keywords))
4701 (if (stringp (car kwds))
4702 (setq kwds (list (cons org-todo-interpretation
4703 (default-value 'org-todo-keywords)))))
4704 (setq kwds (reverse kwds)))
4705 (setq kwds (nreverse kwds))
4706 (let (inter kws kw)
4707 (while (setq kws (pop kwds))
4708 (setq inter (pop kws) sep (member "|" kws)
4709 kws0 (delete "|" (copy-sequence kws))
4710 kwsa nil
4711 kws1 (mapcar
4712 (lambda (x)
4713 ;; 1 2
4714 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4715 (progn
4716 (setq kw (match-string 1 x)
4717 key (and (match-end 2) (match-string 2 x))
4718 log (org-extract-log-state-settings x))
4719 (push (cons kw (and key (string-to-char key))) kwsa)
4720 (and log (push log org-todo-log-states))
4722 (error "Invalid TODO keyword %s" x)))
4723 kws0)
4724 kwsa (if kwsa (append '((:startgroup))
4725 (nreverse kwsa)
4726 '((:endgroup))))
4727 hw (car kws1)
4728 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4729 tail (list inter hw (car dws) (org-last dws)))
4730 (add-to-list 'org-todo-heads hw 'append)
4731 (push kws1 org-todo-sets)
4732 (setq org-done-keywords (append org-done-keywords dws nil))
4733 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4734 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4735 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4736 (setq org-todo-sets (nreverse org-todo-sets)
4737 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4738 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4739 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4740 ;; Process the constants
4741 (when const
4742 (let (e cst)
4743 (while (setq e (pop const))
4744 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4745 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4746 (setq org-table-formula-constants-local cst)))
4748 ;; Process the tags.
4749 (when tags
4750 (let (e tgs)
4751 (while (setq e (pop tags))
4752 (cond
4753 ((equal e "{") (push '(:startgroup) tgs))
4754 ((equal e "}") (push '(:endgroup) tgs))
4755 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4756 (push (cons (match-string 1 e)
4757 (string-to-char (match-string 2 e)))
4758 tgs))
4759 (t (push (list e) tgs))))
4760 (org-set-local 'org-tag-alist nil)
4761 (while (setq e (pop tgs))
4762 (or (and (stringp (car e))
4763 (assoc (car e) org-tag-alist))
4764 (push e org-tag-alist))))))
4766 ;; Compute the regular expressions and other local variables
4767 (if (not org-done-keywords)
4768 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4769 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4770 (length org-scheduled-string)))
4771 org-drawer-regexp
4772 (concat "^[ \t]*:\\("
4773 (mapconcat 'regexp-quote org-drawers "\\|")
4774 "\\):[ \t]*$")
4775 org-not-done-keywords
4776 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4777 org-todo-regexp
4778 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4779 "\\|") "\\)\\>")
4780 org-not-done-regexp
4781 (concat "\\<\\("
4782 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4783 "\\)\\>")
4784 org-todo-line-regexp
4785 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4786 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4787 "\\)\\>\\)?[ \t]*\\(.*\\)")
4788 org-complex-heading-regexp
4789 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4790 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4791 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4792 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4793 org-nl-done-regexp
4794 (concat "\n\\*+[ \t]+"
4795 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4796 "\\)" "\\>")
4797 org-todo-line-tags-regexp
4798 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4799 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4800 (org-re
4801 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4802 org-looking-at-done-regexp
4803 (concat "^" "\\(?:"
4804 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4805 "\\>")
4806 org-deadline-regexp (concat "\\<" org-deadline-string)
4807 org-deadline-time-regexp
4808 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4809 org-deadline-line-regexp
4810 (concat "\\<\\(" org-deadline-string "\\).*")
4811 org-scheduled-regexp
4812 (concat "\\<" org-scheduled-string)
4813 org-scheduled-time-regexp
4814 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4815 org-closed-time-regexp
4816 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4817 org-keyword-time-regexp
4818 (concat "\\<\\(" org-scheduled-string
4819 "\\|" org-deadline-string
4820 "\\|" org-closed-string
4821 "\\|" org-clock-string "\\)"
4822 " *[[<]\\([^]>]+\\)[]>]")
4823 org-keyword-time-not-clock-regexp
4824 (concat "\\<\\(" org-scheduled-string
4825 "\\|" org-deadline-string
4826 "\\|" org-closed-string
4827 "\\)"
4828 " *[[<]\\([^]>]+\\)[]>]")
4829 org-maybe-keyword-time-regexp
4830 (concat "\\(\\<\\(" org-scheduled-string
4831 "\\|" org-deadline-string
4832 "\\|" org-closed-string
4833 "\\|" org-clock-string "\\)\\)?"
4834 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4835 org-planning-or-clock-line-re
4836 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4837 "\\|" org-deadline-string
4838 "\\|" org-closed-string "\\|" org-clock-string
4839 "\\)\\>\\)")
4841 (org-compute-latex-and-specials-regexp)
4842 (org-set-font-lock-defaults)))
4844 (defun org-extract-log-state-settings (x)
4845 "Extract the log state setting from a TODO keyword string.
4846 This will extract info from a string like \"WAIT(w@/!)\"."
4847 (let (kw key log1 log2)
4848 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4849 (setq kw (match-string 1 x)
4850 key (and (match-end 2) (match-string 2 x))
4851 log1 (and (match-end 3) (match-string 3 x))
4852 log2 (and (match-end 4) (match-string 4 x)))
4853 (and (or log1 log2)
4854 (list kw
4855 (and log1 (if (equal log1 "!") 'time 'note))
4856 (and log2 (if (equal log2 "!") 'time 'note)))))))
4858 (defun org-remove-keyword-keys (list)
4859 "Remove a pair of parenthesis at the end of each string in LIST."
4860 (mapcar (lambda (x)
4861 (if (string-match "(.*)$" x)
4862 (substring x 0 (match-beginning 0))
4864 list))
4866 ;; FIXME: this could be done much better, using second characters etc.
4867 (defun org-assign-fast-keys (alist)
4868 "Assign fast keys to a keyword-key alist.
4869 Respect keys that are already there."
4870 (let (new e k c c1 c2 (char ?a))
4871 (while (setq e (pop alist))
4872 (cond
4873 ((equal e '(:startgroup)) (push e new))
4874 ((equal e '(:endgroup)) (push e new))
4876 (setq k (car e) c2 nil)
4877 (if (cdr e)
4878 (setq c (cdr e))
4879 ;; automatically assign a character.
4880 (setq c1 (string-to-char
4881 (downcase (substring
4882 k (if (= (string-to-char k) ?@) 1 0)))))
4883 (if (or (rassoc c1 new) (rassoc c1 alist))
4884 (while (or (rassoc char new) (rassoc char alist))
4885 (setq char (1+ char)))
4886 (setq c2 c1))
4887 (setq c (or c2 char)))
4888 (push (cons k c) new))))
4889 (nreverse new)))
4891 ;;; Some variables ujsed in various places
4893 (defvar org-window-configuration nil
4894 "Used in various places to store a window configuration.")
4895 (defvar org-finish-function nil
4896 "Function to be called when `C-c C-c' is used.
4897 This is for getting out of special buffers like remember.")
4900 ;; FIXME: Occasionally check by commenting these, to make sure
4901 ;; no other functions uses these, forgetting to let-bind them.
4902 (defvar entry)
4903 (defvar state)
4904 (defvar last-state)
4905 (defvar date)
4906 (defvar description)
4908 ;; Defined somewhere in this file, but used before definition.
4909 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4910 (defvar org-agenda-buffer-name)
4911 (defvar org-agenda-undo-list)
4912 (defvar org-agenda-pending-undo-list)
4913 (defvar org-agenda-overriding-header)
4914 (defvar orgtbl-mode)
4915 (defvar org-html-entities)
4916 (defvar org-struct-menu)
4917 (defvar org-org-menu)
4918 (defvar org-tbl-menu)
4919 (defvar org-agenda-keymap)
4921 ;;;; Emacs/XEmacs compatibility
4923 ;; Overlay compatibility functions
4924 (defun org-make-overlay (beg end &optional buffer)
4925 (if (featurep 'xemacs)
4926 (make-extent beg end buffer)
4927 (make-overlay beg end buffer)))
4928 (defun org-delete-overlay (ovl)
4929 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4930 (defun org-detach-overlay (ovl)
4931 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4932 (defun org-move-overlay (ovl beg end &optional buffer)
4933 (if (featurep 'xemacs)
4934 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4935 (move-overlay ovl beg end buffer)))
4936 (defun org-overlay-put (ovl prop value)
4937 (if (featurep 'xemacs)
4938 (set-extent-property ovl prop value)
4939 (overlay-put ovl prop value)))
4940 (defun org-overlay-display (ovl text &optional face evap)
4941 "Make overlay OVL display TEXT with face FACE."
4942 (if (featurep 'xemacs)
4943 (let ((gl (make-glyph text)))
4944 (and face (set-glyph-face gl face))
4945 (set-extent-property ovl 'invisible t)
4946 (set-extent-property ovl 'end-glyph gl))
4947 (overlay-put ovl 'display text)
4948 (if face (overlay-put ovl 'face face))
4949 (if evap (overlay-put ovl 'evaporate t))))
4950 (defun org-overlay-before-string (ovl text &optional face evap)
4951 "Make overlay OVL display TEXT with face FACE."
4952 (if (featurep 'xemacs)
4953 (let ((gl (make-glyph text)))
4954 (and face (set-glyph-face gl face))
4955 (set-extent-property ovl 'begin-glyph gl))
4956 (if face (org-add-props text nil 'face face))
4957 (overlay-put ovl 'before-string text)
4958 (if evap (overlay-put ovl 'evaporate t))))
4959 (defun org-overlay-get (ovl prop)
4960 (if (featurep 'xemacs)
4961 (extent-property ovl prop)
4962 (overlay-get ovl prop)))
4963 (defun org-overlays-at (pos)
4964 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4965 (defun org-overlays-in (&optional start end)
4966 (if (featurep 'xemacs)
4967 (extent-list nil start end)
4968 (overlays-in start end)))
4969 (defun org-overlay-start (o)
4970 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4971 (defun org-overlay-end (o)
4972 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4973 (defun org-find-overlays (prop &optional pos delete)
4974 "Find all overlays specifying PROP at POS or point.
4975 If DELETE is non-nil, delete all those overlays."
4976 (let ((overlays (org-overlays-at (or pos (point))))
4977 ov found)
4978 (while (setq ov (pop overlays))
4979 (if (org-overlay-get ov prop)
4980 (if delete (org-delete-overlay ov) (push ov found))))
4981 found))
4983 ;; Region compatibility
4985 (defun org-add-hook (hook function &optional append local)
4986 "Add-hook, compatible with both Emacsen."
4987 (if (and local (featurep 'xemacs))
4988 (add-local-hook hook function append)
4989 (add-hook hook function append local)))
4991 (defvar org-ignore-region nil
4992 "To temporarily disable the active region.")
4994 (defun org-region-active-p ()
4995 "Is `transient-mark-mode' on and the region active?
4996 Works on both Emacs and XEmacs."
4997 (if org-ignore-region
4999 (if (featurep 'xemacs)
5000 (and zmacs-regions (region-active-p))
5001 (if (fboundp 'use-region-p)
5002 (use-region-p)
5003 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
5005 ;; Invisibility compatibility
5007 (defun org-add-to-invisibility-spec (arg)
5008 "Add elements to `buffer-invisibility-spec'.
5009 See documentation for `buffer-invisibility-spec' for the kind of elements
5010 that can be added."
5011 (cond
5012 ((fboundp 'add-to-invisibility-spec)
5013 (add-to-invisibility-spec arg))
5014 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
5015 (setq buffer-invisibility-spec (list arg)))
5017 (setq buffer-invisibility-spec
5018 (cons arg buffer-invisibility-spec)))))
5020 (defun org-remove-from-invisibility-spec (arg)
5021 "Remove elements from `buffer-invisibility-spec'."
5022 (if (fboundp 'remove-from-invisibility-spec)
5023 (remove-from-invisibility-spec arg)
5024 (if (consp buffer-invisibility-spec)
5025 (setq buffer-invisibility-spec
5026 (delete arg buffer-invisibility-spec)))))
5028 (defun org-in-invisibility-spec-p (arg)
5029 "Is ARG a member of `buffer-invisibility-spec'?"
5030 (if (consp buffer-invisibility-spec)
5031 (member arg buffer-invisibility-spec)
5032 nil))
5034 ;;;; Define the Org-mode
5036 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5037 (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."))
5040 ;; We use a before-change function to check if a table might need
5041 ;; an update.
5042 (defvar org-table-may-need-update t
5043 "Indicates that a table might need an update.
5044 This variable is set by `org-before-change-function'.
5045 `org-table-align' sets it back to nil.")
5046 (defvar org-mode-map)
5047 (defvar org-mode-hook nil)
5048 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5049 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5050 (defvar org-table-buffer-is-an nil)
5051 (defconst org-outline-regexp "\\*+ ")
5053 ;;;###autoload
5054 (define-derived-mode org-mode outline-mode "Org"
5055 "Outline-based notes management and organizer, alias
5056 \"Carsten's outline-mode for keeping track of everything.\"
5058 Org-mode develops organizational tasks around a NOTES file which
5059 contains information about projects as plain text. Org-mode is
5060 implemented on top of outline-mode, which is ideal to keep the content
5061 of large files well structured. It supports ToDo items, deadlines and
5062 time stamps, which magically appear in the diary listing of the Emacs
5063 calendar. Tables are easily created with a built-in table editor.
5064 Plain text URL-like links connect to websites, emails (VM), Usenet
5065 messages (Gnus), BBDB entries, and any files related to the project.
5066 For printing and sharing of notes, an Org-mode file (or a part of it)
5067 can be exported as a structured ASCII or HTML file.
5069 The following commands are available:
5071 \\{org-mode-map}"
5073 ;; Get rid of Outline menus, they are not needed
5074 ;; Need to do this here because define-derived-mode sets up
5075 ;; the keymap so late. Still, it is a waste to call this each time
5076 ;; we switch another buffer into org-mode.
5077 (if (featurep 'xemacs)
5078 (when (boundp 'outline-mode-menu-heading)
5079 ;; Assume this is Greg's port, it used easymenu
5080 (easy-menu-remove outline-mode-menu-heading)
5081 (easy-menu-remove outline-mode-menu-show)
5082 (easy-menu-remove outline-mode-menu-hide))
5083 (define-key org-mode-map [menu-bar headings] 'undefined)
5084 (define-key org-mode-map [menu-bar hide] 'undefined)
5085 (define-key org-mode-map [menu-bar show] 'undefined))
5087 (easy-menu-add org-org-menu)
5088 (easy-menu-add org-tbl-menu)
5089 (org-install-agenda-files-menu)
5090 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
5091 (org-add-to-invisibility-spec '(org-cwidth))
5092 (when (featurep 'xemacs)
5093 (org-set-local 'line-move-ignore-invisible t))
5094 (org-set-local 'outline-regexp org-outline-regexp)
5095 (org-set-local 'outline-level 'org-outline-level)
5096 (when (and org-ellipsis
5097 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5098 (fboundp 'make-glyph-code))
5099 (unless org-display-table
5100 (setq org-display-table (make-display-table)))
5101 (set-display-table-slot
5102 org-display-table 4
5103 (vconcat (mapcar
5104 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5105 org-ellipsis)))
5106 (if (stringp org-ellipsis) org-ellipsis "..."))))
5107 (setq buffer-display-table org-display-table))
5108 (org-set-regexps-and-options)
5109 ;; Calc embedded
5110 (org-set-local 'calc-embedded-open-mode "# ")
5111 (modify-syntax-entry ?# "<")
5112 (modify-syntax-entry ?@ "w")
5113 (if org-startup-truncated (setq truncate-lines t))
5114 (org-set-local 'font-lock-unfontify-region-function
5115 'org-unfontify-region)
5116 ;; Activate before-change-function
5117 (org-set-local 'org-table-may-need-update t)
5118 (org-add-hook 'before-change-functions 'org-before-change-function nil
5119 'local)
5120 ;; Check for running clock before killing a buffer
5121 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5122 ;; Paragraphs and auto-filling
5123 (org-set-autofill-regexps)
5124 (setq indent-line-function 'org-indent-line-function)
5125 (org-update-radio-target-regexp)
5127 ;; Comment characters
5128 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
5129 (org-set-local 'comment-padding " ")
5131 ;; Align options lines
5132 (org-set-local
5133 'align-mode-rules-list
5134 '((org-in-buffer-settings
5135 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5136 (modes . '(org-mode)))))
5138 ;; Imenu
5139 (org-set-local 'imenu-create-index-function
5140 'org-imenu-get-tree)
5142 ;; Make isearch reveal context
5143 (if (or (featurep 'xemacs)
5144 (not (boundp 'outline-isearch-open-invisible-function)))
5145 ;; Emacs 21 and XEmacs make use of the hook
5146 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5147 ;; Emacs 22 deals with this through a special variable
5148 (org-set-local 'outline-isearch-open-invisible-function
5149 (lambda (&rest ignore) (org-show-context 'isearch))))
5151 ;; If empty file that did not turn on org-mode automatically, make it to.
5152 (if (and org-insert-mode-line-in-empty-file
5153 (interactive-p)
5154 (= (point-min) (point-max)))
5155 (insert "# -*- mode: org -*-\n\n"))
5157 (unless org-inhibit-startup
5158 (when org-startup-align-all-tables
5159 (let ((bmp (buffer-modified-p)))
5160 (org-table-map-tables 'org-table-align)
5161 (set-buffer-modified-p bmp)))
5162 (org-cycle-hide-drawers 'all)
5163 (cond
5164 ((eq org-startup-folded t)
5165 (org-cycle '(4)))
5166 ((eq org-startup-folded 'content)
5167 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5168 (org-cycle '(4)) (org-cycle '(4)))))))
5170 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5172 (defsubst org-call-with-arg (command arg)
5173 "Call COMMAND interactively, but pretend prefix are was ARG."
5174 (let ((current-prefix-arg arg)) (call-interactively command)))
5176 (defsubst org-current-line (&optional pos)
5177 (save-excursion
5178 (and pos (goto-char pos))
5179 ;; works also in narrowed buffer, because we start at 1, not point-min
5180 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
5182 (defun org-current-time ()
5183 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5184 (if (> (car org-time-stamp-rounding-minutes) 1)
5185 (let ((r (car org-time-stamp-rounding-minutes))
5186 (time (decode-time)))
5187 (apply 'encode-time
5188 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5189 (nthcdr 2 time))))
5190 (current-time)))
5192 (defun org-add-props (string plist &rest props)
5193 "Add text properties to entire string, from beginning to end.
5194 PLIST may be a list of properties, PROPS are individual properties and values
5195 that will be added to PLIST. Returns the string that was modified."
5196 (add-text-properties
5197 0 (length string) (if props (append plist props) plist) string)
5198 string)
5199 (put 'org-add-props 'lisp-indent-function 2)
5202 ;;;; Font-Lock stuff, including the activators
5204 (defvar org-mouse-map (make-sparse-keymap))
5205 (org-defkey org-mouse-map
5206 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5207 (org-defkey org-mouse-map
5208 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5209 (when org-mouse-1-follows-link
5210 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5211 (when org-tab-follows-link
5212 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5213 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5214 (when org-return-follows-link
5215 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5216 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5218 (require 'font-lock)
5220 (defconst org-non-link-chars "]\t\n\r<>")
5221 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5222 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5223 (defvar org-link-re-with-space nil
5224 "Matches a link with spaces, optional angular brackets around it.")
5225 (defvar org-link-re-with-space2 nil
5226 "Matches a link with spaces, optional angular brackets around it.")
5227 (defvar org-angle-link-re nil
5228 "Matches link with angular brackets, spaces are allowed.")
5229 (defvar org-plain-link-re nil
5230 "Matches plain link, without spaces.")
5231 (defvar org-bracket-link-regexp nil
5232 "Matches a link in double brackets.")
5233 (defvar org-bracket-link-analytic-regexp nil
5234 "Regular expression used to analyze links.
5235 Here is what the match groups contain after a match:
5236 1: http:
5237 2: http
5238 3: path
5239 4: [desc]
5240 5: desc")
5241 (defvar org-any-link-re nil
5242 "Regular expression matching any link.")
5244 (defun org-make-link-regexps ()
5245 "Update the link regular expressions.
5246 This should be called after the variable `org-link-types' has changed."
5247 (setq org-link-re-with-space
5248 (concat
5249 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5250 "\\([^" org-non-link-chars " ]"
5251 "[^" org-non-link-chars "]*"
5252 "[^" org-non-link-chars " ]\\)>?")
5253 org-link-re-with-space2
5254 (concat
5255 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5256 "\\([^" org-non-link-chars " ]"
5257 "[^]\t\n\r]*"
5258 "[^" org-non-link-chars " ]\\)>?")
5259 org-angle-link-re
5260 (concat
5261 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5262 "\\([^" org-non-link-chars " ]"
5263 "[^" org-non-link-chars "]*"
5264 "\\)>")
5265 org-plain-link-re
5266 (concat
5267 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5268 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5269 org-bracket-link-regexp
5270 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5271 org-bracket-link-analytic-regexp
5272 (concat
5273 "\\[\\["
5274 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5275 "\\([^]]+\\)"
5276 "\\]"
5277 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5278 "\\]")
5279 org-any-link-re
5280 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5281 org-angle-link-re "\\)\\|\\("
5282 org-plain-link-re "\\)")))
5284 (org-make-link-regexps)
5286 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5287 "Regular expression for fast time stamp matching.")
5288 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5289 "Regular expression for fast time stamp matching.")
5290 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5291 "Regular expression matching time strings for analysis.
5292 This one does not require the space after the date.")
5293 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5294 "Regular expression matching time strings for analysis.")
5295 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5296 "Regular expression matching time stamps, with groups.")
5297 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5298 "Regular expression matching time stamps (also [..]), with groups.")
5299 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5300 "Regular expression matching a time stamp range.")
5301 (defconst org-tr-regexp-both
5302 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5303 "Regular expression matching a time stamp range.")
5304 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5305 org-ts-regexp "\\)?")
5306 "Regular expression matching a time stamp or time stamp range.")
5307 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5308 org-ts-regexp-both "\\)?")
5309 "Regular expression matching a time stamp or time stamp range.
5310 The time stamps may be either active or inactive.")
5312 (defvar org-emph-face nil)
5314 (defun org-do-emphasis-faces (limit)
5315 "Run through the buffer and add overlays to links."
5316 (let (rtn)
5317 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5318 (if (not (= (char-after (match-beginning 3))
5319 (char-after (match-beginning 4))))
5320 (progn
5321 (setq rtn t)
5322 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5323 'face
5324 (nth 1 (assoc (match-string 3)
5325 org-emphasis-alist)))
5326 (add-text-properties (match-beginning 2) (match-end 2)
5327 '(font-lock-multiline t))
5328 (when org-hide-emphasis-markers
5329 (add-text-properties (match-end 4) (match-beginning 5)
5330 '(invisible org-link))
5331 (add-text-properties (match-beginning 3) (match-end 3)
5332 '(invisible org-link)))))
5333 (backward-char 1))
5334 rtn))
5336 (defun org-emphasize (&optional char)
5337 "Insert or change an emphasis, i.e. a font like bold or italic.
5338 If there is an active region, change that region to a new emphasis.
5339 If there is no region, just insert the marker characters and position
5340 the cursor between them.
5341 CHAR should be either the marker character, or the first character of the
5342 HTML tag associated with that emphasis. If CHAR is a space, the means
5343 to remove the emphasis of the selected region.
5344 If char is not given (for example in an interactive call) it
5345 will be prompted for."
5346 (interactive)
5347 (let ((eal org-emphasis-alist) e det
5348 (erc org-emphasis-regexp-components)
5349 (prompt "")
5350 (string "") beg end move tag c s)
5351 (if (org-region-active-p)
5352 (setq beg (region-beginning) end (region-end)
5353 string (buffer-substring beg end))
5354 (setq move t))
5356 (while (setq e (pop eal))
5357 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5358 c (aref tag 0))
5359 (push (cons c (string-to-char (car e))) det)
5360 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5361 (substring tag 1)))))
5362 (unless char
5363 (message "%s" (concat "Emphasis marker or tag:" prompt))
5364 (setq char (read-char-exclusive)))
5365 (setq char (or (cdr (assoc char det)) char))
5366 (if (equal char ?\ )
5367 (setq s "" move nil)
5368 (unless (assoc (char-to-string char) org-emphasis-alist)
5369 (error "No such emphasis marker: \"%c\"" char))
5370 (setq s (char-to-string char)))
5371 (while (and (> (length string) 1)
5372 (equal (substring string 0 1) (substring string -1))
5373 (assoc (substring string 0 1) org-emphasis-alist))
5374 (setq string (substring string 1 -1)))
5375 (setq string (concat s string s))
5376 (if beg (delete-region beg end))
5377 (unless (or (bolp)
5378 (string-match (concat "[" (nth 0 erc) "\n]")
5379 (char-to-string (char-before (point)))))
5380 (insert " "))
5381 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5382 (char-to-string (char-after (point))))
5383 (insert " ") (backward-char 1))
5384 (insert string)
5385 (and move (backward-char 1))))
5387 (defconst org-nonsticky-props
5388 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5391 (defun org-activate-plain-links (limit)
5392 "Run through the buffer and add overlays to links."
5393 (catch 'exit
5394 (let (f)
5395 (while (re-search-forward org-plain-link-re limit t)
5396 (setq f (get-text-property (match-beginning 0) 'face))
5397 (if (or (eq f 'org-tag)
5398 (and (listp f) (memq 'org-tag f)))
5400 (add-text-properties (match-beginning 0) (match-end 0)
5401 (list 'mouse-face 'highlight
5402 'rear-nonsticky org-nonsticky-props
5403 'keymap org-mouse-map
5405 (throw 'exit t))))))
5407 (defun org-activate-code (limit)
5408 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5409 (unless (get-text-property (match-beginning 1) 'face)
5410 (remove-text-properties (match-beginning 0) (match-end 0)
5411 '(display t invisible t intangible t))
5412 t)))
5414 (defun org-activate-angle-links (limit)
5415 "Run through the buffer and add overlays to links."
5416 (if (re-search-forward org-angle-link-re limit t)
5417 (progn
5418 (add-text-properties (match-beginning 0) (match-end 0)
5419 (list 'mouse-face 'highlight
5420 'rear-nonsticky org-nonsticky-props
5421 'keymap org-mouse-map
5423 t)))
5425 (defmacro org-maybe-intangible (props)
5426 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5427 In emacs 21, invisible text is not avoided by the command loop, so the
5428 intangible property is needed to make sure point skips this text.
5429 In Emacs 22, this is not necessary. The intangible text property has
5430 led to problems with flyspell. These problems are fixed in flyspell.el,
5431 but we still avoid setting the property in Emacs 22 and later.
5432 We use a macro so that the test can happen at compilation time."
5433 (if (< emacs-major-version 22)
5434 `(append '(intangible t) ,props)
5435 props))
5437 (defun org-activate-bracket-links (limit)
5438 "Run through the buffer and add overlays to bracketed links."
5439 (if (re-search-forward org-bracket-link-regexp limit t)
5440 (let* ((help (concat "LINK: "
5441 (org-match-string-no-properties 1)))
5442 ;; FIXME: above we should remove the escapes.
5443 ;; but that requires another match, protecting match data,
5444 ;; a lot of overhead for font-lock.
5445 (ip (org-maybe-intangible
5446 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5447 'keymap org-mouse-map 'mouse-face 'highlight
5448 'font-lock-multiline t 'help-echo help)))
5449 (vp (list 'rear-nonsticky org-nonsticky-props
5450 'keymap org-mouse-map 'mouse-face 'highlight
5451 ' font-lock-multiline t 'help-echo help)))
5452 ;; We need to remove the invisible property here. Table narrowing
5453 ;; may have made some of this invisible.
5454 (remove-text-properties (match-beginning 0) (match-end 0)
5455 '(invisible nil))
5456 (if (match-end 3)
5457 (progn
5458 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5459 (add-text-properties (match-beginning 3) (match-end 3) vp)
5460 (add-text-properties (match-end 3) (match-end 0) ip))
5461 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5462 (add-text-properties (match-beginning 1) (match-end 1) vp)
5463 (add-text-properties (match-end 1) (match-end 0) ip))
5464 t)))
5466 (defun org-activate-dates (limit)
5467 "Run through the buffer and add overlays to dates."
5468 (if (re-search-forward org-tsr-regexp-both limit t)
5469 (progn
5470 (add-text-properties (match-beginning 0) (match-end 0)
5471 (list 'mouse-face 'highlight
5472 'rear-nonsticky org-nonsticky-props
5473 'keymap org-mouse-map))
5474 (when org-display-custom-times
5475 (if (match-end 3)
5476 (org-display-custom-time (match-beginning 3) (match-end 3)))
5477 (org-display-custom-time (match-beginning 1) (match-end 1)))
5478 t)))
5480 (defvar org-target-link-regexp nil
5481 "Regular expression matching radio targets in plain text.")
5482 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5483 "Regular expression matching a link target.")
5484 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5485 "Regular expression matching a radio target.")
5486 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5487 "Regular expression matching any target.")
5489 (defun org-activate-target-links (limit)
5490 "Run through the buffer and add overlays to target matches."
5491 (when org-target-link-regexp
5492 (let ((case-fold-search t))
5493 (if (re-search-forward org-target-link-regexp limit t)
5494 (progn
5495 (add-text-properties (match-beginning 0) (match-end 0)
5496 (list 'mouse-face 'highlight
5497 'rear-nonsticky org-nonsticky-props
5498 'keymap org-mouse-map
5499 'help-echo "Radio target link"
5500 'org-linked-text t))
5501 t)))))
5503 (defun org-update-radio-target-regexp ()
5504 "Find all radio targets in this file and update the regular expression."
5505 (interactive)
5506 (when (memq 'radio org-activate-links)
5507 (setq org-target-link-regexp
5508 (org-make-target-link-regexp (org-all-targets 'radio)))
5509 (org-restart-font-lock)))
5511 (defun org-hide-wide-columns (limit)
5512 (let (s e)
5513 (setq s (text-property-any (point) (or limit (point-max))
5514 'org-cwidth t))
5515 (when s
5516 (setq e (next-single-property-change s 'org-cwidth))
5517 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5518 (goto-char e)
5519 t)))
5521 (defvar org-latex-and-specials-regexp nil
5522 "Regular expression for highlighting export special stuff.")
5523 (defvar org-match-substring-regexp)
5524 (defvar org-match-substring-with-braces-regexp)
5525 (defvar org-export-html-special-string-regexps)
5527 (defun org-compute-latex-and-specials-regexp ()
5528 "Compute regular expression for stuff treated specially by exporters."
5529 (if (not org-highlight-latex-fragments-and-specials)
5530 (org-set-local 'org-latex-and-specials-regexp nil)
5531 (let*
5532 ((matchers (plist-get org-format-latex-options :matchers))
5533 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5534 org-latex-regexps)))
5535 (options (org-combine-plists (org-default-export-plist)
5536 (org-infile-export-plist)))
5537 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5538 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5539 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5540 (org-export-html-expand (plist-get options :expand-quoted-html))
5541 (org-export-with-special-strings (plist-get options :special-strings))
5542 (re-sub
5543 (cond
5544 ((equal org-export-with-sub-superscripts '{})
5545 (list org-match-substring-with-braces-regexp))
5546 (org-export-with-sub-superscripts
5547 (list org-match-substring-regexp))
5548 (t nil)))
5549 (re-latex
5550 (if org-export-with-LaTeX-fragments
5551 (mapcar (lambda (x) (nth 1 x)) latexs)))
5552 (re-macros
5553 (if org-export-with-TeX-macros
5554 (list (concat "\\\\"
5555 (regexp-opt
5556 (append (mapcar 'car org-html-entities)
5557 (if (boundp 'org-latex-entities)
5558 org-latex-entities nil))
5559 'words))) ; FIXME
5561 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5562 (re-special (if org-export-with-special-strings
5563 (mapcar (lambda (x) (car x))
5564 org-export-html-special-string-regexps)))
5565 (re-rest
5566 (delq nil
5567 (list
5568 (if org-export-html-expand "@<[^>\n]+>")
5569 ))))
5570 (org-set-local
5571 'org-latex-and-specials-regexp
5572 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5573 re-rest) "\\|")))))
5575 (defface org-latex-and-export-specials
5576 (let ((font (cond ((assq :inherit custom-face-attributes)
5577 '(:inherit underline))
5578 (t '(:underline t)))))
5579 `((((class grayscale) (background light))
5580 (:foreground "DimGray" ,@font))
5581 (((class grayscale) (background dark))
5582 (:foreground "LightGray" ,@font))
5583 (((class color) (background light))
5584 (:foreground "SaddleBrown"))
5585 (((class color) (background dark))
5586 (:foreground "burlywood"))
5587 (t (,@font))))
5588 "Face used to highlight math latex and other special exporter stuff."
5589 :group 'org-faces)
5591 (defun org-do-latex-and-special-faces (limit)
5592 "Run through the buffer and add overlays to links."
5593 (when org-latex-and-specials-regexp
5594 (let (rtn d)
5595 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5596 limit t))
5597 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5598 'face))
5599 '(org-code org-verbatim underline)))
5600 (progn
5601 (setq rtn t
5602 d (cond ((member (char-after (1+ (match-beginning 0)))
5603 '(?_ ?^)) 1)
5604 (t 0)))
5605 (font-lock-prepend-text-property
5606 (+ d (match-beginning 0)) (match-end 0)
5607 'face 'org-latex-and-export-specials)
5608 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5609 '(font-lock-multiline t)))))
5610 rtn)))
5612 (defun org-restart-font-lock ()
5613 "Restart font-lock-mode, to force refontification."
5614 (when (and (boundp 'font-lock-mode) font-lock-mode)
5615 (font-lock-mode -1)
5616 (font-lock-mode 1)))
5618 (defun org-all-targets (&optional radio)
5619 "Return a list of all targets in this file.
5620 With optional argument RADIO, only find radio targets."
5621 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5622 rtn)
5623 (save-excursion
5624 (goto-char (point-min))
5625 (while (re-search-forward re nil t)
5626 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5627 rtn)))
5629 (defun org-make-target-link-regexp (targets)
5630 "Make regular expression matching all strings in TARGETS.
5631 The regular expression finds the targets also if there is a line break
5632 between words."
5633 (and targets
5634 (concat
5635 "\\<\\("
5636 (mapconcat
5637 (lambda (x)
5638 (while (string-match " +" x)
5639 (setq x (replace-match "\\s-+" t t x)))
5641 targets
5642 "\\|")
5643 "\\)\\>")))
5645 (defun org-activate-tags (limit)
5646 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5647 (progn
5648 (add-text-properties (match-beginning 1) (match-end 1)
5649 (list 'mouse-face 'highlight
5650 'rear-nonsticky org-nonsticky-props
5651 'keymap org-mouse-map))
5652 t)))
5654 (defun org-outline-level ()
5655 (save-excursion
5656 (looking-at outline-regexp)
5657 (if (match-beginning 1)
5658 (+ (org-get-string-indentation (match-string 1)) 1000)
5659 (1- (- (match-end 0) (match-beginning 0))))))
5661 (defvar org-font-lock-keywords nil)
5663 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5664 "Regular expression matching a property line.")
5666 (defun org-set-font-lock-defaults ()
5667 (let* ((em org-fontify-emphasized-text)
5668 (lk org-activate-links)
5669 (org-font-lock-extra-keywords
5670 (list
5671 ;; Headlines
5672 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5673 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5674 ;; Table lines
5675 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5676 (1 'org-table t))
5677 ;; Table internals
5678 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5679 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5680 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5681 ;; Drawers
5682 (list org-drawer-regexp '(0 'org-special-keyword t))
5683 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5684 ;; Properties
5685 (list org-property-re
5686 '(1 'org-special-keyword t)
5687 '(3 'org-property-value t))
5688 (if org-format-transports-properties-p
5689 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5690 ;; Links
5691 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5692 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5693 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5694 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5695 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5696 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5697 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5698 '(org-hide-wide-columns (0 nil append))
5699 ;; TODO lines
5700 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5701 '(1 (org-get-todo-face 1) t))
5702 ;; DONE
5703 (if org-fontify-done-headline
5704 (list (concat "^[*]+ +\\<\\("
5705 (mapconcat 'regexp-quote org-done-keywords "\\|")
5706 "\\)\\(.*\\)")
5707 '(2 'org-headline-done t))
5708 nil)
5709 ;; Priorities
5710 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5711 ;; Special keywords
5712 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5713 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5714 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5715 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5716 ;; Emphasis
5717 (if em
5718 (if (featurep 'xemacs)
5719 '(org-do-emphasis-faces (0 nil append))
5720 '(org-do-emphasis-faces)))
5721 ;; Checkboxes
5722 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5723 2 'bold prepend)
5724 (if org-provide-checkbox-statistics
5725 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5726 (0 (org-get-checkbox-statistics-face) t)))
5727 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5728 '(1 'org-archived prepend))
5729 ;; Specials
5730 '(org-do-latex-and-special-faces)
5731 ;; Code
5732 '(org-activate-code (1 'org-code t))
5733 ;; COMMENT
5734 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5735 "\\|" org-quote-string "\\)\\>")
5736 '(1 'org-special-keyword t))
5737 '("^#.*" (0 'font-lock-comment-face t))
5739 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5740 ;; Now set the full font-lock-keywords
5741 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5742 (org-set-local 'font-lock-defaults
5743 '(org-font-lock-keywords t nil nil backward-paragraph))
5744 (kill-local-variable 'font-lock-keywords) nil))
5746 (defvar org-m nil)
5747 (defvar org-l nil)
5748 (defvar org-f nil)
5749 (defun org-get-level-face (n)
5750 "Get the right face for match N in font-lock matching of healdines."
5751 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5752 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5753 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5754 (cond
5755 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5756 ((eq n 2) org-f)
5757 (t (if org-level-color-stars-only nil org-f))))
5759 (defun org-get-todo-face (kwd)
5760 "Get the right face for a TODO keyword KWD.
5761 If KWD is a number, get the corresponding match group."
5762 (if (numberp kwd) (setq kwd (match-string kwd)))
5763 (or (cdr (assoc kwd org-todo-keyword-faces))
5764 (and (member kwd org-done-keywords) 'org-done)
5765 'org-todo))
5767 (defun org-unfontify-region (beg end &optional maybe_loudly)
5768 "Remove fontification and activation overlays from links."
5769 (font-lock-default-unfontify-region beg end)
5770 (let* ((buffer-undo-list t)
5771 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5772 (inhibit-modification-hooks t)
5773 deactivate-mark buffer-file-name buffer-file-truename)
5774 (remove-text-properties beg end
5775 '(mouse-face t keymap t org-linked-text t
5776 invisible t intangible t))))
5778 ;;;; Visibility cycling, including org-goto and indirect buffer
5780 ;;; Cycling
5782 (defvar org-cycle-global-status nil)
5783 (make-variable-buffer-local 'org-cycle-global-status)
5784 (defvar org-cycle-subtree-status nil)
5785 (make-variable-buffer-local 'org-cycle-subtree-status)
5787 ;;;###autoload
5788 (defun org-cycle (&optional arg)
5789 "Visibility cycling for Org-mode.
5791 - When this function is called with a prefix argument, rotate the entire
5792 buffer through 3 states (global cycling)
5793 1. OVERVIEW: Show only top-level headlines.
5794 2. CONTENTS: Show all headlines of all levels, but no body text.
5795 3. SHOW ALL: Show everything.
5797 - When point is at the beginning of a headline, rotate the subtree started
5798 by this line through 3 different states (local cycling)
5799 1. FOLDED: Only the main headline is shown.
5800 2. CHILDREN: The main headline and the direct children are shown.
5801 From this state, you can move to one of the children
5802 and zoom in further.
5803 3. SUBTREE: Show the entire subtree, including body text.
5805 - When there is a numeric prefix, go up to a heading with level ARG, do
5806 a `show-subtree' and return to the previous cursor position. If ARG
5807 is negative, go up that many levels.
5809 - When point is not at the beginning of a headline, execute
5810 `indent-relative', like TAB normally does. See the option
5811 `org-cycle-emulate-tab' for details.
5813 - Special case: if point is at the beginning of the buffer and there is
5814 no headline in line 1, this function will act as if called with prefix arg.
5815 But only if also the variable `org-cycle-global-at-bob' is t."
5816 (interactive "P")
5817 (let* ((outline-regexp
5818 (if (and (org-mode-p) org-cycle-include-plain-lists)
5819 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5820 outline-regexp))
5821 (bob-special (and org-cycle-global-at-bob (bobp)
5822 (not (looking-at outline-regexp))))
5823 (org-cycle-hook
5824 (if bob-special
5825 (delq 'org-optimize-window-after-visibility-change
5826 (copy-sequence org-cycle-hook))
5827 org-cycle-hook))
5828 (pos (point)))
5830 (if (or bob-special (equal arg '(4)))
5831 ;; special case: use global cycling
5832 (setq arg t))
5834 (cond
5836 ((org-at-table-p 'any)
5837 ;; Enter the table or move to the next field in the table
5838 (or (org-table-recognize-table.el)
5839 (progn
5840 (if arg (org-table-edit-field t)
5841 (org-table-justify-field-maybe)
5842 (call-interactively 'org-table-next-field)))))
5844 ((eq arg t) ;; Global cycling
5846 (cond
5847 ((and (eq last-command this-command)
5848 (eq org-cycle-global-status 'overview))
5849 ;; We just created the overview - now do table of contents
5850 ;; This can be slow in very large buffers, so indicate action
5851 (message "CONTENTS...")
5852 (org-content)
5853 (message "CONTENTS...done")
5854 (setq org-cycle-global-status 'contents)
5855 (run-hook-with-args 'org-cycle-hook 'contents))
5857 ((and (eq last-command this-command)
5858 (eq org-cycle-global-status 'contents))
5859 ;; We just showed the table of contents - now show everything
5860 (show-all)
5861 (message "SHOW ALL")
5862 (setq org-cycle-global-status 'all)
5863 (run-hook-with-args 'org-cycle-hook 'all))
5866 ;; Default action: go to overview
5867 (org-overview)
5868 (message "OVERVIEW")
5869 (setq org-cycle-global-status 'overview)
5870 (run-hook-with-args 'org-cycle-hook 'overview))))
5872 ((and org-drawers org-drawer-regexp
5873 (save-excursion
5874 (beginning-of-line 1)
5875 (looking-at org-drawer-regexp)))
5876 ;; Toggle block visibility
5877 (org-flag-drawer
5878 (not (get-char-property (match-end 0) 'invisible))))
5880 ((integerp arg)
5881 ;; Show-subtree, ARG levels up from here.
5882 (save-excursion
5883 (org-back-to-heading)
5884 (outline-up-heading (if (< arg 0) (- arg)
5885 (- (funcall outline-level) arg)))
5886 (org-show-subtree)))
5888 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5889 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5890 ;; At a heading: rotate between three different views
5891 (org-back-to-heading)
5892 (let ((goal-column 0) eoh eol eos)
5893 ;; First, some boundaries
5894 (save-excursion
5895 (org-back-to-heading)
5896 (save-excursion
5897 (beginning-of-line 2)
5898 (while (and (not (eobp)) ;; this is like `next-line'
5899 (get-char-property (1- (point)) 'invisible))
5900 (beginning-of-line 2)) (setq eol (point)))
5901 (outline-end-of-heading) (setq eoh (point))
5902 (org-end-of-subtree t)
5903 (unless (eobp)
5904 (skip-chars-forward " \t\n")
5905 (beginning-of-line 1) ; in case this is an item
5907 (setq eos (1- (point))))
5908 ;; Find out what to do next and set `this-command'
5909 (cond
5910 ((= eos eoh)
5911 ;; Nothing is hidden behind this heading
5912 (message "EMPTY ENTRY")
5913 (setq org-cycle-subtree-status nil)
5914 (save-excursion
5915 (goto-char eos)
5916 (outline-next-heading)
5917 (if (org-invisible-p) (org-flag-heading nil))))
5918 ((or (>= eol eos)
5919 (not (string-match "\\S-" (buffer-substring eol eos))))
5920 ;; Entire subtree is hidden in one line: open it
5921 (org-show-entry)
5922 (show-children)
5923 (message "CHILDREN")
5924 (save-excursion
5925 (goto-char eos)
5926 (outline-next-heading)
5927 (if (org-invisible-p) (org-flag-heading nil)))
5928 (setq org-cycle-subtree-status 'children)
5929 (run-hook-with-args 'org-cycle-hook 'children))
5930 ((and (eq last-command this-command)
5931 (eq org-cycle-subtree-status 'children))
5932 ;; We just showed the children, now show everything.
5933 (org-show-subtree)
5934 (message "SUBTREE")
5935 (setq org-cycle-subtree-status 'subtree)
5936 (run-hook-with-args 'org-cycle-hook 'subtree))
5938 ;; Default action: hide the subtree.
5939 (hide-subtree)
5940 (message "FOLDED")
5941 (setq org-cycle-subtree-status 'folded)
5942 (run-hook-with-args 'org-cycle-hook 'folded)))))
5944 ;; TAB emulation
5945 (buffer-read-only (org-back-to-heading))
5947 ((org-try-cdlatex-tab))
5949 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5950 (or (not (bolp))
5951 (not (looking-at outline-regexp))))
5952 (call-interactively (global-key-binding "\t")))
5954 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5955 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5956 (or (and (eq org-cycle-emulate-tab 'white)
5957 (= (match-end 0) (point-at-eol)))
5958 (and (eq org-cycle-emulate-tab 'whitestart)
5959 (>= (match-end 0) pos))))
5961 (eq org-cycle-emulate-tab t))
5962 ; (if (and (looking-at "[ \n\r\t]")
5963 ; (string-match "^[ \t]*$" (buffer-substring
5964 ; (point-at-bol) (point))))
5965 ; (progn
5966 ; (beginning-of-line 1)
5967 ; (and (looking-at "[ \t]+") (replace-match ""))))
5968 (call-interactively (global-key-binding "\t")))
5970 (t (save-excursion
5971 (org-back-to-heading)
5972 (org-cycle))))))
5974 ;;;###autoload
5975 (defun org-global-cycle (&optional arg)
5976 "Cycle the global visibility. For details see `org-cycle'."
5977 (interactive "P")
5978 (let ((org-cycle-include-plain-lists
5979 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5980 (if (integerp arg)
5981 (progn
5982 (show-all)
5983 (hide-sublevels arg)
5984 (setq org-cycle-global-status 'contents))
5985 (org-cycle '(4)))))
5987 (defun org-overview ()
5988 "Switch to overview mode, shoing only top-level headlines.
5989 Really, this shows all headlines with level equal or greater than the level
5990 of the first headline in the buffer. This is important, because if the
5991 first headline is not level one, then (hide-sublevels 1) gives confusing
5992 results."
5993 (interactive)
5994 (let ((level (save-excursion
5995 (goto-char (point-min))
5996 (if (re-search-forward (concat "^" outline-regexp) nil t)
5997 (progn
5998 (goto-char (match-beginning 0))
5999 (funcall outline-level))))))
6000 (and level (hide-sublevels level))))
6002 (defun org-content (&optional arg)
6003 "Show all headlines in the buffer, like a table of contents.
6004 With numerical argument N, show content up to level N."
6005 (interactive "P")
6006 (save-excursion
6007 ;; Visit all headings and show their offspring
6008 (and (integerp arg) (org-overview))
6009 (goto-char (point-max))
6010 (catch 'exit
6011 (while (and (progn (condition-case nil
6012 (outline-previous-visible-heading 1)
6013 (error (goto-char (point-min))))
6015 (looking-at outline-regexp))
6016 (if (integerp arg)
6017 (show-children (1- arg))
6018 (show-branches))
6019 (if (bobp) (throw 'exit nil))))))
6022 (defun org-optimize-window-after-visibility-change (state)
6023 "Adjust the window after a change in outline visibility.
6024 This function is the default value of the hook `org-cycle-hook'."
6025 (when (get-buffer-window (current-buffer))
6026 (cond
6027 ; ((eq state 'overview) (org-first-headline-recenter 1))
6028 ; ((eq state 'overview) (org-beginning-of-line))
6029 ((eq state 'content) nil)
6030 ((eq state 'all) nil)
6031 ((eq state 'folded) nil)
6032 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6033 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6035 (defun org-compact-display-after-subtree-move ()
6036 (let (beg end)
6037 (save-excursion
6038 (if (org-up-heading-safe)
6039 (progn
6040 (hide-subtree)
6041 (show-entry)
6042 (show-children)
6043 (org-cycle-show-empty-lines 'children)
6044 (org-cycle-hide-drawers 'children))
6045 (org-overview)))))
6047 (defun org-cycle-show-empty-lines (state)
6048 "Show empty lines above all visible headlines.
6049 The region to be covered depends on STATE when called through
6050 `org-cycle-hook'. Lisp program can use t for STATE to get the
6051 entire buffer covered. Note that an empty line is only shown if there
6052 are at least `org-cycle-separator-lines' empty lines before the headeline."
6053 (when (> org-cycle-separator-lines 0)
6054 (save-excursion
6055 (let* ((n org-cycle-separator-lines)
6056 (re (cond
6057 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6058 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6059 (t (let ((ns (number-to-string (- n 2))))
6060 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6061 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6062 beg end)
6063 (cond
6064 ((memq state '(overview contents t))
6065 (setq beg (point-min) end (point-max)))
6066 ((memq state '(children folded))
6067 (setq beg (point) end (progn (org-end-of-subtree t t)
6068 (beginning-of-line 2)
6069 (point)))))
6070 (when beg
6071 (goto-char beg)
6072 (while (re-search-forward re end t)
6073 (if (not (get-char-property (match-end 1) 'invisible))
6074 (outline-flag-region
6075 (match-beginning 1) (match-end 1) nil)))))))
6076 ;; Never hide empty lines at the end of the file.
6077 (save-excursion
6078 (goto-char (point-max))
6079 (outline-previous-heading)
6080 (outline-end-of-heading)
6081 (if (and (looking-at "[ \t\n]+")
6082 (= (match-end 0) (point-max)))
6083 (outline-flag-region (point) (match-end 0) nil))))
6085 (defun org-subtree-end-visible-p ()
6086 "Is the end of the current subtree visible?"
6087 (pos-visible-in-window-p
6088 (save-excursion (org-end-of-subtree t) (point))))
6090 (defun org-first-headline-recenter (&optional N)
6091 "Move cursor to the first headline and recenter the headline.
6092 Optional argument N means, put the headline into the Nth line of the window."
6093 (goto-char (point-min))
6094 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6095 (beginning-of-line)
6096 (recenter (prefix-numeric-value N))))
6098 ;;; Org-goto
6100 (defvar org-goto-window-configuration nil)
6101 (defvar org-goto-marker nil)
6102 (defvar org-goto-map
6103 (let ((map (make-sparse-keymap)))
6104 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6105 (while (setq cmd (pop cmds))
6106 (substitute-key-definition cmd cmd map global-map)))
6107 (suppress-keymap map)
6108 (org-defkey map "\C-m" 'org-goto-ret)
6109 (org-defkey map [(return)] 'org-goto-ret)
6110 (org-defkey map [(left)] 'org-goto-left)
6111 (org-defkey map [(right)] 'org-goto-right)
6112 (org-defkey map [(control ?g)] 'org-goto-quit)
6113 (org-defkey map "\C-i" 'org-cycle)
6114 (org-defkey map [(tab)] 'org-cycle)
6115 (org-defkey map [(down)] 'outline-next-visible-heading)
6116 (org-defkey map [(up)] 'outline-previous-visible-heading)
6117 (if org-goto-auto-isearch
6118 (if (fboundp 'define-key-after)
6119 (define-key-after map [t] 'org-goto-local-auto-isearch)
6120 nil)
6121 (org-defkey map "q" 'org-goto-quit)
6122 (org-defkey map "n" 'outline-next-visible-heading)
6123 (org-defkey map "p" 'outline-previous-visible-heading)
6124 (org-defkey map "f" 'outline-forward-same-level)
6125 (org-defkey map "b" 'outline-backward-same-level)
6126 (org-defkey map "u" 'outline-up-heading))
6127 (org-defkey map "/" 'org-occur)
6128 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6129 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6130 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6131 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6132 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6133 map))
6135 (defconst org-goto-help
6136 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6137 RET=jump to location [Q]uit and return to previous location
6138 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6140 (defvar org-goto-start-pos) ; dynamically scoped parameter
6142 (defun org-goto (&optional alternative-interface)
6143 "Look up a different location in the current file, keeping current visibility.
6145 When you want look-up or go to a different location in a document, the
6146 fastest way is often to fold the entire buffer and then dive into the tree.
6147 This method has the disadvantage, that the previous location will be folded,
6148 which may not be what you want.
6150 This command works around this by showing a copy of the current buffer
6151 in an indirect buffer, in overview mode. You can dive into the tree in
6152 that copy, use org-occur and incremental search to find a location.
6153 When pressing RET or `Q', the command returns to the original buffer in
6154 which the visibility is still unchanged. After RET is will also jump to
6155 the location selected in the indirect buffer and expose the
6156 the headline hierarchy above."
6157 (interactive "P")
6158 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
6159 (org-refile-use-outline-path t)
6160 (interface
6161 (if (not alternative-interface)
6162 org-goto-interface
6163 (if (eq org-goto-interface 'outline)
6164 'outline-path-completion
6165 'outline)))
6166 (org-goto-start-pos (point))
6167 (selected-point
6168 (if (eq interface 'outline)
6169 (car (org-get-location (current-buffer) org-goto-help))
6170 (nth 3 (org-refile-get-location "Goto: ")))))
6171 (if selected-point
6172 (progn
6173 (org-mark-ring-push org-goto-start-pos)
6174 (goto-char selected-point)
6175 (if (or (org-invisible-p) (org-invisible-p2))
6176 (org-show-context 'org-goto)))
6177 (message "Quit"))))
6179 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6180 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6181 (defvar org-goto-local-auto-isearch-map) ; defined below
6183 (defun org-get-location (buf help)
6184 "Let the user select a location in the Org-mode buffer BUF.
6185 This function uses a recursive edit. It returns the selected position
6186 or nil."
6187 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6188 (isearch-hide-immediately nil)
6189 (isearch-search-fun-function
6190 (lambda () 'org-goto-local-search-forward-headings))
6191 (org-goto-selected-point org-goto-exit-command))
6192 (save-excursion
6193 (save-window-excursion
6194 (delete-other-windows)
6195 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6196 (switch-to-buffer
6197 (condition-case nil
6198 (make-indirect-buffer (current-buffer) "*org-goto*")
6199 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6200 (with-output-to-temp-buffer "*Help*"
6201 (princ help))
6202 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6203 (setq buffer-read-only nil)
6204 (let ((org-startup-truncated t)
6205 (org-startup-folded nil)
6206 (org-startup-align-all-tables nil))
6207 (org-mode)
6208 (org-overview))
6209 (setq buffer-read-only t)
6210 (if (and (boundp 'org-goto-start-pos)
6211 (integer-or-marker-p org-goto-start-pos))
6212 (let ((org-show-hierarchy-above t)
6213 (org-show-siblings t)
6214 (org-show-following-heading t))
6215 (goto-char org-goto-start-pos)
6216 (and (org-invisible-p) (org-show-context)))
6217 (goto-char (point-min)))
6218 (org-beginning-of-line)
6219 (message "Select location and press RET")
6220 (use-local-map org-goto-map)
6221 (recursive-edit)
6223 (kill-buffer "*org-goto*")
6224 (cons org-goto-selected-point org-goto-exit-command)))
6226 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6227 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6228 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6229 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6231 (defun org-goto-local-search-forward-headings (string bound noerror)
6232 "Search and make sure that anu matches are in headlines."
6233 (catch 'return
6234 (while (search-forward string bound noerror)
6235 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6236 (and (member :headline context)
6237 (not (member :tags context))))
6238 (throw 'return (point))))))
6240 (defun org-goto-local-auto-isearch ()
6241 "Start isearch."
6242 (interactive)
6243 (goto-char (point-min))
6244 (let ((keys (this-command-keys)))
6245 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6246 (isearch-mode t)
6247 (isearch-process-search-char (string-to-char keys)))))
6249 (defun org-goto-ret (&optional arg)
6250 "Finish `org-goto' by going to the new location."
6251 (interactive "P")
6252 (setq org-goto-selected-point (point)
6253 org-goto-exit-command 'return)
6254 (throw 'exit nil))
6256 (defun org-goto-left ()
6257 "Finish `org-goto' by going to the new location."
6258 (interactive)
6259 (if (org-on-heading-p)
6260 (progn
6261 (beginning-of-line 1)
6262 (setq org-goto-selected-point (point)
6263 org-goto-exit-command 'left)
6264 (throw 'exit nil))
6265 (error "Not on a heading")))
6267 (defun org-goto-right ()
6268 "Finish `org-goto' by going to the new location."
6269 (interactive)
6270 (if (org-on-heading-p)
6271 (progn
6272 (setq org-goto-selected-point (point)
6273 org-goto-exit-command 'right)
6274 (throw 'exit nil))
6275 (error "Not on a heading")))
6277 (defun org-goto-quit ()
6278 "Finish `org-goto' without cursor motion."
6279 (interactive)
6280 (setq org-goto-selected-point nil)
6281 (setq org-goto-exit-command 'quit)
6282 (throw 'exit nil))
6284 ;;; Indirect buffer display of subtrees
6286 (defvar org-indirect-dedicated-frame nil
6287 "This is the frame being used for indirect tree display.")
6288 (defvar org-last-indirect-buffer nil)
6290 (defun org-tree-to-indirect-buffer (&optional arg)
6291 "Create indirect buffer and narrow it to current subtree.
6292 With numerical prefix ARG, go up to this level and then take that tree.
6293 If ARG is negative, go up that many levels.
6294 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6295 indirect buffer previously made with this command, to avoid proliferation of
6296 indirect buffers. However, when you call the command with a `C-u' prefix, or
6297 when `org-indirect-buffer-display' is `new-frame', the last buffer
6298 is kept so that you can work with several indirect buffers at the same time.
6299 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6300 requests that a new frame be made for the new buffer, so that the dedicated
6301 frame is not changed."
6302 (interactive "P")
6303 (let ((cbuf (current-buffer))
6304 (cwin (selected-window))
6305 (pos (point))
6306 beg end level heading ibuf)
6307 (save-excursion
6308 (org-back-to-heading t)
6309 (when (numberp arg)
6310 (setq level (org-outline-level))
6311 (if (< arg 0) (setq arg (+ level arg)))
6312 (while (> (setq level (org-outline-level)) arg)
6313 (outline-up-heading 1 t)))
6314 (setq beg (point)
6315 heading (org-get-heading))
6316 (org-end-of-subtree t) (setq end (point)))
6317 (if (and (buffer-live-p org-last-indirect-buffer)
6318 (not (eq org-indirect-buffer-display 'new-frame))
6319 (not arg))
6320 (kill-buffer org-last-indirect-buffer))
6321 (setq ibuf (org-get-indirect-buffer cbuf)
6322 org-last-indirect-buffer ibuf)
6323 (cond
6324 ((or (eq org-indirect-buffer-display 'new-frame)
6325 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6326 (select-frame (make-frame))
6327 (delete-other-windows)
6328 (switch-to-buffer ibuf)
6329 (org-set-frame-title heading))
6330 ((eq org-indirect-buffer-display 'dedicated-frame)
6331 (raise-frame
6332 (select-frame (or (and org-indirect-dedicated-frame
6333 (frame-live-p org-indirect-dedicated-frame)
6334 org-indirect-dedicated-frame)
6335 (setq org-indirect-dedicated-frame (make-frame)))))
6336 (delete-other-windows)
6337 (switch-to-buffer ibuf)
6338 (org-set-frame-title (concat "Indirect: " heading)))
6339 ((eq org-indirect-buffer-display 'current-window)
6340 (switch-to-buffer ibuf))
6341 ((eq org-indirect-buffer-display 'other-window)
6342 (pop-to-buffer ibuf))
6343 (t (error "Invalid value.")))
6344 (if (featurep 'xemacs)
6345 (save-excursion (org-mode) (turn-on-font-lock)))
6346 (narrow-to-region beg end)
6347 (show-all)
6348 (goto-char pos)
6349 (and (window-live-p cwin) (select-window cwin))))
6351 (defun org-get-indirect-buffer (&optional buffer)
6352 (setq buffer (or buffer (current-buffer)))
6353 (let ((n 1) (base (buffer-name buffer)) bname)
6354 (while (buffer-live-p
6355 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6356 (setq n (1+ n)))
6357 (condition-case nil
6358 (make-indirect-buffer buffer bname 'clone)
6359 (error (make-indirect-buffer buffer bname)))))
6361 (defun org-set-frame-title (title)
6362 "Set the title of the current frame to the string TITLE."
6363 ;; FIXME: how to name a single frame in XEmacs???
6364 (unless (featurep 'xemacs)
6365 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6367 ;;;; Structure editing
6369 ;;; Inserting headlines
6371 (defun org-insert-heading (&optional force-heading)
6372 "Insert a new heading or item with same depth at point.
6373 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6374 If point is at the beginning of a headline, insert a sibling before the
6375 current headline. If point is not at the beginning, do not split the line,
6376 but create the new hedline after the current line."
6377 (interactive "P")
6378 (if (= (buffer-size) 0)
6379 (insert "\n* ")
6380 (when (or force-heading (not (org-insert-item)))
6381 (let* ((head (save-excursion
6382 (condition-case nil
6383 (progn
6384 (org-back-to-heading)
6385 (match-string 0))
6386 (error "*"))))
6387 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6388 pos)
6389 (cond
6390 ((and (org-on-heading-p) (bolp)
6391 (or (bobp)
6392 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6393 ;; insert before the current line
6394 (open-line (if blank 2 1)))
6395 ((and (bolp)
6396 (or (bobp)
6397 (save-excursion
6398 (backward-char 1) (not (org-invisible-p)))))
6399 ;; insert right here
6400 nil)
6402 ; ;; in the middle of the line
6403 ; (org-show-entry)
6404 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
6405 ; (if (and
6406 ; (org-on-heading-p)
6407 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6408 ; ;; protect the tags
6409 ;; (let ((tags (match-string 2)) pos)
6410 ; (delete-region (match-beginning 1) (match-end 1))
6411 ; (setq pos (point-at-bol))
6412 ; (newline (if blank 2 1))
6413 ; (save-excursion
6414 ; (goto-char pos)
6415 ; (end-of-line 1)
6416 ; (insert " " tags)
6417 ; (org-set-tags nil 'align)))
6418 ; (newline (if blank 2 1)))
6419 ; (newline (if blank 2 1))))
6422 ;; in the middle of the line
6423 (org-show-entry)
6424 (let ((split
6425 (org-get-alist-option org-M-RET-may-split-line 'headline))
6426 tags pos)
6427 (if (org-on-heading-p)
6428 (progn
6429 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6430 (setq tags (and (match-end 2) (match-string 2)))
6431 (and (match-end 1)
6432 (delete-region (match-beginning 1) (match-end 1)))
6433 (setq pos (point-at-bol))
6434 (or split (end-of-line 1))
6435 (delete-horizontal-space)
6436 (newline (if blank 2 1))
6437 (when tags
6438 (save-excursion
6439 (goto-char pos)
6440 (end-of-line 1)
6441 (insert " " tags)
6442 (org-set-tags nil 'align))))
6443 (or split (end-of-line 1))
6444 (newline (if blank 2 1))))))
6445 (insert head) (just-one-space)
6446 (setq pos (point))
6447 (end-of-line 1)
6448 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6449 (run-hooks 'org-insert-heading-hook)))))
6451 (defun org-insert-heading-after-current ()
6452 "Insert a new heading with same level as current, after current subtree."
6453 (interactive)
6454 (org-back-to-heading)
6455 (org-insert-heading)
6456 (org-move-subtree-down)
6457 (end-of-line 1))
6459 (defun org-insert-todo-heading (arg)
6460 "Insert a new heading with the same level and TODO state as current heading.
6461 If the heading has no TODO state, or if the state is DONE, use the first
6462 state (TODO by default). Also with prefix arg, force first state."
6463 (interactive "P")
6464 (when (not (org-insert-item 'checkbox))
6465 (org-insert-heading)
6466 (save-excursion
6467 (org-back-to-heading)
6468 (outline-previous-heading)
6469 (looking-at org-todo-line-regexp))
6470 (if (or arg
6471 (not (match-beginning 2))
6472 (member (match-string 2) org-done-keywords))
6473 (insert (car org-todo-keywords-1) " ")
6474 (insert (match-string 2) " "))))
6476 (defun org-insert-subheading (arg)
6477 "Insert a new subheading and demote it.
6478 Works for outline headings and for plain lists alike."
6479 (interactive "P")
6480 (org-insert-heading arg)
6481 (cond
6482 ((org-on-heading-p) (org-do-demote))
6483 ((org-at-item-p) (org-indent-item 1))))
6485 (defun org-insert-todo-subheading (arg)
6486 "Insert a new subheading with TODO keyword or checkbox and demote it.
6487 Works for outline headings and for plain lists alike."
6488 (interactive "P")
6489 (org-insert-todo-heading arg)
6490 (cond
6491 ((org-on-heading-p) (org-do-demote))
6492 ((org-at-item-p) (org-indent-item 1))))
6494 ;;; Promotion and Demotion
6496 (defun org-promote-subtree ()
6497 "Promote the entire subtree.
6498 See also `org-promote'."
6499 (interactive)
6500 (save-excursion
6501 (org-map-tree 'org-promote))
6502 (org-fix-position-after-promote))
6504 (defun org-demote-subtree ()
6505 "Demote the entire subtree. See `org-demote'.
6506 See also `org-promote'."
6507 (interactive)
6508 (save-excursion
6509 (org-map-tree 'org-demote))
6510 (org-fix-position-after-promote))
6513 (defun org-do-promote ()
6514 "Promote the current heading higher up the tree.
6515 If the region is active in `transient-mark-mode', promote all headings
6516 in the region."
6517 (interactive)
6518 (save-excursion
6519 (if (org-region-active-p)
6520 (org-map-region 'org-promote (region-beginning) (region-end))
6521 (org-promote)))
6522 (org-fix-position-after-promote))
6524 (defun org-do-demote ()
6525 "Demote the current heading lower down the tree.
6526 If the region is active in `transient-mark-mode', demote all headings
6527 in the region."
6528 (interactive)
6529 (save-excursion
6530 (if (org-region-active-p)
6531 (org-map-region 'org-demote (region-beginning) (region-end))
6532 (org-demote)))
6533 (org-fix-position-after-promote))
6535 (defun org-fix-position-after-promote ()
6536 "Make sure that after pro/demotion cursor position is right."
6537 (let ((pos (point)))
6538 (when (save-excursion
6539 (beginning-of-line 1)
6540 (looking-at org-todo-line-regexp)
6541 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6542 (cond ((eobp) (insert " "))
6543 ((eolp) (insert " "))
6544 ((equal (char-after) ?\ ) (forward-char 1))))))
6546 (defun org-reduced-level (l)
6547 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6549 (defun org-get-legal-level (level &optional change)
6550 "Rectify a level change under the influence of `org-odd-levels-only'
6551 LEVEL is a current level, CHANGE is by how much the level should be
6552 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6553 even level numbers will become the next higher odd number."
6554 (if org-odd-levels-only
6555 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6556 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6557 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6558 (max 1 (+ level change))))
6560 (defun org-promote ()
6561 "Promote the current heading higher up the tree.
6562 If the region is active in `transient-mark-mode', promote all headings
6563 in the region."
6564 (org-back-to-heading t)
6565 (let* ((level (save-match-data (funcall outline-level)))
6566 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6567 (diff (abs (- level (length up-head) -1))))
6568 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6569 (replace-match up-head nil t)
6570 ;; Fixup tag positioning
6571 (and org-auto-align-tags (org-set-tags nil t))
6572 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6574 (defun org-demote ()
6575 "Demote the current heading lower down the tree.
6576 If the region is active in `transient-mark-mode', demote all headings
6577 in the region."
6578 (org-back-to-heading t)
6579 (let* ((level (save-match-data (funcall outline-level)))
6580 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6581 (diff (abs (- level (length down-head) -1))))
6582 (replace-match down-head nil t)
6583 ;; Fixup tag positioning
6584 (and org-auto-align-tags (org-set-tags nil t))
6585 (if org-adapt-indentation (org-fixup-indentation diff))))
6587 (defun org-map-tree (fun)
6588 "Call FUN for every heading underneath the current one."
6589 (org-back-to-heading)
6590 (let ((level (funcall outline-level)))
6591 (save-excursion
6592 (funcall fun)
6593 (while (and (progn
6594 (outline-next-heading)
6595 (> (funcall outline-level) level))
6596 (not (eobp)))
6597 (funcall fun)))))
6599 (defun org-map-region (fun beg end)
6600 "Call FUN for every heading between BEG and END."
6601 (let ((org-ignore-region t))
6602 (save-excursion
6603 (setq end (copy-marker end))
6604 (goto-char beg)
6605 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6606 (< (point) end))
6607 (funcall fun))
6608 (while (and (progn
6609 (outline-next-heading)
6610 (< (point) end))
6611 (not (eobp)))
6612 (funcall fun)))))
6614 (defun org-fixup-indentation (diff)
6615 "Change the indentation in the current entry by DIFF
6616 However, if any line in the current entry has no indentation, or if it
6617 would end up with no indentation after the change, nothing at all is done."
6618 (save-excursion
6619 (let ((end (save-excursion (outline-next-heading)
6620 (point-marker)))
6621 (prohibit (if (> diff 0)
6622 "^\\S-"
6623 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6624 col)
6625 (unless (save-excursion (end-of-line 1)
6626 (re-search-forward prohibit end t))
6627 (while (and (< (point) end)
6628 (re-search-forward "^[ \t]+" end t))
6629 (goto-char (match-end 0))
6630 (setq col (current-column))
6631 (if (< diff 0) (replace-match ""))
6632 (indent-to (+ diff col))))
6633 (move-marker end nil))))
6635 (defun org-convert-to-odd-levels ()
6636 "Convert an org-mode file with all levels allowed to one with odd levels.
6637 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6638 level 5 etc."
6639 (interactive)
6640 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6641 (let ((org-odd-levels-only nil) n)
6642 (save-excursion
6643 (goto-char (point-min))
6644 (while (re-search-forward "^\\*\\*+ " nil t)
6645 (setq n (- (length (match-string 0)) 2))
6646 (while (>= (setq n (1- n)) 0)
6647 (org-demote))
6648 (end-of-line 1))))))
6651 (defun org-convert-to-oddeven-levels ()
6652 "Convert an org-mode file with only odd levels to one with odd and even levels.
6653 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6654 section with an even level, conversion would destroy the structure of the file. An error
6655 is signaled in this case."
6656 (interactive)
6657 (goto-char (point-min))
6658 ;; First check if there are no even levels
6659 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6660 (org-show-context t)
6661 (error "Not all levels are odd in this file. Conversion not possible."))
6662 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6663 (let ((org-odd-levels-only nil) n)
6664 (save-excursion
6665 (goto-char (point-min))
6666 (while (re-search-forward "^\\*\\*+ " nil t)
6667 (setq n (/ (1- (length (match-string 0))) 2))
6668 (while (>= (setq n (1- n)) 0)
6669 (org-promote))
6670 (end-of-line 1))))))
6672 (defun org-tr-level (n)
6673 "Make N odd if required."
6674 (if org-odd-levels-only (1+ (/ n 2)) n))
6676 ;;; Vertical tree motion, cutting and pasting of subtrees
6678 (defun org-move-subtree-up (&optional arg)
6679 "Move the current subtree up past ARG headlines of the same level."
6680 (interactive "p")
6681 (org-move-subtree-down (- (prefix-numeric-value arg))))
6683 (defun org-move-subtree-down (&optional arg)
6684 "Move the current subtree down past ARG headlines of the same level."
6685 (interactive "p")
6686 (setq arg (prefix-numeric-value arg))
6687 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6688 'outline-get-last-sibling))
6689 (ins-point (make-marker))
6690 (cnt (abs arg))
6691 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6692 ;; Select the tree
6693 (org-back-to-heading)
6694 (setq beg0 (point))
6695 (save-excursion
6696 (setq ne-beg (org-back-over-empty-lines))
6697 (setq beg (point)))
6698 (save-match-data
6699 (save-excursion (outline-end-of-heading)
6700 (setq folded (org-invisible-p)))
6701 (outline-end-of-subtree))
6702 (outline-next-heading)
6703 (setq ne-end (org-back-over-empty-lines))
6704 (setq end (point))
6705 (goto-char beg0)
6706 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6707 ;; include less whitespace
6708 (save-excursion
6709 (goto-char beg)
6710 (forward-line (- ne-beg ne-end))
6711 (setq beg (point))))
6712 ;; Find insertion point, with error handling
6713 (while (> cnt 0)
6714 (or (and (funcall movfunc) (looking-at outline-regexp))
6715 (progn (goto-char beg0)
6716 (error "Cannot move past superior level or buffer limit")))
6717 (setq cnt (1- cnt)))
6718 (if (> arg 0)
6719 ;; Moving forward - still need to move over subtree
6720 (progn (org-end-of-subtree t t)
6721 (save-excursion
6722 (org-back-over-empty-lines)
6723 (or (bolp) (newline)))))
6724 (setq ne-ins (org-back-over-empty-lines))
6725 (move-marker ins-point (point))
6726 (setq txt (buffer-substring beg end))
6727 (delete-region beg end)
6728 (outline-flag-region (1- beg) beg nil)
6729 (outline-flag-region (1- (point)) (point) nil)
6730 (insert txt)
6731 (or (bolp) (insert "\n"))
6732 (setq ins-end (point))
6733 (goto-char ins-point)
6734 (org-skip-whitespace)
6735 (when (and (< arg 0)
6736 (org-first-sibling-p)
6737 (> ne-ins ne-beg))
6738 ;; Move whitespace back to beginning
6739 (save-excursion
6740 (goto-char ins-end)
6741 (let ((kill-whole-line t))
6742 (kill-line (- ne-ins ne-beg)) (point)))
6743 (insert (make-string (- ne-ins ne-beg) ?\n)))
6744 (move-marker ins-point nil)
6745 (org-compact-display-after-subtree-move)
6746 (unless folded
6747 (org-show-entry)
6748 (show-children)
6749 (org-cycle-hide-drawers 'children))))
6751 (defvar org-subtree-clip ""
6752 "Clipboard for cut and paste of subtrees.
6753 This is actually only a copy of the kill, because we use the normal kill
6754 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6756 (defvar org-subtree-clip-folded nil
6757 "Was the last copied subtree folded?
6758 This is used to fold the tree back after pasting.")
6760 (defun org-cut-subtree (&optional n)
6761 "Cut the current subtree into the clipboard.
6762 With prefix arg N, cut this many sequential subtrees.
6763 This is a short-hand for marking the subtree and then cutting it."
6764 (interactive "p")
6765 (org-copy-subtree n 'cut))
6767 (defun org-copy-subtree (&optional n cut)
6768 "Cut the current subtree into the clipboard.
6769 With prefix arg N, cut this many sequential subtrees.
6770 This is a short-hand for marking the subtree and then copying it.
6771 If CUT is non-nil, actually cut the subtree."
6772 (interactive "p")
6773 (let (beg end folded (beg0 (point)))
6774 (if (interactive-p)
6775 (org-back-to-heading nil) ; take what looks like a subtree
6776 (org-back-to-heading t)) ; take what is really there
6777 (org-back-over-empty-lines)
6778 (setq beg (point))
6779 (skip-chars-forward " \t\r\n")
6780 (save-match-data
6781 (save-excursion (outline-end-of-heading)
6782 (setq folded (org-invisible-p)))
6783 (condition-case nil
6784 (outline-forward-same-level (1- n))
6785 (error nil))
6786 (org-end-of-subtree t t))
6787 (org-back-over-empty-lines)
6788 (setq end (point))
6789 (goto-char beg0)
6790 (when (> end beg)
6791 (setq org-subtree-clip-folded folded)
6792 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6793 (setq org-subtree-clip (current-kill 0))
6794 (message "%s: Subtree(s) with %d characters"
6795 (if cut "Cut" "Copied")
6796 (length org-subtree-clip)))))
6798 (defun org-paste-subtree (&optional level tree)
6799 "Paste the clipboard as a subtree, with modification of headline level.
6800 The entire subtree is promoted or demoted in order to match a new headline
6801 level. By default, the new level is derived from the visible headings
6802 before and after the insertion point, and taken to be the inferior headline
6803 level of the two. So if the previous visible heading is level 3 and the
6804 next is level 4 (or vice versa), level 4 will be used for insertion.
6805 This makes sure that the subtree remains an independent subtree and does
6806 not swallow low level entries.
6808 You can also force a different level, either by using a numeric prefix
6809 argument, or by inserting the heading marker by hand. For example, if the
6810 cursor is after \"*****\", then the tree will be shifted to level 5.
6812 If you want to insert the tree as is, just use \\[yank].
6814 If optional TREE is given, use this text instead of the kill ring."
6815 (interactive "P")
6816 (unless (org-kill-is-subtree-p tree)
6817 (error "%s"
6818 (substitute-command-keys
6819 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6820 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6821 (^re (concat "^\\(" outline-regexp "\\)"))
6822 (re (concat "\\(" outline-regexp "\\)"))
6823 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6825 (old-level (if (string-match ^re txt)
6826 (- (match-end 0) (match-beginning 0) 1)
6827 -1))
6828 (force-level (cond (level (prefix-numeric-value level))
6829 ((string-match
6830 ^re_ (buffer-substring (point-at-bol) (point)))
6831 (- (match-end 1) (match-beginning 1)))
6832 (t nil)))
6833 (previous-level (save-excursion
6834 (condition-case nil
6835 (progn
6836 (outline-previous-visible-heading 1)
6837 (if (looking-at re)
6838 (- (match-end 0) (match-beginning 0) 1)
6840 (error 1))))
6841 (next-level (save-excursion
6842 (condition-case nil
6843 (progn
6844 (or (looking-at outline-regexp)
6845 (outline-next-visible-heading 1))
6846 (if (looking-at re)
6847 (- (match-end 0) (match-beginning 0) 1)
6849 (error 1))))
6850 (new-level (or force-level (max previous-level next-level)))
6851 (shift (if (or (= old-level -1)
6852 (= new-level -1)
6853 (= old-level new-level))
6855 (- new-level old-level)))
6856 (delta (if (> shift 0) -1 1))
6857 (func (if (> shift 0) 'org-demote 'org-promote))
6858 (org-odd-levels-only nil)
6859 beg end)
6860 ;; Remove the forced level indicator
6861 (if force-level
6862 (delete-region (point-at-bol) (point)))
6863 ;; Paste
6864 (beginning-of-line 1)
6865 (org-back-over-empty-lines) ;; FIXME: correct fix????
6866 (setq beg (point))
6867 (insert-before-markers txt) ;; FIXME: correct fix????
6868 (unless (string-match "\n\\'" txt) (insert "\n"))
6869 (setq end (point))
6870 (goto-char beg)
6871 (skip-chars-forward " \t\n\r")
6872 (setq beg (point))
6873 ;; Shift if necessary
6874 (unless (= shift 0)
6875 (save-restriction
6876 (narrow-to-region beg end)
6877 (while (not (= shift 0))
6878 (org-map-region func (point-min) (point-max))
6879 (setq shift (+ delta shift)))
6880 (goto-char (point-min))))
6881 (when (interactive-p)
6882 (message "Clipboard pasted as level %d subtree" new-level))
6883 (if (and kill-ring
6884 (eq org-subtree-clip (current-kill 0))
6885 org-subtree-clip-folded)
6886 ;; The tree was folded before it was killed/copied
6887 (hide-subtree))))
6889 (defun org-kill-is-subtree-p (&optional txt)
6890 "Check if the current kill is an outline subtree, or a set of trees.
6891 Returns nil if kill does not start with a headline, or if the first
6892 headline level is not the largest headline level in the tree.
6893 So this will actually accept several entries of equal levels as well,
6894 which is OK for `org-paste-subtree'.
6895 If optional TXT is given, check this string instead of the current kill."
6896 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6897 (start-level (and kill
6898 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6899 org-outline-regexp "\\)")
6900 kill)
6901 (- (match-end 2) (match-beginning 2) 1)))
6902 (re (concat "^" org-outline-regexp))
6903 (start (1+ (match-beginning 2))))
6904 (if (not start-level)
6905 (progn
6906 nil) ;; does not even start with a heading
6907 (catch 'exit
6908 (while (setq start (string-match re kill (1+ start)))
6909 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6910 (throw 'exit nil)))
6911 t))))
6913 (defun org-narrow-to-subtree ()
6914 "Narrow buffer to the current subtree."
6915 (interactive)
6916 (save-excursion
6917 (save-match-data
6918 (narrow-to-region
6919 (progn (org-back-to-heading) (point))
6920 (progn (org-end-of-subtree t t) (point))))))
6923 ;;; Outline Sorting
6925 (defun org-sort (with-case)
6926 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6927 Optional argument WITH-CASE means sort case-sensitively."
6928 (interactive "P")
6929 (if (org-at-table-p)
6930 (org-call-with-arg 'org-table-sort-lines with-case)
6931 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6933 (defvar org-priority-regexp) ; defined later in the file
6935 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6936 "Sort entries on a certain level of an outline tree.
6937 If there is an active region, the entries in the region are sorted.
6938 Else, if the cursor is before the first entry, sort the top-level items.
6939 Else, the children of the entry at point are sorted.
6941 Sorting can be alphabetically, numerically, and by date/time as given by
6942 the first time stamp in the entry. The command prompts for the sorting
6943 type unless it has been given to the function through the SORTING-TYPE
6944 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6945 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6946 called with point at the beginning of the record. It must return either
6947 a string or a number that should serve as the sorting key for that record.
6949 Comparing entries ignores case by default. However, with an optional argument
6950 WITH-CASE, the sorting considers case as well."
6951 (interactive "P")
6952 (let ((case-func (if with-case 'identity 'downcase))
6953 start beg end stars re re2
6954 txt what tmp plain-list-p)
6955 ;; Find beginning and end of region to sort
6956 (cond
6957 ((org-region-active-p)
6958 ;; we will sort the region
6959 (setq end (region-end)
6960 what "region")
6961 (goto-char (region-beginning))
6962 (if (not (org-on-heading-p)) (outline-next-heading))
6963 (setq start (point)))
6964 ((org-at-item-p)
6965 ;; we will sort this plain list
6966 (org-beginning-of-item-list) (setq start (point))
6967 (org-end-of-item-list) (setq end (point))
6968 (goto-char start)
6969 (setq plain-list-p t
6970 what "plain list"))
6971 ((or (org-on-heading-p)
6972 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6973 ;; we will sort the children of the current headline
6974 (org-back-to-heading)
6975 (setq start (point)
6976 end (progn (org-end-of-subtree t t)
6977 (org-back-over-empty-lines)
6978 (point))
6979 what "children")
6980 (goto-char start)
6981 (show-subtree)
6982 (outline-next-heading))
6984 ;; we will sort the top-level entries in this file
6985 (goto-char (point-min))
6986 (or (org-on-heading-p) (outline-next-heading))
6987 (setq start (point) end (point-max) what "top-level")
6988 (goto-char start)
6989 (show-all)))
6991 (setq beg (point))
6992 (if (>= beg end) (error "Nothing to sort"))
6994 (unless plain-list-p
6995 (looking-at "\\(\\*+\\)")
6996 (setq stars (match-string 1)
6997 re (concat "^" (regexp-quote stars) " +")
6998 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6999 txt (buffer-substring beg end))
7000 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7001 (if (and (not (equal stars "*")) (string-match re2 txt))
7002 (error "Region to sort contains a level above the first entry")))
7004 (unless sorting-type
7005 (message
7006 (if plain-list-p
7007 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7008 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
7009 what)
7010 (setq sorting-type (read-char-exclusive))
7012 (and (= (downcase sorting-type) ?f)
7013 (setq getkey-func
7014 (completing-read "Sort using function: "
7015 obarray 'fboundp t nil nil))
7016 (setq getkey-func (intern getkey-func)))
7018 (and (= (downcase sorting-type) ?r)
7019 (setq property
7020 (completing-read "Property: "
7021 (mapcar 'list (org-buffer-property-keys t))
7022 nil t))))
7024 (message "Sorting entries...")
7026 (save-restriction
7027 (narrow-to-region start end)
7029 (let ((dcst (downcase sorting-type))
7030 (now (current-time)))
7031 (sort-subr
7032 (/= dcst sorting-type)
7033 ;; This function moves to the beginning character of the "record" to
7034 ;; be sorted.
7035 (if plain-list-p
7036 (lambda nil
7037 (if (org-at-item-p) t (goto-char (point-max))))
7038 (lambda nil
7039 (if (re-search-forward re nil t)
7040 (goto-char (match-beginning 0))
7041 (goto-char (point-max)))))
7042 ;; This function moves to the last character of the "record" being
7043 ;; sorted.
7044 (if plain-list-p
7045 'org-end-of-item
7046 (lambda nil
7047 (save-match-data
7048 (condition-case nil
7049 (outline-forward-same-level 1)
7050 (error
7051 (goto-char (point-max)))))))
7053 ;; This function returns the value that gets sorted against.
7054 (if plain-list-p
7055 (lambda nil
7056 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7057 (cond
7058 ((= dcst ?n)
7059 (string-to-number (buffer-substring (match-end 0)
7060 (point-at-eol))))
7061 ((= dcst ?a)
7062 (buffer-substring (match-end 0) (point-at-eol)))
7063 ((= dcst ?t)
7064 (if (re-search-forward org-ts-regexp
7065 (point-at-eol) t)
7066 (org-time-string-to-time (match-string 0))
7067 now))
7068 ((= dcst ?f)
7069 (if getkey-func
7070 (progn
7071 (setq tmp (funcall getkey-func))
7072 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7073 tmp)
7074 (error "Invalid key function `%s'" getkey-func)))
7075 (t (error "Invalid sorting type `%c'" sorting-type)))))
7076 (lambda nil
7077 (cond
7078 ((= dcst ?n)
7079 (if (looking-at outline-regexp)
7080 (string-to-number (buffer-substring (match-end 0)
7081 (point-at-eol)))
7082 nil))
7083 ((= dcst ?a)
7084 (funcall case-func (buffer-substring (point-at-bol)
7085 (point-at-eol))))
7086 ((= dcst ?t)
7087 (if (re-search-forward org-ts-regexp
7088 (save-excursion
7089 (forward-line 2)
7090 (point)) t)
7091 (org-time-string-to-time (match-string 0))
7092 now))
7093 ((= dcst ?p)
7094 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7095 (string-to-char (match-string 2))
7096 org-default-priority))
7097 ((= dcst ?r)
7098 (or (org-entry-get nil property) ""))
7099 ((= dcst ?f)
7100 (if getkey-func
7101 (progn
7102 (setq tmp (funcall getkey-func))
7103 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7104 tmp)
7105 (error "Invalid key function `%s'" getkey-func)))
7106 (t (error "Invalid sorting type `%c'" sorting-type)))))
7108 (cond
7109 ((= dcst ?a) 'string<)
7110 ((= dcst ?t) 'time-less-p)
7111 (t nil)))))
7112 (message "Sorting entries...done")))
7114 (defun org-do-sort (table what &optional with-case sorting-type)
7115 "Sort TABLE of WHAT according to SORTING-TYPE.
7116 The user will be prompted for the SORTING-TYPE if the call to this
7117 function does not specify it. WHAT is only for the prompt, to indicate
7118 what is being sorted. The sorting key will be extracted from
7119 the car of the elements of the table.
7120 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7121 (unless sorting-type
7122 (message
7123 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7124 what)
7125 (setq sorting-type (read-char-exclusive)))
7126 (let ((dcst (downcase sorting-type))
7127 extractfun comparefun)
7128 ;; Define the appropriate functions
7129 (cond
7130 ((= dcst ?n)
7131 (setq extractfun 'string-to-number
7132 comparefun (if (= dcst sorting-type) '< '>)))
7133 ((= dcst ?a)
7134 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7135 (lambda(x) (downcase (org-sort-remove-invisible x))))
7136 comparefun (if (= dcst sorting-type)
7137 'string<
7138 (lambda (a b) (and (not (string< a b))
7139 (not (string= a b)))))))
7140 ((= dcst ?t)
7141 (setq extractfun
7142 (lambda (x)
7143 (if (string-match org-ts-regexp x)
7144 (time-to-seconds
7145 (org-time-string-to-time (match-string 0 x)))
7147 comparefun (if (= dcst sorting-type) '< '>)))
7148 (t (error "Invalid sorting type `%c'" sorting-type)))
7150 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7151 table)
7152 (lambda (a b) (funcall comparefun (car a) (car b))))))
7154 ;;;; Plain list items, including checkboxes
7156 ;;; Plain list items
7158 (defun org-at-item-p ()
7159 "Is point in a line starting a hand-formatted item?"
7160 (let ((llt org-plain-list-ordered-item-terminator))
7161 (save-excursion
7162 (goto-char (point-at-bol))
7163 (looking-at
7164 (cond
7165 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7166 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7167 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7168 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7170 (defun org-in-item-p ()
7171 "It the cursor inside a plain list item.
7172 Does not have to be the first line."
7173 (save-excursion
7174 (condition-case nil
7175 (progn
7176 (org-beginning-of-item)
7177 (org-at-item-p)
7179 (error nil))))
7181 (defun org-insert-item (&optional checkbox)
7182 "Insert a new item at the current level.
7183 Return t when things worked, nil when we are not in an item."
7184 (when (save-excursion
7185 (condition-case nil
7186 (progn
7187 (org-beginning-of-item)
7188 (org-at-item-p)
7189 (if (org-invisible-p) (error "Invisible item"))
7191 (error nil)))
7192 (let* ((bul (match-string 0))
7193 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7194 (match-end 0)))
7195 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7196 pos)
7197 (cond
7198 ((and (org-at-item-p) (<= (point) eow))
7199 ;; before the bullet
7200 (beginning-of-line 1)
7201 (open-line (if blank 2 1)))
7202 ((<= (point) eow)
7203 (beginning-of-line 1))
7205 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7206 (end-of-line 1)
7207 (delete-horizontal-space))
7208 (newline (if blank 2 1))))
7209 (insert bul (if checkbox "[ ]" ""))
7210 (just-one-space)
7211 (setq pos (point))
7212 (end-of-line 1)
7213 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7214 (org-maybe-renumber-ordered-list)
7215 (and checkbox (org-update-checkbox-count-maybe))
7218 ;;; Checkboxes
7220 (defun org-at-item-checkbox-p ()
7221 "Is point at a line starting a plain-list item with a checklet?"
7222 (and (org-at-item-p)
7223 (save-excursion
7224 (goto-char (match-end 0))
7225 (skip-chars-forward " \t")
7226 (looking-at "\\[[- X]\\]"))))
7228 (defun org-toggle-checkbox (&optional arg)
7229 "Toggle the checkbox in the current line."
7230 (interactive "P")
7231 (catch 'exit
7232 (let (beg end status (firstnew 'unknown))
7233 (cond
7234 ((org-region-active-p)
7235 (setq beg (region-beginning) end (region-end)))
7236 ((org-on-heading-p)
7237 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7238 ((org-at-item-checkbox-p)
7239 (let ((pos (point)))
7240 (replace-match
7241 (cond (arg "[-]")
7242 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7243 (t "[ ]"))
7244 t t)
7245 (goto-char pos))
7246 (throw 'exit t))
7247 (t (error "Not at a checkbox or heading, and no active region")))
7248 (save-excursion
7249 (goto-char beg)
7250 (while (< (point) end)
7251 (when (org-at-item-checkbox-p)
7252 (setq status (equal (match-string 0) "[X]"))
7253 (when (eq firstnew 'unknown)
7254 (setq firstnew (not status)))
7255 (replace-match
7256 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7257 (beginning-of-line 2)))))
7258 (org-update-checkbox-count-maybe))
7260 (defun org-update-checkbox-count-maybe ()
7261 "Update checkbox statistics unless turned off by user."
7262 (when org-provide-checkbox-statistics
7263 (org-update-checkbox-count)))
7265 (defun org-update-checkbox-count (&optional all)
7266 "Update the checkbox statistics in the current section.
7267 This will find all statistic cookies like [57%] and [6/12] and update them
7268 with the current numbers. With optional prefix argument ALL, do this for
7269 the whole buffer."
7270 (interactive "P")
7271 (save-excursion
7272 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7273 (beg (condition-case nil
7274 (progn (outline-back-to-heading) (point))
7275 (error (point-min))))
7276 (end (move-marker (make-marker)
7277 (progn (outline-next-heading) (point))))
7278 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7279 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7280 (re-find (concat re "\\|" re-box))
7281 beg-cookie end-cookie is-percent c-on c-off lim
7282 eline curr-ind next-ind continue-from startsearch
7283 (cstat 0)
7285 (when all
7286 (goto-char (point-min))
7287 (outline-next-heading)
7288 (setq beg (point) end (point-max)))
7289 (goto-char end)
7290 ;; find each statistic cookie
7291 (while (re-search-backward re-find beg t)
7292 (setq beg-cookie (match-beginning 1)
7293 end-cookie (match-end 1)
7294 cstat (+ cstat (if end-cookie 1 0))
7295 startsearch (point-at-eol)
7296 continue-from (point-at-bol)
7297 is-percent (match-beginning 2)
7298 lim (cond
7299 ((org-on-heading-p) (outline-next-heading) (point))
7300 ((org-at-item-p) (org-end-of-item) (point))
7301 (t nil))
7302 c-on 0
7303 c-off 0)
7304 (when lim
7305 ;; find first checkbox for this cookie and gather
7306 ;; statistics from all that are at this indentation level
7307 (goto-char startsearch)
7308 (if (re-search-forward re-box lim t)
7309 (progn
7310 (org-beginning-of-item)
7311 (setq curr-ind (org-get-indentation))
7312 (setq next-ind curr-ind)
7313 (while (= curr-ind next-ind)
7314 (save-excursion (end-of-line) (setq eline (point)))
7315 (if (re-search-forward re-box eline t)
7316 (if (member (match-string 2) '("[ ]" "[-]"))
7317 (setq c-off (1+ c-off))
7318 (setq c-on (1+ c-on))
7321 (org-end-of-item)
7322 (setq next-ind (org-get-indentation))
7324 (goto-char continue-from)
7325 ;; update cookie
7326 (when end-cookie
7327 (delete-region beg-cookie end-cookie)
7328 (goto-char beg-cookie)
7329 (insert
7330 (if is-percent
7331 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7332 (format "[%d/%d]" c-on (+ c-on c-off)))))
7333 ;; update items checkbox if it has one
7334 (when (org-at-item-p)
7335 (org-beginning-of-item)
7336 (when (and (> (+ c-on c-off) 0)
7337 (re-search-forward re-box (point-at-eol) t))
7338 (setq beg-cookie (match-beginning 2)
7339 end-cookie (match-end 2))
7340 (delete-region beg-cookie end-cookie)
7341 (goto-char beg-cookie)
7342 (cond ((= c-off 0) (insert "[X]"))
7343 ((= c-on 0) (insert "[ ]"))
7344 (t (insert "[-]")))
7346 (goto-char continue-from))
7347 (when (interactive-p)
7348 (message "Checkbox satistics updated %s (%d places)"
7349 (if all "in entire file" "in current outline entry") cstat)))))
7351 (defun org-get-checkbox-statistics-face ()
7352 "Select the face for checkbox statistics.
7353 The face will be `org-done' when all relevant boxes are checked. Otherwise
7354 it will be `org-todo'."
7355 (if (match-end 1)
7356 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7357 (if (and (> (match-end 2) (match-beginning 2))
7358 (equal (match-string 2) (match-string 3)))
7359 'org-done
7360 'org-todo)))
7362 (defun org-get-indentation (&optional line)
7363 "Get the indentation of the current line, interpreting tabs.
7364 When LINE is given, assume it represents a line and compute its indentation."
7365 (if line
7366 (if (string-match "^ *" (org-remove-tabs line))
7367 (match-end 0))
7368 (save-excursion
7369 (beginning-of-line 1)
7370 (skip-chars-forward " \t")
7371 (current-column))))
7373 (defun org-remove-tabs (s &optional width)
7374 "Replace tabulators in S with spaces.
7375 Assumes that s is a single line, starting in column 0."
7376 (setq width (or width tab-width))
7377 (while (string-match "\t" s)
7378 (setq s (replace-match
7379 (make-string
7380 (- (* width (/ (+ (match-beginning 0) width) width))
7381 (match-beginning 0)) ?\ )
7382 t t s)))
7385 (defun org-fix-indentation (line ind)
7386 "Fix indentation in LINE.
7387 IND is a cons cell with target and minimum indentation.
7388 If the current indenation in LINE is smaller than the minimum,
7389 leave it alone. If it is larger than ind, set it to the target."
7390 (let* ((l (org-remove-tabs line))
7391 (i (org-get-indentation l))
7392 (i1 (car ind)) (i2 (cdr ind)))
7393 (if (>= i i2) (setq l (substring line i2)))
7394 (if (> i1 0)
7395 (concat (make-string i1 ?\ ) l)
7396 l)))
7398 (defcustom org-empty-line-terminates-plain-lists nil
7399 "Non-nil means, an empty line ends all plain list levels.
7400 When nil, empty lines are part of the preceeding item."
7401 :group 'org-plain-lists
7402 :type 'boolean)
7404 (defun org-beginning-of-item ()
7405 "Go to the beginning of the current hand-formatted item.
7406 If the cursor is not in an item, throw an error."
7407 (interactive)
7408 (let ((pos (point))
7409 (limit (save-excursion
7410 (condition-case nil
7411 (progn
7412 (org-back-to-heading)
7413 (beginning-of-line 2) (point))
7414 (error (point-min)))))
7415 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7416 ind ind1)
7417 (if (org-at-item-p)
7418 (beginning-of-line 1)
7419 (beginning-of-line 1)
7420 (skip-chars-forward " \t")
7421 (setq ind (current-column))
7422 (if (catch 'exit
7423 (while t
7424 (beginning-of-line 0)
7425 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7427 (if (looking-at "[ \t]*$")
7428 (setq ind1 ind-empty)
7429 (skip-chars-forward " \t")
7430 (setq ind1 (current-column)))
7431 (if (< ind1 ind)
7432 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7434 (goto-char pos)
7435 (error "Not in an item")))))
7437 (defun org-end-of-item ()
7438 "Go to the end of the current hand-formatted item.
7439 If the cursor is not in an item, throw an error."
7440 (interactive)
7441 (let* ((pos (point))
7442 ind1
7443 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7444 (limit (save-excursion (outline-next-heading) (point)))
7445 (ind (save-excursion
7446 (org-beginning-of-item)
7447 (skip-chars-forward " \t")
7448 (current-column)))
7449 (end (catch 'exit
7450 (while t
7451 (beginning-of-line 2)
7452 (if (eobp) (throw 'exit (point)))
7453 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7454 (if (looking-at "[ \t]*$")
7455 (setq ind1 ind-empty)
7456 (skip-chars-forward " \t")
7457 (setq ind1 (current-column)))
7458 (if (<= ind1 ind)
7459 (throw 'exit (point-at-bol)))))))
7460 (if end
7461 (goto-char end)
7462 (goto-char pos)
7463 (error "Not in an item"))))
7465 (defun org-next-item ()
7466 "Move to the beginning of the next item in the current plain list.
7467 Error if not at a plain list, or if this is the last item in the list."
7468 (interactive)
7469 (let (ind ind1 (pos (point)))
7470 (org-beginning-of-item)
7471 (setq ind (org-get-indentation))
7472 (org-end-of-item)
7473 (setq ind1 (org-get-indentation))
7474 (unless (and (org-at-item-p) (= ind ind1))
7475 (goto-char pos)
7476 (error "On last item"))))
7478 (defun org-previous-item ()
7479 "Move to the beginning of the previous item in the current plain list.
7480 Error if not at a plain list, or if this is the first item in the list."
7481 (interactive)
7482 (let (beg ind ind1 (pos (point)))
7483 (org-beginning-of-item)
7484 (setq beg (point))
7485 (setq ind (org-get-indentation))
7486 (goto-char beg)
7487 (catch 'exit
7488 (while t
7489 (beginning-of-line 0)
7490 (if (looking-at "[ \t]*$")
7492 (if (<= (setq ind1 (org-get-indentation)) ind)
7493 (throw 'exit t)))))
7494 (condition-case nil
7495 (if (or (not (org-at-item-p))
7496 (< ind1 (1- ind)))
7497 (error "")
7498 (org-beginning-of-item))
7499 (error (goto-char pos)
7500 (error "On first item")))))
7502 (defun org-first-list-item-p ()
7503 "Is this heading the item in a plain list?"
7504 (unless (org-at-item-p)
7505 (error "Not at a plain list item"))
7506 (org-beginning-of-item)
7507 (= (point) (save-excursion (org-beginning-of-item-list))))
7509 (defun org-move-item-down ()
7510 "Move the plain list item at point down, i.e. swap with following item.
7511 Subitems (items with larger indentation) are considered part of the item,
7512 so this really moves item trees."
7513 (interactive)
7514 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7515 (org-beginning-of-item)
7516 (setq beg0 (point))
7517 (save-excursion
7518 (setq ne-beg (org-back-over-empty-lines))
7519 (setq beg (point)))
7520 (goto-char beg0)
7521 (setq ind (org-get-indentation))
7522 (org-end-of-item)
7523 (setq end0 (point))
7524 (setq ind1 (org-get-indentation))
7525 (setq ne-end (org-back-over-empty-lines))
7526 (setq end (point))
7527 (goto-char beg0)
7528 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7529 ;; include less whitespace
7530 (save-excursion
7531 (goto-char beg)
7532 (forward-line (- ne-beg ne-end))
7533 (setq beg (point))))
7534 (goto-char end0)
7535 (if (and (org-at-item-p) (= ind ind1))
7536 (progn
7537 (org-end-of-item)
7538 (org-back-over-empty-lines)
7539 (setq txt (buffer-substring beg end))
7540 (save-excursion
7541 (delete-region beg end))
7542 (setq pos (point))
7543 (insert txt)
7544 (goto-char pos) (org-skip-whitespace)
7545 (org-maybe-renumber-ordered-list))
7546 (goto-char pos)
7547 (error "Cannot move this item further down"))))
7549 (defun org-move-item-up (arg)
7550 "Move the plain list item at point up, i.e. swap with previous item.
7551 Subitems (items with larger indentation) are considered part of the item,
7552 so this really moves item trees."
7553 (interactive "p")
7554 (let (beg beg0 end ind ind1 (pos (point)) txt
7555 ne-beg ne-ins ins-end)
7556 (org-beginning-of-item)
7557 (setq beg0 (point))
7558 (setq ind (org-get-indentation))
7559 (save-excursion
7560 (setq ne-beg (org-back-over-empty-lines))
7561 (setq beg (point)))
7562 (goto-char beg0)
7563 (org-end-of-item)
7564 (setq end (point))
7565 (goto-char beg0)
7566 (catch 'exit
7567 (while t
7568 (beginning-of-line 0)
7569 (if (looking-at "[ \t]*$")
7570 (if org-empty-line-terminates-plain-lists
7571 (progn
7572 (goto-char pos)
7573 (error "Cannot move this item further up"))
7574 nil)
7575 (if (<= (setq ind1 (org-get-indentation)) ind)
7576 (throw 'exit t)))))
7577 (condition-case nil
7578 (org-beginning-of-item)
7579 (error (goto-char beg)
7580 (error "Cannot move this item further up")))
7581 (setq ind1 (org-get-indentation))
7582 (if (and (org-at-item-p) (= ind ind1))
7583 (progn
7584 (setq ne-ins (org-back-over-empty-lines))
7585 (setq txt (buffer-substring beg end))
7586 (save-excursion
7587 (delete-region beg end))
7588 (setq pos (point))
7589 (insert txt)
7590 (setq ins-end (point))
7591 (goto-char pos) (org-skip-whitespace)
7593 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7594 ;; Move whitespace back to beginning
7595 (save-excursion
7596 (goto-char ins-end)
7597 (let ((kill-whole-line t))
7598 (kill-line (- ne-ins ne-beg)) (point)))
7599 (insert (make-string (- ne-ins ne-beg) ?\n)))
7601 (org-maybe-renumber-ordered-list))
7602 (goto-char pos)
7603 (error "Cannot move this item further up"))))
7605 (defun org-maybe-renumber-ordered-list ()
7606 "Renumber the ordered list at point if setup allows it.
7607 This tests the user option `org-auto-renumber-ordered-lists' before
7608 doing the renumbering."
7609 (interactive)
7610 (when (and org-auto-renumber-ordered-lists
7611 (org-at-item-p))
7612 (if (match-beginning 3)
7613 (org-renumber-ordered-list 1)
7614 (org-fix-bullet-type))))
7616 (defun org-maybe-renumber-ordered-list-safe ()
7617 (condition-case nil
7618 (save-excursion
7619 (org-maybe-renumber-ordered-list))
7620 (error nil)))
7622 (defun org-cycle-list-bullet (&optional which)
7623 "Cycle through the different itemize/enumerate bullets.
7624 This cycle the entire list level through the sequence:
7626 `-' -> `+' -> `*' -> `1.' -> `1)'
7628 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7629 0 meand `-', 1 means `+' etc."
7630 (interactive "P")
7631 (org-preserve-lc
7632 (org-beginning-of-item-list)
7633 (org-at-item-p)
7634 (beginning-of-line 1)
7635 (let ((current (match-string 0))
7636 (prevp (eq which 'previous))
7637 new)
7638 (setq new (cond
7639 ((and (numberp which)
7640 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7641 ((string-match "-" current) (if prevp "1)" "+"))
7642 ((string-match "\\+" current)
7643 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7644 ((string-match "\\*" current) (if prevp "+" "1."))
7645 ((string-match "\\." current) (if prevp "*" "1)"))
7646 ((string-match ")" current) (if prevp "1." "-"))
7647 (t (error "This should not happen"))))
7648 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7649 (org-fix-bullet-type)
7650 (org-maybe-renumber-ordered-list))))
7652 (defun org-get-string-indentation (s)
7653 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7654 (let ((n -1) (i 0) (w tab-width) c)
7655 (catch 'exit
7656 (while (< (setq n (1+ n)) (length s))
7657 (setq c (aref s n))
7658 (cond ((= c ?\ ) (setq i (1+ i)))
7659 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7660 (t (throw 'exit t)))))
7663 (defun org-renumber-ordered-list (arg)
7664 "Renumber an ordered plain list.
7665 Cursor needs to be in the first line of an item, the line that starts
7666 with something like \"1.\" or \"2)\"."
7667 (interactive "p")
7668 (unless (and (org-at-item-p)
7669 (match-beginning 3))
7670 (error "This is not an ordered list"))
7671 (let ((line (org-current-line))
7672 (col (current-column))
7673 (ind (org-get-string-indentation
7674 (buffer-substring (point-at-bol) (match-beginning 3))))
7675 ;; (term (substring (match-string 3) -1))
7676 ind1 (n (1- arg))
7677 fmt)
7678 ;; find where this list begins
7679 (org-beginning-of-item-list)
7680 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7681 (setq fmt (concat "%d" (match-string 1)))
7682 (beginning-of-line 0)
7683 ;; walk forward and replace these numbers
7684 (catch 'exit
7685 (while t
7686 (catch 'next
7687 (beginning-of-line 2)
7688 (if (eobp) (throw 'exit nil))
7689 (if (looking-at "[ \t]*$") (throw 'next nil))
7690 (skip-chars-forward " \t") (setq ind1 (current-column))
7691 (if (> ind1 ind) (throw 'next t))
7692 (if (< ind1 ind) (throw 'exit t))
7693 (if (not (org-at-item-p)) (throw 'exit nil))
7694 (delete-region (match-beginning 2) (match-end 2))
7695 (goto-char (match-beginning 2))
7696 (insert (format fmt (setq n (1+ n)))))))
7697 (goto-line line)
7698 (move-to-column col)))
7700 (defun org-fix-bullet-type ()
7701 "Make sure all items in this list have the same bullet as the firsst item."
7702 (interactive)
7703 (unless (org-at-item-p) (error "This is not a list"))
7704 (let ((line (org-current-line))
7705 (col (current-column))
7706 (ind (current-indentation))
7707 ind1 bullet)
7708 ;; find where this list begins
7709 (org-beginning-of-item-list)
7710 (beginning-of-line 1)
7711 ;; find out what the bullet type is
7712 (looking-at "[ \t]*\\(\\S-+\\)")
7713 (setq bullet (match-string 1))
7714 ;; walk forward and replace these numbers
7715 (beginning-of-line 0)
7716 (catch 'exit
7717 (while t
7718 (catch 'next
7719 (beginning-of-line 2)
7720 (if (eobp) (throw 'exit nil))
7721 (if (looking-at "[ \t]*$") (throw 'next nil))
7722 (skip-chars-forward " \t") (setq ind1 (current-column))
7723 (if (> ind1 ind) (throw 'next t))
7724 (if (< ind1 ind) (throw 'exit t))
7725 (if (not (org-at-item-p)) (throw 'exit nil))
7726 (skip-chars-forward " \t")
7727 (looking-at "\\S-+")
7728 (replace-match bullet))))
7729 (goto-line line)
7730 (move-to-column col)
7731 (if (string-match "[0-9]" bullet)
7732 (org-renumber-ordered-list 1))))
7734 (defun org-beginning-of-item-list ()
7735 "Go to the beginning of the current item list.
7736 I.e. to the first item in this list."
7737 (interactive)
7738 (org-beginning-of-item)
7739 (let ((pos (point-at-bol))
7740 (ind (org-get-indentation))
7741 ind1)
7742 ;; find where this list begins
7743 (catch 'exit
7744 (while t
7745 (catch 'next
7746 (beginning-of-line 0)
7747 (if (looking-at "[ \t]*$")
7748 (throw (if (bobp) 'exit 'next) t))
7749 (skip-chars-forward " \t") (setq ind1 (current-column))
7750 (if (or (< ind1 ind)
7751 (and (= ind1 ind)
7752 (not (org-at-item-p)))
7753 (bobp))
7754 (throw 'exit t)
7755 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7756 (goto-char pos)))
7759 (defun org-end-of-item-list ()
7760 "Go to the end of the current item list.
7761 I.e. to the text after the last item."
7762 (interactive)
7763 (org-beginning-of-item)
7764 (let ((pos (point-at-bol))
7765 (ind (org-get-indentation))
7766 ind1)
7767 ;; find where this list begins
7768 (catch 'exit
7769 (while t
7770 (catch 'next
7771 (beginning-of-line 2)
7772 (if (looking-at "[ \t]*$")
7773 (throw (if (eobp) 'exit 'next) t))
7774 (skip-chars-forward " \t") (setq ind1 (current-column))
7775 (if (or (< ind1 ind)
7776 (and (= ind1 ind)
7777 (not (org-at-item-p)))
7778 (eobp))
7779 (progn
7780 (setq pos (point-at-bol))
7781 (throw 'exit t))))))
7782 (goto-char pos)))
7785 (defvar org-last-indent-begin-marker (make-marker))
7786 (defvar org-last-indent-end-marker (make-marker))
7788 (defun org-outdent-item (arg)
7789 "Outdent a local list item."
7790 (interactive "p")
7791 (org-indent-item (- arg)))
7793 (defun org-indent-item (arg)
7794 "Indent a local list item."
7795 (interactive "p")
7796 (unless (org-at-item-p)
7797 (error "Not on an item"))
7798 (save-excursion
7799 (let (beg end ind ind1 tmp delta ind-down ind-up)
7800 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7801 (setq beg org-last-indent-begin-marker
7802 end org-last-indent-end-marker)
7803 (org-beginning-of-item)
7804 (setq beg (move-marker org-last-indent-begin-marker (point)))
7805 (org-end-of-item)
7806 (setq end (move-marker org-last-indent-end-marker (point))))
7807 (goto-char beg)
7808 (setq tmp (org-item-indent-positions)
7809 ind (car tmp)
7810 ind-down (nth 2 tmp)
7811 ind-up (nth 1 tmp)
7812 delta (if (> arg 0)
7813 (if ind-down (- ind-down ind) 2)
7814 (if ind-up (- ind-up ind) -2)))
7815 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7816 (while (< (point) end)
7817 (beginning-of-line 1)
7818 (skip-chars-forward " \t") (setq ind1 (current-column))
7819 (delete-region (point-at-bol) (point))
7820 (or (eolp) (indent-to-column (+ ind1 delta)))
7821 (beginning-of-line 2))))
7822 (org-fix-bullet-type)
7823 (org-maybe-renumber-ordered-list-safe)
7824 (save-excursion
7825 (beginning-of-line 0)
7826 (condition-case nil (org-beginning-of-item) (error nil))
7827 (org-maybe-renumber-ordered-list-safe)))
7829 (defun org-item-indent-positions ()
7830 "Return indentation for plain list items.
7831 This returns a list with three values: The current indentation, the
7832 parent indentation and the indentation a child should habe.
7833 Assumes cursor in item line."
7834 (let* ((bolpos (point-at-bol))
7835 (ind (org-get-indentation))
7836 ind-down ind-up pos)
7837 (save-excursion
7838 (org-beginning-of-item-list)
7839 (skip-chars-backward "\n\r \t")
7840 (when (org-in-item-p)
7841 (org-beginning-of-item)
7842 (setq ind-up (org-get-indentation))))
7843 (setq pos (point))
7844 (save-excursion
7845 (cond
7846 ((and (condition-case nil (progn (org-previous-item) t)
7847 (error nil))
7848 (or (forward-char 1) t)
7849 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7850 (setq ind-down (org-get-indentation)))
7851 ((and (goto-char pos)
7852 (org-at-item-p))
7853 (goto-char (match-end 0))
7854 (skip-chars-forward " \t")
7855 (setq ind-down (current-column)))))
7856 (list ind ind-up ind-down)))
7858 ;;; The orgstruct minor mode
7860 ;; Define a minor mode which can be used in other modes in order to
7861 ;; integrate the org-mode structure editing commands.
7863 ;; This is really a hack, because the org-mode structure commands use
7864 ;; keys which normally belong to the major mode. Here is how it
7865 ;; works: The minor mode defines all the keys necessary to operate the
7866 ;; structure commands, but wraps the commands into a function which
7867 ;; tests if the cursor is currently at a headline or a plain list
7868 ;; item. If that is the case, the structure command is used,
7869 ;; temporarily setting many Org-mode variables like regular
7870 ;; expressions for filling etc. However, when any of those keys is
7871 ;; used at a different location, function uses `key-binding' to look
7872 ;; up if the key has an associated command in another currently active
7873 ;; keymap (minor modes, major mode, global), and executes that
7874 ;; command. There might be problems if any of the keys is otherwise
7875 ;; used as a prefix key.
7877 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7878 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7879 ;; addresses this by checking explicitly for both bindings.
7881 (defvar orgstruct-mode-map (make-sparse-keymap)
7882 "Keymap for the minor `orgstruct-mode'.")
7884 (defvar org-local-vars nil
7885 "List of local variables, for use by `orgstruct-mode'")
7887 ;;;###autoload
7888 (define-minor-mode orgstruct-mode
7889 "Toggle the minor more `orgstruct-mode'.
7890 This mode is for using Org-mode structure commands in other modes.
7891 The following key behave as if Org-mode was active, if the cursor
7892 is on a headline, or on a plain list item (both in the definition
7893 of Org-mode).
7895 M-up Move entry/item up
7896 M-down Move entry/item down
7897 M-left Promote
7898 M-right Demote
7899 M-S-up Move entry/item up
7900 M-S-down Move entry/item down
7901 M-S-left Promote subtree
7902 M-S-right Demote subtree
7903 M-q Fill paragraph and items like in Org-mode
7904 C-c ^ Sort entries
7905 C-c - Cycle list bullet
7906 TAB Cycle item visibility
7907 M-RET Insert new heading/item
7908 S-M-RET Insert new TODO heading / Chekbox item
7909 C-c C-c Set tags / toggle checkbox"
7910 nil " OrgStruct" nil
7911 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7913 ;;;###autoload
7914 (defun turn-on-orgstruct ()
7915 "Unconditionally turn on `orgstruct-mode'."
7916 (orgstruct-mode 1))
7918 ;;;###autoload
7919 (defun turn-on-orgstruct++ ()
7920 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7921 In addition to setting orgstruct-mode, this also exports all indentation and
7922 autofilling variables from org-mode into the buffer. Note that turning
7923 off orgstruct-mode will *not* remove these additional settings."
7924 (orgstruct-mode 1)
7925 (let (var val)
7926 (mapc
7927 (lambda (x)
7928 (when (string-match
7929 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7930 (symbol-name (car x)))
7931 (setq var (car x) val (nth 1 x))
7932 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7933 org-local-vars)))
7935 (defun orgstruct-error ()
7936 "Error when there is no default binding for a structure key."
7937 (interactive)
7938 (error "This key has no function outside structure elements"))
7940 (defun orgstruct-setup ()
7941 "Setup orgstruct keymaps."
7942 (let ((nfunc 0)
7943 (bindings
7944 (list
7945 '([(meta up)] org-metaup)
7946 '([(meta down)] org-metadown)
7947 '([(meta left)] org-metaleft)
7948 '([(meta right)] org-metaright)
7949 '([(meta shift up)] org-shiftmetaup)
7950 '([(meta shift down)] org-shiftmetadown)
7951 '([(meta shift left)] org-shiftmetaleft)
7952 '([(meta shift right)] org-shiftmetaright)
7953 '([(shift up)] org-shiftup)
7954 '([(shift down)] org-shiftdown)
7955 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7956 '("\M-q" fill-paragraph)
7957 '("\C-c^" org-sort)
7958 '("\C-c-" org-cycle-list-bullet)))
7959 elt key fun cmd)
7960 (while (setq elt (pop bindings))
7961 (setq nfunc (1+ nfunc))
7962 (setq key (org-key (car elt))
7963 fun (nth 1 elt)
7964 cmd (orgstruct-make-binding fun nfunc key))
7965 (org-defkey orgstruct-mode-map key cmd))
7967 ;; Special treatment needed for TAB and RET
7968 (org-defkey orgstruct-mode-map [(tab)]
7969 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7970 (org-defkey orgstruct-mode-map "\C-i"
7971 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7973 (org-defkey orgstruct-mode-map "\M-\C-m"
7974 (orgstruct-make-binding 'org-insert-heading 105
7975 "\M-\C-m" [(meta return)]))
7976 (org-defkey orgstruct-mode-map [(meta return)]
7977 (orgstruct-make-binding 'org-insert-heading 106
7978 [(meta return)] "\M-\C-m"))
7980 (org-defkey orgstruct-mode-map [(shift meta return)]
7981 (orgstruct-make-binding 'org-insert-todo-heading 107
7982 [(meta return)] "\M-\C-m"))
7984 (unless org-local-vars
7985 (setq org-local-vars (org-get-local-variables)))
7989 (defun orgstruct-make-binding (fun n &rest keys)
7990 "Create a function for binding in the structure minor mode.
7991 FUN is the command to call inside a table. N is used to create a unique
7992 command name. KEYS are keys that should be checked in for a command
7993 to execute outside of tables."
7994 (eval
7995 (list 'defun
7996 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7997 '(arg)
7998 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7999 "Outside of structure, run the binding of `"
8000 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8001 "'.")
8002 '(interactive "p")
8003 (list 'if
8004 '(org-context-p 'headline 'item)
8005 (list 'org-run-like-in-org-mode (list 'quote fun))
8006 (list 'let '(orgstruct-mode)
8007 (list 'call-interactively
8008 (append '(or)
8009 (mapcar (lambda (k)
8010 (list 'key-binding k))
8011 keys)
8012 '('orgstruct-error))))))))
8014 (defun org-context-p (&rest contexts)
8015 "Check if local context is and of CONTEXTS.
8016 Possible values in the list of contexts are `table', `headline', and `item'."
8017 (let ((pos (point)))
8018 (goto-char (point-at-bol))
8019 (prog1 (or (and (memq 'table contexts)
8020 (looking-at "[ \t]*|"))
8021 (and (memq 'headline contexts)
8022 (looking-at "\\*+"))
8023 (and (memq 'item contexts)
8024 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
8025 (goto-char pos))))
8027 (defun org-get-local-variables ()
8028 "Return a list of all local variables in an org-mode buffer."
8029 (let (varlist)
8030 (with-current-buffer (get-buffer-create "*Org tmp*")
8031 (erase-buffer)
8032 (org-mode)
8033 (setq varlist (buffer-local-variables)))
8034 (kill-buffer "*Org tmp*")
8035 (delq nil
8036 (mapcar
8037 (lambda (x)
8038 (setq x
8039 (if (symbolp x)
8040 (list x)
8041 (list (car x) (list 'quote (cdr x)))))
8042 (if (string-match
8043 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8044 (symbol-name (car x)))
8045 x nil))
8046 varlist))))
8048 ;;;###autoload
8049 (defun org-run-like-in-org-mode (cmd)
8050 (unless org-local-vars
8051 (setq org-local-vars (org-get-local-variables)))
8052 (eval (list 'let org-local-vars
8053 (list 'call-interactively (list 'quote cmd)))))
8055 ;;;; Archiving
8057 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
8059 (defun org-archive-subtree (&optional find-done)
8060 "Move the current subtree to the archive.
8061 The archive can be a certain top-level heading in the current file, or in
8062 a different file. The tree will be moved to that location, the subtree
8063 heading be marked DONE, and the current time will be added.
8065 When called with prefix argument FIND-DONE, find whole trees without any
8066 open TODO items and archive them (after getting confirmation from the user).
8067 If the cursor is not at a headline when this comand is called, try all level
8068 1 trees. If the cursor is on a headline, only try the direct children of
8069 this heading."
8070 (interactive "P")
8071 (if find-done
8072 (org-archive-all-done)
8073 ;; Save all relevant TODO keyword-relatex variables
8075 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
8076 (tr-org-todo-keywords-1 org-todo-keywords-1)
8077 (tr-org-todo-kwd-alist org-todo-kwd-alist)
8078 (tr-org-done-keywords org-done-keywords)
8079 (tr-org-todo-regexp org-todo-regexp)
8080 (tr-org-todo-line-regexp org-todo-line-regexp)
8081 (tr-org-odd-levels-only org-odd-levels-only)
8082 (this-buffer (current-buffer))
8083 (org-archive-location org-archive-location)
8084 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
8085 ;; start of variables that will be used for saving context
8086 ;; The compiler complains about them - keep them anyway!
8087 (file (abbreviate-file-name (buffer-file-name)))
8088 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
8089 (time (format-time-string
8090 (substring (cdr org-time-stamp-formats) 1 -1)
8091 (current-time)))
8092 afile heading buffer level newfile-p
8093 category todo priority
8094 ;; start of variables that will be used for savind context
8095 ltags itags prop)
8097 ;; Try to find a local archive location
8098 (save-excursion
8099 (save-restriction
8100 (widen)
8101 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
8102 (if (and prop (string-match "\\S-" prop))
8103 (setq org-archive-location prop)
8104 (if (or (re-search-backward re nil t)
8105 (re-search-forward re nil t))
8106 (setq org-archive-location (match-string 1))))))
8108 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
8109 (progn
8110 (setq afile (format (match-string 1 org-archive-location)
8111 (file-name-nondirectory buffer-file-name))
8112 heading (match-string 2 org-archive-location)))
8113 (error "Invalid `org-archive-location'"))
8114 (if (> (length afile) 0)
8115 (setq newfile-p (not (file-exists-p afile))
8116 buffer (find-file-noselect afile))
8117 (setq buffer (current-buffer)))
8118 (unless buffer
8119 (error "Cannot access file \"%s\"" afile))
8120 (if (and (> (length heading) 0)
8121 (string-match "^\\*+" heading))
8122 (setq level (match-end 0))
8123 (setq heading nil level 0))
8124 (save-excursion
8125 (org-back-to-heading t)
8126 ;; Get context information that will be lost by moving the tree
8127 (org-refresh-category-properties)
8128 (setq category (org-get-category)
8129 todo (and (looking-at org-todo-line-regexp)
8130 (match-string 2))
8131 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
8132 ltags (org-get-tags)
8133 itags (org-delete-all ltags (org-get-tags-at)))
8134 (setq ltags (mapconcat 'identity ltags " ")
8135 itags (mapconcat 'identity itags " "))
8136 ;; We first only copy, in case something goes wrong
8137 ;; we need to protect this-command, to avoid kill-region sets it,
8138 ;; which would lead to duplication of subtrees
8139 (let (this-command) (org-copy-subtree))
8140 (set-buffer buffer)
8141 ;; Enforce org-mode for the archive buffer
8142 (if (not (org-mode-p))
8143 ;; Force the mode for future visits.
8144 (let ((org-insert-mode-line-in-empty-file t)
8145 (org-inhibit-startup t))
8146 (call-interactively 'org-mode)))
8147 (when newfile-p
8148 (goto-char (point-max))
8149 (insert (format "\nArchived entries from file %s\n\n"
8150 (buffer-file-name this-buffer))))
8151 ;; Force the TODO keywords of the original buffer
8152 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
8153 (org-todo-keywords-1 tr-org-todo-keywords-1)
8154 (org-todo-kwd-alist tr-org-todo-kwd-alist)
8155 (org-done-keywords tr-org-done-keywords)
8156 (org-todo-regexp tr-org-todo-regexp)
8157 (org-todo-line-regexp tr-org-todo-line-regexp)
8158 (org-odd-levels-only
8159 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8160 org-odd-levels-only
8161 tr-org-odd-levels-only)))
8162 (goto-char (point-min))
8163 (show-all)
8164 (if heading
8165 (progn
8166 (if (re-search-forward
8167 (concat "^" (regexp-quote heading)
8168 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8169 nil t)
8170 (goto-char (match-end 0))
8171 ;; Heading not found, just insert it at the end
8172 (goto-char (point-max))
8173 (or (bolp) (insert "\n"))
8174 (insert "\n" heading "\n")
8175 (end-of-line 0))
8176 ;; Make the subtree visible
8177 (show-subtree)
8178 (org-end-of-subtree t)
8179 (skip-chars-backward " \t\r\n")
8180 (and (looking-at "[ \t\r\n]*")
8181 (replace-match "\n\n")))
8182 ;; No specific heading, just go to end of file.
8183 (goto-char (point-max)) (insert "\n"))
8184 ;; Paste
8185 (org-paste-subtree (org-get-legal-level level 1))
8187 ;; Mark the entry as done
8188 (when (and org-archive-mark-done
8189 (looking-at org-todo-line-regexp)
8190 (or (not (match-end 2))
8191 (not (member (match-string 2) org-done-keywords))))
8192 (let (org-log-done org-todo-log-states)
8193 (org-todo
8194 (car (or (member org-archive-mark-done org-done-keywords)
8195 org-done-keywords)))))
8197 ;; Add the context info
8198 (when org-archive-save-context-info
8199 (let ((l org-archive-save-context-info) e n v)
8200 (while (setq e (pop l))
8201 (when (and (setq v (symbol-value e))
8202 (stringp v) (string-match "\\S-" v))
8203 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8204 (org-entry-put (point) n v)))))
8206 ;; Save and kill the buffer, if it is not the same buffer.
8207 (if (not (eq this-buffer buffer))
8208 (progn (save-buffer) (kill-buffer buffer)))))
8209 ;; Here we are back in the original buffer. Everything seems to have
8210 ;; worked. So now cut the tree and finish up.
8211 (let (this-command) (org-cut-subtree))
8212 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8213 (message "Subtree archived %s"
8214 (if (eq this-buffer buffer)
8215 (concat "under heading: " heading)
8216 (concat "in file: " (abbreviate-file-name afile)))))))
8218 (defun org-refresh-category-properties ()
8219 "Refresh category text properties in teh buffer."
8220 (let ((def-cat (cond
8221 ((null org-category)
8222 (if buffer-file-name
8223 (file-name-sans-extension
8224 (file-name-nondirectory buffer-file-name))
8225 "???"))
8226 ((symbolp org-category) (symbol-name org-category))
8227 (t org-category)))
8228 beg end cat pos optionp)
8229 (org-unmodified
8230 (save-excursion
8231 (save-restriction
8232 (widen)
8233 (goto-char (point-min))
8234 (put-text-property (point) (point-max) 'org-category def-cat)
8235 (while (re-search-forward
8236 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8237 (setq pos (match-end 0)
8238 optionp (equal (char-after (match-beginning 0)) ?#)
8239 cat (org-trim (match-string 2)))
8240 (if optionp
8241 (setq beg (point-at-bol) end (point-max))
8242 (org-back-to-heading t)
8243 (setq beg (point) end (org-end-of-subtree t t)))
8244 (put-text-property beg end 'org-category cat)
8245 (goto-char pos)))))))
8247 (defun org-archive-all-done (&optional tag)
8248 "Archive sublevels of the current tree without open TODO items.
8249 If the cursor is not on a headline, try all level 1 trees. If
8250 it is on a headline, try all direct children.
8251 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8252 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8253 (rea (concat ".*:" org-archive-tag ":"))
8254 (begm (make-marker))
8255 (endm (make-marker))
8256 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8257 "Move subtree to archive (no open TODO items)? "))
8258 beg end (cntarch 0))
8259 (if (org-on-heading-p)
8260 (progn
8261 (setq re1 (concat "^" (regexp-quote
8262 (make-string
8263 (1+ (- (match-end 0) (match-beginning 0) 1))
8264 ?*))
8265 " "))
8266 (move-marker begm (point))
8267 (move-marker endm (org-end-of-subtree t)))
8268 (setq re1 "^* ")
8269 (move-marker begm (point-min))
8270 (move-marker endm (point-max)))
8271 (save-excursion
8272 (goto-char begm)
8273 (while (re-search-forward re1 endm t)
8274 (setq beg (match-beginning 0)
8275 end (save-excursion (org-end-of-subtree t) (point)))
8276 (goto-char beg)
8277 (if (re-search-forward re end t)
8278 (goto-char end)
8279 (goto-char beg)
8280 (if (and (or (not tag) (not (looking-at rea)))
8281 (y-or-n-p question))
8282 (progn
8283 (if tag
8284 (org-toggle-tag org-archive-tag 'on)
8285 (org-archive-subtree))
8286 (setq cntarch (1+ cntarch)))
8287 (goto-char end)))))
8288 (message "%d trees archived" cntarch)))
8290 (defun org-cycle-hide-drawers (state)
8291 "Re-hide all drawers after a visibility state change."
8292 (when (and (org-mode-p)
8293 (not (memq state '(overview folded))))
8294 (save-excursion
8295 (let* ((globalp (memq state '(contents all)))
8296 (beg (if globalp (point-min) (point)))
8297 (end (if globalp (point-max) (org-end-of-subtree t))))
8298 (goto-char beg)
8299 (while (re-search-forward org-drawer-regexp end t)
8300 (org-flag-drawer t))))))
8302 (defun org-flag-drawer (flag)
8303 (save-excursion
8304 (beginning-of-line 1)
8305 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8306 (let ((b (match-end 0))
8307 (outline-regexp org-outline-regexp))
8308 (if (re-search-forward
8309 "^[ \t]*:END:"
8310 (save-excursion (outline-next-heading) (point)) t)
8311 (outline-flag-region b (point-at-eol) flag)
8312 (error ":END: line missing"))))))
8314 (defun org-cycle-hide-archived-subtrees (state)
8315 "Re-hide all archived subtrees after a visibility state change."
8316 (when (and (not org-cycle-open-archived-trees)
8317 (not (memq state '(overview folded))))
8318 (save-excursion
8319 (let* ((globalp (memq state '(contents all)))
8320 (beg (if globalp (point-min) (point)))
8321 (end (if globalp (point-max) (org-end-of-subtree t))))
8322 (org-hide-archived-subtrees beg end)
8323 (goto-char beg)
8324 (if (looking-at (concat ".*:" org-archive-tag ":"))
8325 (message "%s" (substitute-command-keys
8326 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8328 (defun org-force-cycle-archived ()
8329 "Cycle subtree even if it is archived."
8330 (interactive)
8331 (setq this-command 'org-cycle)
8332 (let ((org-cycle-open-archived-trees t))
8333 (call-interactively 'org-cycle)))
8335 (defun org-hide-archived-subtrees (beg end)
8336 "Re-hide all archived subtrees after a visibility state change."
8337 (save-excursion
8338 (let* ((re (concat ":" org-archive-tag ":")))
8339 (goto-char beg)
8340 (while (re-search-forward re end t)
8341 (and (org-on-heading-p) (hide-subtree))
8342 (org-end-of-subtree t)))))
8344 (defun org-toggle-tag (tag &optional onoff)
8345 "Toggle the tag TAG for the current line.
8346 If ONOFF is `on' or `off', don't toggle but set to this state."
8347 (unless (org-on-heading-p t) (error "Not on headling"))
8348 (let (res current)
8349 (save-excursion
8350 (beginning-of-line)
8351 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8352 (point-at-eol) t)
8353 (progn
8354 (setq current (match-string 1))
8355 (replace-match ""))
8356 (setq current ""))
8357 (setq current (nreverse (org-split-string current ":")))
8358 (cond
8359 ((eq onoff 'on)
8360 (setq res t)
8361 (or (member tag current) (push tag current)))
8362 ((eq onoff 'off)
8363 (or (not (member tag current)) (setq current (delete tag current))))
8364 (t (if (member tag current)
8365 (setq current (delete tag current))
8366 (setq res t)
8367 (push tag current))))
8368 (end-of-line 1)
8369 (if current
8370 (progn
8371 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8372 (org-set-tags nil t))
8373 (delete-horizontal-space))
8374 (run-hooks 'org-after-tags-change-hook))
8375 res))
8377 (defun org-toggle-archive-tag (&optional arg)
8378 "Toggle the archive tag for the current headline.
8379 With prefix ARG, check all children of current headline and offer tagging
8380 the children that do not contain any open TODO items."
8381 (interactive "P")
8382 (if arg
8383 (org-archive-all-done 'tag)
8384 (let (set)
8385 (save-excursion
8386 (org-back-to-heading t)
8387 (setq set (org-toggle-tag org-archive-tag))
8388 (when set (hide-subtree)))
8389 (and set (beginning-of-line 1))
8390 (message "Subtree %s" (if set "archived" "unarchived")))))
8393 ;;;; Tables
8395 ;;; The table editor
8397 ;; Watch out: Here we are talking about two different kind of tables.
8398 ;; Most of the code is for the tables created with the Org-mode table editor.
8399 ;; Sometimes, we talk about tables created and edited with the table.el
8400 ;; Emacs package. We call the former org-type tables, and the latter
8401 ;; table.el-type tables.
8403 (defun org-before-change-function (beg end)
8404 "Every change indicates that a table might need an update."
8405 (setq org-table-may-need-update t))
8407 (defconst org-table-line-regexp "^[ \t]*|"
8408 "Detects an org-type table line.")
8409 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8410 "Detects an org-type table line.")
8411 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8412 "Detects a table line marked for automatic recalculation.")
8413 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8414 "Detects a table line marked for automatic recalculation.")
8415 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8416 "Detects a table line marked for automatic recalculation.")
8417 (defconst org-table-hline-regexp "^[ \t]*|-"
8418 "Detects an org-type table hline.")
8419 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8420 "Detects a table-type table hline.")
8421 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8422 "Detects an org-type or table-type table.")
8423 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8424 "Searching from within a table (any type) this finds the first line
8425 outside the table.")
8426 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8427 "Searching from within a table (any type) this finds the first line
8428 outside the table.")
8430 (defvar org-table-last-highlighted-reference nil)
8431 (defvar org-table-formula-history nil)
8433 (defvar org-table-column-names nil
8434 "Alist with column names, derived from the `!' line.")
8435 (defvar org-table-column-name-regexp nil
8436 "Regular expression matching the current column names.")
8437 (defvar org-table-local-parameters nil
8438 "Alist with parameter names, derived from the `$' line.")
8439 (defvar org-table-named-field-locations nil
8440 "Alist with locations of named fields.")
8442 (defvar org-table-current-line-types nil
8443 "Table row types, non-nil only for the duration of a comand.")
8444 (defvar org-table-current-begin-line nil
8445 "Table begin line, non-nil only for the duration of a comand.")
8446 (defvar org-table-current-begin-pos nil
8447 "Table begin position, non-nil only for the duration of a comand.")
8448 (defvar org-table-dlines nil
8449 "Vector of data line line numbers in the current table.")
8450 (defvar org-table-hlines nil
8451 "Vector of hline line numbers in the current table.")
8453 (defconst org-table-range-regexp
8454 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8455 ;; 1 2 3 4 5
8456 "Regular expression for matching ranges in formulas.")
8458 (defconst org-table-range-regexp2
8459 (concat
8460 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8461 "\\.\\."
8462 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8463 "Match a range for reference display.")
8465 (defconst org-table-translate-regexp
8466 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8467 "Match a reference that needs translation, for reference display.")
8469 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8471 (defun org-table-create-with-table.el ()
8472 "Use the table.el package to insert a new table.
8473 If there is already a table at point, convert between Org-mode tables
8474 and table.el tables."
8475 (interactive)
8476 (require 'table)
8477 (cond
8478 ((org-at-table.el-p)
8479 (if (y-or-n-p "Convert table to Org-mode table? ")
8480 (org-table-convert)))
8481 ((org-at-table-p)
8482 (if (y-or-n-p "Convert table to table.el table? ")
8483 (org-table-convert)))
8484 (t (call-interactively 'table-insert))))
8486 (defun org-table-create-or-convert-from-region (arg)
8487 "Convert region to table, or create an empty table.
8488 If there is an active region, convert it to a table, using the function
8489 `org-table-convert-region'. See the documentation of that function
8490 to learn how the prefix argument is interpreted to determine the field
8491 separator.
8492 If there is no such region, create an empty table with `org-table-create'."
8493 (interactive "P")
8494 (if (org-region-active-p)
8495 (org-table-convert-region (region-beginning) (region-end) arg)
8496 (org-table-create arg)))
8498 (defun org-table-create (&optional size)
8499 "Query for a size and insert a table skeleton.
8500 SIZE is a string Columns x Rows like for example \"3x2\"."
8501 (interactive "P")
8502 (unless size
8503 (setq size (read-string
8504 (concat "Table size Columns x Rows [e.g. "
8505 org-table-default-size "]: ")
8506 "" nil org-table-default-size)))
8508 (let* ((pos (point))
8509 (indent (make-string (current-column) ?\ ))
8510 (split (org-split-string size " *x *"))
8511 (rows (string-to-number (nth 1 split)))
8512 (columns (string-to-number (car split)))
8513 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8514 "\n")))
8515 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8516 (point-at-bol) (point)))
8517 (beginning-of-line 1)
8518 (newline))
8519 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8520 (dotimes (i rows) (insert line))
8521 (goto-char pos)
8522 (if (> rows 1)
8523 ;; Insert a hline after the first row.
8524 (progn
8525 (end-of-line 1)
8526 (insert "\n|-")
8527 (goto-char pos)))
8528 (org-table-align)))
8530 (defun org-table-convert-region (beg0 end0 &optional separator)
8531 "Convert region to a table.
8532 The region goes from BEG0 to END0, but these borders will be moved
8533 slightly, to make sure a beginning of line in the first line is included.
8535 SEPARATOR specifies the field separator in the lines. It can have the
8536 following values:
8538 '(4) Use the comma as a field separator
8539 '(16) Use a TAB as field separator
8540 integer When a number, use that many spaces as field separator
8541 nil When nil, the command tries to be smart and figure out the
8542 separator in the following way:
8543 - when each line contains a TAB, assume TAB-separated material
8544 - when each line contains a comme, assume CSV material
8545 - else, assume one or more SPACE charcters as separator."
8546 (interactive "rP")
8547 (let* ((beg (min beg0 end0))
8548 (end (max beg0 end0))
8550 (goto-char beg)
8551 (beginning-of-line 1)
8552 (setq beg (move-marker (make-marker) (point)))
8553 (goto-char end)
8554 (if (bolp) (backward-char 1) (end-of-line 1))
8555 (setq end (move-marker (make-marker) (point)))
8556 ;; Get the right field separator
8557 (unless separator
8558 (goto-char beg)
8559 (setq separator
8560 (cond
8561 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8562 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8563 (t 1))))
8564 (setq re (cond
8565 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8566 ((equal separator '(16)) "^\\|\t")
8567 ((integerp separator)
8568 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8569 (t (error "This should not happen"))))
8570 (goto-char beg)
8571 (while (re-search-forward re end t)
8572 (replace-match "| " t t))
8573 (goto-char beg)
8574 (insert " ")
8575 (org-table-align)))
8577 (defun org-table-import (file arg)
8578 "Import FILE as a table.
8579 The file is assumed to be tab-separated. Such files can be produced by most
8580 spreadsheet and database applications. If no tabs (at least one per line)
8581 are found, lines will be split on whitespace into fields."
8582 (interactive "f\nP")
8583 (or (bolp) (newline))
8584 (let ((beg (point))
8585 (pm (point-max)))
8586 (insert-file-contents file)
8587 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8589 (defun org-table-export ()
8590 "Export table as a tab-separated file.
8591 Such a file can be imported into a spreadsheet program like Excel."
8592 (interactive)
8593 (let* ((beg (org-table-begin))
8594 (end (org-table-end))
8595 (table (buffer-substring beg end))
8596 (file (read-file-name "Export table to: "))
8597 buf)
8598 (unless (or (not (file-exists-p file))
8599 (y-or-n-p (format "Overwrite file %s? " file)))
8600 (error "Abort"))
8601 (with-current-buffer (find-file-noselect file)
8602 (setq buf (current-buffer))
8603 (erase-buffer)
8604 (fundamental-mode)
8605 (insert table)
8606 (goto-char (point-min))
8607 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8608 (replace-match "" t t)
8609 (end-of-line 1))
8610 (goto-char (point-min))
8611 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8612 (replace-match "" t t)
8613 (goto-char (min (1+ (point)) (point-max))))
8614 (goto-char (point-min))
8615 (while (re-search-forward "^-[-+]*$" nil t)
8616 (replace-match "")
8617 (if (looking-at "\n")
8618 (delete-char 1)))
8619 (goto-char (point-min))
8620 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8621 (replace-match "\t" t t))
8622 (save-buffer))
8623 (kill-buffer buf)))
8625 (defvar org-table-aligned-begin-marker (make-marker)
8626 "Marker at the beginning of the table last aligned.
8627 Used to check if cursor still is in that table, to minimize realignment.")
8628 (defvar org-table-aligned-end-marker (make-marker)
8629 "Marker at the end of the table last aligned.
8630 Used to check if cursor still is in that table, to minimize realignment.")
8631 (defvar org-table-last-alignment nil
8632 "List of flags for flushright alignment, from the last re-alignment.
8633 This is being used to correctly align a single field after TAB or RET.")
8634 (defvar org-table-last-column-widths nil
8635 "List of max width of fields in each column.
8636 This is being used to correctly align a single field after TAB or RET.")
8637 (defvar org-table-overlay-coordinates nil
8638 "Overlay coordinates after each align of a table.")
8639 (make-variable-buffer-local 'org-table-overlay-coordinates)
8641 (defvar org-last-recalc-line nil)
8642 (defconst org-narrow-column-arrow "=>"
8643 "Used as display property in narrowed table columns.")
8645 (defun org-table-align ()
8646 "Align the table at point by aligning all vertical bars."
8647 (interactive)
8648 (let* (
8649 ;; Limits of table
8650 (beg (org-table-begin))
8651 (end (org-table-end))
8652 ;; Current cursor position
8653 (linepos (org-current-line))
8654 (colpos (org-table-current-column))
8655 (winstart (window-start))
8656 (winstartline (org-current-line (min winstart (1- (point-max)))))
8657 lines (new "") lengths l typenums ty fields maxfields i
8658 column
8659 (indent "") cnt frac
8660 rfmt hfmt
8661 (spaces '(1 . 1))
8662 (sp1 (car spaces))
8663 (sp2 (cdr spaces))
8664 (rfmt1 (concat
8665 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8666 (hfmt1 (concat
8667 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8668 emptystrings links dates emph narrow fmax f1 len c e)
8669 (untabify beg end)
8670 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8671 ;; Check if we have links or dates
8672 (goto-char beg)
8673 (setq links (re-search-forward org-bracket-link-regexp end t))
8674 (goto-char beg)
8675 (setq emph (and org-hide-emphasis-markers
8676 (re-search-forward org-emph-re end t)))
8677 (goto-char beg)
8678 (setq dates (and org-display-custom-times
8679 (re-search-forward org-ts-regexp-both end t)))
8680 ;; Make sure the link properties are right
8681 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8682 ;; Make sure the date properties are right
8683 (when dates (goto-char beg) (while (org-activate-dates end)))
8684 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8686 ;; Check if we are narrowing any columns
8687 (goto-char beg)
8688 (setq narrow (and org-format-transports-properties-p
8689 (re-search-forward "<[0-9]+>" end t)))
8690 ;; Get the rows
8691 (setq lines (org-split-string
8692 (buffer-substring beg end) "\n"))
8693 ;; Store the indentation of the first line
8694 (if (string-match "^ *" (car lines))
8695 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8696 ;; Mark the hlines by setting the corresponding element to nil
8697 ;; At the same time, we remove trailing space.
8698 (setq lines (mapcar (lambda (l)
8699 (if (string-match "^ *|-" l)
8701 (if (string-match "[ \t]+$" l)
8702 (substring l 0 (match-beginning 0))
8703 l)))
8704 lines))
8705 ;; Get the data fields by splitting the lines.
8706 (setq fields (mapcar
8707 (lambda (l)
8708 (org-split-string l " *| *"))
8709 (delq nil (copy-sequence lines))))
8710 ;; How many fields in the longest line?
8711 (condition-case nil
8712 (setq maxfields (apply 'max (mapcar 'length fields)))
8713 (error
8714 (kill-region beg end)
8715 (org-table-create org-table-default-size)
8716 (error "Empty table - created default table")))
8717 ;; A list of empty strings to fill any short rows on output
8718 (setq emptystrings (make-list maxfields ""))
8719 ;; Check for special formatting.
8720 (setq i -1)
8721 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8722 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8723 ;; Check if there is an explicit width specified
8724 (when narrow
8725 (setq c column fmax nil)
8726 (while c
8727 (setq e (pop c))
8728 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8729 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8730 ;; Find fields that are wider than fmax, and shorten them
8731 (when fmax
8732 (loop for xx in column do
8733 (when (and (stringp xx)
8734 (> (org-string-width xx) fmax))
8735 (org-add-props xx nil
8736 'help-echo
8737 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8738 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8739 (unless (> f1 1)
8740 (error "Cannot narrow field starting with wide link \"%s\""
8741 (match-string 0 xx)))
8742 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8743 (add-text-properties (- f1 2) f1
8744 (list 'display org-narrow-column-arrow)
8745 xx)))))
8746 ;; Get the maximum width for each column
8747 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8748 ;; Get the fraction of numbers, to decide about alignment of the column
8749 (setq cnt 0 frac 0.0)
8750 (loop for x in column do
8751 (if (equal x "")
8753 (setq frac ( / (+ (* frac cnt)
8754 (if (string-match org-table-number-regexp x) 1 0))
8755 (setq cnt (1+ cnt))))))
8756 (push (>= frac org-table-number-fraction) typenums))
8757 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8759 ;; Store the alignment of this table, for later editing of single fields
8760 (setq org-table-last-alignment typenums
8761 org-table-last-column-widths lengths)
8763 ;; With invisible characters, `format' does not get the field width right
8764 ;; So we need to make these fields wide by hand.
8765 (when (or links emph)
8766 (loop for i from 0 upto (1- maxfields) do
8767 (setq len (nth i lengths))
8768 (loop for j from 0 upto (1- (length fields)) do
8769 (setq c (nthcdr i (car (nthcdr j fields))))
8770 (if (and (stringp (car c))
8771 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8772 ; (string-match org-bracket-link-regexp (car c))
8773 (< (org-string-width (car c)) len))
8774 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8776 ;; Compute the formats needed for output of the table
8777 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8778 (while (setq l (pop lengths))
8779 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8780 (setq rfmt (concat rfmt (format rfmt1 ty l))
8781 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8782 (setq rfmt (concat rfmt "\n")
8783 hfmt (concat (substring hfmt 0 -1) "|\n"))
8785 (setq new (mapconcat
8786 (lambda (l)
8787 (if l (apply 'format rfmt
8788 (append (pop fields) emptystrings))
8789 hfmt))
8790 lines ""))
8791 ;; Replace the old one
8792 (delete-region beg end)
8793 (move-marker end nil)
8794 (move-marker org-table-aligned-begin-marker (point))
8795 (insert new)
8796 (move-marker org-table-aligned-end-marker (point))
8797 (when (and orgtbl-mode (not (org-mode-p)))
8798 (goto-char org-table-aligned-begin-marker)
8799 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8800 ;; Try to move to the old location
8801 (goto-line winstartline)
8802 (setq winstart (point-at-bol))
8803 (goto-line linepos)
8804 (set-window-start (selected-window) winstart 'noforce)
8805 (org-table-goto-column colpos)
8806 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8807 (setq org-table-may-need-update nil)
8810 (defun org-string-width (s)
8811 "Compute width of string, ignoring invisible characters.
8812 This ignores character with invisibility property `org-link', and also
8813 characters with property `org-cwidth', because these will become invisible
8814 upon the next fontification round."
8815 (let (b l)
8816 (when (or (eq t buffer-invisibility-spec)
8817 (assq 'org-link buffer-invisibility-spec))
8818 (while (setq b (text-property-any 0 (length s)
8819 'invisible 'org-link s))
8820 (setq s (concat (substring s 0 b)
8821 (substring s (or (next-single-property-change
8822 b 'invisible s) (length s)))))))
8823 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8824 (setq s (concat (substring s 0 b)
8825 (substring s (or (next-single-property-change
8826 b 'org-cwidth s) (length s))))))
8827 (setq l (string-width s) b -1)
8828 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8829 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8832 (defun org-table-begin (&optional table-type)
8833 "Find the beginning of the table and return its position.
8834 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8835 (save-excursion
8836 (if (not (re-search-backward
8837 (if table-type org-table-any-border-regexp
8838 org-table-border-regexp)
8839 nil t))
8840 (progn (goto-char (point-min)) (point))
8841 (goto-char (match-beginning 0))
8842 (beginning-of-line 2)
8843 (point))))
8845 (defun org-table-end (&optional table-type)
8846 "Find the end of the table and return its position.
8847 With argument TABLE-TYPE, go to the end of a table.el-type table."
8848 (save-excursion
8849 (if (not (re-search-forward
8850 (if table-type org-table-any-border-regexp
8851 org-table-border-regexp)
8852 nil t))
8853 (goto-char (point-max))
8854 (goto-char (match-beginning 0)))
8855 (point-marker)))
8857 (defun org-table-justify-field-maybe (&optional new)
8858 "Justify the current field, text to left, number to right.
8859 Optional argument NEW may specify text to replace the current field content."
8860 (cond
8861 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8862 ((org-at-table-hline-p))
8863 ((and (not new)
8864 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8865 (current-buffer)))
8866 (< (point) org-table-aligned-begin-marker)
8867 (>= (point) org-table-aligned-end-marker)))
8868 ;; This is not the same table, force a full re-align
8869 (setq org-table-may-need-update t))
8870 (t ;; realign the current field, based on previous full realign
8871 (let* ((pos (point)) s
8872 (col (org-table-current-column))
8873 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8874 l f n o e)
8875 (when (> col 0)
8876 (skip-chars-backward "^|\n")
8877 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8878 (progn
8879 (setq s (match-string 1)
8880 o (match-string 0)
8881 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8882 e (not (= (match-beginning 2) (match-end 2))))
8883 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8884 l (if e "|" (setq org-table-may-need-update t) ""))
8885 n (format f s))
8886 (if new
8887 (if (<= (length new) l) ;; FIXME: length -> str-width?
8888 (setq n (format f new))
8889 (setq n (concat new "|") org-table-may-need-update t)))
8890 (or (equal n o)
8891 (let (org-table-may-need-update)
8892 (replace-match n t t))))
8893 (setq org-table-may-need-update t))
8894 (goto-char pos))))))
8896 (defun org-table-next-field ()
8897 "Go to the next field in the current table, creating new lines as needed.
8898 Before doing so, re-align the table if necessary."
8899 (interactive)
8900 (org-table-maybe-eval-formula)
8901 (org-table-maybe-recalculate-line)
8902 (if (and org-table-automatic-realign
8903 org-table-may-need-update)
8904 (org-table-align))
8905 (let ((end (org-table-end)))
8906 (if (org-at-table-hline-p)
8907 (end-of-line 1))
8908 (condition-case nil
8909 (progn
8910 (re-search-forward "|" end)
8911 (if (looking-at "[ \t]*$")
8912 (re-search-forward "|" end))
8913 (if (and (looking-at "-")
8914 org-table-tab-jumps-over-hlines
8915 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8916 (goto-char (match-beginning 1)))
8917 (if (looking-at "-")
8918 (progn
8919 (beginning-of-line 0)
8920 (org-table-insert-row 'below))
8921 (if (looking-at " ") (forward-char 1))))
8922 (error
8923 (org-table-insert-row 'below)))))
8925 (defun org-table-previous-field ()
8926 "Go to the previous field in the table.
8927 Before doing so, re-align the table if necessary."
8928 (interactive)
8929 (org-table-justify-field-maybe)
8930 (org-table-maybe-recalculate-line)
8931 (if (and org-table-automatic-realign
8932 org-table-may-need-update)
8933 (org-table-align))
8934 (if (org-at-table-hline-p)
8935 (end-of-line 1))
8936 (re-search-backward "|" (org-table-begin))
8937 (re-search-backward "|" (org-table-begin))
8938 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8939 (re-search-backward "|" (org-table-begin)))
8940 (if (looking-at "| ?")
8941 (goto-char (match-end 0))))
8943 (defun org-table-next-row ()
8944 "Go to the next row (same column) in the current table.
8945 Before doing so, re-align the table if necessary."
8946 (interactive)
8947 (org-table-maybe-eval-formula)
8948 (org-table-maybe-recalculate-line)
8949 (if (or (looking-at "[ \t]*$")
8950 (save-excursion (skip-chars-backward " \t") (bolp)))
8951 (newline)
8952 (if (and org-table-automatic-realign
8953 org-table-may-need-update)
8954 (org-table-align))
8955 (let ((col (org-table-current-column)))
8956 (beginning-of-line 2)
8957 (if (or (not (org-at-table-p))
8958 (org-at-table-hline-p))
8959 (progn
8960 (beginning-of-line 0)
8961 (org-table-insert-row 'below)))
8962 (org-table-goto-column col)
8963 (skip-chars-backward "^|\n\r")
8964 (if (looking-at " ") (forward-char 1)))))
8966 (defun org-table-copy-down (n)
8967 "Copy a field down in the current column.
8968 If the field at the cursor is empty, copy into it the content of the nearest
8969 non-empty field above. With argument N, use the Nth non-empty field.
8970 If the current field is not empty, it is copied down to the next row, and
8971 the cursor is moved with it. Therefore, repeating this command causes the
8972 column to be filled row-by-row.
8973 If the variable `org-table-copy-increment' is non-nil and the field is an
8974 integer or a timestamp, it will be incremented while copying. In the case of
8975 a timestamp, if the cursor is on the year, change the year. If it is on the
8976 month or the day, change that. Point will stay on the current date field
8977 in order to easily repeat the interval."
8978 (interactive "p")
8979 (let* ((colpos (org-table-current-column))
8980 (col (current-column))
8981 (field (org-table-get-field))
8982 (non-empty (string-match "[^ \t]" field))
8983 (beg (org-table-begin))
8984 txt)
8985 (org-table-check-inside-data-field)
8986 (if non-empty
8987 (progn
8988 (setq txt (org-trim field))
8989 (org-table-next-row)
8990 (org-table-blank-field))
8991 (save-excursion
8992 (setq txt
8993 (catch 'exit
8994 (while (progn (beginning-of-line 1)
8995 (re-search-backward org-table-dataline-regexp
8996 beg t))
8997 (org-table-goto-column colpos t)
8998 (if (and (looking-at
8999 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
9000 (= (setq n (1- n)) 0))
9001 (throw 'exit (match-string 1))))))))
9002 (if txt
9003 (progn
9004 (if (and org-table-copy-increment
9005 (string-match "^[0-9]+$" txt))
9006 (setq txt (format "%d" (+ (string-to-number txt) 1))))
9007 (insert txt)
9008 (move-to-column col)
9009 (if (and org-table-copy-increment (org-at-timestamp-p t))
9010 (org-timestamp-up 1)
9011 (org-table-maybe-recalculate-line))
9012 (org-table-align)
9013 (move-to-column col))
9014 (error "No non-empty field found"))))
9016 (defun org-table-check-inside-data-field ()
9017 "Is point inside a table data field?
9018 I.e. not on a hline or before the first or after the last column?
9019 This actually throws an error, so it aborts the current command."
9020 (if (or (not (org-at-table-p))
9021 (= (org-table-current-column) 0)
9022 (org-at-table-hline-p)
9023 (looking-at "[ \t]*$"))
9024 (error "Not in table data field")))
9026 (defvar org-table-clip nil
9027 "Clipboard for table regions.")
9029 (defun org-table-blank-field ()
9030 "Blank the current table field or active region."
9031 (interactive)
9032 (org-table-check-inside-data-field)
9033 (if (and (interactive-p) (org-region-active-p))
9034 (let (org-table-clip)
9035 (org-table-cut-region (region-beginning) (region-end)))
9036 (skip-chars-backward "^|")
9037 (backward-char 1)
9038 (if (looking-at "|[^|\n]+")
9039 (let* ((pos (match-beginning 0))
9040 (match (match-string 0))
9041 (len (org-string-width match)))
9042 (replace-match (concat "|" (make-string (1- len) ?\ )))
9043 (goto-char (+ 2 pos))
9044 (substring match 1)))))
9046 (defun org-table-get-field (&optional n replace)
9047 "Return the value of the field in column N of current row.
9048 N defaults to current field.
9049 If REPLACE is a string, replace field with this value. The return value
9050 is always the old value."
9051 (and n (org-table-goto-column n))
9052 (skip-chars-backward "^|\n")
9053 (backward-char 1)
9054 (if (looking-at "|[^|\r\n]*")
9055 (let* ((pos (match-beginning 0))
9056 (val (buffer-substring (1+ pos) (match-end 0))))
9057 (if replace
9058 (replace-match (concat "|" replace) t t))
9059 (goto-char (min (point-at-eol) (+ 2 pos)))
9060 val)
9061 (forward-char 1) ""))
9063 (defun org-table-field-info (arg)
9064 "Show info about the current field, and highlight any reference at point."
9065 (interactive "P")
9066 (org-table-get-specials)
9067 (save-excursion
9068 (let* ((pos (point))
9069 (col (org-table-current-column))
9070 (cname (car (rassoc (int-to-string col) org-table-column-names)))
9071 (name (car (rassoc (list (org-current-line) col)
9072 org-table-named-field-locations)))
9073 (eql (org-table-get-stored-formulas))
9074 (dline (org-table-current-dline))
9075 (ref (format "@%d$%d" dline col))
9076 (ref1 (org-table-convert-refs-to-an ref))
9077 (fequation (or (assoc name eql) (assoc ref eql)))
9078 (cequation (assoc (int-to-string col) eql))
9079 (eqn (or fequation cequation)))
9080 (goto-char pos)
9081 (condition-case nil
9082 (org-table-show-reference 'local)
9083 (error nil))
9084 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
9085 dline col
9086 (if cname (concat " or $" cname) "")
9087 dline col ref1
9088 (if name (concat " or $" name) "")
9089 ;; FIXME: formula info not correct if special table line
9090 (if eqn
9091 (concat ", formula: "
9092 (org-table-formula-to-user
9093 (concat
9094 (if (string-match "^[$@]"(car eqn)) "" "$")
9095 (car eqn) "=" (cdr eqn))))
9096 "")))))
9098 (defun org-table-current-column ()
9099 "Find out which column we are in.
9100 When called interactively, column is also displayed in echo area."
9101 (interactive)
9102 (if (interactive-p) (org-table-check-inside-data-field))
9103 (save-excursion
9104 (let ((cnt 0) (pos (point)))
9105 (beginning-of-line 1)
9106 (while (search-forward "|" pos t)
9107 (setq cnt (1+ cnt)))
9108 (if (interactive-p) (message "This is table column %d" cnt))
9109 cnt)))
9111 (defun org-table-current-dline ()
9112 "Find out what table data line we are in.
9113 Only datalins count for this."
9114 (interactive)
9115 (if (interactive-p) (org-table-check-inside-data-field))
9116 (save-excursion
9117 (let ((cnt 0) (pos (point)))
9118 (goto-char (org-table-begin))
9119 (while (<= (point) pos)
9120 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
9121 (beginning-of-line 2))
9122 (if (interactive-p) (message "This is table line %d" cnt))
9123 cnt)))
9125 (defun org-table-goto-column (n &optional on-delim force)
9126 "Move the cursor to the Nth column in the current table line.
9127 With optional argument ON-DELIM, stop with point before the left delimiter
9128 of the field.
9129 If there are less than N fields, just go to after the last delimiter.
9130 However, when FORCE is non-nil, create new columns if necessary."
9131 (interactive "p")
9132 (let ((pos (point-at-eol)))
9133 (beginning-of-line 1)
9134 (when (> n 0)
9135 (while (and (> (setq n (1- n)) -1)
9136 (or (search-forward "|" pos t)
9137 (and force
9138 (progn (end-of-line 1)
9139 (skip-chars-backward "^|")
9140 (insert " | "))))))
9141 ; (backward-char 2) t)))))
9142 (when (and force (not (looking-at ".*|")))
9143 (save-excursion (end-of-line 1) (insert " | ")))
9144 (if on-delim
9145 (backward-char 1)
9146 (if (looking-at " ") (forward-char 1))))))
9148 (defun org-at-table-p (&optional table-type)
9149 "Return t if the cursor is inside an org-type table.
9150 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9151 (if org-enable-table-editor
9152 (save-excursion
9153 (beginning-of-line 1)
9154 (looking-at (if table-type org-table-any-line-regexp
9155 org-table-line-regexp)))
9156 nil))
9158 (defun org-at-table.el-p ()
9159 "Return t if and only if we are at a table.el table."
9160 (and (org-at-table-p 'any)
9161 (save-excursion
9162 (goto-char (org-table-begin 'any))
9163 (looking-at org-table1-hline-regexp))))
9165 (defun org-table-recognize-table.el ()
9166 "If there is a table.el table nearby, recognize it and move into it."
9167 (if org-table-tab-recognizes-table.el
9168 (if (org-at-table.el-p)
9169 (progn
9170 (beginning-of-line 1)
9171 (if (looking-at org-table-dataline-regexp)
9173 (if (looking-at org-table1-hline-regexp)
9174 (progn
9175 (beginning-of-line 2)
9176 (if (looking-at org-table-any-border-regexp)
9177 (beginning-of-line -1)))))
9178 (if (re-search-forward "|" (org-table-end t) t)
9179 (progn
9180 (require 'table)
9181 (if (table--at-cell-p (point))
9183 (message "recognizing table.el table...")
9184 (table-recognize-table)
9185 (message "recognizing table.el table...done")))
9186 (error "This should not happen..."))
9188 nil)
9189 nil))
9191 (defun org-at-table-hline-p ()
9192 "Return t if the cursor is inside a hline in a table."
9193 (if org-enable-table-editor
9194 (save-excursion
9195 (beginning-of-line 1)
9196 (looking-at org-table-hline-regexp))
9197 nil))
9199 (defun org-table-insert-column ()
9200 "Insert a new column into the table."
9201 (interactive)
9202 (if (not (org-at-table-p))
9203 (error "Not at a table"))
9204 (org-table-find-dataline)
9205 (let* ((col (max 1 (org-table-current-column)))
9206 (beg (org-table-begin))
9207 (end (org-table-end))
9208 ;; Current cursor position
9209 (linepos (org-current-line))
9210 (colpos col))
9211 (goto-char beg)
9212 (while (< (point) end)
9213 (if (org-at-table-hline-p)
9215 (org-table-goto-column col t)
9216 (insert "| "))
9217 (beginning-of-line 2))
9218 (move-marker end nil)
9219 (goto-line linepos)
9220 (org-table-goto-column colpos)
9221 (org-table-align)
9222 (org-table-fix-formulas "$" nil (1- col) 1)))
9224 (defun org-table-find-dataline ()
9225 "Find a dataline in the current table, which is needed for column commands."
9226 (if (and (org-at-table-p)
9227 (not (org-at-table-hline-p)))
9229 (let ((col (current-column))
9230 (end (org-table-end)))
9231 (move-to-column col)
9232 (while (and (< (point) end)
9233 (or (not (= (current-column) col))
9234 (org-at-table-hline-p)))
9235 (beginning-of-line 2)
9236 (move-to-column col))
9237 (if (and (org-at-table-p)
9238 (not (org-at-table-hline-p)))
9240 (error
9241 "Please position cursor in a data line for column operations")))))
9243 (defun org-table-delete-column ()
9244 "Delete a column from the table."
9245 (interactive)
9246 (if (not (org-at-table-p))
9247 (error "Not at a table"))
9248 (org-table-find-dataline)
9249 (org-table-check-inside-data-field)
9250 (let* ((col (org-table-current-column))
9251 (beg (org-table-begin))
9252 (end (org-table-end))
9253 ;; Current cursor position
9254 (linepos (org-current-line))
9255 (colpos col))
9256 (goto-char beg)
9257 (while (< (point) end)
9258 (if (org-at-table-hline-p)
9260 (org-table-goto-column col t)
9261 (and (looking-at "|[^|\n]+|")
9262 (replace-match "|")))
9263 (beginning-of-line 2))
9264 (move-marker end nil)
9265 (goto-line linepos)
9266 (org-table-goto-column colpos)
9267 (org-table-align)
9268 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9269 col -1 col)))
9271 (defun org-table-move-column-right ()
9272 "Move column to the right."
9273 (interactive)
9274 (org-table-move-column nil))
9275 (defun org-table-move-column-left ()
9276 "Move column to the left."
9277 (interactive)
9278 (org-table-move-column 'left))
9280 (defun org-table-move-column (&optional left)
9281 "Move the current column to the right. With arg LEFT, move to the left."
9282 (interactive "P")
9283 (if (not (org-at-table-p))
9284 (error "Not at a table"))
9285 (org-table-find-dataline)
9286 (org-table-check-inside-data-field)
9287 (let* ((col (org-table-current-column))
9288 (col1 (if left (1- col) col))
9289 (beg (org-table-begin))
9290 (end (org-table-end))
9291 ;; Current cursor position
9292 (linepos (org-current-line))
9293 (colpos (if left (1- col) (1+ col))))
9294 (if (and left (= col 1))
9295 (error "Cannot move column further left"))
9296 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9297 (error "Cannot move column further right"))
9298 (goto-char beg)
9299 (while (< (point) end)
9300 (if (org-at-table-hline-p)
9302 (org-table-goto-column col1 t)
9303 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9304 (replace-match "|\\2|\\1|")))
9305 (beginning-of-line 2))
9306 (move-marker end nil)
9307 (goto-line linepos)
9308 (org-table-goto-column colpos)
9309 (org-table-align)
9310 (org-table-fix-formulas
9311 "$" (list (cons (number-to-string col) (number-to-string colpos))
9312 (cons (number-to-string colpos) (number-to-string col))))))
9314 (defun org-table-move-row-down ()
9315 "Move table row down."
9316 (interactive)
9317 (org-table-move-row nil))
9318 (defun org-table-move-row-up ()
9319 "Move table row up."
9320 (interactive)
9321 (org-table-move-row 'up))
9323 (defun org-table-move-row (&optional up)
9324 "Move the current table line down. With arg UP, move it up."
9325 (interactive "P")
9326 (let* ((col (current-column))
9327 (pos (point))
9328 (hline1p (save-excursion (beginning-of-line 1)
9329 (looking-at org-table-hline-regexp)))
9330 (dline1 (org-table-current-dline))
9331 (dline2 (+ dline1 (if up -1 1)))
9332 (tonew (if up 0 2))
9333 txt hline2p)
9334 (beginning-of-line tonew)
9335 (unless (org-at-table-p)
9336 (goto-char pos)
9337 (error "Cannot move row further"))
9338 (setq hline2p (looking-at org-table-hline-regexp))
9339 (goto-char pos)
9340 (beginning-of-line 1)
9341 (setq pos (point))
9342 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9343 (delete-region (point) (1+ (point-at-eol)))
9344 (beginning-of-line tonew)
9345 (insert txt)
9346 (beginning-of-line 0)
9347 (move-to-column col)
9348 (unless (or hline1p hline2p)
9349 (org-table-fix-formulas
9350 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9351 (cons (number-to-string dline2) (number-to-string dline1)))))))
9353 (defun org-table-insert-row (&optional arg)
9354 "Insert a new row above the current line into the table.
9355 With prefix ARG, insert below the current line."
9356 (interactive "P")
9357 (if (not (org-at-table-p))
9358 (error "Not at a table"))
9359 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9360 (new (org-table-clean-line line)))
9361 ;; Fix the first field if necessary
9362 (if (string-match "^[ \t]*| *[#$] *|" line)
9363 (setq new (replace-match (match-string 0 line) t t new)))
9364 (beginning-of-line (if arg 2 1))
9365 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9366 (beginning-of-line 0)
9367 (re-search-forward "| ?" (point-at-eol) t)
9368 (and (or org-table-may-need-update org-table-overlay-coordinates)
9369 (org-table-align))
9370 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9372 (defun org-table-insert-hline (&optional above)
9373 "Insert a horizontal-line below the current line into the table.
9374 With prefix ABOVE, insert above the current line."
9375 (interactive "P")
9376 (if (not (org-at-table-p))
9377 (error "Not at a table"))
9378 (let ((line (org-table-clean-line
9379 (buffer-substring (point-at-bol) (point-at-eol))))
9380 (col (current-column)))
9381 (while (string-match "|\\( +\\)|" line)
9382 (setq line (replace-match
9383 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9384 ?-) "|") t t line)))
9385 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9386 (beginning-of-line (if above 1 2))
9387 (insert line "\n")
9388 (beginning-of-line (if above 1 -1))
9389 (move-to-column col)
9390 (and org-table-overlay-coordinates (org-table-align))))
9392 (defun org-table-hline-and-move (&optional same-column)
9393 "Insert a hline and move to the row below that line."
9394 (interactive "P")
9395 (let ((col (org-table-current-column)))
9396 (org-table-maybe-eval-formula)
9397 (org-table-maybe-recalculate-line)
9398 (org-table-insert-hline)
9399 (end-of-line 2)
9400 (if (looking-at "\n[ \t]*|-")
9401 (progn (insert "\n|") (org-table-align))
9402 (org-table-next-field))
9403 (if same-column (org-table-goto-column col))))
9405 (defun org-table-clean-line (s)
9406 "Convert a table line S into a string with only \"|\" and space.
9407 In particular, this does handle wide and invisible characters."
9408 (if (string-match "^[ \t]*|-" s)
9409 ;; It's a hline, just map the characters
9410 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9411 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9412 (setq s (replace-match
9413 (concat "|" (make-string (org-string-width (match-string 1 s))
9414 ?\ ) "|")
9415 t t s)))
9418 (defun org-table-kill-row ()
9419 "Delete the current row or horizontal line from the table."
9420 (interactive)
9421 (if (not (org-at-table-p))
9422 (error "Not at a table"))
9423 (let ((col (current-column))
9424 (dline (org-table-current-dline)))
9425 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9426 (if (not (org-at-table-p)) (beginning-of-line 0))
9427 (move-to-column col)
9428 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9429 dline -1 dline)))
9431 (defun org-table-sort-lines (with-case &optional sorting-type)
9432 "Sort table lines according to the column at point.
9434 The position of point indicates the column to be used for
9435 sorting, and the range of lines is the range between the nearest
9436 horizontal separator lines, or the entire table of no such lines
9437 exist. If point is before the first column, you will be prompted
9438 for the sorting column. If there is an active region, the mark
9439 specifies the first line and the sorting column, while point
9440 should be in the last line to be included into the sorting.
9442 The command then prompts for the sorting type which can be
9443 alphabetically, numerically, or by time (as given in a time stamp
9444 in the field). Sorting in reverse order is also possible.
9446 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9448 If SORTING-TYPE is specified when this function is called from a Lisp
9449 program, no prompting will take place. SORTING-TYPE must be a character,
9450 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9451 should be done in reverse order."
9452 (interactive "P")
9453 (let* ((thisline (org-current-line))
9454 (thiscol (org-table-current-column))
9455 beg end bcol ecol tend tbeg column lns pos)
9456 (when (equal thiscol 0)
9457 (if (interactive-p)
9458 (setq thiscol
9459 (string-to-number
9460 (read-string "Use column N for sorting: ")))
9461 (setq thiscol 1))
9462 (org-table-goto-column thiscol))
9463 (org-table-check-inside-data-field)
9464 (if (org-region-active-p)
9465 (progn
9466 (setq beg (region-beginning) end (region-end))
9467 (goto-char beg)
9468 (setq column (org-table-current-column)
9469 beg (point-at-bol))
9470 (goto-char end)
9471 (setq end (point-at-bol 2)))
9472 (setq column (org-table-current-column)
9473 pos (point)
9474 tbeg (org-table-begin)
9475 tend (org-table-end))
9476 (if (re-search-backward org-table-hline-regexp tbeg t)
9477 (setq beg (point-at-bol 2))
9478 (goto-char tbeg)
9479 (setq beg (point-at-bol 1)))
9480 (goto-char pos)
9481 (if (re-search-forward org-table-hline-regexp tend t)
9482 (setq end (point-at-bol 1))
9483 (goto-char tend)
9484 (setq end (point-at-bol))))
9485 (setq beg (move-marker (make-marker) beg)
9486 end (move-marker (make-marker) end))
9487 (untabify beg end)
9488 (goto-char beg)
9489 (org-table-goto-column column)
9490 (skip-chars-backward "^|")
9491 (setq bcol (current-column))
9492 (org-table-goto-column (1+ column))
9493 (skip-chars-backward "^|")
9494 (setq ecol (1- (current-column)))
9495 (org-table-goto-column column)
9496 (setq lns (mapcar (lambda(x) (cons
9497 (org-sort-remove-invisible
9498 (nth (1- column)
9499 (org-split-string x "[ \t]*|[ \t]*")))
9501 (org-split-string (buffer-substring beg end) "\n")))
9502 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9503 (delete-region beg end)
9504 (move-marker beg nil)
9505 (move-marker end nil)
9506 (insert (mapconcat 'cdr lns "\n") "\n")
9507 (goto-line thisline)
9508 (org-table-goto-column thiscol)
9509 (message "%d lines sorted, based on column %d" (length lns) column)))
9511 ;; FIXME: maybe we will not need this? Table sorting is broken....
9512 (defun org-sort-remove-invisible (s)
9513 (remove-text-properties 0 (length s) org-rm-props s)
9514 (while (string-match org-bracket-link-regexp s)
9515 (setq s (replace-match (if (match-end 2)
9516 (match-string 3 s)
9517 (match-string 1 s)) t t s)))
9520 (defun org-table-cut-region (beg end)
9521 "Copy region in table to the clipboard and blank all relevant fields."
9522 (interactive "r")
9523 (org-table-copy-region beg end 'cut))
9525 (defun org-table-copy-region (beg end &optional cut)
9526 "Copy rectangular region in table to clipboard.
9527 A special clipboard is used which can only be accessed
9528 with `org-table-paste-rectangle'."
9529 (interactive "rP")
9530 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9531 region cols
9532 (rpl (if cut " " nil)))
9533 (goto-char beg)
9534 (org-table-check-inside-data-field)
9535 (setq l01 (org-current-line)
9536 c01 (org-table-current-column))
9537 (goto-char end)
9538 (org-table-check-inside-data-field)
9539 (setq l02 (org-current-line)
9540 c02 (org-table-current-column))
9541 (setq l1 (min l01 l02) l2 (max l01 l02)
9542 c1 (min c01 c02) c2 (max c01 c02))
9543 (catch 'exit
9544 (while t
9545 (catch 'nextline
9546 (if (> l1 l2) (throw 'exit t))
9547 (goto-line l1)
9548 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9549 (setq cols nil ic1 c1 ic2 c2)
9550 (while (< ic1 (1+ ic2))
9551 (push (org-table-get-field ic1 rpl) cols)
9552 (setq ic1 (1+ ic1)))
9553 (push (nreverse cols) region)
9554 (setq l1 (1+ l1)))))
9555 (setq org-table-clip (nreverse region))
9556 (if cut (org-table-align))
9557 org-table-clip))
9559 (defun org-table-paste-rectangle ()
9560 "Paste a rectangular region into a table.
9561 The upper right corner ends up in the current field. All involved fields
9562 will be overwritten. If the rectangle does not fit into the present table,
9563 the table is enlarged as needed. The process ignores horizontal separator
9564 lines."
9565 (interactive)
9566 (unless (and org-table-clip (listp org-table-clip))
9567 (error "First cut/copy a region to paste!"))
9568 (org-table-check-inside-data-field)
9569 (let* ((clip org-table-clip)
9570 (line (org-current-line))
9571 (col (org-table-current-column))
9572 (org-enable-table-editor t)
9573 (org-table-automatic-realign nil)
9574 c cols field)
9575 (while (setq cols (pop clip))
9576 (while (org-at-table-hline-p) (beginning-of-line 2))
9577 (if (not (org-at-table-p))
9578 (progn (end-of-line 0) (org-table-next-field)))
9579 (setq c col)
9580 (while (setq field (pop cols))
9581 (org-table-goto-column c nil 'force)
9582 (org-table-get-field nil field)
9583 (setq c (1+ c)))
9584 (beginning-of-line 2))
9585 (goto-line line)
9586 (org-table-goto-column col)
9587 (org-table-align)))
9589 (defun org-table-convert ()
9590 "Convert from `org-mode' table to table.el and back.
9591 Obviously, this only works within limits. When an Org-mode table is
9592 converted to table.el, all horizontal separator lines get lost, because
9593 table.el uses these as cell boundaries and has no notion of horizontal lines.
9594 A table.el table can be converted to an Org-mode table only if it does not
9595 do row or column spanning. Multiline cells will become multiple cells.
9596 Beware, Org-mode does not test if the table can be successfully converted - it
9597 blindly applies a recipe that works for simple tables."
9598 (interactive)
9599 (require 'table)
9600 (if (org-at-table.el-p)
9601 ;; convert to Org-mode table
9602 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9603 (end (move-marker (make-marker) (org-table-end t))))
9604 (table-unrecognize-region beg end)
9605 (goto-char beg)
9606 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9607 (replace-match ""))
9608 (goto-char beg))
9609 (if (org-at-table-p)
9610 ;; convert to table.el table
9611 (let ((beg (move-marker (make-marker) (org-table-begin)))
9612 (end (move-marker (make-marker) (org-table-end))))
9613 ;; first, get rid of all horizontal lines
9614 (goto-char beg)
9615 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9616 (replace-match ""))
9617 ;; insert a hline before first
9618 (goto-char beg)
9619 (org-table-insert-hline 'above)
9620 (beginning-of-line -1)
9621 ;; insert a hline after each line
9622 (while (progn (beginning-of-line 3) (< (point) end))
9623 (org-table-insert-hline))
9624 (goto-char beg)
9625 (setq end (move-marker end (org-table-end)))
9626 ;; replace "+" at beginning and ending of hlines
9627 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9628 (replace-match "\\1+-"))
9629 (goto-char beg)
9630 (while (re-search-forward "-|[ \t]*$" end t)
9631 (replace-match "-+"))
9632 (goto-char beg)))))
9634 (defun org-table-wrap-region (arg)
9635 "Wrap several fields in a column like a paragraph.
9636 This is useful if you'd like to spread the contents of a field over several
9637 lines, in order to keep the table compact.
9639 If there is an active region, and both point and mark are in the same column,
9640 the text in the column is wrapped to minimum width for the given number of
9641 lines. Generally, this makes the table more compact. A prefix ARG may be
9642 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9643 formats the selected text to two lines. If the region was longer than two
9644 lines, the remaining lines remain empty. A negative prefix argument reduces
9645 the current number of lines by that amount. The wrapped text is pasted back
9646 into the table. If you formatted it to more lines than it was before, fields
9647 further down in the table get overwritten - so you might need to make space in
9648 the table first.
9650 If there is no region, the current field is split at the cursor position and
9651 the text fragment to the right of the cursor is prepended to the field one
9652 line down.
9654 If there is no region, but you specify a prefix ARG, the current field gets
9655 blank, and the content is appended to the field above."
9656 (interactive "P")
9657 (org-table-check-inside-data-field)
9658 (if (org-region-active-p)
9659 ;; There is a region: fill as a paragraph
9660 (let* ((beg (region-beginning))
9661 (cline (save-excursion (goto-char beg) (org-current-line)))
9662 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9663 nlines)
9664 (org-table-cut-region (region-beginning) (region-end))
9665 (if (> (length (car org-table-clip)) 1)
9666 (error "Region must be limited to single column"))
9667 (setq nlines (if arg
9668 (if (< arg 1)
9669 (+ (length org-table-clip) arg)
9670 arg)
9671 (length org-table-clip)))
9672 (setq org-table-clip
9673 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9674 nil nlines)))
9675 (goto-line cline)
9676 (org-table-goto-column ccol)
9677 (org-table-paste-rectangle))
9678 ;; No region, split the current field at point
9679 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9680 (skip-chars-forward "^\r\n|"))
9681 (if arg
9682 ;; combine with field above
9683 (let ((s (org-table-blank-field))
9684 (col (org-table-current-column)))
9685 (beginning-of-line 0)
9686 (while (org-at-table-hline-p) (beginning-of-line 0))
9687 (org-table-goto-column col)
9688 (skip-chars-forward "^|")
9689 (skip-chars-backward " ")
9690 (insert " " (org-trim s))
9691 (org-table-align))
9692 ;; split field
9693 (if (looking-at "\\([^|]+\\)+|")
9694 (let ((s (match-string 1)))
9695 (replace-match " |")
9696 (goto-char (match-beginning 0))
9697 (org-table-next-row)
9698 (insert (org-trim s) " ")
9699 (org-table-align))
9700 (org-table-next-row)))))
9702 (defvar org-field-marker nil)
9704 (defun org-table-edit-field (arg)
9705 "Edit table field in a different window.
9706 This is mainly useful for fields that contain hidden parts.
9707 When called with a \\[universal-argument] prefix, just make the full field visible so that
9708 it can be edited in place."
9709 (interactive "P")
9710 (if arg
9711 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9712 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9713 (remove-text-properties b e '(org-cwidth t invisible t
9714 display t intangible t))
9715 (if (and (boundp 'font-lock-mode) font-lock-mode)
9716 (font-lock-fontify-block)))
9717 (let ((pos (move-marker (make-marker) (point)))
9718 (field (org-table-get-field))
9719 (cw (current-window-configuration))
9721 (org-switch-to-buffer-other-window "*Org tmp*")
9722 (erase-buffer)
9723 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9724 (let ((org-inhibit-startup t)) (org-mode))
9725 (goto-char (setq p (point-max)))
9726 (insert (org-trim field))
9727 (remove-text-properties p (point-max)
9728 '(invisible t org-cwidth t display t
9729 intangible t))
9730 (goto-char p)
9731 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9732 (org-set-local 'org-window-configuration cw)
9733 (org-set-local 'org-field-marker pos)
9734 (message "Edit and finish with C-c C-c"))))
9736 (defun org-table-finish-edit-field ()
9737 "Finish editing a table data field.
9738 Remove all newline characters, insert the result into the table, realign
9739 the table and kill the editing buffer."
9740 (let ((pos org-field-marker)
9741 (cw org-window-configuration)
9742 (cb (current-buffer))
9743 text)
9744 (goto-char (point-min))
9745 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9746 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9747 (replace-match " "))
9748 (setq text (org-trim (buffer-string)))
9749 (set-window-configuration cw)
9750 (kill-buffer cb)
9751 (select-window (get-buffer-window (marker-buffer pos)))
9752 (goto-char pos)
9753 (move-marker pos nil)
9754 (org-table-check-inside-data-field)
9755 (org-table-get-field nil text)
9756 (org-table-align)
9757 (message "New field value inserted")))
9759 (defun org-trim (s)
9760 "Remove whitespace at beginning and end of string."
9761 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9762 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9765 (defun org-wrap (string &optional width lines)
9766 "Wrap string to either a number of lines, or a width in characters.
9767 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9768 that costs. If there is a word longer than WIDTH, the text is actually
9769 wrapped to the length of that word.
9770 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9771 many lines, whatever width that takes.
9772 The return value is a list of lines, without newlines at the end."
9773 (let* ((words (org-split-string string "[ \t\n]+"))
9774 (maxword (apply 'max (mapcar 'org-string-width words)))
9775 w ll)
9776 (cond (width
9777 (org-do-wrap words (max maxword width)))
9778 (lines
9779 (setq w maxword)
9780 (setq ll (org-do-wrap words maxword))
9781 (if (<= (length ll) lines)
9783 (setq ll words)
9784 (while (> (length ll) lines)
9785 (setq w (1+ w))
9786 (setq ll (org-do-wrap words w)))
9787 ll))
9788 (t (error "Cannot wrap this")))))
9791 (defun org-do-wrap (words width)
9792 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9793 (let (lines line)
9794 (while words
9795 (setq line (pop words))
9796 (while (and words (< (+ (length line) (length (car words))) width))
9797 (setq line (concat line " " (pop words))))
9798 (setq lines (push line lines)))
9799 (nreverse lines)))
9801 (defun org-split-string (string &optional separators)
9802 "Splits STRING into substrings at SEPARATORS.
9803 No empty strings are returned if there are matches at the beginning
9804 and end of string."
9805 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9806 (start 0)
9807 notfirst
9808 (list nil))
9809 (while (and (string-match rexp string
9810 (if (and notfirst
9811 (= start (match-beginning 0))
9812 (< start (length string)))
9813 (1+ start) start))
9814 (< (match-beginning 0) (length string)))
9815 (setq notfirst t)
9816 (or (eq (match-beginning 0) 0)
9817 (and (eq (match-beginning 0) (match-end 0))
9818 (eq (match-beginning 0) start))
9819 (setq list
9820 (cons (substring string start (match-beginning 0))
9821 list)))
9822 (setq start (match-end 0)))
9823 (or (eq start (length string))
9824 (setq list
9825 (cons (substring string start)
9826 list)))
9827 (nreverse list)))
9829 (defun org-table-map-tables (function)
9830 "Apply FUNCTION to the start of all tables in the buffer."
9831 (save-excursion
9832 (save-restriction
9833 (widen)
9834 (goto-char (point-min))
9835 (while (re-search-forward org-table-any-line-regexp nil t)
9836 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9837 (beginning-of-line 1)
9838 (if (looking-at org-table-line-regexp)
9839 (save-excursion (funcall function)))
9840 (re-search-forward org-table-any-border-regexp nil 1))))
9841 (message "Mapping tables: done"))
9843 (defvar org-timecnt) ; dynamically scoped parameter
9845 (defun org-table-sum (&optional beg end nlast)
9846 "Sum numbers in region of current table column.
9847 The result will be displayed in the echo area, and will be available
9848 as kill to be inserted with \\[yank].
9850 If there is an active region, it is interpreted as a rectangle and all
9851 numbers in that rectangle will be summed. If there is no active
9852 region and point is located in a table column, sum all numbers in that
9853 column.
9855 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9856 numbers are assumed to be times as well (in decimal hours) and the
9857 numbers are added as such.
9859 If NLAST is a number, only the NLAST fields will actually be summed."
9860 (interactive)
9861 (save-excursion
9862 (let (col (org-timecnt 0) diff h m s org-table-clip)
9863 (cond
9864 ((and beg end)) ; beg and end given explicitly
9865 ((org-region-active-p)
9866 (setq beg (region-beginning) end (region-end)))
9868 (setq col (org-table-current-column))
9869 (goto-char (org-table-begin))
9870 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9871 (error "No table data"))
9872 (org-table-goto-column col)
9873 (setq beg (point))
9874 (goto-char (org-table-end))
9875 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9876 (error "No table data"))
9877 (org-table-goto-column col)
9878 (setq end (point))))
9879 (let* ((items (apply 'append (org-table-copy-region beg end)))
9880 (items1 (cond ((not nlast) items)
9881 ((>= nlast (length items)) items)
9882 (t (setq items (reverse items))
9883 (setcdr (nthcdr (1- nlast) items) nil)
9884 (nreverse items))))
9885 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9886 items1)))
9887 (res (apply '+ numbers))
9888 (sres (if (= org-timecnt 0)
9889 (format "%g" res)
9890 (setq diff (* 3600 res)
9891 h (floor (/ diff 3600)) diff (mod diff 3600)
9892 m (floor (/ diff 60)) diff (mod diff 60)
9893 s diff)
9894 (format "%d:%02d:%02d" h m s))))
9895 (kill-new sres)
9896 (if (interactive-p)
9897 (message "%s"
9898 (substitute-command-keys
9899 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9900 (length numbers) sres))))
9901 sres))))
9903 (defun org-table-get-number-for-summing (s)
9904 (let (n)
9905 (if (string-match "^ *|? *" s)
9906 (setq s (replace-match "" nil nil s)))
9907 (if (string-match " *|? *$" s)
9908 (setq s (replace-match "" nil nil s)))
9909 (setq n (string-to-number s))
9910 (cond
9911 ((and (string-match "0" s)
9912 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9913 ((string-match "\\`[ \t]+\\'" s) nil)
9914 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9915 (let ((h (string-to-number (or (match-string 1 s) "0")))
9916 (m (string-to-number (or (match-string 2 s) "0")))
9917 (s (string-to-number (or (match-string 4 s) "0"))))
9918 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9919 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9920 ((equal n 0) nil)
9921 (t n))))
9923 (defun org-table-current-field-formula (&optional key noerror)
9924 "Return the formula active for the current field.
9925 Assumes that specials are in place.
9926 If KEY is given, return the key to this formula.
9927 Otherwise return the formula preceeded with \"=\" or \":=\"."
9928 (let* ((name (car (rassoc (list (org-current-line)
9929 (org-table-current-column))
9930 org-table-named-field-locations)))
9931 (col (org-table-current-column))
9932 (scol (int-to-string col))
9933 (ref (format "@%d$%d" (org-table-current-dline) col))
9934 (stored-list (org-table-get-stored-formulas noerror))
9935 (ass (or (assoc name stored-list)
9936 (assoc ref stored-list)
9937 (assoc scol stored-list))))
9938 (if key
9939 (car ass)
9940 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9941 (cdr ass))))))
9943 (defun org-table-get-formula (&optional equation named)
9944 "Read a formula from the minibuffer, offer stored formula as default.
9945 When NAMED is non-nil, look for a named equation."
9946 (let* ((stored-list (org-table-get-stored-formulas))
9947 (name (car (rassoc (list (org-current-line)
9948 (org-table-current-column))
9949 org-table-named-field-locations)))
9950 (ref (format "@%d$%d" (org-table-current-dline)
9951 (org-table-current-column)))
9952 (refass (assoc ref stored-list))
9953 (scol (if named
9954 (if name name ref)
9955 (int-to-string (org-table-current-column))))
9956 (dummy (and (or name refass) (not named)
9957 (not (y-or-n-p "Replace field formula with column formula? " ))
9958 (error "Abort")))
9959 (name (or name ref))
9960 (org-table-may-need-update nil)
9961 (stored (cdr (assoc scol stored-list)))
9962 (eq (cond
9963 ((and stored equation (string-match "^ *=? *$" equation))
9964 stored)
9965 ((stringp equation)
9966 equation)
9967 (t (org-table-formula-from-user
9968 (read-string
9969 (org-table-formula-to-user
9970 (format "%s formula %s%s="
9971 (if named "Field" "Column")
9972 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9973 scol))
9974 (if stored (org-table-formula-to-user stored) "")
9975 'org-table-formula-history
9976 )))))
9977 mustsave)
9978 (when (not (string-match "\\S-" eq))
9979 ;; remove formula
9980 (setq stored-list (delq (assoc scol stored-list) stored-list))
9981 (org-table-store-formulas stored-list)
9982 (error "Formula removed"))
9983 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9984 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9985 (if (and name (not named))
9986 ;; We set the column equation, delete the named one.
9987 (setq stored-list (delq (assoc name stored-list) stored-list)
9988 mustsave t))
9989 (if stored
9990 (setcdr (assoc scol stored-list) eq)
9991 (setq stored-list (cons (cons scol eq) stored-list)))
9992 (if (or mustsave (not (equal stored eq)))
9993 (org-table-store-formulas stored-list))
9994 eq))
9996 (defun org-table-store-formulas (alist)
9997 "Store the list of formulas below the current table."
9998 (setq alist (sort alist 'org-table-formula-less-p))
9999 (save-excursion
10000 (goto-char (org-table-end))
10001 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
10002 (progn
10003 ;; don't overwrite TBLFM, we might use text properties to store stuff
10004 (goto-char (match-beginning 2))
10005 (delete-region (match-beginning 2) (match-end 0)))
10006 (insert "#+TBLFM:"))
10007 (insert " "
10008 (mapconcat (lambda (x)
10009 (concat
10010 (if (equal (string-to-char (car x)) ?@) "" "$")
10011 (car x) "=" (cdr x)))
10012 alist "::")
10013 "\n")))
10015 (defsubst org-table-formula-make-cmp-string (a)
10016 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
10017 (concat
10018 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
10019 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
10020 (if (match-end 5) (concat "@@" (match-string 5 a))))))
10022 (defun org-table-formula-less-p (a b)
10023 "Compare two formulas for sorting."
10024 (let ((as (org-table-formula-make-cmp-string (car a)))
10025 (bs (org-table-formula-make-cmp-string (car b))))
10026 (and as bs (string< as bs))))
10028 (defun org-table-get-stored-formulas (&optional noerror)
10029 "Return an alist with the stored formulas directly after current table."
10030 (interactive)
10031 (let (scol eq eq-alist strings string seen)
10032 (save-excursion
10033 (goto-char (org-table-end))
10034 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
10035 (setq strings (org-split-string (match-string 2) " *:: *"))
10036 (while (setq string (pop strings))
10037 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
10038 (setq scol (if (match-end 2)
10039 (match-string 2 string)
10040 (match-string 1 string))
10041 eq (match-string 3 string)
10042 eq-alist (cons (cons scol eq) eq-alist))
10043 (if (member scol seen)
10044 (if noerror
10045 (progn
10046 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
10047 (ding)
10048 (sit-for 2))
10049 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
10050 (push scol seen))))))
10051 (nreverse eq-alist)))
10053 (defun org-table-fix-formulas (key replace &optional limit delta remove)
10054 "Modify the equations after the table structure has been edited.
10055 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
10056 For all numbers larger than LIMIT, shift them by DELTA."
10057 (save-excursion
10058 (goto-char (org-table-end))
10059 (when (looking-at "#\\+TBLFM:")
10060 (let ((re (concat key "\\([0-9]+\\)"))
10061 (re2
10062 (when remove
10063 (if (equal key "$")
10064 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
10065 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
10066 s n a)
10067 (when remove
10068 (while (re-search-forward re2 (point-at-eol) t)
10069 (replace-match "")))
10070 (while (re-search-forward re (point-at-eol) t)
10071 (setq s (match-string 1) n (string-to-number s))
10072 (cond
10073 ((setq a (assoc s replace))
10074 (replace-match (concat key (cdr a)) t t))
10075 ((and limit (> n limit))
10076 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
10078 (defun org-table-get-specials ()
10079 "Get the column names and local parameters for this table."
10080 (save-excursion
10081 (let ((beg (org-table-begin)) (end (org-table-end))
10082 names name fields fields1 field cnt
10083 c v l line col types dlines hlines)
10084 (setq org-table-column-names nil
10085 org-table-local-parameters nil
10086 org-table-named-field-locations nil
10087 org-table-current-begin-line nil
10088 org-table-current-begin-pos nil
10089 org-table-current-line-types nil)
10090 (goto-char beg)
10091 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10092 (setq names (org-split-string (match-string 1) " *| *")
10093 cnt 1)
10094 (while (setq name (pop names))
10095 (setq cnt (1+ cnt))
10096 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10097 (push (cons name (int-to-string cnt)) org-table-column-names))))
10098 (setq org-table-column-names (nreverse org-table-column-names))
10099 (setq org-table-column-name-regexp
10100 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10101 (goto-char beg)
10102 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10103 (setq fields (org-split-string (match-string 1) " *| *"))
10104 (while (setq field (pop fields))
10105 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10106 (push (cons (match-string 1 field) (match-string 2 field))
10107 org-table-local-parameters))))
10108 (goto-char beg)
10109 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10110 (setq c (match-string 1)
10111 fields (org-split-string (match-string 2) " *| *"))
10112 (save-excursion
10113 (beginning-of-line (if (equal c "_") 2 0))
10114 (setq line (org-current-line) col 1)
10115 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10116 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10117 (while (and fields1 (setq field (pop fields)))
10118 (setq v (pop fields1) col (1+ col))
10119 (when (and (stringp field) (stringp v)
10120 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10121 (push (cons field v) org-table-local-parameters)
10122 (push (list field line col) org-table-named-field-locations))))
10123 ;; Analyse the line types
10124 (goto-char beg)
10125 (setq org-table-current-begin-line (org-current-line)
10126 org-table-current-begin-pos (point)
10127 l org-table-current-begin-line)
10128 (while (looking-at "[ \t]*|\\(-\\)?")
10129 (push (if (match-end 1) 'hline 'dline) types)
10130 (if (match-end 1) (push l hlines) (push l dlines))
10131 (beginning-of-line 2)
10132 (setq l (1+ l)))
10133 (setq org-table-current-line-types (apply 'vector (nreverse types))
10134 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
10135 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
10137 (defun org-table-maybe-eval-formula ()
10138 "Check if the current field starts with \"=\" or \":=\".
10139 If yes, store the formula and apply it."
10140 ;; We already know we are in a table. Get field will only return a formula
10141 ;; when appropriate. It might return a separator line, but no problem.
10142 (when org-table-formula-evaluate-inline
10143 (let* ((field (org-trim (or (org-table-get-field) "")))
10144 named eq)
10145 (when (string-match "^:?=\\(.*\\)" field)
10146 (setq named (equal (string-to-char field) ?:)
10147 eq (match-string 1 field))
10148 (if (or (fboundp 'calc-eval)
10149 (equal (substring eq 0 (min 2 (length eq))) "'("))
10150 (org-table-eval-formula (if named '(4) nil)
10151 (org-table-formula-from-user eq))
10152 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10154 (defvar org-recalc-commands nil
10155 "List of commands triggering the recalculation of a line.
10156 Will be filled automatically during use.")
10158 (defvar org-recalc-marks
10159 '((" " . "Unmarked: no special line, no automatic recalculation")
10160 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10161 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10162 ("!" . "Column name definition line. Reference in formula as $name.")
10163 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10164 ("_" . "Names for values in row below this one.")
10165 ("^" . "Names for values in row above this one.")))
10167 (defun org-table-rotate-recalc-marks (&optional newchar)
10168 "Rotate the recalculation mark in the first column.
10169 If in any row, the first field is not consistent with a mark,
10170 insert a new column for the markers.
10171 When there is an active region, change all the lines in the region,
10172 after prompting for the marking character.
10173 After each change, a message will be displayed indicating the meaning
10174 of the new mark."
10175 (interactive)
10176 (unless (org-at-table-p) (error "Not at a table"))
10177 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10178 (beg (org-table-begin))
10179 (end (org-table-end))
10180 (l (org-current-line))
10181 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10182 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10183 (have-col
10184 (save-excursion
10185 (goto-char beg)
10186 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10187 (col (org-table-current-column))
10188 (forcenew (car (assoc newchar org-recalc-marks)))
10189 epos new)
10190 (when l1
10191 (message "Change region to what mark? Type # * ! $ or SPC: ")
10192 (setq newchar (char-to-string (read-char-exclusive))
10193 forcenew (car (assoc newchar org-recalc-marks))))
10194 (if (and newchar (not forcenew))
10195 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10196 newchar))
10197 (if l1 (goto-line l1))
10198 (save-excursion
10199 (beginning-of-line 1)
10200 (unless (looking-at org-table-dataline-regexp)
10201 (error "Not at a table data line")))
10202 (unless have-col
10203 (org-table-goto-column 1)
10204 (org-table-insert-column)
10205 (org-table-goto-column (1+ col)))
10206 (setq epos (point-at-eol))
10207 (save-excursion
10208 (beginning-of-line 1)
10209 (org-table-get-field
10210 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10211 (concat " "
10212 (setq new (or forcenew
10213 (cadr (member (match-string 1) marks))))
10214 " ")
10215 " # ")))
10216 (if (and l1 l2)
10217 (progn
10218 (goto-line l1)
10219 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10220 (and (looking-at org-table-dataline-regexp)
10221 (org-table-get-field 1 (concat " " new " "))))
10222 (goto-line l1)))
10223 (if (not (= epos (point-at-eol))) (org-table-align))
10224 (goto-line l)
10225 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10227 (defun org-table-maybe-recalculate-line ()
10228 "Recompute the current line if marked for it, and if we haven't just done it."
10229 (interactive)
10230 (and org-table-allow-automatic-line-recalculation
10231 (not (and (memq last-command org-recalc-commands)
10232 (equal org-last-recalc-line (org-current-line))))
10233 (save-excursion (beginning-of-line 1)
10234 (looking-at org-table-auto-recalculate-regexp))
10235 (org-table-recalculate) t))
10237 (defvar org-table-formula-debug nil
10238 "Non-nil means, debug table formulas.
10239 When nil, simply write \"#ERROR\" in corrupted fields.")
10240 (make-variable-buffer-local 'org-table-formula-debug)
10242 (defvar modes)
10243 (defsubst org-set-calc-mode (var &optional value)
10244 (if (stringp var)
10245 (setq var (assoc var '(("D" calc-angle-mode deg)
10246 ("R" calc-angle-mode rad)
10247 ("F" calc-prefer-frac t)
10248 ("S" calc-symbolic-mode t)))
10249 value (nth 2 var) var (nth 1 var)))
10250 (if (memq var modes)
10251 (setcar (cdr (memq var modes)) value)
10252 (cons var (cons value modes)))
10253 modes)
10255 (defun org-table-eval-formula (&optional arg equation
10256 suppress-align suppress-const
10257 suppress-store suppress-analysis)
10258 "Replace the table field value at the cursor by the result of a calculation.
10260 This function makes use of Dave Gillespie's Calc package, in my view the
10261 most exciting program ever written for GNU Emacs. So you need to have Calc
10262 installed in order to use this function.
10264 In a table, this command replaces the value in the current field with the
10265 result of a formula. It also installs the formula as the \"current\" column
10266 formula, by storing it in a special line below the table. When called
10267 with a `C-u' prefix, the current field must ba a named field, and the
10268 formula is installed as valid in only this specific field.
10270 When called with two `C-u' prefixes, insert the active equation
10271 for the field back into the current field, so that it can be
10272 edited there. This is useful in order to use \\[org-table-show-reference]
10273 to check the referenced fields.
10275 When called, the command first prompts for a formula, which is read in
10276 the minibuffer. Previously entered formulas are available through the
10277 history list, and the last used formula is offered as a default.
10278 These stored formulas are adapted correctly when moving, inserting, or
10279 deleting columns with the corresponding commands.
10281 The formula can be any algebraic expression understood by the Calc package.
10282 For details, see the Org-mode manual.
10284 This function can also be called from Lisp programs and offers
10285 additional arguments: EQUATION can be the formula to apply. If this
10286 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10287 used to speed-up recursive calls by by-passing unnecessary aligns.
10288 SUPPRESS-CONST suppresses the interpretation of constants in the
10289 formula, assuming that this has been done already outside the function.
10290 SUPPRESS-STORE means the formula should not be stored, either because
10291 it is already stored, or because it is a modified equation that should
10292 not overwrite the stored one."
10293 (interactive "P")
10294 (org-table-check-inside-data-field)
10295 (or suppress-analysis (org-table-get-specials))
10296 (if (equal arg '(16))
10297 (let ((eq (org-table-current-field-formula)))
10298 (or eq (error "No equation active for current field"))
10299 (org-table-get-field nil eq)
10300 (org-table-align)
10301 (setq org-table-may-need-update t))
10302 (let* (fields
10303 (ndown (if (integerp arg) arg 1))
10304 (org-table-automatic-realign nil)
10305 (case-fold-search nil)
10306 (down (> ndown 1))
10307 (formula (if (and equation suppress-store)
10308 equation
10309 (org-table-get-formula equation (equal arg '(4)))))
10310 (n0 (org-table-current-column))
10311 (modes (copy-sequence org-calc-default-modes))
10312 (numbers nil) ; was a variable, now fixed default
10313 (keep-empty nil)
10314 n form form0 bw fmt x ev orig c lispp literal)
10315 ;; Parse the format string. Since we have a lot of modes, this is
10316 ;; a lot of work. However, I think calc still uses most of the time.
10317 (if (string-match ";" formula)
10318 (let ((tmp (org-split-string formula ";")))
10319 (setq formula (car tmp)
10320 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10321 (nth 1 tmp)))
10322 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10323 (setq c (string-to-char (match-string 1 fmt))
10324 n (string-to-number (match-string 2 fmt)))
10325 (if (= c ?p)
10326 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10327 (setq modes (org-set-calc-mode
10328 'calc-float-format
10329 (list (cdr (assoc c '((?n . float) (?f . fix)
10330 (?s . sci) (?e . eng))))
10331 n))))
10332 (setq fmt (replace-match "" t t fmt)))
10333 (if (string-match "[NT]" fmt)
10334 (setq numbers (equal (match-string 0 fmt) "N")
10335 fmt (replace-match "" t t fmt)))
10336 (if (string-match "L" fmt)
10337 (setq literal t
10338 fmt (replace-match "" t t fmt)))
10339 (if (string-match "E" fmt)
10340 (setq keep-empty t
10341 fmt (replace-match "" t t fmt)))
10342 (while (string-match "[DRFS]" fmt)
10343 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10344 (setq fmt (replace-match "" t t fmt)))
10345 (unless (string-match "\\S-" fmt)
10346 (setq fmt nil))))
10347 (if (and (not suppress-const) org-table-formula-use-constants)
10348 (setq formula (org-table-formula-substitute-names formula)))
10349 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10350 (while (> ndown 0)
10351 (setq fields (org-split-string
10352 (org-no-properties
10353 (buffer-substring (point-at-bol) (point-at-eol)))
10354 " *| *"))
10355 (if (eq numbers t)
10356 (setq fields (mapcar
10357 (lambda (x) (number-to-string (string-to-number x)))
10358 fields)))
10359 (setq ndown (1- ndown))
10360 (setq form (copy-sequence formula)
10361 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10362 (if (and lispp literal) (setq lispp 'literal))
10363 ;; Check for old vertical references
10364 (setq form (org-rewrite-old-row-references form))
10365 ;; Insert complex ranges
10366 (while (string-match org-table-range-regexp form)
10367 (setq form
10368 (replace-match
10369 (save-match-data
10370 (org-table-make-reference
10371 (org-table-get-range (match-string 0 form) nil n0)
10372 keep-empty numbers lispp))
10373 t t form)))
10374 ;; Insert simple ranges
10375 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10376 (setq form
10377 (replace-match
10378 (save-match-data
10379 (org-table-make-reference
10380 (org-sublist
10381 fields (string-to-number (match-string 1 form))
10382 (string-to-number (match-string 2 form)))
10383 keep-empty numbers lispp))
10384 t t form)))
10385 (setq form0 form)
10386 ;; Insert the references to fields in same row
10387 (while (string-match "\\$\\([0-9]+\\)" form)
10388 (setq n (string-to-number (match-string 1 form))
10389 x (nth (1- (if (= n 0) n0 n)) fields))
10390 (unless x (error "Invalid field specifier \"%s\""
10391 (match-string 0 form)))
10392 (setq form (replace-match
10393 (save-match-data
10394 (org-table-make-reference x nil numbers lispp))
10395 t t form)))
10397 (if lispp
10398 (setq ev (condition-case nil
10399 (eval (eval (read form)))
10400 (error "#ERROR"))
10401 ev (if (numberp ev) (number-to-string ev) ev))
10402 (or (fboundp 'calc-eval)
10403 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10404 (setq ev (calc-eval (cons form modes)
10405 (if numbers 'num))))
10407 (when org-table-formula-debug
10408 (with-output-to-temp-buffer "*Substitution History*"
10409 (princ (format "Substitution history of formula
10410 Orig: %s
10411 $xyz-> %s
10412 @r$c-> %s
10413 $1-> %s\n" orig formula form0 form))
10414 (if (listp ev)
10415 (princ (format " %s^\nError: %s"
10416 (make-string (car ev) ?\-) (nth 1 ev)))
10417 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10418 ev (or fmt "NONE")
10419 (if fmt (format fmt (string-to-number ev)) ev)))))
10420 (setq bw (get-buffer-window "*Substitution History*"))
10421 (shrink-window-if-larger-than-buffer bw)
10422 (unless (and (interactive-p) (not ndown))
10423 (unless (let (inhibit-redisplay)
10424 (y-or-n-p "Debugging Formula. Continue to next? "))
10425 (org-table-align)
10426 (error "Abort"))
10427 (delete-window bw)
10428 (message "")))
10429 (if (listp ev) (setq fmt nil ev "#ERROR"))
10430 (org-table-justify-field-maybe
10431 (if fmt (format fmt (string-to-number ev)) ev))
10432 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10433 (call-interactively 'org-return)
10434 (setq ndown 0)))
10435 (and down (org-table-maybe-recalculate-line))
10436 (or suppress-align (and org-table-may-need-update
10437 (org-table-align))))))
10439 (defun org-table-put-field-property (prop value)
10440 (save-excursion
10441 (put-text-property (progn (skip-chars-backward "^|") (point))
10442 (progn (skip-chars-forward "^|") (point))
10443 prop value)))
10445 (defun org-table-get-range (desc &optional tbeg col highlight)
10446 "Get a calc vector from a column, accorting to descriptor DESC.
10447 Optional arguments TBEG and COL can give the beginning of the table and
10448 the current column, to avoid unnecessary parsing.
10449 HIGHLIGHT means, just highlight the range."
10450 (if (not (equal (string-to-char desc) ?@))
10451 (setq desc (concat "@" desc)))
10452 (save-excursion
10453 (or tbeg (setq tbeg (org-table-begin)))
10454 (or col (setq col (org-table-current-column)))
10455 (let ((thisline (org-current-line))
10456 beg end c1 c2 r1 r2 rangep tmp)
10457 (unless (string-match org-table-range-regexp desc)
10458 (error "Invalid table range specifier `%s'" desc))
10459 (setq rangep (match-end 3)
10460 r1 (and (match-end 1) (match-string 1 desc))
10461 r2 (and (match-end 4) (match-string 4 desc))
10462 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10463 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10465 (and c1 (setq c1 (+ (string-to-number c1)
10466 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10467 (and c2 (setq c2 (+ (string-to-number c2)
10468 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10469 (if (equal r1 "") (setq r1 nil))
10470 (if (equal r2 "") (setq r2 nil))
10471 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10472 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10473 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10474 (if (not r1) (setq r1 thisline))
10475 (if (not r2) (setq r2 thisline))
10476 (if (not c1) (setq c1 col))
10477 (if (not c2) (setq c2 col))
10478 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10479 ;; just one field
10480 (progn
10481 (goto-line r1)
10482 (while (not (looking-at org-table-dataline-regexp))
10483 (beginning-of-line 2))
10484 (prog1 (org-trim (org-table-get-field c1))
10485 (if highlight (org-table-highlight-rectangle (point) (point)))))
10486 ;; A range, return a vector
10487 ;; First sort the numbers to get a regular ractangle
10488 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10489 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10490 (goto-line r1)
10491 (while (not (looking-at org-table-dataline-regexp))
10492 (beginning-of-line 2))
10493 (org-table-goto-column c1)
10494 (setq beg (point))
10495 (goto-line r2)
10496 (while (not (looking-at org-table-dataline-regexp))
10497 (beginning-of-line 0))
10498 (org-table-goto-column c2)
10499 (setq end (point))
10500 (if highlight
10501 (org-table-highlight-rectangle
10502 beg (progn (skip-chars-forward "^|\n") (point))))
10503 ;; return string representation of calc vector
10504 (mapcar 'org-trim
10505 (apply 'append (org-table-copy-region beg end)))))))
10507 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10508 "Analyze descriptor DESC and retrieve the corresponding line number.
10509 The cursor is currently in line CLINE, the table begins in line BLINE,
10510 and TABLE is a vector with line types."
10511 (if (string-match "^[0-9]+$" desc)
10512 (aref org-table-dlines (string-to-number desc))
10513 (setq cline (or cline (org-current-line))
10514 bline (or bline org-table-current-begin-line)
10515 table (or table org-table-current-line-types))
10516 (if (or
10517 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10518 ;; 1 2 3 4 5 6
10519 (and (not (match-end 3)) (not (match-end 6)))
10520 (and (match-end 3) (match-end 6) (not (match-end 5))))
10521 (error "invalid row descriptor `%s'" desc))
10522 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10523 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10524 (odir (and (match-end 5) (match-string 5 desc)))
10525 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10526 (i (- cline bline))
10527 (rel (and (match-end 6)
10528 (or (and (match-end 1) (not (match-end 3)))
10529 (match-end 5)))))
10530 (if (and hn (not hdir))
10531 (progn
10532 (setq i 0 hdir "+")
10533 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10534 (if (and (not hn) on (not odir))
10535 (error "should never happen");;(aref org-table-dlines on)
10536 (if (and hn (> hn 0))
10537 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10538 (if on
10539 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10540 (+ bline i)))))
10542 (defun org-find-row-type (table i type backwards relative n)
10543 (let ((l (length table)))
10544 (while (> n 0)
10545 (while (and (setq i (+ i (if backwards -1 1)))
10546 (>= i 0) (< i l)
10547 (not (eq (aref table i) type))
10548 (if (and relative (eq (aref table i) 'hline))
10549 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10550 t)))
10551 (setq n (1- n)))
10552 (if (or (< i 0) (>= i l))
10553 (error "Row descriptior leads outside table")
10554 i)))
10556 (defun org-rewrite-old-row-references (s)
10557 (if (string-match "&[-+0-9I]" s)
10558 (error "Formula contains old &row reference, please rewrite using @-syntax")
10561 (defun org-table-make-reference (elements keep-empty numbers lispp)
10562 "Convert list ELEMENTS to something appropriate to insert into formula.
10563 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10564 NUMBERS indicates that everything should be converted to numbers.
10565 LISPP means to return something appropriate for a Lisp list."
10566 (if (stringp elements) ; just a single val
10567 (if lispp
10568 (if (eq lispp 'literal)
10569 elements
10570 (prin1-to-string (if numbers (string-to-number elements) elements)))
10571 (if (equal elements "") (setq elements "0"))
10572 (if numbers (number-to-string (string-to-number elements)) elements))
10573 (unless keep-empty
10574 (setq elements
10575 (delq nil
10576 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10577 elements))))
10578 (setq elements (or elements '("0")))
10579 (if lispp
10580 (mapconcat
10581 (lambda (x)
10582 (if (eq lispp 'literal)
10584 (prin1-to-string (if numbers (string-to-number x) x))))
10585 elements " ")
10586 (concat "[" (mapconcat
10587 (lambda (x)
10588 (if numbers (number-to-string (string-to-number x)) x))
10589 elements
10590 ",") "]"))))
10592 (defun org-table-recalculate (&optional all noalign)
10593 "Recalculate the current table line by applying all stored formulas.
10594 With prefix arg ALL, do this for all lines in the table."
10595 (interactive "P")
10596 (or (memq this-command org-recalc-commands)
10597 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10598 (unless (org-at-table-p) (error "Not at a table"))
10599 (if (equal all '(16))
10600 (org-table-iterate)
10601 (org-table-get-specials)
10602 (let* ((eqlist (sort (org-table-get-stored-formulas)
10603 (lambda (a b) (string< (car a) (car b)))))
10604 (inhibit-redisplay (not debug-on-error))
10605 (line-re org-table-dataline-regexp)
10606 (thisline (org-current-line))
10607 (thiscol (org-table-current-column))
10608 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10609 ;; Insert constants in all formulas
10610 (setq eqlist
10611 (mapcar (lambda (x)
10612 (setcdr x (org-table-formula-substitute-names (cdr x)))
10614 eqlist))
10615 ;; Split the equation list
10616 (while (setq eq (pop eqlist))
10617 (if (<= (string-to-char (car eq)) ?9)
10618 (push eq eqlnum)
10619 (push eq eqlname)))
10620 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10621 (if all
10622 (progn
10623 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10624 (goto-char (setq beg (org-table-begin)))
10625 (if (re-search-forward org-table-calculate-mark-regexp end t)
10626 ;; This is a table with marked lines, compute selected lines
10627 (setq line-re org-table-recalculate-regexp)
10628 ;; Move forward to the first non-header line
10629 (if (and (re-search-forward org-table-dataline-regexp end t)
10630 (re-search-forward org-table-hline-regexp end t)
10631 (re-search-forward org-table-dataline-regexp end t))
10632 (setq beg (match-beginning 0))
10633 nil))) ;; just leave beg where it is
10634 (setq beg (point-at-bol)
10635 end (move-marker (make-marker) (1+ (point-at-eol)))))
10636 (goto-char beg)
10637 (and all (message "Re-applying formulas to full table..."))
10639 ;; First find the named fields, and mark them untouchanble
10640 (remove-text-properties beg end '(org-untouchable t))
10641 (while (setq eq (pop eqlname))
10642 (setq name (car eq)
10643 a (assoc name org-table-named-field-locations))
10644 (and (not a)
10645 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10646 (setq a (list name
10647 (aref org-table-dlines
10648 (string-to-number (match-string 1 name)))
10649 (string-to-number (match-string 2 name)))))
10650 (when (and a (or all (equal (nth 1 a) thisline)))
10651 (message "Re-applying formula to field: %s" name)
10652 (goto-line (nth 1 a))
10653 (org-table-goto-column (nth 2 a))
10654 (push (append a (list (cdr eq))) eqlname1)
10655 (org-table-put-field-property :org-untouchable t)))
10657 ;; Now evauluate the column formulas, but skip fields covered by
10658 ;; field formulas
10659 (goto-char beg)
10660 (while (re-search-forward line-re end t)
10661 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10662 ;; Unprotected line, recalculate
10663 (and all (message "Re-applying formulas to full table...(line %d)"
10664 (setq cnt (1+ cnt))))
10665 (setq org-last-recalc-line (org-current-line))
10666 (setq eql eqlnum)
10667 (while (setq entry (pop eql))
10668 (goto-line org-last-recalc-line)
10669 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10670 (unless (get-text-property (point) :org-untouchable)
10671 (org-table-eval-formula nil (cdr entry)
10672 'noalign 'nocst 'nostore 'noanalysis)))))
10674 ;; Now evaluate the field formulas
10675 (while (setq eq (pop eqlname1))
10676 (message "Re-applying formula to field: %s" (car eq))
10677 (goto-line (nth 1 eq))
10678 (org-table-goto-column (nth 2 eq))
10679 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10680 'nostore 'noanalysis))
10682 (goto-line thisline)
10683 (org-table-goto-column thiscol)
10684 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10685 (or noalign (and org-table-may-need-update (org-table-align))
10686 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10688 ;; back to initial position
10689 (message "Re-applying formulas...done")
10690 (goto-line thisline)
10691 (org-table-goto-column thiscol)
10692 (or noalign (and org-table-may-need-update (org-table-align))
10693 (and all (message "Re-applying formulas...done"))))))
10695 (defun org-table-iterate (&optional arg)
10696 "Recalculate the table until it does not change anymore."
10697 (interactive "P")
10698 (let ((imax (if arg (prefix-numeric-value arg) 10))
10699 (i 0)
10700 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10701 thistbl)
10702 (catch 'exit
10703 (while (< i imax)
10704 (setq i (1+ i))
10705 (org-table-recalculate 'all)
10706 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10707 (if (not (string= lasttbl thistbl))
10708 (setq lasttbl thistbl)
10709 (if (> i 1)
10710 (message "Convergence after %d iterations" i)
10711 (message "Table was already stable"))
10712 (throw 'exit t)))
10713 (error "No convergence after %d iterations" i))))
10715 (defun org-table-formula-substitute-names (f)
10716 "Replace $const with values in string F."
10717 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10718 ;; First, check for column names
10719 (while (setq start (string-match org-table-column-name-regexp f start))
10720 (setq start (1+ start))
10721 (setq a (assoc (match-string 1 f) org-table-column-names))
10722 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10723 ;; Parameters and constants
10724 (setq start 0)
10725 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10726 (setq start (1+ start))
10727 (if (setq a (save-match-data
10728 (org-table-get-constant (match-string 1 f))))
10729 (setq f (replace-match
10730 (concat (if pp "(") a (if pp ")")) t t f))))
10731 (if org-table-formula-debug
10732 (put-text-property 0 (length f) :orig-formula f1 f))
10735 (defun org-table-get-constant (const)
10736 "Find the value for a parameter or constant in a formula.
10737 Parameters get priority."
10738 (or (cdr (assoc const org-table-local-parameters))
10739 (cdr (assoc const org-table-formula-constants-local))
10740 (cdr (assoc const org-table-formula-constants))
10741 (and (fboundp 'constants-get) (constants-get const))
10742 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10743 (org-entry-get nil (substring const 5) 'inherit))
10744 "#UNDEFINED_NAME"))
10746 (defvar org-table-fedit-map
10747 (let ((map (make-sparse-keymap)))
10748 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10749 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10750 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10751 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10752 (org-defkey map "\C-c?" 'org-table-show-reference)
10753 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10754 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10755 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10756 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10757 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10758 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10759 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10760 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10761 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10762 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10763 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10764 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10765 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10766 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10767 map))
10769 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10770 '("Edit-Formulas"
10771 ["Finish and Install" org-table-fedit-finish t]
10772 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10773 ["Abort" org-table-fedit-abort t]
10774 "--"
10775 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10776 ["Complete Lisp Symbol" lisp-complete-symbol t]
10777 "--"
10778 "Shift Reference at Point"
10779 ["Up" org-table-fedit-ref-up t]
10780 ["Down" org-table-fedit-ref-down t]
10781 ["Left" org-table-fedit-ref-left t]
10782 ["Right" org-table-fedit-ref-right t]
10784 "Change Test Row for Column Formulas"
10785 ["Up" org-table-fedit-line-up t]
10786 ["Down" org-table-fedit-line-down t]
10787 "--"
10788 ["Scroll Table Window" org-table-fedit-scroll t]
10789 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10790 ["Show Table Grid" org-table-fedit-toggle-coordinates
10791 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10792 org-table-overlay-coordinates)]
10793 "--"
10794 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10795 :style toggle :selected org-table-buffer-is-an]))
10797 (defvar org-pos)
10799 (defun org-table-edit-formulas ()
10800 "Edit the formulas of the current table in a separate buffer."
10801 (interactive)
10802 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10803 (beginning-of-line 0))
10804 (unless (org-at-table-p) (error "Not at a table"))
10805 (org-table-get-specials)
10806 (let ((key (org-table-current-field-formula 'key 'noerror))
10807 (eql (sort (org-table-get-stored-formulas 'noerror)
10808 'org-table-formula-less-p))
10809 (pos (move-marker (make-marker) (point)))
10810 (startline 1)
10811 (wc (current-window-configuration))
10812 (titles '((column . "# Column Formulas\n")
10813 (field . "# Field Formulas\n")
10814 (named . "# Named Field Formulas\n")))
10815 entry s type title)
10816 (org-switch-to-buffer-other-window "*Edit Formulas*")
10817 (erase-buffer)
10818 ;; Keep global-font-lock-mode from turning on font-lock-mode
10819 (let ((font-lock-global-modes '(not fundamental-mode)))
10820 (fundamental-mode))
10821 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10822 (org-set-local 'org-pos pos)
10823 (org-set-local 'org-window-configuration wc)
10824 (use-local-map org-table-fedit-map)
10825 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10826 (easy-menu-add org-table-fedit-menu)
10827 (setq startline (org-current-line))
10828 (while (setq entry (pop eql))
10829 (setq type (cond
10830 ((equal (string-to-char (car entry)) ?@) 'field)
10831 ((string-match "^[0-9]" (car entry)) 'column)
10832 (t 'named)))
10833 (when (setq title (assq type titles))
10834 (or (bobp) (insert "\n"))
10835 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10836 (setq titles (delq title titles)))
10837 (if (equal key (car entry)) (setq startline (org-current-line)))
10838 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10839 (car entry) " = " (cdr entry) "\n"))
10840 (remove-text-properties 0 (length s) '(face nil) s)
10841 (insert s))
10842 (if (eq org-table-use-standard-references t)
10843 (org-table-fedit-toggle-ref-type))
10844 (goto-line startline)
10845 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10847 (defun org-table-fedit-post-command ()
10848 (when (not (memq this-command '(lisp-complete-symbol)))
10849 (let ((win (selected-window)))
10850 (save-excursion
10851 (condition-case nil
10852 (org-table-show-reference)
10853 (error nil))
10854 (select-window win)))))
10856 (defun org-table-formula-to-user (s)
10857 "Convert a formula from internal to user representation."
10858 (if (eq org-table-use-standard-references t)
10859 (org-table-convert-refs-to-an s)
10862 (defun org-table-formula-from-user (s)
10863 "Convert a formula from user to internal representation."
10864 (if org-table-use-standard-references
10865 (org-table-convert-refs-to-rc s)
10868 (defun org-table-convert-refs-to-rc (s)
10869 "Convert spreadsheet references from AB7 to @7$28.
10870 Works for single references, but also for entire formulas and even the
10871 full TBLFM line."
10872 (let ((start 0))
10873 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10874 (cond
10875 ((match-end 3)
10876 ;; format match, just advance
10877 (setq start (match-end 0)))
10878 ((and (> (match-beginning 0) 0)
10879 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10880 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10881 ;; 3.e5 or something like this.
10882 (setq start (match-end 0)))
10884 (setq start (match-beginning 0)
10885 s (replace-match
10886 (if (equal (match-string 2 s) "&")
10887 (format "$%d" (org-letters-to-number (match-string 1 s)))
10888 (format "@%d$%d"
10889 (string-to-number (match-string 2 s))
10890 (org-letters-to-number (match-string 1 s))))
10891 t t s)))))
10894 (defun org-table-convert-refs-to-an (s)
10895 "Convert spreadsheet references from to @7$28 to AB7.
10896 Works for single references, but also for entire formulas and even the
10897 full TBLFM line."
10898 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10899 (setq s (replace-match
10900 (format "%s%d"
10901 (org-number-to-letters
10902 (string-to-number (match-string 2 s)))
10903 (string-to-number (match-string 1 s)))
10904 t t s)))
10905 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10906 (setq s (replace-match (concat "\\1"
10907 (org-number-to-letters
10908 (string-to-number (match-string 2 s))) "&")
10909 t nil s)))
10912 (defun org-letters-to-number (s)
10913 "Convert a base 26 number represented by letters into an integer.
10914 For example: AB -> 28."
10915 (let ((n 0))
10916 (setq s (upcase s))
10917 (while (> (length s) 0)
10918 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10919 s (substring s 1)))
10922 (defun org-number-to-letters (n)
10923 "Convert an integer into a base 26 number represented by letters.
10924 For example: 28 -> AB."
10925 (let ((s ""))
10926 (while (> n 0)
10927 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10928 n (/ (1- n) 26)))
10931 (defun org-table-fedit-convert-buffer (function)
10932 "Convert all references in this buffer, using FUNTION."
10933 (let ((line (org-current-line)))
10934 (goto-char (point-min))
10935 (while (not (eobp))
10936 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10937 (delete-region (point) (point-at-eol))
10938 (or (eobp) (forward-char 1)))
10939 (goto-line line)))
10941 (defun org-table-fedit-toggle-ref-type ()
10942 "Convert all references in the buffer from B3 to @3$2 and back."
10943 (interactive)
10944 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10945 (org-table-fedit-convert-buffer
10946 (if org-table-buffer-is-an
10947 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10948 (message "Reference type switched to %s"
10949 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10951 (defun org-table-fedit-ref-up ()
10952 "Shift the reference at point one row/hline up."
10953 (interactive)
10954 (org-table-fedit-shift-reference 'up))
10955 (defun org-table-fedit-ref-down ()
10956 "Shift the reference at point one row/hline down."
10957 (interactive)
10958 (org-table-fedit-shift-reference 'down))
10959 (defun org-table-fedit-ref-left ()
10960 "Shift the reference at point one field to the left."
10961 (interactive)
10962 (org-table-fedit-shift-reference 'left))
10963 (defun org-table-fedit-ref-right ()
10964 "Shift the reference at point one field to the right."
10965 (interactive)
10966 (org-table-fedit-shift-reference 'right))
10968 (defun org-table-fedit-shift-reference (dir)
10969 (cond
10970 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10971 (if (memq dir '(left right))
10972 (org-rematch-and-replace 1 (eq dir 'left))
10973 (error "Cannot shift reference in this direction")))
10974 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10975 ;; A B3-like reference
10976 (if (memq dir '(up down))
10977 (org-rematch-and-replace 2 (eq dir 'up))
10978 (org-rematch-and-replace 1 (eq dir 'left))))
10979 ((org-at-regexp-p
10980 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10981 ;; An internal reference
10982 (if (memq dir '(up down))
10983 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10984 (org-rematch-and-replace 5 (eq dir 'left))))))
10986 (defun org-rematch-and-replace (n &optional decr hline)
10987 "Re-match the group N, and replace it with the shifted refrence."
10988 (or (match-end n) (error "Cannot shift reference in this direction"))
10989 (goto-char (match-beginning n))
10990 (and (looking-at (regexp-quote (match-string n)))
10991 (replace-match (org-shift-refpart (match-string 0) decr hline)
10992 t t)))
10994 (defun org-shift-refpart (ref &optional decr hline)
10995 "Shift a refrence part REF.
10996 If DECR is set, decrease the references row/column, else increase.
10997 If HLINE is set, this may be a hline reference, it certainly is not
10998 a translation reference."
10999 (save-match-data
11000 (let* ((sign (string-match "^[-+]" ref)) n)
11002 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
11003 (cond
11004 ((and hline (string-match "^I+" ref))
11005 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
11006 (setq n (+ n (if decr -1 1)))
11007 (if (= n 0) (setq n (+ n (if decr -1 1))))
11008 (if sign
11009 (setq sign (if (< n 0) "-" "+") n (abs n))
11010 (setq n (max 1 n)))
11011 (concat sign (make-string n ?I)))
11013 ((string-match "^[0-9]+" ref)
11014 (setq n (string-to-number (concat sign ref)))
11015 (setq n (+ n (if decr -1 1)))
11016 (if sign
11017 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
11018 (number-to-string (max 1 n))))
11020 ((string-match "^[a-zA-Z]+" ref)
11021 (org-number-to-letters
11022 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
11024 (t (error "Cannot shift reference"))))))
11026 (defun org-table-fedit-toggle-coordinates ()
11027 "Toggle the display of coordinates in the refrenced table."
11028 (interactive)
11029 (let ((pos (marker-position org-pos)))
11030 (with-current-buffer (marker-buffer org-pos)
11031 (save-excursion
11032 (goto-char pos)
11033 (org-table-toggle-coordinate-overlays)))))
11035 (defun org-table-fedit-finish (&optional arg)
11036 "Parse the buffer for formula definitions and install them.
11037 With prefix ARG, apply the new formulas to the table."
11038 (interactive "P")
11039 (org-table-remove-rectangle-highlight)
11040 (if org-table-use-standard-references
11041 (progn
11042 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
11043 (setq org-table-buffer-is-an nil)))
11044 (let ((pos org-pos) eql var form)
11045 (goto-char (point-min))
11046 (while (re-search-forward
11047 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
11048 nil t)
11049 (setq var (if (match-end 2) (match-string 2) (match-string 1))
11050 form (match-string 3))
11051 (setq form (org-trim form))
11052 (when (not (equal form ""))
11053 (while (string-match "[ \t]*\n[ \t]*" form)
11054 (setq form (replace-match " " t t form)))
11055 (when (assoc var eql)
11056 (error "Double formulas for %s" var))
11057 (push (cons var form) eql)))
11058 (setq org-pos nil)
11059 (set-window-configuration org-window-configuration)
11060 (select-window (get-buffer-window (marker-buffer pos)))
11061 (goto-char pos)
11062 (unless (org-at-table-p)
11063 (error "Lost table position - cannot install formulae"))
11064 (org-table-store-formulas eql)
11065 (move-marker pos nil)
11066 (kill-buffer "*Edit Formulas*")
11067 (if arg
11068 (org-table-recalculate 'all)
11069 (message "New formulas installed - press C-u C-c C-c to apply."))))
11071 (defun org-table-fedit-abort ()
11072 "Abort editing formulas, without installing the changes."
11073 (interactive)
11074 (org-table-remove-rectangle-highlight)
11075 (let ((pos org-pos))
11076 (set-window-configuration org-window-configuration)
11077 (select-window (get-buffer-window (marker-buffer pos)))
11078 (goto-char pos)
11079 (move-marker pos nil)
11080 (message "Formula editing aborted without installing changes")))
11082 (defun org-table-fedit-lisp-indent ()
11083 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
11084 (interactive)
11085 (let ((pos (point)) beg end ind)
11086 (beginning-of-line 1)
11087 (cond
11088 ((looking-at "[ \t]")
11089 (goto-char pos)
11090 (call-interactively 'lisp-indent-line))
11091 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
11092 ((not (fboundp 'pp-buffer))
11093 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
11094 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
11095 (goto-char (- (match-end 0) 2))
11096 (setq beg (point))
11097 (setq ind (make-string (current-column) ?\ ))
11098 (condition-case nil (forward-sexp 1)
11099 (error
11100 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
11101 (setq end (point))
11102 (save-restriction
11103 (narrow-to-region beg end)
11104 (if (eq last-command this-command)
11105 (progn
11106 (goto-char (point-min))
11107 (setq this-command nil)
11108 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
11109 (replace-match " ")))
11110 (pp-buffer)
11111 (untabify (point-min) (point-max))
11112 (goto-char (1+ (point-min)))
11113 (while (re-search-forward "^." nil t)
11114 (beginning-of-line 1)
11115 (insert ind))
11116 (goto-char (point-max))
11117 (backward-delete-char 1)))
11118 (goto-char beg))
11119 (t nil))))
11121 (defvar org-show-positions nil)
11123 (defun org-table-show-reference (&optional local)
11124 "Show the location/value of the $ expression at point."
11125 (interactive)
11126 (org-table-remove-rectangle-highlight)
11127 (catch 'exit
11128 (let ((pos (if local (point) org-pos))
11129 (face2 'highlight)
11130 (org-inhibit-highlight-removal t)
11131 (win (selected-window))
11132 (org-show-positions nil)
11133 var name e what match dest)
11134 (if local (org-table-get-specials))
11135 (setq what (cond
11136 ((or (org-at-regexp-p org-table-range-regexp2)
11137 (org-at-regexp-p org-table-translate-regexp)
11138 (org-at-regexp-p org-table-range-regexp))
11139 (setq match
11140 (save-match-data
11141 (org-table-convert-refs-to-rc (match-string 0))))
11142 'range)
11143 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11144 ((org-at-regexp-p "\\$[0-9]+") 'column)
11145 ((not local) nil)
11146 (t (error "No reference at point")))
11147 match (and what (or match (match-string 0))))
11148 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11149 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11150 'secondary-selection))
11151 (org-add-hook 'before-change-functions
11152 'org-table-remove-rectangle-highlight)
11153 (if (eq what 'name) (setq var (substring match 1)))
11154 (when (eq what 'range)
11155 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11156 (setq match (org-table-formula-substitute-names match)))
11157 (unless local
11158 (save-excursion
11159 (end-of-line 1)
11160 (re-search-backward "^\\S-" nil t)
11161 (beginning-of-line 1)
11162 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11163 (setq dest
11164 (save-match-data
11165 (org-table-convert-refs-to-rc (match-string 1))))
11166 (org-table-add-rectangle-overlay
11167 (match-beginning 1) (match-end 1) face2))))
11168 (if (and (markerp pos) (marker-buffer pos))
11169 (if (get-buffer-window (marker-buffer pos))
11170 (select-window (get-buffer-window (marker-buffer pos)))
11171 (org-switch-to-buffer-other-window (get-buffer-window
11172 (marker-buffer pos)))))
11173 (goto-char pos)
11174 (org-table-force-dataline)
11175 (when dest
11176 (setq name (substring dest 1))
11177 (cond
11178 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11179 (setq e (assoc name org-table-named-field-locations))
11180 (goto-line (nth 1 e))
11181 (org-table-goto-column (nth 2 e)))
11182 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11183 (let ((l (string-to-number (match-string 1 dest)))
11184 (c (string-to-number (match-string 2 dest))))
11185 (goto-line (aref org-table-dlines l))
11186 (org-table-goto-column c)))
11187 (t (org-table-goto-column (string-to-number name))))
11188 (move-marker pos (point))
11189 (org-table-highlight-rectangle nil nil face2))
11190 (cond
11191 ((equal dest match))
11192 ((not match))
11193 ((eq what 'range)
11194 (condition-case nil
11195 (save-excursion
11196 (org-table-get-range match nil nil 'highlight))
11197 (error nil)))
11198 ((setq e (assoc var org-table-named-field-locations))
11199 (goto-line (nth 1 e))
11200 (org-table-goto-column (nth 2 e))
11201 (org-table-highlight-rectangle (point) (point))
11202 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11203 ((setq e (assoc var org-table-column-names))
11204 (org-table-goto-column (string-to-number (cdr e)))
11205 (org-table-highlight-rectangle (point) (point))
11206 (goto-char (org-table-begin))
11207 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11208 (org-table-end) t)
11209 (progn
11210 (goto-char (match-beginning 1))
11211 (org-table-highlight-rectangle)
11212 (message "Named column (column %s)" (cdr e)))
11213 (error "Column name not found")))
11214 ((eq what 'column)
11215 ;; column number
11216 (org-table-goto-column (string-to-number (substring match 1)))
11217 (org-table-highlight-rectangle (point) (point))
11218 (message "Column %s" (substring match 1)))
11219 ((setq e (assoc var org-table-local-parameters))
11220 (goto-char (org-table-begin))
11221 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11222 (progn
11223 (goto-char (match-beginning 1))
11224 (org-table-highlight-rectangle)
11225 (message "Local parameter."))
11226 (error "Parameter not found")))
11228 (cond
11229 ((not var) (error "No reference at point"))
11230 ((setq e (assoc var org-table-formula-constants-local))
11231 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11232 var (cdr e)))
11233 ((setq e (assoc var org-table-formula-constants))
11234 (message "Constant: $%s=%s in `org-table-formula-constants'."
11235 var (cdr e)))
11236 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11237 (message "Constant: $%s=%s, from `constants.el'%s."
11238 var e (format " (%s units)" constants-unit-system)))
11239 (t (error "Undefined name $%s" var)))))
11240 (goto-char pos)
11241 (when (and org-show-positions
11242 (not (memq this-command '(org-table-fedit-scroll
11243 org-table-fedit-scroll-down))))
11244 (push pos org-show-positions)
11245 (push org-table-current-begin-pos org-show-positions)
11246 (let ((min (apply 'min org-show-positions))
11247 (max (apply 'max org-show-positions)))
11248 (goto-char min) (recenter 0)
11249 (goto-char max)
11250 (or (pos-visible-in-window-p max) (recenter -1))))
11251 (select-window win))))
11253 (defun org-table-force-dataline ()
11254 "Make sure the cursor is in a dataline in a table."
11255 (unless (save-excursion
11256 (beginning-of-line 1)
11257 (looking-at org-table-dataline-regexp))
11258 (let* ((re org-table-dataline-regexp)
11259 (p1 (save-excursion (re-search-forward re nil 'move)))
11260 (p2 (save-excursion (re-search-backward re nil 'move))))
11261 (cond ((and p1 p2)
11262 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11263 p1 p2)))
11264 ((or p1 p2) (goto-char (or p1 p2)))
11265 (t (error "No table dataline around here"))))))
11267 (defun org-table-fedit-line-up ()
11268 "Move cursor one line up in the window showing the table."
11269 (interactive)
11270 (org-table-fedit-move 'previous-line))
11272 (defun org-table-fedit-line-down ()
11273 "Move cursor one line down in the window showing the table."
11274 (interactive)
11275 (org-table-fedit-move 'next-line))
11277 (defun org-table-fedit-move (command)
11278 "Move the cursor in the window shoinw the table.
11279 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11280 (let ((org-table-allow-automatic-line-recalculation nil)
11281 (pos org-pos) (win (selected-window)) p)
11282 (select-window (get-buffer-window (marker-buffer org-pos)))
11283 (setq p (point))
11284 (call-interactively command)
11285 (while (and (org-at-table-p)
11286 (org-at-table-hline-p))
11287 (call-interactively command))
11288 (or (org-at-table-p) (goto-char p))
11289 (move-marker pos (point))
11290 (select-window win)))
11292 (defun org-table-fedit-scroll (N)
11293 (interactive "p")
11294 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11295 (scroll-other-window N)))
11297 (defun org-table-fedit-scroll-down (N)
11298 (interactive "p")
11299 (org-table-fedit-scroll (- N)))
11301 (defvar org-table-rectangle-overlays nil)
11303 (defun org-table-add-rectangle-overlay (beg end &optional face)
11304 "Add a new overlay."
11305 (let ((ov (org-make-overlay beg end)))
11306 (org-overlay-put ov 'face (or face 'secondary-selection))
11307 (push ov org-table-rectangle-overlays)))
11309 (defun org-table-highlight-rectangle (&optional beg end face)
11310 "Highlight rectangular region in a table."
11311 (setq beg (or beg (point)) end (or end (point)))
11312 (let ((b (min beg end))
11313 (e (max beg end))
11314 l1 c1 l2 c2 tmp)
11315 (and (boundp 'org-show-positions)
11316 (setq org-show-positions (cons b (cons e org-show-positions))))
11317 (goto-char (min beg end))
11318 (setq l1 (org-current-line)
11319 c1 (org-table-current-column))
11320 (goto-char (max beg end))
11321 (setq l2 (org-current-line)
11322 c2 (org-table-current-column))
11323 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11324 (goto-line l1)
11325 (beginning-of-line 1)
11326 (loop for line from l1 to l2 do
11327 (when (looking-at org-table-dataline-regexp)
11328 (org-table-goto-column c1)
11329 (skip-chars-backward "^|\n") (setq beg (point))
11330 (org-table-goto-column c2)
11331 (skip-chars-forward "^|\n") (setq end (point))
11332 (org-table-add-rectangle-overlay beg end face))
11333 (beginning-of-line 2))
11334 (goto-char b))
11335 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11337 (defun org-table-remove-rectangle-highlight (&rest ignore)
11338 "Remove the rectangle overlays."
11339 (unless org-inhibit-highlight-removal
11340 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11341 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11342 (setq org-table-rectangle-overlays nil)))
11344 (defvar org-table-coordinate-overlays nil
11345 "Collects the cooordinate grid overlays, so that they can be removed.")
11346 (make-variable-buffer-local 'org-table-coordinate-overlays)
11348 (defun org-table-overlay-coordinates ()
11349 "Add overlays to the table at point, to show row/column coordinates."
11350 (interactive)
11351 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11352 (setq org-table-coordinate-overlays nil)
11353 (save-excursion
11354 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11355 (goto-char (org-table-begin))
11356 (while (org-at-table-p)
11357 (setq eol (point-at-eol))
11358 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11359 (push ov org-table-coordinate-overlays)
11360 (setq hline (looking-at org-table-hline-regexp))
11361 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11362 (format "%4d" (setq id (1+ id)))))
11363 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11364 (when hline
11365 (setq ic 0)
11366 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11367 (setq beg (1+ (match-beginning 0))
11368 ic (1+ ic)
11369 s1 (concat "$" (int-to-string ic))
11370 s2 (org-number-to-letters ic)
11371 str (if (eq org-table-use-standard-references t) s2 s1))
11372 (setq ov (org-make-overlay beg (+ beg (length str))))
11373 (push ov org-table-coordinate-overlays)
11374 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11375 (beginning-of-line 2)))))
11377 (defun org-table-toggle-coordinate-overlays ()
11378 "Toggle the display of Row/Column numbers in tables."
11379 (interactive)
11380 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11381 (message "Row/Column number display turned %s"
11382 (if org-table-overlay-coordinates "on" "off"))
11383 (if (and (org-at-table-p) org-table-overlay-coordinates)
11384 (org-table-align))
11385 (unless org-table-overlay-coordinates
11386 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11387 (setq org-table-coordinate-overlays nil)))
11389 (defun org-table-toggle-formula-debugger ()
11390 "Toggle the formula debugger in tables."
11391 (interactive)
11392 (setq org-table-formula-debug (not org-table-formula-debug))
11393 (message "Formula debugging has been turned %s"
11394 (if org-table-formula-debug "on" "off")))
11396 ;;; The orgtbl minor mode
11398 ;; Define a minor mode which can be used in other modes in order to
11399 ;; integrate the org-mode table editor.
11401 ;; This is really a hack, because the org-mode table editor uses several
11402 ;; keys which normally belong to the major mode, for example the TAB and
11403 ;; RET keys. Here is how it works: The minor mode defines all the keys
11404 ;; necessary to operate the table editor, but wraps the commands into a
11405 ;; function which tests if the cursor is currently inside a table. If that
11406 ;; is the case, the table editor command is executed. However, when any of
11407 ;; those keys is used outside a table, the function uses `key-binding' to
11408 ;; look up if the key has an associated command in another currently active
11409 ;; keymap (minor modes, major mode, global), and executes that command.
11410 ;; There might be problems if any of the keys used by the table editor is
11411 ;; otherwise used as a prefix key.
11413 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11414 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11415 ;; addresses this by checking explicitly for both bindings.
11417 ;; The optimized version (see variable `orgtbl-optimized') takes over
11418 ;; all keys which are bound to `self-insert-command' in the *global map*.
11419 ;; Some modes bind other commands to simple characters, for example
11420 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11421 ;; active, this binding is ignored inside tables and replaced with a
11422 ;; modified self-insert.
11424 (defvar orgtbl-mode nil
11425 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11426 table editor in arbitrary modes.")
11427 (make-variable-buffer-local 'orgtbl-mode)
11429 (defvar orgtbl-mode-map (make-keymap)
11430 "Keymap for `orgtbl-mode'.")
11432 ;;;###autoload
11433 (defun turn-on-orgtbl ()
11434 "Unconditionally turn on `orgtbl-mode'."
11435 (orgtbl-mode 1))
11437 (defvar org-old-auto-fill-inhibit-regexp nil
11438 "Local variable used by `orgtbl-mode'")
11440 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11441 "Matches a line belonging to an orgtbl.")
11443 (defconst orgtbl-extra-font-lock-keywords
11444 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11445 0 (quote 'org-table) 'prepend))
11446 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11448 ;;;###autoload
11449 (defun orgtbl-mode (&optional arg)
11450 "The `org-mode' table editor as a minor mode for use in other modes."
11451 (interactive)
11452 (if (org-mode-p)
11453 ;; Exit without error, in case some hook functions calls this
11454 ;; by accident in org-mode.
11455 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11456 (setq orgtbl-mode
11457 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11458 (if orgtbl-mode
11459 (progn
11460 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11461 ;; Make sure we are first in minor-mode-map-alist
11462 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11463 (and c (setq minor-mode-map-alist
11464 (cons c (delq c minor-mode-map-alist)))))
11465 (org-set-local (quote org-table-may-need-update) t)
11466 (org-add-hook 'before-change-functions 'org-before-change-function
11467 nil 'local)
11468 (org-set-local 'org-old-auto-fill-inhibit-regexp
11469 auto-fill-inhibit-regexp)
11470 (org-set-local 'auto-fill-inhibit-regexp
11471 (if auto-fill-inhibit-regexp
11472 (concat orgtbl-line-start-regexp "\\|"
11473 auto-fill-inhibit-regexp)
11474 orgtbl-line-start-regexp))
11475 (org-add-to-invisibility-spec '(org-cwidth))
11476 (when (fboundp 'font-lock-add-keywords)
11477 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11478 (org-restart-font-lock))
11479 (easy-menu-add orgtbl-mode-menu)
11480 (run-hooks 'orgtbl-mode-hook))
11481 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11482 (org-cleanup-narrow-column-properties)
11483 (org-remove-from-invisibility-spec '(org-cwidth))
11484 (remove-hook 'before-change-functions 'org-before-change-function t)
11485 (when (fboundp 'font-lock-remove-keywords)
11486 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11487 (org-restart-font-lock))
11488 (easy-menu-remove orgtbl-mode-menu)
11489 (force-mode-line-update 'all))))
11491 (defun org-cleanup-narrow-column-properties ()
11492 "Remove all properties related to narrow-column invisibility."
11493 (let ((s 1))
11494 (while (setq s (text-property-any s (point-max)
11495 'display org-narrow-column-arrow))
11496 (remove-text-properties s (1+ s) '(display t)))
11497 (setq s 1)
11498 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11499 (remove-text-properties s (1+ s) '(org-cwidth t)))
11500 (setq s 1)
11501 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11502 (remove-text-properties s (1+ s) '(invisible t)))))
11504 ;; Install it as a minor mode.
11505 (put 'orgtbl-mode :included t)
11506 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11507 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11509 (defun orgtbl-make-binding (fun n &rest keys)
11510 "Create a function for binding in the table minor mode.
11511 FUN is the command to call inside a table. N is used to create a unique
11512 command name. KEYS are keys that should be checked in for a command
11513 to execute outside of tables."
11514 (eval
11515 (list 'defun
11516 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11517 '(arg)
11518 (concat "In tables, run `" (symbol-name fun) "'.\n"
11519 "Outside of tables, run the binding of `"
11520 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11521 "'.")
11522 '(interactive "p")
11523 (list 'if
11524 '(org-at-table-p)
11525 (list 'call-interactively (list 'quote fun))
11526 (list 'let '(orgtbl-mode)
11527 (list 'call-interactively
11528 (append '(or)
11529 (mapcar (lambda (k)
11530 (list 'key-binding k))
11531 keys)
11532 '('orgtbl-error))))))))
11534 (defun orgtbl-error ()
11535 "Error when there is no default binding for a table key."
11536 (interactive)
11537 (error "This key has no function outside tables"))
11539 (defun orgtbl-setup ()
11540 "Setup orgtbl keymaps."
11541 (let ((nfunc 0)
11542 (bindings
11543 (list
11544 '([(meta shift left)] org-table-delete-column)
11545 '([(meta left)] org-table-move-column-left)
11546 '([(meta right)] org-table-move-column-right)
11547 '([(meta shift right)] org-table-insert-column)
11548 '([(meta shift up)] org-table-kill-row)
11549 '([(meta shift down)] org-table-insert-row)
11550 '([(meta up)] org-table-move-row-up)
11551 '([(meta down)] org-table-move-row-down)
11552 '("\C-c\C-w" org-table-cut-region)
11553 '("\C-c\M-w" org-table-copy-region)
11554 '("\C-c\C-y" org-table-paste-rectangle)
11555 '("\C-c-" org-table-insert-hline)
11556 '("\C-c}" org-table-toggle-coordinate-overlays)
11557 '("\C-c{" org-table-toggle-formula-debugger)
11558 '("\C-m" org-table-next-row)
11559 '([(shift return)] org-table-copy-down)
11560 '("\C-c\C-q" org-table-wrap-region)
11561 '("\C-c?" org-table-field-info)
11562 '("\C-c " org-table-blank-field)
11563 '("\C-c+" org-table-sum)
11564 '("\C-c=" org-table-eval-formula)
11565 '("\C-c'" org-table-edit-formulas)
11566 '("\C-c`" org-table-edit-field)
11567 '("\C-c*" org-table-recalculate)
11568 '("\C-c|" org-table-create-or-convert-from-region)
11569 '("\C-c^" org-table-sort-lines)
11570 '([(control ?#)] org-table-rotate-recalc-marks)))
11571 elt key fun cmd)
11572 (while (setq elt (pop bindings))
11573 (setq nfunc (1+ nfunc))
11574 (setq key (org-key (car elt))
11575 fun (nth 1 elt)
11576 cmd (orgtbl-make-binding fun nfunc key))
11577 (org-defkey orgtbl-mode-map key cmd))
11579 ;; Special treatment needed for TAB and RET
11580 (org-defkey orgtbl-mode-map [(return)]
11581 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11582 (org-defkey orgtbl-mode-map "\C-m"
11583 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11585 (org-defkey orgtbl-mode-map [(tab)]
11586 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11587 (org-defkey orgtbl-mode-map "\C-i"
11588 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11590 (org-defkey orgtbl-mode-map [(shift tab)]
11591 (orgtbl-make-binding 'org-table-previous-field 104
11592 [(shift tab)] [(tab)] "\C-i"))
11594 (org-defkey orgtbl-mode-map "\M-\C-m"
11595 (orgtbl-make-binding 'org-table-wrap-region 105
11596 "\M-\C-m" [(meta return)]))
11597 (org-defkey orgtbl-mode-map [(meta return)]
11598 (orgtbl-make-binding 'org-table-wrap-region 106
11599 [(meta return)] "\M-\C-m"))
11601 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11602 (when orgtbl-optimized
11603 ;; If the user wants maximum table support, we need to hijack
11604 ;; some standard editing functions
11605 (org-remap orgtbl-mode-map
11606 'self-insert-command 'orgtbl-self-insert-command
11607 'delete-char 'org-delete-char
11608 'delete-backward-char 'org-delete-backward-char)
11609 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11610 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11611 '("OrgTbl"
11612 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11613 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11614 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11615 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11616 "--"
11617 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11618 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11619 ["Copy Field from Above"
11620 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11621 "--"
11622 ("Column"
11623 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11624 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11625 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11626 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11627 ("Row"
11628 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11629 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11630 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11631 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11632 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
11633 "--"
11634 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11635 ("Rectangle"
11636 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11637 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11638 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11639 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11640 "--"
11641 ("Radio tables"
11642 ["Insert table template" orgtbl-insert-radio-table
11643 (assq major-mode orgtbl-radio-table-templates)]
11644 ["Comment/uncomment table" orgtbl-toggle-comment t])
11645 "--"
11646 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11647 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11648 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11649 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11650 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11651 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11652 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11653 ["Sum Column/Rectangle" org-table-sum
11654 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11655 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11656 ["Debug Formulas"
11657 org-table-toggle-formula-debugger :active (org-at-table-p)
11658 :keys "C-c {"
11659 :style toggle :selected org-table-formula-debug]
11660 ["Show Col/Row Numbers"
11661 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11662 :keys "C-c }"
11663 :style toggle :selected org-table-overlay-coordinates]
11667 (defun orgtbl-ctrl-c-ctrl-c (arg)
11668 "If the cursor is inside a table, realign the table.
11669 It it is a table to be sent away to a receiver, do it.
11670 With prefix arg, also recompute table."
11671 (interactive "P")
11672 (let ((pos (point)) action)
11673 (save-excursion
11674 (beginning-of-line 1)
11675 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11676 ((looking-at "[ \t]*|") pos)
11677 ((looking-at "#\\+TBLFM:") 'recalc))))
11678 (cond
11679 ((integerp action)
11680 (goto-char action)
11681 (org-table-maybe-eval-formula)
11682 (if arg
11683 (call-interactively 'org-table-recalculate)
11684 (org-table-maybe-recalculate-line))
11685 (call-interactively 'org-table-align)
11686 (orgtbl-send-table 'maybe))
11687 ((eq action 'recalc)
11688 (save-excursion
11689 (beginning-of-line 1)
11690 (skip-chars-backward " \r\n\t")
11691 (if (org-at-table-p)
11692 (org-call-with-arg 'org-table-recalculate t))))
11693 (t (let (orgtbl-mode)
11694 (call-interactively (key-binding "\C-c\C-c")))))))
11696 (defun orgtbl-tab (arg)
11697 "Justification and field motion for `orgtbl-mode'."
11698 (interactive "P")
11699 (if arg (org-table-edit-field t)
11700 (org-table-justify-field-maybe)
11701 (org-table-next-field)))
11703 (defun orgtbl-ret ()
11704 "Justification and field motion for `orgtbl-mode'."
11705 (interactive)
11706 (org-table-justify-field-maybe)
11707 (org-table-next-row))
11709 (defun orgtbl-self-insert-command (N)
11710 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11711 If the cursor is in a table looking at whitespace, the whitespace is
11712 overwritten, and the table is not marked as requiring realignment."
11713 (interactive "p")
11714 (if (and (org-at-table-p)
11716 (and org-table-auto-blank-field
11717 (member last-command
11718 '(orgtbl-hijacker-command-100
11719 orgtbl-hijacker-command-101
11720 orgtbl-hijacker-command-102
11721 orgtbl-hijacker-command-103
11722 orgtbl-hijacker-command-104
11723 orgtbl-hijacker-command-105))
11724 (org-table-blank-field))
11726 (eq N 1)
11727 (looking-at "[^|\n]* +|"))
11728 (let (org-table-may-need-update)
11729 (goto-char (1- (match-end 0)))
11730 (delete-backward-char 1)
11731 (goto-char (match-beginning 0))
11732 (self-insert-command N))
11733 (setq org-table-may-need-update t)
11734 (let (orgtbl-mode)
11735 (call-interactively (key-binding (vector last-input-event))))))
11737 (defun org-force-self-insert (N)
11738 "Needed to enforce self-insert under remapping."
11739 (interactive "p")
11740 (self-insert-command N))
11742 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11743 "Regula expression matching exponentials as produced by calc.")
11745 (defvar org-table-clean-did-remove-column nil)
11747 (defun orgtbl-export (table target)
11748 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11749 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11750 org-table-last-alignment org-table-last-column-widths
11751 maxcol column)
11752 (if (not (fboundp func))
11753 (error "Cannot export orgtbl table to %s" target))
11754 (setq lines (org-table-clean-before-export lines))
11755 (setq table
11756 (mapcar
11757 (lambda (x)
11758 (if (string-match org-table-hline-regexp x)
11759 'hline
11760 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11761 lines))
11762 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11763 table)))
11764 (loop for i from (1- maxcol) downto 0 do
11765 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11766 (setq column (delq nil column))
11767 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11768 (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))
11769 (funcall func table nil)))
11771 (defun orgtbl-send-table (&optional maybe)
11772 "Send a tranformed version of this table to the receiver position.
11773 With argument MAYBE, fail quietly if no transformation is defined for
11774 this table."
11775 (interactive)
11776 (catch 'exit
11777 (unless (org-at-table-p) (error "Not at a table"))
11778 ;; when non-interactive, we assume align has just happened.
11779 (when (interactive-p) (org-table-align))
11780 (save-excursion
11781 (goto-char (org-table-begin))
11782 (beginning-of-line 0)
11783 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11784 (if maybe
11785 (throw 'exit nil)
11786 (error "Don't know how to transform this table."))))
11787 (let* ((name (match-string 1))
11789 (transform (intern (match-string 2)))
11790 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11791 (skip (plist-get params :skip))
11792 (skipcols (plist-get params :skipcols))
11793 (txt (buffer-substring-no-properties
11794 (org-table-begin) (org-table-end)))
11795 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11796 (lines (org-table-clean-before-export lines))
11797 (i0 (if org-table-clean-did-remove-column 2 1))
11798 (table (mapcar
11799 (lambda (x)
11800 (if (string-match org-table-hline-regexp x)
11801 'hline
11802 (org-remove-by-index
11803 (org-split-string (org-trim x) "\\s-*|\\s-*")
11804 skipcols i0)))
11805 lines))
11806 (fun (if (= i0 2) 'cdr 'identity))
11807 (org-table-last-alignment
11808 (org-remove-by-index (funcall fun org-table-last-alignment)
11809 skipcols i0))
11810 (org-table-last-column-widths
11811 (org-remove-by-index (funcall fun org-table-last-column-widths)
11812 skipcols i0)))
11814 (unless (fboundp transform)
11815 (error "No such transformation function %s" transform))
11816 (setq txt (funcall transform table params))
11817 ;; Find the insertion place
11818 (save-excursion
11819 (goto-char (point-min))
11820 (unless (re-search-forward
11821 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11822 (error "Don't know where to insert translated table"))
11823 (goto-char (match-beginning 0))
11824 (beginning-of-line 2)
11825 (setq beg (point))
11826 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11827 (error "Cannot find end of insertion region"))
11828 (beginning-of-line 1)
11829 (delete-region beg (point))
11830 (goto-char beg)
11831 (insert txt "\n"))
11832 (message "Table converted and installed at receiver location"))))
11834 (defun org-remove-by-index (list indices &optional i0)
11835 "Remove the elements in LIST with indices in INDICES.
11836 First element has index 0, or I0 if given."
11837 (if (not indices)
11838 list
11839 (if (integerp indices) (setq indices (list indices)))
11840 (setq i0 (1- (or i0 0)))
11841 (delq :rm (mapcar (lambda (x)
11842 (setq i0 (1+ i0))
11843 (if (memq i0 indices) :rm x))
11844 list))))
11846 (defun orgtbl-toggle-comment ()
11847 "Comment or uncomment the orgtbl at point."
11848 (interactive)
11849 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11850 (re2 (concat "^" orgtbl-line-start-regexp))
11851 (commented (save-excursion (beginning-of-line 1)
11852 (cond ((looking-at re1) t)
11853 ((looking-at re2) nil)
11854 (t (error "Not at an org table")))))
11855 (re (if commented re1 re2))
11856 beg end)
11857 (save-excursion
11858 (beginning-of-line 1)
11859 (while (looking-at re) (beginning-of-line 0))
11860 (beginning-of-line 2)
11861 (setq beg (point))
11862 (while (looking-at re) (beginning-of-line 2))
11863 (setq end (point)))
11864 (comment-region beg end (if commented '(4) nil))))
11866 (defun orgtbl-insert-radio-table ()
11867 "Insert a radio table template appropriate for this major mode."
11868 (interactive)
11869 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11870 (txt (nth 1 e))
11871 name pos)
11872 (unless e (error "No radio table setup defined for %s" major-mode))
11873 (setq name (read-string "Table name: "))
11874 (while (string-match "%n" txt)
11875 (setq txt (replace-match name t t txt)))
11876 (or (bolp) (insert "\n"))
11877 (setq pos (point))
11878 (insert txt)
11879 (goto-char pos)))
11881 (defun org-get-param (params header i sym &optional hsym)
11882 "Get parameter value for symbol SYM.
11883 If this is a header line, actually get the value for the symbol with an
11884 additional \"h\" inserted after the colon.
11885 If the value is a protperty list, get the element for the current column.
11886 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11887 (let ((val (plist-get params sym)))
11888 (and hsym header (setq val (or (plist-get params hsym) val)))
11889 (if (consp val) (plist-get val i) val)))
11891 (defun orgtbl-to-generic (table params)
11892 "Convert the orgtbl-mode TABLE to some other format.
11893 This generic routine can be used for many standard cases.
11894 TABLE is a list, each entry either the symbol `hline' for a horizontal
11895 separator line, or a list of fields for that line.
11896 PARAMS is a property list of parameters that can influence the conversion.
11897 For the generic converter, some parameters are obligatory: You need to
11898 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11899 :splice, you must have :tstart and :tend.
11901 Valid parameters are
11903 :tstart String to start the table. Ignored when :splice is t.
11904 :tend String to end the table. Ignored when :splice is t.
11906 :splice When set to t, return only table body lines, don't wrap
11907 them into :tstart and :tend. Default is nil.
11909 :hline String to be inserted on horizontal separation lines.
11910 May be nil to ignore hlines.
11912 :lstart String to start a new table line.
11913 :lend String to end a table line
11914 :sep Separator between two fields
11915 :lfmt Format for entire line, with enough %s to capture all fields.
11916 If this is present, :lstart, :lend, and :sep are ignored.
11917 :fmt A format to be used to wrap the field, should contain
11918 %s for the original field value. For example, to wrap
11919 everything in dollars, you could use :fmt \"$%s$\".
11920 This may also be a property list with column numbers and
11921 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11923 :hlstart :hlend :hlsep :hlfmt :hfmt
11924 Same as above, specific for the header lines in the table.
11925 All lines before the first hline are treated as header.
11926 If any of these is not present, the data line value is used.
11928 :efmt Use this format to print numbers with exponentials.
11929 The format should have %s twice for inserting mantissa
11930 and exponent, for example \"%s\\\\times10^{%s}\". This
11931 may also be a property list with column numbers and
11932 formats. :fmt will still be applied after :efmt.
11934 In addition to this, the parameters :skip and :skipcols are always handled
11935 directly by `orgtbl-send-table'. See manual."
11936 (interactive)
11937 (let* ((p params)
11938 (splicep (plist-get p :splice))
11939 (hline (plist-get p :hline))
11940 rtn line i fm efm lfmt h)
11942 ;; Do we have a header?
11943 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11944 (setq h t))
11946 ;; Put header
11947 (unless splicep
11948 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11950 ;; Now loop over all lines
11951 (while (setq line (pop table))
11952 (if (eq line 'hline)
11953 ;; A horizontal separator line
11954 (progn (if hline (push hline rtn))
11955 (setq h nil)) ; no longer in header
11956 ;; A normal line. Convert the fields, push line onto the result list
11957 (setq i 0)
11958 (setq line
11959 (mapcar
11960 (lambda (f)
11961 (setq i (1+ i)
11962 fm (org-get-param p h i :fmt :hfmt)
11963 efm (org-get-param p h i :efmt))
11964 (if (and efm (string-match orgtbl-exp-regexp f))
11965 (setq f (format
11966 efm (match-string 1 f) (match-string 2 f))))
11967 (if fm (setq f (format fm f)))
11969 line))
11970 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11971 (push (apply 'format lfmt line) rtn)
11972 (push (concat
11973 (org-get-param p h i :lstart :hlstart)
11974 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11975 (org-get-param p h i :lend :hlend))
11976 rtn))))
11978 (unless splicep
11979 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11981 (mapconcat 'identity (nreverse rtn) "\n")))
11983 (defun orgtbl-to-latex (table params)
11984 "Convert the orgtbl-mode TABLE to LaTeX.
11985 TABLE is a list, each entry either the symbol `hline' for a horizontal
11986 separator line, or a list of fields for that line.
11987 PARAMS is a property list of parameters that can influence the conversion.
11988 Supports all parameters from `orgtbl-to-generic'. Most important for
11989 LaTeX are:
11991 :splice When set to t, return only table body lines, don't wrap
11992 them into a tabular environment. Default is nil.
11994 :fmt A format to be used to wrap the field, should contain %s for the
11995 original field value. For example, to wrap everything in dollars,
11996 use :fmt \"$%s$\". This may also be a property list with column
11997 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11999 :efmt Format for transforming numbers with exponentials. The format
12000 should have %s twice for inserting mantissa and exponent, for
12001 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
12002 This may also be a property list with column numbers and formats.
12004 The general parameters :skip and :skipcols have already been applied when
12005 this function is called."
12006 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
12007 org-table-last-alignment ""))
12008 (params2
12009 (list
12010 :tstart (concat "\\begin{tabular}{" alignment "}")
12011 :tend "\\end{tabular}"
12012 :lstart "" :lend " \\\\" :sep " & "
12013 :efmt "%s\\,(%s)" :hline "\\hline")))
12014 (orgtbl-to-generic table (org-combine-plists params2 params))))
12016 (defun orgtbl-to-html (table params)
12017 "Convert the orgtbl-mode TABLE to LaTeX.
12018 TABLE is a list, each entry either the symbol `hline' for a horizontal
12019 separator line, or a list of fields for that line.
12020 PARAMS is a property list of parameters that can influence the conversion.
12021 Currently this function recognizes the following parameters:
12023 :splice When set to t, return only table body lines, don't wrap
12024 them into a <table> environment. Default is nil.
12026 The general parameters :skip and :skipcols have already been applied when
12027 this function is called. The function does *not* use `orgtbl-to-generic',
12028 so you cannot specify parameters for it."
12029 (let* ((splicep (plist-get params :splice))
12030 html)
12031 ;; Just call the formatter we already have
12032 ;; We need to make text lines for it, so put the fields back together.
12033 (setq html (org-format-org-table-html
12034 (mapcar
12035 (lambda (x)
12036 (if (eq x 'hline)
12037 "|----+----|"
12038 (concat "| " (mapconcat 'identity x " | ") " |")))
12039 table)
12040 splicep))
12041 (if (string-match "\n+\\'" html)
12042 (setq html (replace-match "" t t html)))
12043 html))
12045 (defun orgtbl-to-texinfo (table params)
12046 "Convert the orgtbl-mode TABLE to TeXInfo.
12047 TABLE is a list, each entry either the symbol `hline' for a horizontal
12048 separator line, or a list of fields for that line.
12049 PARAMS is a property list of parameters that can influence the conversion.
12050 Supports all parameters from `orgtbl-to-generic'. Most important for
12051 TeXInfo are:
12053 :splice nil/t When set to t, return only table body lines, don't wrap
12054 them into a multitable environment. Default is nil.
12056 :fmt fmt A format to be used to wrap the field, should contain
12057 %s for the original field value. For example, to wrap
12058 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
12059 This may also be a property list with column numbers and
12060 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
12062 :cf \"f1 f2..\" The column fractions for the table. By default these
12063 are computed automatically from the width of the columns
12064 under org-mode.
12066 The general parameters :skip and :skipcols have already been applied when
12067 this function is called."
12068 (let* ((total (float (apply '+ org-table-last-column-widths)))
12069 (colfrac (or (plist-get params :cf)
12070 (mapconcat
12071 (lambda (x) (format "%.3f" (/ (float x) total)))
12072 org-table-last-column-widths " ")))
12073 (params2
12074 (list
12075 :tstart (concat "@multitable @columnfractions " colfrac)
12076 :tend "@end multitable"
12077 :lstart "@item " :lend "" :sep " @tab "
12078 :hlstart "@headitem ")))
12079 (orgtbl-to-generic table (org-combine-plists params2 params))))
12081 ;;;; Link Stuff
12083 ;;; Link abbreviations
12085 (defun org-link-expand-abbrev (link)
12086 "Apply replacements as defined in `org-link-abbrev-alist."
12087 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
12088 (let* ((key (match-string 1 link))
12089 (as (or (assoc key org-link-abbrev-alist-local)
12090 (assoc key org-link-abbrev-alist)))
12091 (tag (and (match-end 2) (match-string 3 link)))
12092 rpl)
12093 (if (not as)
12094 link
12095 (setq rpl (cdr as))
12096 (cond
12097 ((symbolp rpl) (funcall rpl tag))
12098 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
12099 (t (concat rpl tag)))))
12100 link))
12102 ;;; Storing and inserting links
12104 (defvar org-insert-link-history nil
12105 "Minibuffer history for links inserted with `org-insert-link'.")
12107 (defvar org-stored-links nil
12108 "Contains the links stored with `org-store-link'.")
12110 (defvar org-store-link-plist nil
12111 "Plist with info about the most recently link created with `org-store-link'.")
12113 (defvar org-link-protocols nil
12114 "Link protocols added to Org-mode using `org-add-link-type'.")
12116 (defvar org-store-link-functions nil
12117 "List of functions that are called to create and store a link.
12118 Each function will be called in turn until one returns a non-nil
12119 value. Each function should check if it is responsible for creating
12120 this link (for example by looking at the major mode).
12121 If not, it must exit and return nil.
12122 If yes, it should return a non-nil value after a calling
12123 `org-store-link-props' with a list of properties and values.
12124 Special properties are:
12126 :type The link prefix. like \"http\". This must be given.
12127 :link The link, like \"http://www.astro.uva.nl/~dominik\".
12128 This is obligatory as well.
12129 :description Optional default description for the second pair
12130 of brackets in an Org-mode link. The user can still change
12131 this when inserting this link into an Org-mode buffer.
12133 In addition to these, any additional properties can be specified
12134 and then used in remember templates.")
12136 (defun org-add-link-type (type &optional follow publish)
12137 "Add TYPE to the list of `org-link-types'.
12138 Re-compute all regular expressions depending on `org-link-types'
12139 FOLLOW and PUBLISH are two functions. Both take the link path as
12140 an argument.
12141 FOLLOW should do whatever is necessary to follow the link, for example
12142 to find a file or display a mail message.
12144 PUBLISH takes the path and retuns the string that should be used when
12145 this document is published. FIMXE: This is actually not yet implemented."
12146 (add-to-list 'org-link-types type t)
12147 (org-make-link-regexps)
12148 (add-to-list 'org-link-protocols
12149 (list type follow publish)))
12151 (defun org-add-agenda-custom-command (entry)
12152 "Replace or add a command in `org-agenda-custom-commands'.
12153 This is mostly for hacking and trying a new command - once the command
12154 works you probably want to add it to `org-agenda-custom-commands' for good."
12155 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12156 (if ass
12157 (setcdr ass (cdr entry))
12158 (push entry org-agenda-custom-commands))))
12160 ;;;###autoload
12161 (defun org-store-link (arg)
12162 "\\<org-mode-map>Store an org-link to the current location.
12163 This link is added to `org-stored-links' and can later be inserted
12164 into an org-buffer with \\[org-insert-link].
12166 For some link types, a prefix arg is interpreted:
12167 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12168 For file links, arg negates `org-context-in-file-links'."
12169 (interactive "P")
12170 (setq org-store-link-plist nil) ; reset
12171 (let (link cpltxt desc description search txt)
12172 (cond
12174 ((run-hook-with-args-until-success 'org-store-link-functions)
12175 (setq link (plist-get org-store-link-plist :link)
12176 desc (or (plist-get org-store-link-plist :description) link)))
12178 ((eq major-mode 'bbdb-mode)
12179 (let ((name (bbdb-record-name (bbdb-current-record)))
12180 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
12181 (setq cpltxt (concat "bbdb:" (or name company))
12182 link (org-make-link cpltxt))
12183 (org-store-link-props :type "bbdb" :name name :company company)))
12185 ((eq major-mode 'Info-mode)
12186 (setq link (org-make-link "info:"
12187 (file-name-nondirectory Info-current-file)
12188 ":" Info-current-node))
12189 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
12190 ":" Info-current-node))
12191 (org-store-link-props :type "info" :file Info-current-file
12192 :node Info-current-node))
12194 ((eq major-mode 'calendar-mode)
12195 (let ((cd (calendar-cursor-to-date)))
12196 (setq link
12197 (format-time-string
12198 (car org-time-stamp-formats)
12199 (apply 'encode-time
12200 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12201 nil nil nil))))
12202 (org-store-link-props :type "calendar" :date cd)))
12204 ((or (eq major-mode 'vm-summary-mode)
12205 (eq major-mode 'vm-presentation-mode))
12206 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
12207 (vm-follow-summary-cursor)
12208 (save-excursion
12209 (vm-select-folder-buffer)
12210 (let* ((message (car vm-message-pointer))
12211 (folder buffer-file-name)
12212 (subject (vm-su-subject message))
12213 (to (vm-get-header-contents message "To"))
12214 (from (vm-get-header-contents message "From"))
12215 (message-id (vm-su-message-id message)))
12216 (org-store-link-props :type "vm" :from from :to to :subject subject
12217 :message-id message-id)
12218 (setq message-id (org-remove-angle-brackets message-id))
12219 (setq folder (abbreviate-file-name folder))
12220 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
12221 folder)
12222 (setq folder (replace-match "" t t folder)))
12223 (setq cpltxt (org-email-link-description))
12224 (setq link (org-make-link "vm:" folder "#" message-id)))))
12226 ((eq major-mode 'wl-summary-mode)
12227 (let* ((msgnum (wl-summary-message-number))
12228 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
12229 msgnum 'message-id))
12230 (wl-message-entity
12231 (if (fboundp 'elmo-message-entity)
12232 (elmo-message-entity
12233 wl-summary-buffer-elmo-folder msgnum)
12234 (elmo-msgdb-overview-get-entity
12235 msgnum (wl-summary-buffer-msgdb))))
12236 (from (wl-summary-line-from))
12237 (to (car (elmo-message-entity-field wl-message-entity 'to)))
12238 (subject (let (wl-thr-indent-string wl-parent-message-entity)
12239 (wl-summary-line-subject))))
12240 (org-store-link-props :type "wl" :from from :to to
12241 :subject subject :message-id message-id)
12242 (setq message-id (org-remove-angle-brackets message-id))
12243 (setq cpltxt (org-email-link-description))
12244 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
12245 "#" message-id))))
12247 ((or (equal major-mode 'mh-folder-mode)
12248 (equal major-mode 'mh-show-mode))
12249 (let ((from (org-mhe-get-header "From:"))
12250 (to (org-mhe-get-header "To:"))
12251 (message-id (org-mhe-get-header "Message-Id:"))
12252 (subject (org-mhe-get-header "Subject:")))
12253 (org-store-link-props :type "mh" :from from :to to
12254 :subject subject :message-id message-id)
12255 (setq cpltxt (org-email-link-description))
12256 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
12257 (org-remove-angle-brackets message-id)))))
12259 ((or (eq major-mode 'rmail-mode)
12260 (eq major-mode 'rmail-summary-mode))
12261 (save-window-excursion
12262 (save-restriction
12263 (when (eq major-mode 'rmail-summary-mode)
12264 (rmail-show-message rmail-current-message))
12265 (rmail-narrow-to-non-pruned-header)
12266 (let ((folder buffer-file-name)
12267 (message-id (mail-fetch-field "message-id"))
12268 (from (mail-fetch-field "from"))
12269 (to (mail-fetch-field "to"))
12270 (subject (mail-fetch-field "subject")))
12271 (org-store-link-props
12272 :type "rmail" :from from :to to
12273 :subject subject :message-id message-id)
12274 (setq message-id (org-remove-angle-brackets message-id))
12275 (setq cpltxt (org-email-link-description))
12276 (setq link (org-make-link "rmail:" folder "#" message-id)))
12277 (rmail-show-message rmail-current-message))))
12279 ((eq major-mode 'gnus-group-mode)
12280 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12281 (gnus-group-group-name)) ; version
12282 ((fboundp 'gnus-group-name)
12283 (gnus-group-name))
12284 (t "???"))))
12285 (unless group (error "Not on a group"))
12286 (org-store-link-props :type "gnus" :group group)
12287 (setq cpltxt (concat
12288 (if (org-xor arg org-usenet-links-prefer-google)
12289 "http://groups.google.com/groups?group="
12290 "gnus:")
12291 group)
12292 link (org-make-link cpltxt))))
12294 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12295 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12296 (let* ((group gnus-newsgroup-name)
12297 (article (gnus-summary-article-number))
12298 (header (gnus-summary-article-header article))
12299 (from (mail-header-from header))
12300 (message-id (mail-header-id header))
12301 (date (mail-header-date header))
12302 (subject (gnus-summary-subject-string)))
12303 (org-store-link-props :type "gnus" :from from :subject subject
12304 :message-id message-id :group group)
12305 (setq cpltxt (org-email-link-description))
12306 (if (org-xor arg org-usenet-links-prefer-google)
12307 (setq link
12308 (concat
12309 cpltxt "\n "
12310 (format "http://groups.google.com/groups?as_umsgid=%s"
12311 (org-fixup-message-id-for-http message-id))))
12312 (setq link (org-make-link "gnus:" group
12313 "#" (number-to-string article))))))
12315 ((eq major-mode 'w3-mode)
12316 (setq cpltxt (url-view-url t)
12317 link (org-make-link cpltxt))
12318 (org-store-link-props :type "w3" :url (url-view-url t)))
12320 ((eq major-mode 'w3m-mode)
12321 (setq cpltxt (or w3m-current-title w3m-current-url)
12322 link (org-make-link w3m-current-url))
12323 (org-store-link-props :type "w3m" :url (url-view-url t)))
12325 ((setq search (run-hook-with-args-until-success
12326 'org-create-file-search-functions))
12327 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12328 "::" search))
12329 (setq cpltxt (or description link)))
12331 ((eq major-mode 'image-mode)
12332 (setq cpltxt (concat "file:"
12333 (abbreviate-file-name buffer-file-name))
12334 link (org-make-link cpltxt))
12335 (org-store-link-props :type "image" :file buffer-file-name))
12337 ((eq major-mode 'dired-mode)
12338 ;; link to the file in the current line
12339 (setq cpltxt (concat "file:"
12340 (abbreviate-file-name
12341 (expand-file-name
12342 (dired-get-filename nil t))))
12343 link (org-make-link cpltxt)))
12345 ((and buffer-file-name (org-mode-p))
12346 ;; Just link to current headline
12347 (setq cpltxt (concat "file:"
12348 (abbreviate-file-name buffer-file-name)))
12349 ;; Add a context search string
12350 (when (org-xor org-context-in-file-links arg)
12351 ;; Check if we are on a target
12352 (if (org-in-regexp "<<\\(.*?\\)>>")
12353 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12354 (setq txt (cond
12355 ((org-on-heading-p) nil)
12356 ((org-region-active-p)
12357 (buffer-substring (region-beginning) (region-end)))
12358 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12359 (when (or (null txt) (string-match "\\S-" txt))
12360 (setq cpltxt
12361 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12362 desc "NONE"))))
12363 (if (string-match "::\\'" cpltxt)
12364 (setq cpltxt (substring cpltxt 0 -2)))
12365 (setq link (org-make-link cpltxt)))
12367 ((buffer-file-name (buffer-base-buffer))
12368 ;; Just link to this file here.
12369 (setq cpltxt (concat "file:"
12370 (abbreviate-file-name
12371 (buffer-file-name (buffer-base-buffer)))))
12372 ;; Add a context string
12373 (when (org-xor org-context-in-file-links arg)
12374 (setq txt (if (org-region-active-p)
12375 (buffer-substring (region-beginning) (region-end))
12376 (buffer-substring (point-at-bol) (point-at-eol))))
12377 ;; Only use search option if there is some text.
12378 (when (string-match "\\S-" txt)
12379 (setq cpltxt
12380 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12381 desc "NONE")))
12382 (setq link (org-make-link cpltxt)))
12384 ((interactive-p)
12385 (error "Cannot link to a buffer which is not visiting a file"))
12387 (t (setq link nil)))
12389 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12390 (setq link (or link cpltxt)
12391 desc (or desc cpltxt))
12392 (if (equal desc "NONE") (setq desc nil))
12394 (if (and (interactive-p) link)
12395 (progn
12396 (setq org-stored-links
12397 (cons (list link desc) org-stored-links))
12398 (message "Stored: %s" (or desc link)))
12399 (and link (org-make-link-string link desc)))))
12401 (defun org-store-link-props (&rest plist)
12402 "Store link properties, extract names and addresses."
12403 (let (x adr)
12404 (when (setq x (plist-get plist :from))
12405 (setq adr (mail-extract-address-components x))
12406 (plist-put plist :fromname (car adr))
12407 (plist-put plist :fromaddress (nth 1 adr)))
12408 (when (setq x (plist-get plist :to))
12409 (setq adr (mail-extract-address-components x))
12410 (plist-put plist :toname (car adr))
12411 (plist-put plist :toaddress (nth 1 adr))))
12412 (let ((from (plist-get plist :from))
12413 (to (plist-get plist :to)))
12414 (when (and from to org-from-is-user-regexp)
12415 (plist-put plist :fromto
12416 (if (string-match org-from-is-user-regexp from)
12417 (concat "to %t")
12418 (concat "from %f")))))
12419 (setq org-store-link-plist plist))
12421 (defun org-email-link-description (&optional fmt)
12422 "Return the description part of an email link.
12423 This takes information from `org-store-link-plist' and formats it
12424 according to FMT (default from `org-email-link-description-format')."
12425 (setq fmt (or fmt org-email-link-description-format))
12426 (let* ((p org-store-link-plist)
12427 (to (plist-get p :toaddress))
12428 (from (plist-get p :fromaddress))
12429 (table
12430 (list
12431 (cons "%c" (plist-get p :fromto))
12432 (cons "%F" (plist-get p :from))
12433 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12434 (cons "%T" (plist-get p :to))
12435 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12436 (cons "%s" (plist-get p :subject))
12437 (cons "%m" (plist-get p :message-id)))))
12438 (when (string-match "%c" fmt)
12439 ;; Check if the user wrote this message
12440 (if (and org-from-is-user-regexp from to
12441 (save-match-data (string-match org-from-is-user-regexp from)))
12442 (setq fmt (replace-match "to %t" t t fmt))
12443 (setq fmt (replace-match "from %f" t t fmt))))
12444 (org-replace-escapes fmt table)))
12446 (defun org-make-org-heading-search-string (&optional string heading)
12447 "Make search string for STRING or current headline."
12448 (interactive)
12449 (let ((s (or string (org-get-heading))))
12450 (unless (and string (not heading))
12451 ;; We are using a headline, clean up garbage in there.
12452 (if (string-match org-todo-regexp s)
12453 (setq s (replace-match "" t t s)))
12454 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12455 (setq s (replace-match "" t t s)))
12456 (setq s (org-trim s))
12457 (if (string-match (concat "^\\(" org-quote-string "\\|"
12458 org-comment-string "\\)") s)
12459 (setq s (replace-match "" t t s)))
12460 (while (string-match org-ts-regexp s)
12461 (setq s (replace-match "" t t s))))
12462 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12463 (setq s (replace-match " " t t s)))
12464 (or string (setq s (concat "*" s))) ; Add * for headlines
12465 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12467 (defun org-make-link (&rest strings)
12468 "Concatenate STRINGS."
12469 (apply 'concat strings))
12471 (defun org-make-link-string (link &optional description)
12472 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12473 (unless (string-match "\\S-" link)
12474 (error "Empty link"))
12475 (when (stringp description)
12476 ;; Remove brackets from the description, they are fatal.
12477 (while (string-match "\\[" description)
12478 (setq description (replace-match "{" t t description)))
12479 (while (string-match "\\]" description)
12480 (setq description (replace-match "}" t t description))))
12481 (when (equal (org-link-escape link) description)
12482 ;; No description needed, it is identical
12483 (setq description nil))
12484 (when (and (not description)
12485 (not (equal link (org-link-escape link))))
12486 (setq description link))
12487 (concat "[[" (org-link-escape link) "]"
12488 (if description (concat "[" description "]") "")
12489 "]"))
12491 (defconst org-link-escape-chars
12492 '((?\ . "%20")
12493 (?\[ . "%5B")
12494 (?\] . "%5D")
12495 (?\340 . "%E0") ; `a
12496 (?\342 . "%E2") ; ^a
12497 (?\347 . "%E7") ; ,c
12498 (?\350 . "%E8") ; `e
12499 (?\351 . "%E9") ; 'e
12500 (?\352 . "%EA") ; ^e
12501 (?\356 . "%EE") ; ^i
12502 (?\364 . "%F4") ; ^o
12503 (?\371 . "%F9") ; `u
12504 (?\373 . "%FB") ; ^u
12505 (?\; . "%3B")
12506 (?? . "%3F")
12507 (?= . "%3D")
12508 (?+ . "%2B")
12510 "Association list of escapes for some characters problematic in links.
12511 This is the list that is used for internal purposes.")
12513 (defconst org-link-escape-chars-browser
12514 '((?\ . "%20")) ; 32 for the SPC char
12515 "Association list of escapes for some characters problematic in links.
12516 This is the list that is used before handing over to the browser.")
12518 (defun org-link-escape (text &optional table)
12519 "Escape charaters in TEXT that are problematic for links."
12520 (setq table (or table org-link-escape-chars))
12521 (when text
12522 (let ((re (mapconcat (lambda (x) (regexp-quote
12523 (char-to-string (car x))))
12524 table "\\|")))
12525 (while (string-match re text)
12526 (setq text
12527 (replace-match
12528 (cdr (assoc (string-to-char (match-string 0 text))
12529 table))
12530 t t text)))
12531 text)))
12533 (defun org-link-unescape (text &optional table)
12534 "Reverse the action of `org-link-escape'."
12535 (setq table (or table org-link-escape-chars))
12536 (when text
12537 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12538 table "\\|")))
12539 (while (string-match re text)
12540 (setq text
12541 (replace-match
12542 (char-to-string (car (rassoc (match-string 0 text) table)))
12543 t t text)))
12544 text)))
12546 (defun org-xor (a b)
12547 "Exclusive or."
12548 (if a (not b) b))
12550 (defun org-get-header (header)
12551 "Find a header field in the current buffer."
12552 (save-excursion
12553 (goto-char (point-min))
12554 (let ((case-fold-search t) s)
12555 (cond
12556 ((eq header 'from)
12557 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12558 (setq s (match-string 1)))
12559 (while (string-match "\"" s)
12560 (setq s (replace-match "" t t s)))
12561 (if (string-match "[<(].*" s)
12562 (setq s (replace-match "" t t s))))
12563 ((eq header 'message-id)
12564 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12565 (setq s (match-string 1))))
12566 ((eq header 'subject)
12567 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12568 (setq s (match-string 1)))))
12569 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12570 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12571 s)))
12574 (defun org-fixup-message-id-for-http (s)
12575 "Replace special characters in a message id, so it can be used in an http query."
12576 (while (string-match "<" s)
12577 (setq s (replace-match "%3C" t t s)))
12578 (while (string-match ">" s)
12579 (setq s (replace-match "%3E" t t s)))
12580 (while (string-match "@" s)
12581 (setq s (replace-match "%40" t t s)))
12584 ;;;###autoload
12585 (defun org-insert-link-global ()
12586 "Insert a link like Org-mode does.
12587 This command can be called in any mode to insert a link in Org-mode syntax."
12588 (interactive)
12589 (org-run-like-in-org-mode 'org-insert-link))
12591 (defun org-insert-link (&optional complete-file)
12592 "Insert a link. At the prompt, enter the link.
12594 Completion can be used to select a link previously stored with
12595 `org-store-link'. When the empty string is entered (i.e. if you just
12596 press RET at the prompt), the link defaults to the most recently
12597 stored link. As SPC triggers completion in the minibuffer, you need to
12598 use M-SPC or C-q SPC to force the insertion of a space character.
12600 You will also be prompted for a description, and if one is given, it will
12601 be displayed in the buffer instead of the link.
12603 If there is already a link at point, this command will allow you to edit link
12604 and description parts.
12606 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12607 selected using completion. The path to the file will be relative to
12608 the current directory if the file is in the current directory or a
12609 subdirectory. Otherwise, the link will be the absolute path as
12610 completed in the minibuffer (i.e. normally ~/path/to/file).
12612 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12613 is in the current directory or below.
12614 With three \\[universal-argument] prefixes, negate the meaning of
12615 `org-keep-stored-link-after-insertion'."
12616 (interactive "P")
12617 (let* ((wcf (current-window-configuration))
12618 (region (if (org-region-active-p)
12619 (buffer-substring (region-beginning) (region-end))))
12620 (remove (and region (list (region-beginning) (region-end))))
12621 (desc region)
12622 tmphist ; byte-compile incorrectly complains about this
12623 link entry file)
12624 (cond
12625 ((org-in-regexp org-bracket-link-regexp 1)
12626 ;; We do have a link at point, and we are going to edit it.
12627 (setq remove (list (match-beginning 0) (match-end 0)))
12628 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12629 (setq link (read-string "Link: "
12630 (org-link-unescape
12631 (org-match-string-no-properties 1)))))
12632 ((or (org-in-regexp org-angle-link-re)
12633 (org-in-regexp org-plain-link-re))
12634 ;; Convert to bracket link
12635 (setq remove (list (match-beginning 0) (match-end 0))
12636 link (read-string "Link: "
12637 (org-remove-angle-brackets (match-string 0)))))
12638 ((equal complete-file '(4))
12639 ;; Completing read for file names.
12640 (setq file (read-file-name "File: "))
12641 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12642 (pwd1 (file-name-as-directory (abbreviate-file-name
12643 (expand-file-name ".")))))
12644 (cond
12645 ((equal complete-file '(16))
12646 (setq link (org-make-link
12647 "file:"
12648 (abbreviate-file-name (expand-file-name file)))))
12649 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12650 (setq link (org-make-link "file:" (match-string 1 file))))
12651 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12652 (expand-file-name file))
12653 (setq link (org-make-link
12654 "file:" (match-string 1 (expand-file-name file)))))
12655 (t (setq link (org-make-link "file:" file))))))
12657 ;; Read link, with completion for stored links.
12658 (with-output-to-temp-buffer "*Org Links*"
12659 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12660 (when org-stored-links
12661 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12662 (princ (mapconcat
12663 (lambda (x)
12664 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12665 (reverse org-stored-links) "\n"))))
12666 (let ((cw (selected-window)))
12667 (select-window (get-buffer-window "*Org Links*"))
12668 (shrink-window-if-larger-than-buffer)
12669 (setq truncate-lines t)
12670 (select-window cw))
12671 ;; Fake a link history, containing the stored links.
12672 (setq tmphist (append (mapcar 'car org-stored-links)
12673 org-insert-link-history))
12674 (unwind-protect
12675 (setq link (org-completing-read
12676 "Link: "
12677 (append
12678 (mapcar (lambda (x) (list (concat (car x) ":")))
12679 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12680 (mapcar (lambda (x) (list (concat x ":")))
12681 org-link-types))
12682 nil nil nil
12683 'tmphist
12684 (or (car (car org-stored-links)))))
12685 (set-window-configuration wcf)
12686 (kill-buffer "*Org Links*"))
12687 (setq entry (assoc link org-stored-links))
12688 (or entry (push link org-insert-link-history))
12689 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12690 (not org-keep-stored-link-after-insertion))
12691 (setq org-stored-links (delq (assoc link org-stored-links)
12692 org-stored-links)))
12693 (setq desc (or desc (nth 1 entry)))))
12695 (if (string-match org-plain-link-re link)
12696 ;; URL-like link, normalize the use of angular brackets.
12697 (setq link (org-make-link (org-remove-angle-brackets link))))
12699 ;; Check if we are linking to the current file with a search option
12700 ;; If yes, simplify the link by using only the search option.
12701 (when (and buffer-file-name
12702 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12703 (let* ((path (match-string 1 link))
12704 (case-fold-search nil)
12705 (search (match-string 2 link)))
12706 (save-match-data
12707 (if (equal (file-truename buffer-file-name) (file-truename path))
12708 ;; We are linking to this same file, with a search option
12709 (setq link search)))))
12711 ;; Check if we can/should use a relative path. If yes, simplify the link
12712 (when (string-match "\\<file:\\(.*\\)" link)
12713 (let* ((path (match-string 1 link))
12714 (origpath path)
12715 (case-fold-search nil))
12716 (cond
12717 ((eq org-link-file-path-type 'absolute)
12718 (setq path (abbreviate-file-name (expand-file-name path))))
12719 ((eq org-link-file-path-type 'noabbrev)
12720 (setq path (expand-file-name path)))
12721 ((eq org-link-file-path-type 'relative)
12722 (setq path (file-relative-name path)))
12724 (save-match-data
12725 (if (string-match (concat "^" (regexp-quote
12726 (file-name-as-directory
12727 (expand-file-name "."))))
12728 (expand-file-name path))
12729 ;; We are linking a file with relative path name.
12730 (setq path (substring (expand-file-name path)
12731 (match-end 0)))))))
12732 (setq link (concat "file:" path))
12733 (if (equal desc origpath)
12734 (setq desc path))))
12736 (setq desc (read-string "Description: " desc))
12737 (unless (string-match "\\S-" desc) (setq desc nil))
12738 (if remove (apply 'delete-region remove))
12739 (insert (org-make-link-string link desc))))
12741 (defun org-completing-read (&rest args)
12742 (let ((minibuffer-local-completion-map
12743 (copy-keymap minibuffer-local-completion-map)))
12744 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12745 (apply 'completing-read args)))
12747 ;;; Opening/following a link
12748 (defvar org-link-search-failed nil)
12750 (defun org-next-link ()
12751 "Move forward to the next link.
12752 If the link is in hidden text, expose it."
12753 (interactive)
12754 (when (and org-link-search-failed (eq this-command last-command))
12755 (goto-char (point-min))
12756 (message "Link search wrapped back to beginning of buffer"))
12757 (setq org-link-search-failed nil)
12758 (let* ((pos (point))
12759 (ct (org-context))
12760 (a (assoc :link ct)))
12761 (if a (goto-char (nth 2 a)))
12762 (if (re-search-forward org-any-link-re nil t)
12763 (progn
12764 (goto-char (match-beginning 0))
12765 (if (org-invisible-p) (org-show-context)))
12766 (goto-char pos)
12767 (setq org-link-search-failed t)
12768 (error "No further link found"))))
12770 (defun org-previous-link ()
12771 "Move backward to the previous link.
12772 If the link is in hidden text, expose it."
12773 (interactive)
12774 (when (and org-link-search-failed (eq this-command last-command))
12775 (goto-char (point-max))
12776 (message "Link search wrapped back to end of buffer"))
12777 (setq org-link-search-failed nil)
12778 (let* ((pos (point))
12779 (ct (org-context))
12780 (a (assoc :link ct)))
12781 (if a (goto-char (nth 1 a)))
12782 (if (re-search-backward org-any-link-re nil t)
12783 (progn
12784 (goto-char (match-beginning 0))
12785 (if (org-invisible-p) (org-show-context)))
12786 (goto-char pos)
12787 (setq org-link-search-failed t)
12788 (error "No further link found"))))
12790 (defun org-find-file-at-mouse (ev)
12791 "Open file link or URL at mouse."
12792 (interactive "e")
12793 (mouse-set-point ev)
12794 (org-open-at-point 'in-emacs))
12796 (defun org-open-at-mouse (ev)
12797 "Open file link or URL at mouse."
12798 (interactive "e")
12799 (mouse-set-point ev)
12800 (org-open-at-point))
12802 (defvar org-window-config-before-follow-link nil
12803 "The window configuration before following a link.
12804 This is saved in case the need arises to restore it.")
12806 (defvar org-open-link-marker (make-marker)
12807 "Marker pointing to the location where `org-open-at-point; was called.")
12809 ;;;###autoload
12810 (defun org-open-at-point-global ()
12811 "Follow a link like Org-mode does.
12812 This command can be called in any mode to follow a link that has
12813 Org-mode syntax."
12814 (interactive)
12815 (org-run-like-in-org-mode 'org-open-at-point))
12817 (defun org-open-at-point (&optional in-emacs)
12818 "Open link at or after point.
12819 If there is no link at point, this function will search forward up to
12820 the end of the current subtree.
12821 Normally, files will be opened by an appropriate application. If the
12822 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12823 (interactive "P")
12824 (move-marker org-open-link-marker (point))
12825 (setq org-window-config-before-follow-link (current-window-configuration))
12826 (org-remove-occur-highlights nil nil t)
12827 (if (org-at-timestamp-p t)
12828 (org-follow-timestamp-link)
12829 (let (type path link line search (pos (point)))
12830 (catch 'match
12831 (save-excursion
12832 (skip-chars-forward "^]\n\r")
12833 (when (org-in-regexp org-bracket-link-regexp)
12834 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12835 (while (string-match " *\n *" link)
12836 (setq link (replace-match " " t t link)))
12837 (setq link (org-link-expand-abbrev link))
12838 (if (string-match org-link-re-with-space2 link)
12839 (setq type (match-string 1 link) path (match-string 2 link))
12840 (setq type "thisfile" path link))
12841 (throw 'match t)))
12843 (when (get-text-property (point) 'org-linked-text)
12844 (setq type "thisfile"
12845 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12846 (1+ (point)) (point))
12847 path (buffer-substring
12848 (previous-single-property-change pos 'org-linked-text)
12849 (next-single-property-change pos 'org-linked-text)))
12850 (throw 'match t))
12852 (save-excursion
12853 (when (or (org-in-regexp org-angle-link-re)
12854 (org-in-regexp org-plain-link-re))
12855 (setq type (match-string 1) path (match-string 2))
12856 (throw 'match t)))
12857 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12858 (setq type "tree-match"
12859 path (match-string 1))
12860 (throw 'match t))
12861 (save-excursion
12862 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12863 (setq type "tags"
12864 path (match-string 1))
12865 (while (string-match ":" path)
12866 (setq path (replace-match "+" t t path)))
12867 (throw 'match t))))
12868 (unless path
12869 (error "No link found"))
12870 ;; Remove any trailing spaces in path
12871 (if (string-match " +\\'" path)
12872 (setq path (replace-match "" t t path)))
12874 (cond
12876 ((assoc type org-link-protocols)
12877 (funcall (nth 1 (assoc type org-link-protocols)) path))
12879 ((equal type "mailto")
12880 (let ((cmd (car org-link-mailto-program))
12881 (args (cdr org-link-mailto-program)) args1
12882 (address path) (subject "") a)
12883 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12884 (setq address (match-string 1 path)
12885 subject (org-link-escape (match-string 2 path))))
12886 (while args
12887 (cond
12888 ((not (stringp (car args))) (push (pop args) args1))
12889 (t (setq a (pop args))
12890 (if (string-match "%a" a)
12891 (setq a (replace-match address t t a)))
12892 (if (string-match "%s" a)
12893 (setq a (replace-match subject t t a)))
12894 (push a args1))))
12895 (apply cmd (nreverse args1))))
12897 ((member type '("http" "https" "ftp" "news"))
12898 (browse-url (concat type ":" (org-link-escape
12899 path org-link-escape-chars-browser))))
12901 ((member type '("message"))
12902 (browse-url (concat type ":" path)))
12904 ((string= type "tags")
12905 (org-tags-view in-emacs path))
12906 ((string= type "thisfile")
12907 (if in-emacs
12908 (switch-to-buffer-other-window
12909 (org-get-buffer-for-internal-link (current-buffer)))
12910 (org-mark-ring-push))
12911 (let ((cmd `(org-link-search
12912 ,path
12913 ,(cond ((equal in-emacs '(4)) 'occur)
12914 ((equal in-emacs '(16)) 'org-occur)
12915 (t nil))
12916 ,pos)))
12917 (condition-case nil (eval cmd)
12918 (error (progn (widen) (eval cmd))))))
12920 ((string= type "tree-match")
12921 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12923 ((string= type "file")
12924 (if (string-match "::\\([0-9]+\\)\\'" path)
12925 (setq line (string-to-number (match-string 1 path))
12926 path (substring path 0 (match-beginning 0)))
12927 (if (string-match "::\\(.+\\)\\'" path)
12928 (setq search (match-string 1 path)
12929 path (substring path 0 (match-beginning 0)))))
12930 (if (string-match "[*?{]" (file-name-nondirectory path))
12931 (dired path)
12932 (org-open-file path in-emacs line search)))
12934 ((string= type "news")
12935 (org-follow-gnus-link path))
12937 ((string= type "bbdb")
12938 (org-follow-bbdb-link path))
12940 ((string= type "info")
12941 (org-follow-info-link path))
12943 ((string= type "gnus")
12944 (let (group article)
12945 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12946 (error "Error in Gnus link"))
12947 (setq group (match-string 1 path)
12948 article (match-string 3 path))
12949 (org-follow-gnus-link group article)))
12951 ((string= type "vm")
12952 (let (folder article)
12953 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12954 (error "Error in VM link"))
12955 (setq folder (match-string 1 path)
12956 article (match-string 3 path))
12957 ;; in-emacs is the prefix arg, will be interpreted as read-only
12958 (org-follow-vm-link folder article in-emacs)))
12960 ((string= type "wl")
12961 (let (folder article)
12962 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12963 (error "Error in Wanderlust link"))
12964 (setq folder (match-string 1 path)
12965 article (match-string 3 path))
12966 (org-follow-wl-link folder article)))
12968 ((string= type "mhe")
12969 (let (folder article)
12970 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12971 (error "Error in MHE link"))
12972 (setq folder (match-string 1 path)
12973 article (match-string 3 path))
12974 (org-follow-mhe-link folder article)))
12976 ((string= type "rmail")
12977 (let (folder article)
12978 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12979 (error "Error in RMAIL link"))
12980 (setq folder (match-string 1 path)
12981 article (match-string 3 path))
12982 (org-follow-rmail-link folder article)))
12984 ((string= type "shell")
12985 (let ((cmd path))
12986 (if (or (not org-confirm-shell-link-function)
12987 (funcall org-confirm-shell-link-function
12988 (format "Execute \"%s\" in shell? "
12989 (org-add-props cmd nil
12990 'face 'org-warning))))
12991 (progn
12992 (message "Executing %s" cmd)
12993 (shell-command cmd))
12994 (error "Abort"))))
12996 ((string= type "elisp")
12997 (let ((cmd path))
12998 (if (or (not org-confirm-elisp-link-function)
12999 (funcall org-confirm-elisp-link-function
13000 (format "Execute \"%s\" as elisp? "
13001 (org-add-props cmd nil
13002 'face 'org-warning))))
13003 (message "%s => %s" cmd (eval (read cmd)))
13004 (error "Abort"))))
13007 (browse-url-at-point)))))
13008 (move-marker org-open-link-marker nil)
13009 (run-hook-with-args 'org-follow-link-hook))
13011 ;;; File search
13013 (defvar org-create-file-search-functions nil
13014 "List of functions to construct the right search string for a file link.
13015 These functions are called in turn with point at the location to
13016 which the link should point.
13018 A function in the hook should first test if it would like to
13019 handle this file type, for example by checking the major-mode or
13020 the file extension. If it decides not to handle this file, it
13021 should just return nil to give other functions a chance. If it
13022 does handle the file, it must return the search string to be used
13023 when following the link. The search string will be part of the
13024 file link, given after a double colon, and `org-open-at-point'
13025 will automatically search for it. If special measures must be
13026 taken to make the search successful, another function should be
13027 added to the companion hook `org-execute-file-search-functions',
13028 which see.
13030 A function in this hook may also use `setq' to set the variable
13031 `description' to provide a suggestion for the descriptive text to
13032 be used for this link when it gets inserted into an Org-mode
13033 buffer with \\[org-insert-link].")
13035 (defvar org-execute-file-search-functions nil
13036 "List of functions to execute a file search triggered by a link.
13038 Functions added to this hook must accept a single argument, the
13039 search string that was part of the file link, the part after the
13040 double colon. The function must first check if it would like to
13041 handle this search, for example by checking the major-mode or the
13042 file extension. If it decides not to handle this search, it
13043 should just return nil to give other functions a chance. If it
13044 does handle the search, it must return a non-nil value to keep
13045 other functions from trying.
13047 Each function can access the current prefix argument through the
13048 variable `current-prefix-argument'. Note that a single prefix is
13049 used to force opening a link in Emacs, so it may be good to only
13050 use a numeric or double prefix to guide the search function.
13052 In case this is needed, a function in this hook can also restore
13053 the window configuration before `org-open-at-point' was called using:
13055 (set-window-configuration org-window-config-before-follow-link)")
13057 (defun org-link-search (s &optional type avoid-pos)
13058 "Search for a link search option.
13059 If S is surrounded by forward slashes, it is interpreted as a
13060 regular expression. In org-mode files, this will create an `org-occur'
13061 sparse tree. In ordinary files, `occur' will be used to list matches.
13062 If the current buffer is in `dired-mode', grep will be used to search
13063 in all files. If AVOID-POS is given, ignore matches near that position."
13064 (let ((case-fold-search t)
13065 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
13066 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
13067 (append '(("") (" ") ("\t") ("\n"))
13068 org-emphasis-alist)
13069 "\\|") "\\)"))
13070 (pos (point))
13071 (pre "") (post "")
13072 words re0 re1 re2 re3 re4 re5 re2a reall)
13073 (cond
13074 ;; First check if there are any special
13075 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
13076 ;; Now try the builtin stuff
13077 ((save-excursion
13078 (goto-char (point-min))
13079 (and
13080 (re-search-forward
13081 (concat "<<" (regexp-quote s0) ">>") nil t)
13082 (setq pos (match-beginning 0))))
13083 ;; There is an exact target for this
13084 (goto-char pos))
13085 ((string-match "^/\\(.*\\)/$" s)
13086 ;; A regular expression
13087 (cond
13088 ((org-mode-p)
13089 (org-occur (match-string 1 s)))
13090 ;;((eq major-mode 'dired-mode)
13091 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
13092 (t (org-do-occur (match-string 1 s)))))
13094 ;; A normal search strings
13095 (when (equal (string-to-char s) ?*)
13096 ;; Anchor on headlines, post may include tags.
13097 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
13098 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
13099 s (substring s 1)))
13100 (remove-text-properties
13101 0 (length s)
13102 '(face nil mouse-face nil keymap nil fontified nil) s)
13103 ;; Make a series of regular expressions to find a match
13104 (setq words (org-split-string s "[ \n\r\t]+")
13105 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
13106 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
13107 "\\)" markers)
13108 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
13109 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
13110 re1 (concat pre re2 post)
13111 re3 (concat pre re4 post)
13112 re5 (concat pre ".*" re4)
13113 re2 (concat pre re2)
13114 re2a (concat pre re2a)
13115 re4 (concat pre re4)
13116 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
13117 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
13118 re5 "\\)"
13120 (cond
13121 ((eq type 'org-occur) (org-occur reall))
13122 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
13123 (t (goto-char (point-min))
13124 (if (or (org-search-not-self 1 re0 nil t)
13125 (org-search-not-self 1 re1 nil t)
13126 (org-search-not-self 1 re2 nil t)
13127 (org-search-not-self 1 re2a nil t)
13128 (org-search-not-self 1 re3 nil t)
13129 (org-search-not-self 1 re4 nil t)
13130 (org-search-not-self 1 re5 nil t)
13132 (goto-char (match-beginning 1))
13133 (goto-char pos)
13134 (error "No match")))))
13136 ;; Normal string-search
13137 (goto-char (point-min))
13138 (if (search-forward s nil t)
13139 (goto-char (match-beginning 0))
13140 (error "No match"))))
13141 (and (org-mode-p) (org-show-context 'link-search))))
13143 (defun org-search-not-self (group &rest args)
13144 "Execute `re-search-forward', but only accept matches that do not
13145 enclose the position of `org-open-link-marker'."
13146 (let ((m org-open-link-marker))
13147 (catch 'exit
13148 (while (apply 're-search-forward args)
13149 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
13150 (goto-char (match-end group))
13151 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
13152 (> (match-beginning 0) (marker-position m))
13153 (< (match-end 0) (marker-position m)))
13154 (save-match-data
13155 (or (not (org-in-regexp
13156 org-bracket-link-analytic-regexp 1))
13157 (not (match-end 4)) ; no description
13158 (and (<= (match-beginning 4) (point))
13159 (>= (match-end 4) (point))))))
13160 (throw 'exit (point))))))))
13162 (defun org-get-buffer-for-internal-link (buffer)
13163 "Return a buffer to be used for displaying the link target of internal links."
13164 (cond
13165 ((not org-display-internal-link-with-indirect-buffer)
13166 buffer)
13167 ((string-match "(Clone)$" (buffer-name buffer))
13168 (message "Buffer is already a clone, not making another one")
13169 ;; we also do not modify visibility in this case
13170 buffer)
13171 (t ; make a new indirect buffer for displaying the link
13172 (let* ((bn (buffer-name buffer))
13173 (ibn (concat bn "(Clone)"))
13174 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13175 (with-current-buffer ib (org-overview))
13176 ib))))
13178 (defun org-do-occur (regexp &optional cleanup)
13179 "Call the Emacs command `occur'.
13180 If CLEANUP is non-nil, remove the printout of the regular expression
13181 in the *Occur* buffer. This is useful if the regex is long and not useful
13182 to read."
13183 (occur regexp)
13184 (when cleanup
13185 (let ((cwin (selected-window)) win beg end)
13186 (when (setq win (get-buffer-window "*Occur*"))
13187 (select-window win))
13188 (goto-char (point-min))
13189 (when (re-search-forward "match[a-z]+" nil t)
13190 (setq beg (match-end 0))
13191 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13192 (setq end (1- (match-beginning 0)))))
13193 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13194 (goto-char (point-min))
13195 (select-window cwin))))
13197 ;;; The mark ring for links jumps
13199 (defvar org-mark-ring nil
13200 "Mark ring for positions before jumps in Org-mode.")
13201 (defvar org-mark-ring-last-goto nil
13202 "Last position in the mark ring used to go back.")
13203 ;; Fill and close the ring
13204 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13205 (loop for i from 1 to org-mark-ring-length do
13206 (push (make-marker) org-mark-ring))
13207 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13208 org-mark-ring)
13210 (defun org-mark-ring-push (&optional pos buffer)
13211 "Put the current position or POS into the mark ring and rotate it."
13212 (interactive)
13213 (setq pos (or pos (point)))
13214 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13215 (move-marker (car org-mark-ring)
13216 (or pos (point))
13217 (or buffer (current-buffer)))
13218 (message "%s"
13219 (substitute-command-keys
13220 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13222 (defun org-mark-ring-goto (&optional n)
13223 "Jump to the previous position in the mark ring.
13224 With prefix arg N, jump back that many stored positions. When
13225 called several times in succession, walk through the entire ring.
13226 Org-mode commands jumping to a different position in the current file,
13227 or to another Org-mode file, automatically push the old position
13228 onto the ring."
13229 (interactive "p")
13230 (let (p m)
13231 (if (eq last-command this-command)
13232 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13233 (setq p org-mark-ring))
13234 (setq org-mark-ring-last-goto p)
13235 (setq m (car p))
13236 (switch-to-buffer (marker-buffer m))
13237 (goto-char m)
13238 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13240 (defun org-remove-angle-brackets (s)
13241 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13242 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13244 (defun org-add-angle-brackets (s)
13245 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13246 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13249 ;;; Following specific links
13251 (defun org-follow-timestamp-link ()
13252 (cond
13253 ((org-at-date-range-p t)
13254 (let ((org-agenda-start-on-weekday)
13255 (t1 (match-string 1))
13256 (t2 (match-string 2)))
13257 (setq t1 (time-to-days (org-time-string-to-time t1))
13258 t2 (time-to-days (org-time-string-to-time t2)))
13259 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13260 ((org-at-timestamp-p t)
13261 (org-agenda-list nil (time-to-days (org-time-string-to-time
13262 (substring (match-string 1) 0 10)))
13264 (t (error "This should not happen"))))
13267 (defun org-follow-bbdb-link (name)
13268 "Follow a BBDB link to NAME."
13269 (require 'bbdb)
13270 (let ((inhibit-redisplay (not debug-on-error))
13271 (bbdb-electric-p nil))
13272 (catch 'exit
13273 ;; Exact match on name
13274 (bbdb-name (concat "\\`" name "\\'") nil)
13275 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13276 ;; Exact match on name
13277 (bbdb-company (concat "\\`" name "\\'") nil)
13278 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13279 ;; Partial match on name
13280 (bbdb-name name nil)
13281 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13282 ;; Partial match on company
13283 (bbdb-company name nil)
13284 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13285 ;; General match including network address and notes
13286 (bbdb name nil)
13287 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13288 (delete-window (get-buffer-window "*BBDB*"))
13289 (error "No matching BBDB record")))))
13291 (defun org-follow-info-link (name)
13292 "Follow an info file & node link to NAME."
13293 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13294 (string-match "\\(.*\\)" name))
13295 (progn
13296 (require 'info)
13297 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13298 (Info-find-node (match-string 1 name) (match-string 2 name))
13299 (Info-find-node (match-string 1 name) "Top")))
13300 (message "Could not open: %s" name)))
13302 (defun org-follow-gnus-link (&optional group article)
13303 "Follow a Gnus link to GROUP and ARTICLE."
13304 (require 'gnus)
13305 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13306 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13307 (cond ((and group article)
13308 (gnus-group-read-group 1 nil group)
13309 (gnus-summary-goto-article (string-to-number article) nil t))
13310 (group (gnus-group-jump-to-group group))))
13312 (defun org-follow-vm-link (&optional folder article readonly)
13313 "Follow a VM link to FOLDER and ARTICLE."
13314 (require 'vm)
13315 (setq article (org-add-angle-brackets article))
13316 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13317 ;; ange-ftp or efs or tramp access
13318 (let ((user (or (match-string 1 folder) (user-login-name)))
13319 (host (match-string 2 folder))
13320 (file (match-string 3 folder)))
13321 (cond
13322 ((featurep 'tramp)
13323 ;; use tramp to access the file
13324 (if (featurep 'xemacs)
13325 (setq folder (format "[%s@%s]%s" user host file))
13326 (setq folder (format "/%s@%s:%s" user host file))))
13328 ;; use ange-ftp or efs
13329 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13330 (setq folder (format "/%s@%s:%s" user host file))))))
13331 (when folder
13332 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13333 (sit-for 0.1)
13334 (when article
13335 (vm-select-folder-buffer)
13336 (widen)
13337 (let ((case-fold-search t))
13338 (goto-char (point-min))
13339 (if (not (re-search-forward
13340 (concat "^" "message-id: *" (regexp-quote article))))
13341 (error "Could not find the specified message in this folder"))
13342 (vm-isearch-update)
13343 (vm-isearch-narrow)
13344 (vm-beginning-of-message)
13345 (vm-summarize)))))
13347 (defun org-follow-wl-link (folder article)
13348 "Follow a Wanderlust link to FOLDER and ARTICLE."
13349 (if (and (string= folder "%")
13350 article
13351 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13352 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13353 ;; Thus, we recompose folder and article ids.
13354 (setq folder (format "%s#%s" folder (match-string 1 article))
13355 article (match-string 3 article)))
13356 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13357 (error "No such folder: %s" folder))
13358 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13359 (and article
13360 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13361 (wl-summary-redisplay)))
13363 (defun org-follow-rmail-link (folder article)
13364 "Follow an RMAIL link to FOLDER and ARTICLE."
13365 (setq article (org-add-angle-brackets article))
13366 (let (message-number)
13367 (save-excursion
13368 (save-window-excursion
13369 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13370 (setq message-number
13371 (save-restriction
13372 (widen)
13373 (goto-char (point-max))
13374 (if (re-search-backward
13375 (concat "^Message-ID:\\s-+" (regexp-quote
13376 (or article "")))
13377 nil t)
13378 (rmail-what-message))))))
13379 (if message-number
13380 (progn
13381 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13382 (rmail-show-message message-number)
13383 message-number)
13384 (error "Message not found"))))
13386 ;;; mh-e integration based on planner-mode
13387 (defun org-mhe-get-message-real-folder ()
13388 "Return the name of the current message real folder, so if you use
13389 sequences, it will now work."
13390 (save-excursion
13391 (let* ((folder
13392 (if (equal major-mode 'mh-folder-mode)
13393 mh-current-folder
13394 ;; Refer to the show buffer
13395 mh-show-folder-buffer))
13396 (end-index
13397 (if (boundp 'mh-index-folder)
13398 (min (length mh-index-folder) (length folder))))
13400 ;; a simple test on mh-index-data does not work, because
13401 ;; mh-index-data is always nil in a show buffer.
13402 (if (and (boundp 'mh-index-folder)
13403 (string= mh-index-folder (substring folder 0 end-index)))
13404 (if (equal major-mode 'mh-show-mode)
13405 (save-window-excursion
13406 (let (pop-up-frames)
13407 (when (buffer-live-p (get-buffer folder))
13408 (progn
13409 (pop-to-buffer folder)
13410 (org-mhe-get-message-folder-from-index)
13413 (org-mhe-get-message-folder-from-index)
13415 folder
13419 (defun org-mhe-get-message-folder-from-index ()
13420 "Returns the name of the message folder in a index folder buffer."
13421 (save-excursion
13422 (mh-index-previous-folder)
13423 (re-search-forward "^\\(+.*\\)$" nil t)
13424 (message "%s" (match-string 1))))
13426 (defun org-mhe-get-message-folder ()
13427 "Return the name of the current message folder. Be careful if you
13428 use sequences."
13429 (save-excursion
13430 (if (equal major-mode 'mh-folder-mode)
13431 mh-current-folder
13432 ;; Refer to the show buffer
13433 mh-show-folder-buffer)))
13435 (defun org-mhe-get-message-num ()
13436 "Return the number of the current message. Be careful if you
13437 use sequences."
13438 (save-excursion
13439 (if (equal major-mode 'mh-folder-mode)
13440 (mh-get-msg-num nil)
13441 ;; Refer to the show buffer
13442 (mh-show-buffer-message-number))))
13444 (defun org-mhe-get-header (header)
13445 "Return a header of the message in folder mode. This will create a
13446 show buffer for the corresponding message. If you have a more clever
13447 idea..."
13448 (let* ((folder (org-mhe-get-message-folder))
13449 (num (org-mhe-get-message-num))
13450 (buffer (get-buffer-create (concat "show-" folder)))
13451 (header-field))
13452 (with-current-buffer buffer
13453 (mh-display-msg num folder)
13454 (if (equal major-mode 'mh-folder-mode)
13455 (mh-header-display)
13456 (mh-show-header-display))
13457 (set-buffer buffer)
13458 (setq header-field (mh-get-header-field header))
13459 (if (equal major-mode 'mh-folder-mode)
13460 (mh-show)
13461 (mh-show-show))
13462 header-field)))
13464 (defun org-follow-mhe-link (folder article)
13465 "Follow an MHE link to FOLDER and ARTICLE.
13466 If ARTICLE is nil FOLDER is shown. If the configuration variable
13467 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13468 ARTICLE is searched in all folders. Indexed searches (swish++,
13469 namazu, and others supported by MH-E) will always search in all
13470 folders."
13471 (require 'mh-e)
13472 (require 'mh-search)
13473 (require 'mh-utils)
13474 (mh-find-path)
13475 (if (not article)
13476 (mh-visit-folder (mh-normalize-folder-name folder))
13477 (setq article (org-add-angle-brackets article))
13478 (mh-search-choose)
13479 (if (equal mh-searcher 'pick)
13480 (progn
13481 (mh-search folder (list "--message-id" article))
13482 (when (and org-mhe-search-all-folders
13483 (not (org-mhe-get-message-real-folder)))
13484 (kill-this-buffer)
13485 (mh-search "+" (list "--message-id" article))))
13486 (mh-search "+" article))
13487 (if (org-mhe-get-message-real-folder)
13488 (mh-show-msg 1)
13489 (kill-this-buffer)
13490 (error "Message not found"))))
13492 ;;; BibTeX links
13494 ;; Use the custom search meachnism to construct and use search strings for
13495 ;; file links to BibTeX database entries.
13497 (defun org-create-file-search-in-bibtex ()
13498 "Create the search string and description for a BibTeX database entry."
13499 (when (eq major-mode 'bibtex-mode)
13500 ;; yes, we want to construct this search string.
13501 ;; Make a good description for this entry, using names, year and the title
13502 ;; Put it into the `description' variable which is dynamically scoped.
13503 (let ((bibtex-autokey-names 1)
13504 (bibtex-autokey-names-stretch 1)
13505 (bibtex-autokey-name-case-convert-function 'identity)
13506 (bibtex-autokey-name-separator " & ")
13507 (bibtex-autokey-additional-names " et al.")
13508 (bibtex-autokey-year-length 4)
13509 (bibtex-autokey-name-year-separator " ")
13510 (bibtex-autokey-titlewords 3)
13511 (bibtex-autokey-titleword-separator " ")
13512 (bibtex-autokey-titleword-case-convert-function 'identity)
13513 (bibtex-autokey-titleword-length 'infty)
13514 (bibtex-autokey-year-title-separator ": "))
13515 (setq description (bibtex-generate-autokey)))
13516 ;; Now parse the entry, get the key and return it.
13517 (save-excursion
13518 (bibtex-beginning-of-entry)
13519 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13521 (defun org-execute-file-search-in-bibtex (s)
13522 "Find the link search string S as a key for a database entry."
13523 (when (eq major-mode 'bibtex-mode)
13524 ;; Yes, we want to do the search in this file.
13525 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13526 (goto-char (point-min))
13527 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13528 (regexp-quote s) "[ \t\n]*,") nil t)
13529 (goto-char (match-beginning 0)))
13530 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13531 ;; Use double prefix to indicate that any web link should be browsed
13532 (let ((b (current-buffer)) (p (point)))
13533 ;; Restore the window configuration because we just use the web link
13534 (set-window-configuration org-window-config-before-follow-link)
13535 (save-excursion (set-buffer b) (goto-char p)
13536 (bibtex-url)))
13537 (recenter 0)) ; Move entry start to beginning of window
13538 ;; return t to indicate that the search is done.
13541 ;; Finally add the functions to the right hooks.
13542 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13543 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13545 ;; end of Bibtex link setup
13547 ;;; Following file links
13549 (defun org-open-file (path &optional in-emacs line search)
13550 "Open the file at PATH.
13551 First, this expands any special file name abbreviations. Then the
13552 configuration variable `org-file-apps' is checked if it contains an
13553 entry for this file type, and if yes, the corresponding command is launched.
13554 If no application is found, Emacs simply visits the file.
13555 With optional argument IN-EMACS, Emacs will visit the file.
13556 Optional LINE specifies a line to go to, optional SEARCH a string to
13557 search for. If LINE or SEARCH is given, the file will always be
13558 opened in Emacs.
13559 If the file does not exist, an error is thrown."
13560 (setq in-emacs (or in-emacs line search))
13561 (let* ((file (if (equal path "")
13562 buffer-file-name
13563 (substitute-in-file-name (expand-file-name path))))
13564 (apps (append org-file-apps (org-default-apps)))
13565 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13566 (dirp (if remp nil (file-directory-p file)))
13567 (dfile (downcase file))
13568 (old-buffer (current-buffer))
13569 (old-pos (point))
13570 (old-mode major-mode)
13571 ext cmd)
13572 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13573 (setq ext (match-string 1 dfile))
13574 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13575 (setq ext (match-string 1 dfile))))
13576 (if in-emacs
13577 (setq cmd 'emacs)
13578 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13579 (and dirp (cdr (assoc 'directory apps)))
13580 (cdr (assoc ext apps))
13581 (cdr (assoc t apps)))))
13582 (when (eq cmd 'mailcap)
13583 (require 'mailcap)
13584 (mailcap-parse-mailcaps)
13585 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13586 (command (mailcap-mime-info mime-type)))
13587 (if (stringp command)
13588 (setq cmd command)
13589 (setq cmd 'emacs))))
13590 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13591 (not (file-exists-p file))
13592 (not org-open-non-existing-files))
13593 (error "No such file: %s" file))
13594 (cond
13595 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13596 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13597 (while (string-match "['\"]%s['\"]" cmd)
13598 (setq cmd (replace-match "%s" t t cmd)))
13599 (while (string-match "%s" cmd)
13600 (setq cmd (replace-match
13601 (save-match-data (shell-quote-argument file))
13602 t t cmd)))
13603 (save-window-excursion
13604 (start-process-shell-command cmd nil cmd)))
13605 ((or (stringp cmd)
13606 (eq cmd 'emacs))
13607 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13608 (widen)
13609 (if line (goto-line line)
13610 (if search (org-link-search search))))
13611 ((consp cmd)
13612 (eval cmd))
13613 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13614 (and (org-mode-p) (eq old-mode 'org-mode)
13615 (or (not (equal old-buffer (current-buffer)))
13616 (not (equal old-pos (point))))
13617 (org-mark-ring-push old-pos old-buffer))))
13619 (defun org-default-apps ()
13620 "Return the default applications for this operating system."
13621 (cond
13622 ((eq system-type 'darwin)
13623 org-file-apps-defaults-macosx)
13624 ((eq system-type 'windows-nt)
13625 org-file-apps-defaults-windowsnt)
13626 (t org-file-apps-defaults-gnu)))
13628 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13629 (defun org-file-remote-p (file)
13630 "Test whether FILE specifies a location on a remote system.
13631 Return non-nil if the location is indeed remote.
13633 For example, the filename \"/user@host:/foo\" specifies a location
13634 on the system \"/user@host:\"."
13635 (cond ((fboundp 'file-remote-p)
13636 (file-remote-p file))
13637 ((fboundp 'tramp-handle-file-remote-p)
13638 (tramp-handle-file-remote-p file))
13639 ((and (boundp 'ange-ftp-name-format)
13640 (string-match (car ange-ftp-name-format) file))
13642 (t nil)))
13645 ;;;; Hooks for remember.el, and refiling
13647 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13648 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13650 ;;;###autoload
13651 (defun org-remember-insinuate ()
13652 "Setup remember.el for use wiht Org-mode."
13653 (require 'remember)
13654 (setq remember-annotation-functions '(org-remember-annotation))
13655 (setq remember-handler-functions '(org-remember-handler))
13656 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13658 ;;;###autoload
13659 (defun org-remember-annotation ()
13660 "Return a link to the current location as an annotation for remember.el.
13661 If you are using Org-mode files as target for data storage with
13662 remember.el, then the annotations should include a link compatible with the
13663 conventions in Org-mode. This function returns such a link."
13664 (org-store-link nil))
13666 (defconst org-remember-help
13667 "Select a destination location for the note.
13668 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13669 RET on headline -> Store as sublevel entry to current headline
13670 RET at beg-of-buf -> Append to file as level 2 headline
13671 <left>/<right> -> before/after current headline, same headings level")
13673 (defvar org-remember-previous-location nil)
13674 (defvar org-force-remember-template-char) ;; dynamically scoped
13676 ;; Save the major mode of the buffer we called remember from
13677 (defvar org-select-template-temp-major-mode nil)
13679 ;; Temporary store the buffer where remember was called from
13680 (defvar org-select-template-original-buffer nil)
13682 (defun org-select-remember-template (&optional use-char)
13683 (when org-remember-templates
13684 (let* ((pre-selected-templates
13685 (mapcar
13686 (lambda (tpl)
13687 (let ((ctxt (nth 5 tpl))
13688 (mode org-select-template-temp-major-mode)
13689 (buf org-select-template-original-buffer))
13690 (if (or (and (functionp ctxt)
13691 (save-excursion
13692 (set-buffer buf)
13693 ;; Protect the user-defined function from error
13694 (condition-case nil (funcall ctxt) (error nil))))
13695 (and ctxt (listp ctxt)
13696 (delq nil (mapcar (lambda(x) (eq mode x)) ctxt))))
13697 tpl)))
13698 org-remember-templates))
13699 ;; If no template at this point, add the default templates:
13700 (pre-selected-templates1
13701 (if (not (delq nil pre-selected-templates))
13702 (mapcar (lambda(x) (if (not (nth 5 x)) x))
13703 org-remember-templates)
13704 pre-selected-templates))
13705 ;; Then unconditionnally add template for any contexts
13706 (pre-selected-templates2
13707 (append (mapcar (lambda(x) (if (eq (nth 5 x) t) x))
13708 org-remember-templates)
13709 (delq nil pre-selected-templates1)))
13710 (templates (mapcar (lambda (x)
13711 (if (stringp (car x))
13712 (append (list (nth 1 x) (car x)) (cddr x))
13713 (append (list (car x) "") (cdr x))))
13714 (delq nil pre-selected-templates2)))
13715 (char (or use-char
13716 (cond
13717 ((= (length templates) 1)
13718 (caar templates))
13719 ((and (boundp 'org-force-remember-template-char)
13720 org-force-remember-template-char)
13721 (if (stringp org-force-remember-template-char)
13722 (string-to-char org-force-remember-template-char)
13723 org-force-remember-template-char))
13725 (message "Select template: %s"
13726 (mapconcat
13727 (lambda (x)
13728 (cond
13729 ((not (string-match "\\S-" (nth 1 x)))
13730 (format "[%c]" (car x)))
13731 ((equal (downcase (car x))
13732 (downcase (aref (nth 1 x) 0)))
13733 (format "[%c]%s" (car x)
13734 (substring (nth 1 x) 1)))
13735 (t (format "[%c]%s" (car x) (nth 1 x)))))
13736 templates " "))
13737 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13738 (when (equal char0 ?\C-g)
13739 (jump-to-register remember-register)
13740 (kill-buffer remember-buffer))
13741 char0))))))
13742 (cddr (assoc char templates)))))
13744 (defvar x-last-selected-text)
13745 (defvar x-last-selected-text-primary)
13747 ;;;###autoload
13748 (defun org-remember-apply-template (&optional use-char skip-interactive)
13749 "Initialize *remember* buffer with template, invoke `org-mode'.
13750 This function should be placed into `remember-mode-hook' and in fact requires
13751 to be run from that hook to function properly."
13752 (if org-remember-templates
13753 (let* ((entry (org-select-remember-template use-char))
13754 (tpl (car entry))
13755 (plist-p (if org-store-link-plist t nil))
13756 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13757 (string-match "\\S-" (nth 1 entry)))
13758 (nth 1 entry)
13759 org-default-notes-file))
13760 (headline (nth 2 entry))
13761 (v-c (or (and (eq window-system 'x)
13762 (fboundp 'x-cut-buffer-or-selection-value)
13763 (x-cut-buffer-or-selection-value))
13764 (org-bound-and-true-p x-last-selected-text)
13765 (org-bound-and-true-p x-last-selected-text-primary)
13766 (and (> (length kill-ring) 0) (current-kill 0))))
13767 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13768 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13769 (v-u (concat "[" (substring v-t 1 -1) "]"))
13770 (v-U (concat "[" (substring v-T 1 -1) "]"))
13771 ;; `initial' and `annotation' are bound in `remember'
13772 (v-i (if (boundp 'initial) initial))
13773 (v-a (if (and (boundp 'annotation) annotation)
13774 (if (equal annotation "[[]]") "" annotation)
13775 ""))
13776 (v-A (if (and v-a
13777 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13778 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13779 v-a))
13780 (v-n user-full-name)
13781 (org-startup-folded nil)
13782 org-time-was-given org-end-time-was-given x
13783 prompt completions char time pos default histvar)
13784 (setq org-store-link-plist
13785 (append (list :annotation v-a :initial v-i)
13786 org-store-link-plist))
13787 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13788 (erase-buffer)
13789 (insert (substitute-command-keys
13790 (format
13791 "## Filing location: Select interactively, default, or last used:
13792 ## %s to select file and header location interactively.
13793 ## %s \"%s\" -> \"* %s\"
13794 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13795 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13796 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13797 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13798 (abbreviate-file-name (or file org-default-notes-file))
13799 (or headline "")
13800 (or (car org-remember-previous-location) "???")
13801 (or (cdr org-remember-previous-location) "???"))))
13802 (insert tpl) (goto-char (point-min))
13803 ;; Simple %-escapes
13804 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13805 (when (and initial (equal (match-string 0) "%i"))
13806 (save-match-data
13807 (let* ((lead (buffer-substring
13808 (point-at-bol) (match-beginning 0))))
13809 (setq v-i (mapconcat 'identity
13810 (org-split-string initial "\n")
13811 (concat "\n" lead))))))
13812 (replace-match
13813 (or (eval (intern (concat "v-" (match-string 1)))) "")
13814 t t))
13816 ;; %[] Insert contents of a file.
13817 (goto-char (point-min))
13818 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13819 (let ((start (match-beginning 0))
13820 (end (match-end 0))
13821 (filename (expand-file-name (match-string 1))))
13822 (goto-char start)
13823 (delete-region start end)
13824 (condition-case error
13825 (insert-file-contents filename)
13826 (error (insert (format "%%![Couldn't insert %s: %s]"
13827 filename error))))))
13828 ;; %() embedded elisp
13829 (goto-char (point-min))
13830 (while (re-search-forward "%\\((.+)\\)" nil t)
13831 (goto-char (match-beginning 0))
13832 (let ((template-start (point)))
13833 (forward-char 1)
13834 (let ((result
13835 (condition-case error
13836 (eval (read (current-buffer)))
13837 (error (format "%%![Error: %s]" error)))))
13838 (delete-region template-start (point))
13839 (insert result))))
13841 ;; From the property list
13842 (when plist-p
13843 (goto-char (point-min))
13844 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13845 (and (setq x (or (plist-get org-store-link-plist
13846 (intern (match-string 1))) ""))
13847 (replace-match x t t))))
13849 ;; Turn on org-mode in the remember buffer, set local variables
13850 (org-mode)
13851 (org-set-local 'org-finish-function 'org-remember-finalize)
13852 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13853 (org-set-local 'org-default-notes-file file))
13854 (if (and headline (stringp headline) (string-match "\\S-" headline))
13855 (org-set-local 'org-remember-default-headline headline))
13856 ;; Interactive template entries
13857 (goto-char (point-min))
13858 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13859 (setq char (if (match-end 3) (match-string 3))
13860 prompt (if (match-end 2) (match-string 2)))
13861 (goto-char (match-beginning 0))
13862 (replace-match "")
13863 (setq completions nil default nil)
13864 (when prompt
13865 (setq completions (org-split-string prompt "|")
13866 prompt (pop completions)
13867 default (car completions)
13868 histvar (intern (concat
13869 "org-remember-template-prompt-history::"
13870 (or prompt "")))
13871 completions (mapcar 'list completions)))
13872 (cond
13873 ((member char '("G" "g"))
13874 (let* ((org-last-tags-completion-table
13875 (org-global-tags-completion-table
13876 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13877 (org-add-colon-after-tag-completion t)
13878 (ins (completing-read
13879 (if prompt (concat prompt ": ") "Tags: ")
13880 'org-tags-completion-function nil nil nil
13881 'org-tags-history)))
13882 (setq ins (mapconcat 'identity
13883 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13884 ":"))
13885 (when (string-match "\\S-" ins)
13886 (or (equal (char-before) ?:) (insert ":"))
13887 (insert ins)
13888 (or (equal (char-after) ?:) (insert ":")))))
13889 (char
13890 (setq org-time-was-given (equal (upcase char) char))
13891 (setq time (org-read-date (equal (upcase char) "U") t nil
13892 prompt))
13893 (org-insert-time-stamp time org-time-was-given
13894 (member char '("u" "U"))
13895 nil nil (list org-end-time-was-given)))
13897 (insert (org-completing-read
13898 (concat (if prompt prompt "Enter string")
13899 (if default (concat " [" default "]"))
13900 ": ")
13901 completions nil nil nil histvar default)))))
13902 (goto-char (point-min))
13903 (if (re-search-forward "%\\?" nil t)
13904 (replace-match "")
13905 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13906 (org-mode)
13907 (org-set-local 'org-finish-function 'org-remember-finalize))
13908 (when (save-excursion
13909 (goto-char (point-min))
13910 (re-search-forward "%!" nil t))
13911 (replace-match "")
13912 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13914 (defun org-remember-finish-immediately ()
13915 "File remember note immediately.
13916 This should be run in `post-command-hook' and will remove itself
13917 from that hook."
13918 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13919 (when org-finish-function
13920 (funcall org-finish-function)))
13922 (defvar org-clock-marker) ; Defined below
13923 (defun org-remember-finalize ()
13924 "Finalize the remember process."
13925 (unless (fboundp 'remember-finalize)
13926 (defalias 'remember-finalize 'remember-buffer))
13927 (when (and org-clock-marker
13928 (equal (marker-buffer org-clock-marker) (current-buffer)))
13929 ;; FIXME: test this, this is w/o notetaking!
13930 (let (org-log-note-clock-out) (org-clock-out)))
13931 (when buffer-file-name
13932 (save-buffer)
13933 (setq buffer-file-name nil))
13934 (remember-finalize))
13936 ;;;###autoload
13937 (defun org-remember (&optional goto org-force-remember-template-char)
13938 "Call `remember'. If this is already a remember buffer, re-apply template.
13939 If there is an active region, make sure remember uses it as initial content
13940 of the remember buffer.
13942 When called interactively with a `C-u' prefix argument GOTO, don't remember
13943 anything, just go to the file/headline where the selected template usually
13944 stores its notes. With a double prefix arg `C-u C-u', go to the last
13945 note stored by remember.
13947 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13948 associated with a template in `org-remember-templates'."
13949 (interactive "P")
13950 (cond
13951 ((equal goto '(4)) (org-go-to-remember-target))
13952 ((equal goto '(16)) (org-remember-goto-last-stored))
13954 ;; set temporary variables that will be needed in
13955 ;; `org-select-remember-template'
13956 (setq org-select-template-temp-major-mode major-mode)
13957 (setq org-select-template-original-buffer (current-buffer))
13958 (if (memq org-finish-function '(remember-buffer remember-finalize))
13959 (progn
13960 (when (< (length org-remember-templates) 2)
13961 (error "No other template available"))
13962 (erase-buffer)
13963 (let ((annotation (plist-get org-store-link-plist :annotation))
13964 (initial (plist-get org-store-link-plist :initial)))
13965 (org-remember-apply-template))
13966 (message "Press C-c C-c to remember data"))
13967 (if (org-region-active-p)
13968 (remember (buffer-substring (point) (mark)))
13969 (call-interactively 'remember))))))
13971 (defun org-remember-goto-last-stored ()
13972 "Go to the location where the last remember note was stored."
13973 (interactive)
13974 (bookmark-jump "org-remember-last-stored")
13975 (message "This is the last note stored by remember"))
13977 (defun org-go-to-remember-target (&optional template-key)
13978 "Go to the target location of a remember template.
13979 The user is queried for the template."
13980 (interactive)
13981 (let* (org-select-template-temp-major-mode
13982 (entry (org-select-remember-template template-key))
13983 (file (nth 1 entry))
13984 (heading (nth 2 entry))
13985 visiting)
13986 (unless (and file (stringp file) (string-match "\\S-" file))
13987 (setq file org-default-notes-file))
13988 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13989 (setq heading org-remember-default-headline))
13990 (setq visiting (org-find-base-buffer-visiting file))
13991 (if (not visiting) (find-file-noselect file))
13992 (switch-to-buffer (or visiting (get-file-buffer file)))
13993 (widen)
13994 (goto-char (point-min))
13995 (if (re-search-forward
13996 (concat "^\\*+[ \t]+" (regexp-quote heading)
13997 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13998 nil t)
13999 (goto-char (match-beginning 0))
14000 (error "Target headline not found: %s" heading))))
14002 (defvar org-note-abort nil) ; dynamically scoped
14004 ;;;###autoload
14005 (defun org-remember-handler ()
14006 "Store stuff from remember.el into an org file.
14007 First prompts for an org file. If the user just presses return, the value
14008 of `org-default-notes-file' is used.
14009 Then the command offers the headings tree of the selected file in order to
14010 file the text at a specific location.
14011 You can either immediately press RET to get the note appended to the
14012 file, or you can use vertical cursor motion and visibility cycling (TAB) to
14013 find a better place. Then press RET or <left> or <right> in insert the note.
14015 Key Cursor position Note gets inserted
14016 -----------------------------------------------------------------------------
14017 RET buffer-start as level 1 heading at end of file
14018 RET on headline as sublevel of the heading at cursor
14019 RET no heading at cursor position, level taken from context.
14020 Or use prefix arg to specify level manually.
14021 <left> on headline as same level, before current heading
14022 <right> on headline as same level, after current heading
14024 So the fastest way to store the note is to press RET RET to append it to
14025 the default file. This way your current train of thought is not
14026 interrupted, in accordance with the principles of remember.el.
14027 You can also get the fast execution without prompting by using
14028 C-u C-c C-c to exit the remember buffer. See also the variable
14029 `org-remember-store-without-prompt'.
14031 Before being stored away, the function ensures that the text has a
14032 headline, i.e. a first line that starts with a \"*\". If not, a headline
14033 is constructed from the current date and some additional data.
14035 If the variable `org-adapt-indentation' is non-nil, the entire text is
14036 also indented so that it starts in the same column as the headline
14037 \(i.e. after the stars).
14039 See also the variable `org-reverse-note-order'."
14040 (goto-char (point-min))
14041 (while (looking-at "^[ \t]*\n\\|^##.*\n")
14042 (replace-match ""))
14043 (goto-char (point-max))
14044 (beginning-of-line 1)
14045 (while (looking-at "[ \t]*$\\|##.*")
14046 (delete-region (1- (point)) (point-max))
14047 (beginning-of-line 1))
14048 (catch 'quit
14049 (if org-note-abort (throw 'quit nil))
14050 (let* ((txt (buffer-substring (point-min) (point-max)))
14051 (fastp (org-xor (equal current-prefix-arg '(4))
14052 org-remember-store-without-prompt))
14053 (file (cond
14054 (fastp org-default-notes-file)
14055 ((and (eq org-remember-interactive-interface 'refile)
14056 org-refile-targets)
14057 org-default-notes-file)
14058 ((not (and (equal current-prefix-arg '(16))
14059 org-remember-previous-location))
14060 (org-get-org-file))))
14061 (heading org-remember-default-headline)
14062 (visiting (and file (org-find-base-buffer-visiting file)))
14063 (org-startup-folded nil)
14064 (org-startup-align-all-tables nil)
14065 (org-goto-start-pos 1)
14066 spos exitcmd level indent reversed)
14067 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
14068 (setq file (car org-remember-previous-location)
14069 heading (cdr org-remember-previous-location)
14070 fastp t))
14071 (setq current-prefix-arg nil)
14072 (if (string-match "[ \t\n]+\\'" txt)
14073 (setq txt (replace-match "" t t txt)))
14074 ;; Modify text so that it becomes a nice subtree which can be inserted
14075 ;; into an org tree.
14076 (let* ((lines (split-string txt "\n"))
14077 first)
14078 (setq first (car lines) lines (cdr lines))
14079 (if (string-match "^\\*+ " first)
14080 ;; Is already a headline
14081 (setq indent nil)
14082 ;; We need to add a headline: Use time and first buffer line
14083 (setq lines (cons first lines)
14084 first (concat "* " (current-time-string)
14085 " (" (remember-buffer-desc) ")")
14086 indent " "))
14087 (if (and org-adapt-indentation indent)
14088 (setq lines (mapcar
14089 (lambda (x)
14090 (if (string-match "\\S-" x)
14091 (concat indent x) x))
14092 lines)))
14093 (setq txt (concat first "\n"
14094 (mapconcat 'identity lines "\n"))))
14095 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
14096 (setq txt (replace-match "\n\n" t t txt))
14097 (if (string-match "[ \t\n]*\\'" txt)
14098 (setq txt (replace-match "\n" t t txt))))
14099 ;; Put the modified text back into the remember buffer, for refile.
14100 (erase-buffer)
14101 (insert txt)
14102 (goto-char (point-min))
14103 (when (and (eq org-remember-interactive-interface 'refile)
14104 (not fastp))
14105 (org-refile nil (or visiting (find-file-noselect file)))
14106 (throw 'quit t))
14107 ;; Find the file
14108 (if (not visiting) (find-file-noselect file))
14109 (with-current-buffer (or visiting (get-file-buffer file))
14110 (unless (org-mode-p)
14111 (error "Target files for remember notes must be in Org-mode"))
14112 (save-excursion
14113 (save-restriction
14114 (widen)
14115 (and (goto-char (point-min))
14116 (not (re-search-forward "^\\* " nil t))
14117 (insert "\n* " (or heading "Notes") "\n"))
14118 (setq reversed (org-notes-order-reversed-p))
14120 ;; Find the default location
14121 (when (and heading (stringp heading) (string-match "\\S-" heading))
14122 (goto-char (point-min))
14123 (if (re-search-forward
14124 (concat "^\\*+[ \t]+" (regexp-quote heading)
14125 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
14126 nil t)
14127 (setq org-goto-start-pos (match-beginning 0))
14128 (when fastp
14129 (goto-char (point-max))
14130 (unless (bolp) (newline))
14131 (insert "* " heading "\n")
14132 (setq org-goto-start-pos (point-at-bol 0)))))
14134 ;; Ask the User for a location, using the appropriate interface
14135 (cond
14136 (fastp (setq spos org-goto-start-pos
14137 exitcmd 'return))
14138 ((eq org-remember-interactive-interface 'outline)
14139 (setq spos (org-get-location (current-buffer)
14140 org-remember-help)
14141 exitcmd (cdr spos)
14142 spos (car spos)))
14143 ((eq org-remember-interactive-interface 'outline-path-completion)
14144 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
14145 (org-refile-use-outline-path t))
14146 (setq spos (org-refile-get-location "Heading: ")
14147 exitcmd 'return
14148 spos (nth 3 spos))))
14149 (t (error "this should not hapen")))
14150 (if (not spos) (throw 'quit nil)) ; return nil to show we did
14151 ; not handle this note
14152 (goto-char spos)
14153 (cond ((org-on-heading-p t)
14154 (org-back-to-heading t)
14155 (setq level (funcall outline-level))
14156 (cond
14157 ((eq exitcmd 'return)
14158 ;; sublevel of current
14159 (setq org-remember-previous-location
14160 (cons (abbreviate-file-name file)
14161 (org-get-heading 'notags)))
14162 (if reversed
14163 (outline-next-heading)
14164 (org-end-of-subtree t)
14165 (if (not (bolp))
14166 (if (looking-at "[ \t]*\n")
14167 (beginning-of-line 2)
14168 (end-of-line 1)
14169 (insert "\n"))))
14170 (bookmark-set "org-remember-last-stored")
14171 (org-paste-subtree (org-get-legal-level level 1) txt))
14172 ((eq exitcmd 'left)
14173 ;; before current
14174 (bookmark-set "org-remember-last-stored")
14175 (org-paste-subtree level txt))
14176 ((eq exitcmd 'right)
14177 ;; after current
14178 (org-end-of-subtree t)
14179 (bookmark-set "org-remember-last-stored")
14180 (org-paste-subtree level txt))
14181 (t (error "This should not happen"))))
14183 ((and (bobp) (not reversed))
14184 ;; Put it at the end, one level below level 1
14185 (save-restriction
14186 (widen)
14187 (goto-char (point-max))
14188 (if (not (bolp)) (newline))
14189 (bookmark-set "org-remember-last-stored")
14190 (org-paste-subtree (org-get-legal-level 1 1) txt)))
14192 ((and (bobp) reversed)
14193 ;; Put it at the start, as level 1
14194 (save-restriction
14195 (widen)
14196 (goto-char (point-min))
14197 (re-search-forward "^\\*+ " nil t)
14198 (beginning-of-line 1)
14199 (bookmark-set "org-remember-last-stored")
14200 (org-paste-subtree 1 txt)))
14202 ;; Put it right there, with automatic level determined by
14203 ;; org-paste-subtree or from prefix arg
14204 (bookmark-set "org-remember-last-stored")
14205 (org-paste-subtree
14206 (if (numberp current-prefix-arg) current-prefix-arg)
14207 txt)))
14208 (when remember-save-after-remembering
14209 (save-buffer)
14210 (if (not visiting) (kill-buffer (current-buffer)))))))))
14212 t) ;; return t to indicate that we took care of this note.
14214 (defun org-get-org-file ()
14215 "Read a filename, with default directory `org-directory'."
14216 (let ((default (or org-default-notes-file remember-data-file)))
14217 (read-file-name (format "File name [%s]: " default)
14218 (file-name-as-directory org-directory)
14219 default)))
14221 (defun org-notes-order-reversed-p ()
14222 "Check if the current file should receive notes in reversed order."
14223 (cond
14224 ((not org-reverse-note-order) nil)
14225 ((eq t org-reverse-note-order) t)
14226 ((not (listp org-reverse-note-order)) nil)
14227 (t (catch 'exit
14228 (let ((all org-reverse-note-order)
14229 entry)
14230 (while (setq entry (pop all))
14231 (if (string-match (car entry) buffer-file-name)
14232 (throw 'exit (cdr entry))))
14233 nil)))))
14235 ;;; Refiling
14237 (defvar org-refile-target-table nil
14238 "The list of refile targets, created by `org-refile'.")
14240 (defvar org-agenda-new-buffers nil
14241 "Buffers created to visit agenda files.")
14243 (defun org-get-refile-targets (&optional default-buffer)
14244 "Produce a table with refile targets."
14245 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
14246 targets txt re files f desc descre)
14247 (with-current-buffer (or default-buffer (current-buffer))
14248 (while (setq entry (pop entries))
14249 (setq files (car entry) desc (cdr entry))
14250 (cond
14251 ((null files) (setq files (list (current-buffer))))
14252 ((eq files 'org-agenda-files)
14253 (setq files (org-agenda-files 'unrestricted)))
14254 ((and (symbolp files) (fboundp files))
14255 (setq files (funcall files)))
14256 ((and (symbolp files) (boundp files))
14257 (setq files (symbol-value files))))
14258 (if (stringp files) (setq files (list files)))
14259 (cond
14260 ((eq (car desc) :tag)
14261 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
14262 ((eq (car desc) :todo)
14263 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
14264 ((eq (car desc) :regexp)
14265 (setq descre (cdr desc)))
14266 ((eq (car desc) :level)
14267 (setq descre (concat "^\\*\\{" (number-to-string
14268 (if org-odd-levels-only
14269 (1- (* 2 (cdr desc)))
14270 (cdr desc)))
14271 "\\}[ \t]")))
14272 ((eq (car desc) :maxlevel)
14273 (setq descre (concat "^\\*\\{1," (number-to-string
14274 (if org-odd-levels-only
14275 (1- (* 2 (cdr desc)))
14276 (cdr desc)))
14277 "\\}[ \t]")))
14278 (t (error "Bad refiling target description %s" desc)))
14279 (while (setq f (pop files))
14280 (save-excursion
14281 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
14282 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
14283 (save-excursion
14284 (save-restriction
14285 (widen)
14286 (goto-char (point-min))
14287 (while (re-search-forward descre nil t)
14288 (goto-char (point-at-bol))
14289 (when (looking-at org-complex-heading-regexp)
14290 (setq txt (match-string 4)
14291 re (concat "^" (regexp-quote
14292 (buffer-substring (match-beginning 1)
14293 (match-end 4)))))
14294 (if (match-end 5) (setq re (concat re "[ \t]+"
14295 (regexp-quote
14296 (match-string 5)))))
14297 (setq re (concat re "[ \t]*$"))
14298 (when org-refile-use-outline-path
14299 (setq txt (mapconcat 'identity
14300 (append
14301 (if (eq org-refile-use-outline-path 'file)
14302 (list (file-name-nondirectory
14303 (buffer-file-name (buffer-base-buffer))))
14304 (if (eq org-refile-use-outline-path 'full-file-path)
14305 (list (buffer-file-name (buffer-base-buffer)))))
14306 (org-get-outline-path)
14307 (list txt))
14308 "/")))
14309 (push (list txt f re (point)) targets))
14310 (goto-char (point-at-eol))))))))
14311 (nreverse targets))))
14313 (defun org-get-outline-path ()
14314 "Return the outline path to the current entry, as a list."
14315 (let (rtn)
14316 (save-excursion
14317 (while (org-up-heading-safe)
14318 (when (looking-at org-complex-heading-regexp)
14319 (push (org-match-string-no-properties 4) rtn)))
14320 rtn)))
14322 (defvar org-refile-history nil
14323 "History for refiling operations.")
14325 (defun org-refile (&optional goto default-buffer)
14326 "Move the entry at point to another heading.
14327 The list of target headings is compiled using the information in
14328 `org-refile-targets', which see. This list is created upon first use, and
14329 you can update it by calling this command with a double prefix (`C-u C-u').
14330 FIXME: Can we find a better way of updating?
14332 At the target location, the entry is filed as a subitem of the target heading.
14333 Depending on `org-reverse-note-order', the new subitem will either be the
14334 first of the last subitem.
14336 With prefix arg GOTO, the command will only visit the target location,
14337 not actually move anything.
14338 With a double prefix `C-c C-c', go to the location where the last refiling
14339 operation has put the subtree.
14341 With a double prefix argument, the command can be used to jump to any
14342 heading in the current buffer."
14343 (interactive "P")
14344 (let* ((cbuf (current-buffer))
14345 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14346 pos it nbuf file re level reversed)
14347 (if (equal goto '(16))
14348 (org-refile-goto-last-stored)
14349 (when (setq it (org-refile-get-location
14350 (if goto "Goto: " "Refile to: ") default-buffer))
14351 (setq file (nth 1 it)
14352 re (nth 2 it)
14353 pos (nth 3 it))
14354 (setq nbuf (or (find-buffer-visiting file)
14355 (find-file-noselect file)))
14356 (if goto
14357 (progn
14358 (switch-to-buffer nbuf)
14359 (goto-char pos)
14360 (org-show-context 'org-goto))
14361 (org-copy-special)
14362 (save-excursion
14363 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14364 (find-file-noselect file))))
14365 (setq reversed (org-notes-order-reversed-p))
14366 (save-excursion
14367 (save-restriction
14368 (widen)
14369 (goto-char pos)
14370 (looking-at outline-regexp)
14371 (setq level (org-get-legal-level (funcall outline-level) 1))
14372 (goto-char
14373 (if reversed
14374 (outline-next-heading)
14375 (or (save-excursion (outline-get-next-sibling))
14376 (org-end-of-subtree t t)
14377 (point-max))))
14378 (bookmark-set "org-refile-last-stored")
14379 (org-paste-subtree level))))
14380 (org-cut-special)
14381 (message "Entry refiled to \"%s\"" (car it)))))))
14383 (defun org-refile-goto-last-stored ()
14384 "Go to the location where the last refile was stored."
14385 (interactive)
14386 (bookmark-jump "org-refile-last-stored")
14387 (message "This is the location of the last refile"))
14389 (defun org-refile-get-location (&optional prompt default-buffer)
14390 "Prompt the user for a refile location, using PROMPT."
14391 (let ((org-refile-targets org-refile-targets)
14392 (org-refile-use-outline-path org-refile-use-outline-path))
14393 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14394 (unless org-refile-target-table
14395 (error "No refile targets"))
14396 (let* ((cbuf (current-buffer))
14397 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14398 (fname (and filename (file-truename filename)))
14399 (tbl (mapcar
14400 (lambda (x)
14401 (if (not (equal fname (file-truename (nth 1 x))))
14402 (cons (concat (car x) " (" (file-name-nondirectory
14403 (nth 1 x)) ")")
14404 (cdr x))
14406 org-refile-target-table))
14407 (completion-ignore-case t))
14408 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14409 tbl)))
14411 ;;;; Dynamic blocks
14413 (defun org-find-dblock (name)
14414 "Find the first dynamic block with name NAME in the buffer.
14415 If not found, stay at current position and return nil."
14416 (let (pos)
14417 (save-excursion
14418 (goto-char (point-min))
14419 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14420 nil t)
14421 (match-beginning 0))))
14422 (if pos (goto-char pos))
14423 pos))
14425 (defconst org-dblock-start-re
14426 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14427 "Matches the startline of a dynamic block, with parameters.")
14429 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14430 "Matches the end of a dyhamic block.")
14432 (defun org-create-dblock (plist)
14433 "Create a dynamic block section, with parameters taken from PLIST.
14434 PLIST must containe a :name entry which is used as name of the block."
14435 (unless (bolp) (newline))
14436 (let ((name (plist-get plist :name)))
14437 (insert "#+BEGIN: " name)
14438 (while plist
14439 (if (eq (car plist) :name)
14440 (setq plist (cddr plist))
14441 (insert " " (prin1-to-string (pop plist)))))
14442 (insert "\n\n#+END:\n")
14443 (beginning-of-line -2)))
14445 (defun org-prepare-dblock ()
14446 "Prepare dynamic block for refresh.
14447 This empties the block, puts the cursor at the insert position and returns
14448 the property list including an extra property :name with the block name."
14449 (unless (looking-at org-dblock-start-re)
14450 (error "Not at a dynamic block"))
14451 (let* ((begdel (1+ (match-end 0)))
14452 (name (org-no-properties (match-string 1)))
14453 (params (append (list :name name)
14454 (read (concat "(" (match-string 3) ")")))))
14455 (unless (re-search-forward org-dblock-end-re nil t)
14456 (error "Dynamic block not terminated"))
14457 (delete-region begdel (match-beginning 0))
14458 (goto-char begdel)
14459 (open-line 1)
14460 params))
14462 (defun org-map-dblocks (&optional command)
14463 "Apply COMMAND to all dynamic blocks in the current buffer.
14464 If COMMAND is not given, use `org-update-dblock'."
14465 (let ((cmd (or command 'org-update-dblock))
14466 pos)
14467 (save-excursion
14468 (goto-char (point-min))
14469 (while (re-search-forward org-dblock-start-re nil t)
14470 (goto-char (setq pos (match-beginning 0)))
14471 (condition-case nil
14472 (funcall cmd)
14473 (error (message "Error during update of dynamic block")))
14474 (goto-char pos)
14475 (unless (re-search-forward org-dblock-end-re nil t)
14476 (error "Dynamic block not terminated"))))))
14478 (defun org-dblock-update (&optional arg)
14479 "User command for updating dynamic blocks.
14480 Update the dynamic block at point. With prefix ARG, update all dynamic
14481 blocks in the buffer."
14482 (interactive "P")
14483 (if arg
14484 (org-update-all-dblocks)
14485 (or (looking-at org-dblock-start-re)
14486 (org-beginning-of-dblock))
14487 (org-update-dblock)))
14489 (defun org-update-dblock ()
14490 "Update the dynamic block at point
14491 This means to empty the block, parse for parameters and then call
14492 the correct writing function."
14493 (save-window-excursion
14494 (let* ((pos (point))
14495 (line (org-current-line))
14496 (params (org-prepare-dblock))
14497 (name (plist-get params :name))
14498 (cmd (intern (concat "org-dblock-write:" name))))
14499 (message "Updating dynamic block `%s' at line %d..." name line)
14500 (funcall cmd params)
14501 (message "Updating dynamic block `%s' at line %d...done" name line)
14502 (goto-char pos))))
14504 (defun org-beginning-of-dblock ()
14505 "Find the beginning of the dynamic block at point.
14506 Error if there is no scuh block at point."
14507 (let ((pos (point))
14508 beg)
14509 (end-of-line 1)
14510 (if (and (re-search-backward org-dblock-start-re nil t)
14511 (setq beg (match-beginning 0))
14512 (re-search-forward org-dblock-end-re nil t)
14513 (> (match-end 0) pos))
14514 (goto-char beg)
14515 (goto-char pos)
14516 (error "Not in a dynamic block"))))
14518 (defun org-update-all-dblocks ()
14519 "Update all dynamic blocks in the buffer.
14520 This function can be used in a hook."
14521 (when (org-mode-p)
14522 (org-map-dblocks 'org-update-dblock)))
14525 ;;;; Completion
14527 (defconst org-additional-option-like-keywords
14528 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14529 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14530 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14532 (defun org-complete (&optional arg)
14533 "Perform completion on word at point.
14534 At the beginning of a headline, this completes TODO keywords as given in
14535 `org-todo-keywords'.
14536 If the current word is preceded by a backslash, completes the TeX symbols
14537 that are supported for HTML support.
14538 If the current word is preceded by \"#+\", completes special words for
14539 setting file options.
14540 In the line after \"#+STARTUP:, complete valid keywords.\"
14541 At all other locations, this simply calls the value of
14542 `org-completion-fallback-command'."
14543 (interactive "P")
14544 (org-without-partial-completion
14545 (catch 'exit
14546 (let* ((end (point))
14547 (beg1 (save-excursion
14548 (skip-chars-backward (org-re "[:alnum:]_@"))
14549 (point)))
14550 (beg (save-excursion
14551 (skip-chars-backward "a-zA-Z0-9_:$")
14552 (point)))
14553 (confirm (lambda (x) (stringp (car x))))
14554 (searchhead (equal (char-before beg) ?*))
14555 (tag (and (equal (char-before beg1) ?:)
14556 (equal (char-after (point-at-bol)) ?*)))
14557 (prop (and (equal (char-before beg1) ?:)
14558 (not (equal (char-after (point-at-bol)) ?*))))
14559 (texp (equal (char-before beg) ?\\))
14560 (link (equal (char-before beg) ?\[))
14561 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14562 beg)
14563 "#+"))
14564 (startup (string-match "^#\\+STARTUP:.*"
14565 (buffer-substring (point-at-bol) (point))))
14566 (completion-ignore-case opt)
14567 (type nil)
14568 (tbl nil)
14569 (table (cond
14570 (opt
14571 (setq type :opt)
14572 (append
14573 (mapcar
14574 (lambda (x)
14575 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14576 (cons (match-string 2 x) (match-string 1 x)))
14577 (org-split-string (org-get-current-options) "\n"))
14578 (mapcar 'list org-additional-option-like-keywords)))
14579 (startup
14580 (setq type :startup)
14581 org-startup-options)
14582 (link (append org-link-abbrev-alist-local
14583 org-link-abbrev-alist))
14584 (texp
14585 (setq type :tex)
14586 org-html-entities)
14587 ((string-match "\\`\\*+[ \t]+\\'"
14588 (buffer-substring (point-at-bol) beg))
14589 (setq type :todo)
14590 (mapcar 'list org-todo-keywords-1))
14591 (searchhead
14592 (setq type :searchhead)
14593 (save-excursion
14594 (goto-char (point-min))
14595 (while (re-search-forward org-todo-line-regexp nil t)
14596 (push (list
14597 (org-make-org-heading-search-string
14598 (match-string 3) t))
14599 tbl)))
14600 tbl)
14601 (tag (setq type :tag beg beg1)
14602 (or org-tag-alist (org-get-buffer-tags)))
14603 (prop (setq type :prop beg beg1)
14604 (mapcar 'list (org-buffer-property-keys nil t t)))
14605 (t (progn
14606 (call-interactively org-completion-fallback-command)
14607 (throw 'exit nil)))))
14608 (pattern (buffer-substring-no-properties beg end))
14609 (completion (try-completion pattern table confirm)))
14610 (cond ((eq completion t)
14611 (if (not (assoc (upcase pattern) table))
14612 (message "Already complete")
14613 (if (equal type :opt)
14614 (insert (substring (cdr (assoc (upcase pattern) table))
14615 (length pattern)))
14616 (if (memq type '(:tag :prop)) (insert ":")))))
14617 ((null completion)
14618 (message "Can't find completion for \"%s\"" pattern)
14619 (ding))
14620 ((not (string= pattern completion))
14621 (delete-region beg end)
14622 (if (string-match " +$" completion)
14623 (setq completion (replace-match "" t t completion)))
14624 (insert completion)
14625 (if (get-buffer-window "*Completions*")
14626 (delete-window (get-buffer-window "*Completions*")))
14627 (if (assoc completion table)
14628 (if (eq type :todo) (insert " ")
14629 (if (memq type '(:tag :prop)) (insert ":"))))
14630 (if (and (equal type :opt) (assoc completion table))
14631 (message "%s" (substitute-command-keys
14632 "Press \\[org-complete] again to insert example settings"))))
14634 (message "Making completion list...")
14635 (let ((list (sort (all-completions pattern table confirm)
14636 'string<)))
14637 (with-output-to-temp-buffer "*Completions*"
14638 (condition-case nil
14639 ;; Protection needed for XEmacs and emacs 21
14640 (display-completion-list list pattern)
14641 (error (display-completion-list list)))))
14642 (message "Making completion list...%s" "done")))))))
14644 ;;;; TODO, DEADLINE, Comments
14646 (defun org-toggle-comment ()
14647 "Change the COMMENT state of an entry."
14648 (interactive)
14649 (save-excursion
14650 (org-back-to-heading)
14651 (let (case-fold-search)
14652 (if (looking-at (concat outline-regexp
14653 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14654 (replace-match "" t t nil 1)
14655 (if (looking-at outline-regexp)
14656 (progn
14657 (goto-char (match-end 0))
14658 (insert org-comment-string " ")))))))
14660 (defvar org-last-todo-state-is-todo nil
14661 "This is non-nil when the last TODO state change led to a TODO state.
14662 If the last change removed the TODO tag or switched to DONE, then
14663 this is nil.")
14665 (defvar org-setting-tags nil) ; dynamically skiped
14667 ;; FIXME: better place
14668 (defun org-property-or-variable-value (var &optional inherit)
14669 "Check if there is a property fixing the value of VAR.
14670 If yes, return this value. If not, return the current value of the variable."
14671 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14672 (if (and prop (stringp prop) (string-match "\\S-" prop))
14673 (read prop)
14674 (symbol-value var))))
14676 (defun org-parse-local-options (string var)
14677 "Parse STRING for startup setting relevant for variable VAR."
14678 (let ((rtn (symbol-value var))
14679 e opts)
14680 (save-match-data
14681 (if (or (not string) (not (string-match "\\S-" string)))
14683 (setq opts (delq nil (mapcar (lambda (x)
14684 (setq e (assoc x org-startup-options))
14685 (if (eq (nth 1 e) var) e nil))
14686 (org-split-string string "[ \t]+"))))
14687 (if (not opts)
14689 (setq rtn nil)
14690 (while (setq e (pop opts))
14691 (if (not (nth 3 e))
14692 (setq rtn (nth 2 e))
14693 (if (not (listp rtn)) (setq rtn nil))
14694 (push (nth 2 e) rtn)))
14695 rtn)))))
14697 (defvar org-blocker-hook nil
14698 "Hook for functions that are allowed to block a state change.
14700 Each function gets as its single argument a property list, see
14701 `org-trigger-hook' for more information about this list.
14703 If any of the functions in this hook returns nil, the state change
14704 is blocked.")
14706 (defvar org-trigger-hook nil
14707 "Hook for functions that are triggered by a state change.
14709 Each function gets as its single argument a property list with at least
14710 the following elements:
14712 (:type type-of-change :position pos-at-entry-start
14713 :from old-state :to new-state)
14715 Depending on the type, more properties may be present.
14717 This mechanism is currently implemented for:
14719 TODO state changes
14720 ------------------
14721 :type todo-state-change
14722 :from previous state (keyword as a string), or nil
14723 :to new state (keyword as a string), or nil")
14726 (defun org-todo (&optional arg)
14727 "Change the TODO state of an item.
14728 The state of an item is given by a keyword at the start of the heading,
14729 like
14730 *** TODO Write paper
14731 *** DONE Call mom
14733 The different keywords are specified in the variable `org-todo-keywords'.
14734 By default the available states are \"TODO\" and \"DONE\".
14735 So for this example: when the item starts with TODO, it is changed to DONE.
14736 When it starts with DONE, the DONE is removed. And when neither TODO nor
14737 DONE are present, add TODO at the beginning of the heading.
14739 With C-u prefix arg, use completion to determine the new state.
14740 With numeric prefix arg, switch to that state.
14742 For calling through lisp, arg is also interpreted in the following way:
14743 'none -> empty state
14744 \"\"(empty string) -> switch to empty state
14745 'done -> switch to DONE
14746 'nextset -> switch to the next set of keywords
14747 'previousset -> switch to the previous set of keywords
14748 \"WAITING\" -> switch to the specified keyword, but only if it
14749 really is a member of `org-todo-keywords'."
14750 (interactive "P")
14751 (save-excursion
14752 (catch 'exit
14753 (org-back-to-heading)
14754 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14755 (or (looking-at (concat " +" org-todo-regexp " *"))
14756 (looking-at " *"))
14757 (let* ((match-data (match-data))
14758 (startpos (point-at-bol))
14759 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14760 (org-log-done org-log-done)
14761 (org-log-repeat org-log-repeat)
14762 (org-todo-log-states org-todo-log-states)
14763 (this (match-string 1))
14764 (hl-pos (match-beginning 0))
14765 (head (org-get-todo-sequence-head this))
14766 (ass (assoc head org-todo-kwd-alist))
14767 (interpret (nth 1 ass))
14768 (done-word (nth 3 ass))
14769 (final-done-word (nth 4 ass))
14770 (last-state (or this ""))
14771 (completion-ignore-case t)
14772 (member (member this org-todo-keywords-1))
14773 (tail (cdr member))
14774 (state (cond
14775 ((and org-todo-key-trigger
14776 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14777 (and (not arg) org-use-fast-todo-selection
14778 (not (eq org-use-fast-todo-selection 'prefix)))))
14779 ;; Use fast selection
14780 (org-fast-todo-selection))
14781 ((and (equal arg '(4))
14782 (or (not org-use-fast-todo-selection)
14783 (not org-todo-key-trigger)))
14784 ;; Read a state with completion
14785 (completing-read "State: " (mapcar (lambda(x) (list x))
14786 org-todo-keywords-1)
14787 nil t))
14788 ((eq arg 'right)
14789 (if this
14790 (if tail (car tail) nil)
14791 (car org-todo-keywords-1)))
14792 ((eq arg 'left)
14793 (if (equal member org-todo-keywords-1)
14795 (if this
14796 (nth (- (length org-todo-keywords-1) (length tail) 2)
14797 org-todo-keywords-1)
14798 (org-last org-todo-keywords-1))))
14799 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14800 (setq arg nil))) ; hack to fall back to cycling
14801 (arg
14802 ;; user or caller requests a specific state
14803 (cond
14804 ((equal arg "") nil)
14805 ((eq arg 'none) nil)
14806 ((eq arg 'done) (or done-word (car org-done-keywords)))
14807 ((eq arg 'nextset)
14808 (or (car (cdr (member head org-todo-heads)))
14809 (car org-todo-heads)))
14810 ((eq arg 'previousset)
14811 (let ((org-todo-heads (reverse org-todo-heads)))
14812 (or (car (cdr (member head org-todo-heads)))
14813 (car org-todo-heads))))
14814 ((car (member arg org-todo-keywords-1)))
14815 ((nth (1- (prefix-numeric-value arg))
14816 org-todo-keywords-1))))
14817 ((null member) (or head (car org-todo-keywords-1)))
14818 ((equal this final-done-word) nil) ;; -> make empty
14819 ((null tail) nil) ;; -> first entry
14820 ((eq interpret 'sequence)
14821 (car tail))
14822 ((memq interpret '(type priority))
14823 (if (eq this-command last-command)
14824 (car tail)
14825 (if (> (length tail) 0)
14826 (or done-word (car org-done-keywords))
14827 nil)))
14828 (t nil)))
14829 (next (if state (concat " " state " ") " "))
14830 (change-plist (list :type 'todo-state-change :from this :to state
14831 :position startpos))
14832 dolog now-done-p)
14833 (when org-blocker-hook
14834 (unless (save-excursion
14835 (save-match-data
14836 (run-hook-with-args-until-failure
14837 'org-blocker-hook change-plist)))
14838 (if (interactive-p)
14839 (error "TODO state change from %s to %s blocked" this state)
14840 ;; fail silently
14841 (message "TODO state change from %s to %s blocked" this state)
14842 (throw 'exit nil))))
14843 (store-match-data match-data)
14844 (replace-match next t t)
14845 (unless (pos-visible-in-window-p hl-pos)
14846 (message "TODO state changed to %s" (org-trim next)))
14847 (unless head
14848 (setq head (org-get-todo-sequence-head state)
14849 ass (assoc head org-todo-kwd-alist)
14850 interpret (nth 1 ass)
14851 done-word (nth 3 ass)
14852 final-done-word (nth 4 ass)))
14853 (when (memq arg '(nextset previousset))
14854 (message "Keyword-Set %d/%d: %s"
14855 (- (length org-todo-sets) -1
14856 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14857 (length org-todo-sets)
14858 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14859 (setq org-last-todo-state-is-todo
14860 (not (member state org-done-keywords)))
14861 (setq now-done-p (and (member state org-done-keywords)
14862 (not (member this org-done-keywords))))
14863 (and logging (org-local-logging logging))
14864 (when (and (or org-todo-log-states org-log-done)
14865 (not (memq arg '(nextset previousset))))
14866 ;; we need to look at recording a time and note
14867 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14868 (nth 2 (assoc this org-todo-log-states))))
14869 (when (and state
14870 (member state org-not-done-keywords)
14871 (not (member this org-not-done-keywords)))
14872 ;; This is now a todo state and was not one before
14873 ;; If there was a CLOSED time stamp, get rid of it.
14874 (org-add-planning-info nil nil 'closed))
14875 (when (and now-done-p org-log-done)
14876 ;; It is now done, and it was not done before
14877 (org-add-planning-info 'closed (org-current-time))
14878 (if (and (not dolog) (eq 'note org-log-done))
14879 (org-add-log-maybe 'done state 'findpos 'note)))
14880 (when (and state dolog)
14881 ;; This is a non-nil state, and we need to log it
14882 (org-add-log-maybe 'state state 'findpos dolog)))
14883 ;; Fixup tag positioning
14884 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14885 (run-hooks 'org-after-todo-state-change-hook)
14886 (if (and arg (not (member state org-done-keywords)))
14887 (setq head (org-get-todo-sequence-head state)))
14888 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14889 ;; Do we need to trigger a repeat?
14890 (when now-done-p (org-auto-repeat-maybe state))
14891 ;; Fixup cursor location if close to the keyword
14892 (if (and (outline-on-heading-p)
14893 (not (bolp))
14894 (save-excursion (beginning-of-line 1)
14895 (looking-at org-todo-line-regexp))
14896 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14897 (progn
14898 (goto-char (or (match-end 2) (match-end 1)))
14899 (just-one-space)))
14900 (when org-trigger-hook
14901 (save-excursion
14902 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14904 (defun org-local-logging (value)
14905 "Get logging settings from a property VALUE."
14906 (let* (words w a)
14907 ;; directly set the variables, they are already local.
14908 (setq org-log-done nil
14909 org-log-repeat nil
14910 org-todo-log-states nil)
14911 (setq words (org-split-string value))
14912 (while (setq w (pop words))
14913 (cond
14914 ((setq a (assoc w org-startup-options))
14915 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14916 (set (nth 1 a) (nth 2 a))))
14917 ((setq a (org-extract-log-state-settings w))
14918 (and (member (car a) org-todo-keywords-1)
14919 (push a org-todo-log-states)))))))
14921 (defun org-get-todo-sequence-head (kwd)
14922 "Return the head of the TODO sequence to which KWD belongs.
14923 If KWD is not set, check if there is a text property remembering the
14924 right sequence."
14925 (let (p)
14926 (cond
14927 ((not kwd)
14928 (or (get-text-property (point-at-bol) 'org-todo-head)
14929 (progn
14930 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14931 nil (point-at-eol)))
14932 (get-text-property p 'org-todo-head))))
14933 ((not (member kwd org-todo-keywords-1))
14934 (car org-todo-keywords-1))
14935 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14937 (defun org-fast-todo-selection ()
14938 "Fast TODO keyword selection with single keys.
14939 Returns the new TODO keyword, or nil if no state change should occur."
14940 (let* ((fulltable org-todo-key-alist)
14941 (done-keywords org-done-keywords) ;; needed for the faces.
14942 (maxlen (apply 'max (mapcar
14943 (lambda (x)
14944 (if (stringp (car x)) (string-width (car x)) 0))
14945 fulltable)))
14946 (expert nil)
14947 (fwidth (+ maxlen 3 1 3))
14948 (ncol (/ (- (window-width) 4) fwidth))
14949 tg cnt e c tbl
14950 groups ingroup)
14951 (save-window-excursion
14952 (if expert
14953 (set-buffer (get-buffer-create " *Org todo*"))
14954 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14955 (erase-buffer)
14956 (org-set-local 'org-done-keywords done-keywords)
14957 (setq tbl fulltable cnt 0)
14958 (while (setq e (pop tbl))
14959 (cond
14960 ((equal e '(:startgroup))
14961 (push '() groups) (setq ingroup t)
14962 (when (not (= cnt 0))
14963 (setq cnt 0)
14964 (insert "\n"))
14965 (insert "{ "))
14966 ((equal e '(:endgroup))
14967 (setq ingroup nil cnt 0)
14968 (insert "}\n"))
14970 (setq tg (car e) c (cdr e))
14971 (if ingroup (push tg (car groups)))
14972 (setq tg (org-add-props tg nil 'face
14973 (org-get-todo-face tg)))
14974 (if (and (= cnt 0) (not ingroup)) (insert " "))
14975 (insert "[" c "] " tg (make-string
14976 (- fwidth 4 (length tg)) ?\ ))
14977 (when (= (setq cnt (1+ cnt)) ncol)
14978 (insert "\n")
14979 (if ingroup (insert " "))
14980 (setq cnt 0)))))
14981 (insert "\n")
14982 (goto-char (point-min))
14983 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14984 (fit-window-to-buffer))
14985 (message "[a-z..]:Set [SPC]:clear")
14986 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14987 (cond
14988 ((or (= c ?\C-g)
14989 (and (= c ?q) (not (rassoc c fulltable))))
14990 (setq quit-flag t))
14991 ((= c ?\ ) nil)
14992 ((setq e (rassoc c fulltable) tg (car e))
14994 (t (setq quit-flag t))))))
14996 (defun org-get-repeat ()
14997 "Check if tere is a deadline/schedule with repeater in this entry."
14998 (save-match-data
14999 (save-excursion
15000 (org-back-to-heading t)
15001 (if (re-search-forward
15002 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
15003 (match-string 1)))))
15005 (defvar org-last-changed-timestamp)
15006 (defvar org-log-post-message)
15007 (defvar org-log-note-purpose)
15008 (defun org-auto-repeat-maybe (done-word)
15009 "Check if the current headline contains a repeated deadline/schedule.
15010 If yes, set TODO state back to what it was and change the base date
15011 of repeating deadline/scheduled time stamps to new date.
15012 This function is run automatically after each state change to a DONE state."
15013 ;; last-state is dynamically scoped into this function
15014 (let* ((repeat (org-get-repeat))
15015 (aa (assoc last-state org-todo-kwd-alist))
15016 (interpret (nth 1 aa))
15017 (head (nth 2 aa))
15018 (whata '(("d" . day) ("m" . month) ("y" . year)))
15019 (msg "Entry repeats: ")
15020 (org-log-done nil)
15021 (org-todo-log-states nil)
15022 re type n what ts)
15023 (when repeat
15024 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
15025 (org-todo (if (eq interpret 'type) last-state head))
15026 (when (and org-log-repeat
15027 (or (not (memq 'org-add-log-note
15028 (default-value 'post-command-hook)))
15029 (eq org-log-note-purpose 'done)))
15030 ;; Make sure a note is taken;
15031 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
15032 'findpos org-log-repeat))
15033 (org-back-to-heading t)
15034 (org-add-planning-info nil nil 'closed)
15035 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
15036 org-deadline-time-regexp "\\)\\|\\("
15037 org-ts-regexp "\\)"))
15038 (while (re-search-forward
15039 re (save-excursion (outline-next-heading) (point)) t)
15040 (setq type (if (match-end 1) org-scheduled-string
15041 (if (match-end 3) org-deadline-string "Plain:"))
15042 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
15043 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
15044 (setq n (string-to-number (match-string 1 ts))
15045 what (match-string 2 ts))
15046 (if (equal what "w") (setq n (* n 7) what "d"))
15047 (org-timestamp-change n (cdr (assoc what whata)))
15048 (setq msg (concat msg type org-last-changed-timestamp " "))))
15049 (setq org-log-post-message msg)
15050 (message "%s" msg))))
15052 (defun org-show-todo-tree (arg)
15053 "Make a compact tree which shows all headlines marked with TODO.
15054 The tree will show the lines where the regexp matches, and all higher
15055 headlines above the match.
15056 With a \\[universal-argument] prefix, also show the DONE entries.
15057 With a numeric prefix N, construct a sparse tree for the Nth element
15058 of `org-todo-keywords-1'."
15059 (interactive "P")
15060 (let ((case-fold-search nil)
15061 (kwd-re
15062 (cond ((null arg) org-not-done-regexp)
15063 ((equal arg '(4))
15064 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
15065 (mapcar 'list org-todo-keywords-1))))
15066 (concat "\\("
15067 (mapconcat 'identity (org-split-string kwd "|") "\\|")
15068 "\\)\\>")))
15069 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
15070 (regexp-quote (nth (1- (prefix-numeric-value arg))
15071 org-todo-keywords-1)))
15072 (t (error "Invalid prefix argument: %s" arg)))))
15073 (message "%d TODO entries found"
15074 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
15076 (defun org-deadline (&optional remove)
15077 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
15078 With argument REMOVE, remove any deadline from the item."
15079 (interactive "P")
15080 (if remove
15081 (progn
15082 (org-remove-timestamp-with-keyword org-deadline-string)
15083 (message "Item no longer has a deadline."))
15084 (org-add-planning-info 'deadline nil 'closed)))
15086 (defun org-schedule (&optional remove)
15087 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
15088 With argument REMOVE, remove any scheduling date from the item."
15089 (interactive "P")
15090 (if remove
15091 (progn
15092 (org-remove-timestamp-with-keyword org-scheduled-string)
15093 (message "Item is no longer scheduled."))
15094 (org-add-planning-info 'scheduled nil 'closed)))
15096 (defun org-remove-timestamp-with-keyword (keyword)
15097 "Remove all time stamps with KEYWORD in the current entry."
15098 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
15099 beg)
15100 (save-excursion
15101 (org-back-to-heading t)
15102 (setq beg (point))
15103 (org-end-of-subtree t t)
15104 (while (re-search-backward re beg t)
15105 (replace-match "")
15106 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
15107 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
15109 (defun org-add-planning-info (what &optional time &rest remove)
15110 "Insert new timestamp with keyword in the line directly after the headline.
15111 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
15112 If non is given, the user is prompted for a date.
15113 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
15114 be removed."
15115 (interactive)
15116 (let (org-time-was-given org-end-time-was-given)
15117 (when what (setq time (or time (org-read-date nil 'to-time))))
15118 (when (and org-insert-labeled-timestamps-at-point
15119 (member what '(scheduled deadline)))
15120 (insert
15121 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
15122 (org-insert-time-stamp time org-time-was-given
15123 nil nil nil (list org-end-time-was-given))
15124 (setq what nil))
15125 (save-excursion
15126 (save-restriction
15127 (let (col list elt ts buffer-invisibility-spec)
15128 (org-back-to-heading t)
15129 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
15130 (goto-char (match-end 1))
15131 (setq col (current-column))
15132 (goto-char (match-end 0))
15133 (if (eobp) (insert "\n") (forward-char 1))
15134 (if (and (not (looking-at outline-regexp))
15135 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
15136 "[^\r\n]*"))
15137 (not (equal (match-string 1) org-clock-string)))
15138 (narrow-to-region (match-beginning 0) (match-end 0))
15139 (insert-before-markers "\n")
15140 (backward-char 1)
15141 (narrow-to-region (point) (point))
15142 (indent-to-column col))
15143 ;; Check if we have to remove something.
15144 (setq list (cons what remove))
15145 (while list
15146 (setq elt (pop list))
15147 (goto-char (point-min))
15148 (when (or (and (eq elt 'scheduled)
15149 (re-search-forward org-scheduled-time-regexp nil t))
15150 (and (eq elt 'deadline)
15151 (re-search-forward org-deadline-time-regexp nil t))
15152 (and (eq elt 'closed)
15153 (re-search-forward org-closed-time-regexp nil t)))
15154 (replace-match "")
15155 (if (looking-at "--+<[^>]+>") (replace-match ""))
15156 (if (looking-at " +") (replace-match ""))))
15157 (goto-char (point-max))
15158 (when what
15159 (insert
15160 (if (not (equal (char-before) ?\ )) " " "")
15161 (cond ((eq what 'scheduled) org-scheduled-string)
15162 ((eq what 'deadline) org-deadline-string)
15163 ((eq what 'closed) org-closed-string))
15164 " ")
15165 (setq ts (org-insert-time-stamp
15166 time
15167 (or org-time-was-given
15168 (and (eq what 'closed) org-log-done-with-time))
15169 (eq what 'closed)
15170 nil nil (list org-end-time-was-given)))
15171 (end-of-line 1))
15172 (goto-char (point-min))
15173 (widen)
15174 (if (looking-at "[ \t]+\r?\n")
15175 (replace-match ""))
15176 ts)))))
15178 (defvar org-log-note-marker (make-marker))
15179 (defvar org-log-note-purpose nil)
15180 (defvar org-log-note-state nil)
15181 (defvar org-log-note-how nil)
15182 (defvar org-log-note-window-configuration nil)
15183 (defvar org-log-note-return-to (make-marker))
15184 (defvar org-log-post-message nil
15185 "Message to be displayed after a log note has been stored.
15186 The auto-repeater uses this.")
15188 (defun org-add-log-maybe (&optional purpose state findpos how)
15189 "Set up the post command hook to take a note.
15190 If this is about to TODO state change, the new state is expected in STATE.
15191 When FINDPOS is non-nil, find the correct position for the note in
15192 the current entry. If not, assume that it can be inserted at point."
15193 (save-excursion
15194 (when findpos
15195 (org-back-to-heading t)
15196 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
15197 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
15198 "[^\r\n]*\\)?"))
15199 (goto-char (match-end 0))
15200 (unless org-log-states-order-reversed
15201 (and (= (char-after) ?\n) (forward-char 1))
15202 (org-skip-over-state-notes)
15203 (skip-chars-backward " \t\n\r")))
15204 (move-marker org-log-note-marker (point))
15205 (setq org-log-note-purpose purpose
15206 org-log-note-state state
15207 org-log-note-how how)
15208 (add-hook 'post-command-hook 'org-add-log-note 'append)))
15210 (defun org-skip-over-state-notes ()
15211 "Skip past the list of State notes in an entry."
15212 (if (looking-at "\n[ \t]*- State") (forward-char 1))
15213 (while (looking-at "[ \t]*- State")
15214 (condition-case nil
15215 (org-next-item)
15216 (error (org-end-of-item)))))
15218 (defun org-add-log-note (&optional purpose)
15219 "Pop up a window for taking a note, and add this note later at point."
15220 (remove-hook 'post-command-hook 'org-add-log-note)
15221 (setq org-log-note-window-configuration (current-window-configuration))
15222 (delete-other-windows)
15223 (move-marker org-log-note-return-to (point))
15224 (switch-to-buffer (marker-buffer org-log-note-marker))
15225 (goto-char org-log-note-marker)
15226 (org-switch-to-buffer-other-window "*Org Note*")
15227 (erase-buffer)
15228 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
15229 (org-store-log-note)
15230 (let ((org-inhibit-startup t)) (org-mode))
15231 (insert (format "# Insert note for %s.
15232 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
15233 (cond
15234 ((eq org-log-note-purpose 'clock-out) "stopped clock")
15235 ((eq org-log-note-purpose 'done) "closed todo item")
15236 ((eq org-log-note-purpose 'state)
15237 (format "state change to \"%s\"" org-log-note-state))
15238 (t (error "This should not happen")))))
15239 (org-set-local 'org-finish-function 'org-store-log-note)))
15241 (defun org-store-log-note ()
15242 "Finish taking a log note, and insert it to where it belongs."
15243 (let ((txt (buffer-string))
15244 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
15245 lines ind)
15246 (kill-buffer (current-buffer))
15247 (while (string-match "\\`#.*\n[ \t\n]*" txt)
15248 (setq txt (replace-match "" t t txt)))
15249 (if (string-match "\\s-+\\'" txt)
15250 (setq txt (replace-match "" t t txt)))
15251 (setq lines (org-split-string txt "\n"))
15252 (when (and note (string-match "\\S-" note))
15253 (setq note
15254 (org-replace-escapes
15255 note
15256 (list (cons "%u" (user-login-name))
15257 (cons "%U" user-full-name)
15258 (cons "%t" (format-time-string
15259 (org-time-stamp-format 'long 'inactive)
15260 (current-time)))
15261 (cons "%s" (if org-log-note-state
15262 (concat "\"" org-log-note-state "\"")
15263 "")))))
15264 (if lines (setq note (concat note " \\\\")))
15265 (push note lines))
15266 (when (or current-prefix-arg org-note-abort) (setq lines nil))
15267 (when lines
15268 (save-excursion
15269 (set-buffer (marker-buffer org-log-note-marker))
15270 (save-excursion
15271 (goto-char org-log-note-marker)
15272 (move-marker org-log-note-marker nil)
15273 (end-of-line 1)
15274 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
15275 (indent-relative nil)
15276 (insert "- " (pop lines))
15277 (org-indent-line-function)
15278 (beginning-of-line 1)
15279 (looking-at "[ \t]*")
15280 (setq ind (concat (match-string 0) " "))
15281 (end-of-line 1)
15282 (while lines (insert "\n" ind (pop lines)))))))
15283 (set-window-configuration org-log-note-window-configuration)
15284 (with-current-buffer (marker-buffer org-log-note-return-to)
15285 (goto-char org-log-note-return-to))
15286 (move-marker org-log-note-return-to nil)
15287 (and org-log-post-message (message "%s" org-log-post-message)))
15289 ;; FIXME: what else would be useful?
15290 ;; - priority
15291 ;; - date
15293 (defun org-sparse-tree (&optional arg)
15294 "Create a sparse tree, prompt for the details.
15295 This command can create sparse trees. You first need to select the type
15296 of match used to create the tree:
15298 t Show entries with a specific TODO keyword.
15299 T Show entries selected by a tags match.
15300 p Enter a property name and its value (both with completion on existing
15301 names/values) and show entries with that property.
15302 r Show entries matching a regular expression
15303 d Show deadlines due within `org-deadline-warning-days'."
15304 (interactive "P")
15305 (let (ans kwd value)
15306 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15307 (setq ans (read-char-exclusive))
15308 (cond
15309 ((equal ans ?d)
15310 (call-interactively 'org-check-deadlines))
15311 ((equal ans ?b)
15312 (call-interactively 'org-check-before-date))
15313 ((equal ans ?t)
15314 (org-show-todo-tree '(4)))
15315 ((equal ans ?T)
15316 (call-interactively 'org-tags-sparse-tree))
15317 ((member ans '(?p ?P))
15318 (setq kwd (completing-read "Property: "
15319 (mapcar 'list (org-buffer-property-keys))))
15320 (setq value (completing-read "Value: "
15321 (mapcar 'list (org-property-values kwd))))
15322 (unless (string-match "\\`{.*}\\'" value)
15323 (setq value (concat "\"" value "\"")))
15324 (org-tags-sparse-tree arg (concat kwd "=" value)))
15325 ((member ans '(?r ?R ?/))
15326 (call-interactively 'org-occur))
15327 (t (error "No such sparse tree command \"%c\"" ans)))))
15329 (defvar org-occur-highlights nil
15330 "List of overlays used for occur matches.")
15331 (make-variable-buffer-local 'org-occur-highlights)
15332 (defvar org-occur-parameters nil
15333 "Parameters of the active org-occur calls.
15334 This is a list, each call to org-occur pushes as cons cell,
15335 containing the regular expression and the callback, onto the list.
15336 The list can contain several entries if `org-occur' has been called
15337 several time with the KEEP-PREVIOUS argument. Otherwise, this list
15338 will only contain one set of parameters. When the highlights are
15339 removed (for example with `C-c C-c', or with the next edit (depending
15340 on `org-remove-highlights-with-change'), this variable is emptied
15341 as well.")
15342 (make-variable-buffer-local 'org-occur-parameters)
15344 (defun org-occur (regexp &optional keep-previous callback)
15345 "Make a compact tree which shows all matches of REGEXP.
15346 The tree will show the lines where the regexp matches, and all higher
15347 headlines above the match. It will also show the heading after the match,
15348 to make sure editing the matching entry is easy.
15349 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15350 call to `org-occur' will be kept, to allow stacking of calls to this
15351 command.
15352 If CALLBACK is non-nil, it is a function which is called to confirm
15353 that the match should indeed be shown."
15354 (interactive "sRegexp: \nP")
15355 (unless keep-previous
15356 (org-remove-occur-highlights nil nil t))
15357 (push (cons regexp callback) org-occur-parameters)
15358 (let ((cnt 0))
15359 (save-excursion
15360 (goto-char (point-min))
15361 (if (or (not keep-previous) ; do not want to keep
15362 (not org-occur-highlights)) ; no previous matches
15363 ;; hide everything
15364 (org-overview))
15365 (while (re-search-forward regexp nil t)
15366 (when (or (not callback)
15367 (save-match-data (funcall callback)))
15368 (setq cnt (1+ cnt))
15369 (when org-highlight-sparse-tree-matches
15370 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15371 (org-show-context 'occur-tree))))
15372 (when org-remove-highlights-with-change
15373 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15374 nil 'local))
15375 (unless org-sparse-tree-open-archived-trees
15376 (org-hide-archived-subtrees (point-min) (point-max)))
15377 (run-hooks 'org-occur-hook)
15378 (if (interactive-p)
15379 (message "%d match(es) for regexp %s" cnt regexp))
15380 cnt))
15382 (defun org-show-context (&optional key)
15383 "Make sure point and context and visible.
15384 How much context is shown depends upon the variables
15385 `org-show-hierarchy-above', `org-show-following-heading'. and
15386 `org-show-siblings'."
15387 (let ((heading-p (org-on-heading-p t))
15388 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15389 (following-p (org-get-alist-option org-show-following-heading key))
15390 (entry-p (org-get-alist-option org-show-entry-below key))
15391 (siblings-p (org-get-alist-option org-show-siblings key)))
15392 (catch 'exit
15393 ;; Show heading or entry text
15394 (if (and heading-p (not entry-p))
15395 (org-flag-heading nil) ; only show the heading
15396 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15397 (org-show-hidden-entry))) ; show entire entry
15398 (when following-p
15399 ;; Show next sibling, or heading below text
15400 (save-excursion
15401 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15402 (org-flag-heading nil))))
15403 (when siblings-p (org-show-siblings))
15404 (when hierarchy-p
15405 ;; show all higher headings, possibly with siblings
15406 (save-excursion
15407 (while (and (condition-case nil
15408 (progn (org-up-heading-all 1) t)
15409 (error nil))
15410 (not (bobp)))
15411 (org-flag-heading nil)
15412 (when siblings-p (org-show-siblings))))))))
15414 (defun org-reveal (&optional siblings)
15415 "Show current entry, hierarchy above it, and the following headline.
15416 This can be used to show a consistent set of context around locations
15417 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15418 not t for the search context.
15420 With optional argument SIBLINGS, on each level of the hierarchy all
15421 siblings are shown. This repairs the tree structure to what it would
15422 look like when opened with hierarchical calls to `org-cycle'."
15423 (interactive "P")
15424 (let ((org-show-hierarchy-above t)
15425 (org-show-following-heading t)
15426 (org-show-siblings (if siblings t org-show-siblings)))
15427 (org-show-context nil)))
15429 (defun org-highlight-new-match (beg end)
15430 "Highlight from BEG to END and mark the highlight is an occur headline."
15431 (let ((ov (org-make-overlay beg end)))
15432 (org-overlay-put ov 'face 'secondary-selection)
15433 (push ov org-occur-highlights)))
15435 (defun org-remove-occur-highlights (&optional beg end noremove)
15436 "Remove the occur highlights from the buffer.
15437 BEG and END are ignored. If NOREMOVE is nil, remove this function
15438 from the `before-change-functions' in the current buffer."
15439 (interactive)
15440 (unless org-inhibit-highlight-removal
15441 (mapc 'org-delete-overlay org-occur-highlights)
15442 (setq org-occur-highlights nil)
15443 (setq org-occur-parameters nil)
15444 (unless noremove
15445 (remove-hook 'before-change-functions
15446 'org-remove-occur-highlights 'local))))
15448 ;;;; Priorities
15450 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15451 "Regular expression matching the priority indicator.")
15453 (defvar org-remove-priority-next-time nil)
15455 (defun org-priority-up ()
15456 "Increase the priority of the current item."
15457 (interactive)
15458 (org-priority 'up))
15460 (defun org-priority-down ()
15461 "Decrease the priority of the current item."
15462 (interactive)
15463 (org-priority 'down))
15465 (defun org-priority (&optional action)
15466 "Change the priority of an item by ARG.
15467 ACTION can be `set', `up', `down', or a character."
15468 (interactive)
15469 (setq action (or action 'set))
15470 (let (current new news have remove)
15471 (save-excursion
15472 (org-back-to-heading)
15473 (if (looking-at org-priority-regexp)
15474 (setq current (string-to-char (match-string 2))
15475 have t)
15476 (setq current org-default-priority))
15477 (cond
15478 ((or (eq action 'set) (integerp action))
15479 (if (integerp action)
15480 (setq new action)
15481 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15482 (setq new (read-char-exclusive)))
15483 (if (and (= (upcase org-highest-priority) org-highest-priority)
15484 (= (upcase org-lowest-priority) org-lowest-priority))
15485 (setq new (upcase new)))
15486 (cond ((equal new ?\ ) (setq remove t))
15487 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15488 (error "Priority must be between `%c' and `%c'"
15489 org-highest-priority org-lowest-priority))))
15490 ((eq action 'up)
15491 (if (and (not have) (eq last-command this-command))
15492 (setq new org-lowest-priority)
15493 (setq new (if (and org-priority-start-cycle-with-default (not have))
15494 org-default-priority (1- current)))))
15495 ((eq action 'down)
15496 (if (and (not have) (eq last-command this-command))
15497 (setq new org-highest-priority)
15498 (setq new (if (and org-priority-start-cycle-with-default (not have))
15499 org-default-priority (1+ current)))))
15500 (t (error "Invalid action")))
15501 (if (or (< (upcase new) org-highest-priority)
15502 (> (upcase new) org-lowest-priority))
15503 (setq remove t))
15504 (setq news (format "%c" new))
15505 (if have
15506 (if remove
15507 (replace-match "" t t nil 1)
15508 (replace-match news t t nil 2))
15509 (if remove
15510 (error "No priority cookie found in line")
15511 (looking-at org-todo-line-regexp)
15512 (if (match-end 2)
15513 (progn
15514 (goto-char (match-end 2))
15515 (insert " [#" news "]"))
15516 (goto-char (match-beginning 3))
15517 (insert "[#" news "] ")))))
15518 (org-preserve-lc (org-set-tags nil 'align))
15519 (if remove
15520 (message "Priority removed")
15521 (message "Priority of current item set to %s" news))))
15524 (defun org-get-priority (s)
15525 "Find priority cookie and return priority."
15526 (save-match-data
15527 (if (not (string-match org-priority-regexp s))
15528 (* 1000 (- org-lowest-priority org-default-priority))
15529 (* 1000 (- org-lowest-priority
15530 (string-to-char (match-string 2 s)))))))
15532 ;;;; Tags
15534 (defun org-scan-tags (action matcher &optional todo-only)
15535 "Scan headline tags with inheritance and produce output ACTION.
15536 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15537 evaluated, testing if a given set of tags qualifies a headline for
15538 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15539 are included in the output."
15540 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15541 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15542 (org-re
15543 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15544 (props (list 'face nil
15545 'done-face 'org-done
15546 'undone-face nil
15547 'mouse-face 'highlight
15548 'org-not-done-regexp org-not-done-regexp
15549 'org-todo-regexp org-todo-regexp
15550 'keymap org-agenda-keymap
15551 'help-echo
15552 (format "mouse-2 or RET jump to org file %s"
15553 (abbreviate-file-name
15554 (or (buffer-file-name (buffer-base-buffer))
15555 (buffer-name (buffer-base-buffer)))))))
15556 (case-fold-search nil)
15557 lspos
15558 tags tags-list tags-alist (llast 0) rtn level category i txt
15559 todo marker entry priority)
15560 (save-excursion
15561 (goto-char (point-min))
15562 (when (eq action 'sparse-tree)
15563 (org-overview)
15564 (org-remove-occur-highlights))
15565 (while (re-search-forward re nil t)
15566 (catch :skip
15567 (setq todo (if (match-end 1) (match-string 2))
15568 tags (if (match-end 4) (match-string 4)))
15569 (goto-char (setq lspos (1+ (match-beginning 0))))
15570 (setq level (org-reduced-level (funcall outline-level))
15571 category (org-get-category))
15572 (setq i llast llast level)
15573 ;; remove tag lists from same and sublevels
15574 (while (>= i level)
15575 (when (setq entry (assoc i tags-alist))
15576 (setq tags-alist (delete entry tags-alist)))
15577 (setq i (1- i)))
15578 ;; add the nex tags
15579 (when tags
15580 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15581 tags-alist
15582 (cons (cons level tags) tags-alist)))
15583 ;; compile tags for current headline
15584 (setq tags-list
15585 (if org-use-tag-inheritance
15586 (apply 'append (mapcar 'cdr tags-alist))
15587 tags))
15588 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15589 (eval matcher)
15590 (or (not org-agenda-skip-archived-trees)
15591 (not (member org-archive-tag tags-list))))
15592 (and (eq action 'agenda) (org-agenda-skip))
15593 ;; list this headline
15595 (if (eq action 'sparse-tree)
15596 (progn
15597 (and org-highlight-sparse-tree-matches
15598 (org-get-heading) (match-end 0)
15599 (org-highlight-new-match
15600 (match-beginning 0) (match-beginning 1)))
15601 (org-show-context 'tags-tree))
15602 (setq txt (org-format-agenda-item
15604 (concat
15605 (if org-tags-match-list-sublevels
15606 (make-string (1- level) ?.) "")
15607 (org-get-heading))
15608 category tags-list)
15609 priority (org-get-priority txt))
15610 (goto-char lspos)
15611 (setq marker (org-agenda-new-marker))
15612 (org-add-props txt props
15613 'org-marker marker 'org-hd-marker marker 'org-category category
15614 'priority priority 'type "tagsmatch")
15615 (push txt rtn))
15616 ;; if we are to skip sublevels, jump to end of subtree
15617 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15618 (when (and (eq action 'sparse-tree)
15619 (not org-sparse-tree-open-archived-trees))
15620 (org-hide-archived-subtrees (point-min) (point-max)))
15621 (nreverse rtn)))
15623 (defvar todo-only) ;; dynamically scoped
15625 (defun org-tags-sparse-tree (&optional todo-only match)
15626 "Create a sparse tree according to tags string MATCH.
15627 MATCH can contain positive and negative selection of tags, like
15628 \"+WORK+URGENT-WITHBOSS\".
15629 If optional argument TODO_ONLY is non-nil, only select lines that are
15630 also TODO lines."
15631 (interactive "P")
15632 (org-prepare-agenda-buffers (list (current-buffer)))
15633 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15635 (defvar org-cached-props nil)
15636 (defun org-cached-entry-get (pom property)
15637 (if (or (eq t org-use-property-inheritance)
15638 (member property org-use-property-inheritance))
15639 ;; Caching is not possible, check it directly
15640 (org-entry-get pom property 'inherit)
15641 ;; Get all properties, so that we can do complicated checks easily
15642 (cdr (assoc property (or org-cached-props
15643 (setq org-cached-props
15644 (org-entry-properties pom)))))))
15646 (defun org-global-tags-completion-table (&optional files)
15647 "Return the list of all tags in all agenda buffer/files."
15648 (save-excursion
15649 (org-uniquify
15650 (delq nil
15651 (apply 'append
15652 (mapcar
15653 (lambda (file)
15654 (set-buffer (find-file-noselect file))
15655 (append (org-get-buffer-tags)
15656 (mapcar (lambda (x) (if (stringp (car-safe x))
15657 (list (car-safe x)) nil))
15658 org-tag-alist)))
15659 (if (and files (car files))
15660 files
15661 (org-agenda-files))))))))
15663 (defun org-make-tags-matcher (match)
15664 "Create the TAGS//TODO matcher form for the selection string MATCH."
15665 ;; todo-only is scoped dynamically into this function, and the function
15666 ;; may change it it the matcher asksk for it.
15667 (unless match
15668 ;; Get a new match request, with completion
15669 (let ((org-last-tags-completion-table
15670 (org-global-tags-completion-table)))
15671 (setq match (completing-read
15672 "Match: " 'org-tags-completion-function nil nil nil
15673 'org-tags-history))))
15675 ;; Parse the string and create a lisp form
15676 (let ((match0 match)
15677 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15678 minus tag mm
15679 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15680 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15681 (if (string-match "/+" match)
15682 ;; match contains also a todo-matching request
15683 (progn
15684 (setq tagsmatch (substring match 0 (match-beginning 0))
15685 todomatch (substring match (match-end 0)))
15686 (if (string-match "^!" todomatch)
15687 (setq todo-only t todomatch (substring todomatch 1)))
15688 (if (string-match "^\\s-*$" todomatch)
15689 (setq todomatch nil)))
15690 ;; only matching tags
15691 (setq tagsmatch match todomatch nil))
15693 ;; Make the tags matcher
15694 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15695 (setq tagsmatcher t)
15696 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15697 (while (setq term (pop orterms))
15698 (while (and (equal (substring term -1) "\\") orterms)
15699 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15700 (while (string-match re term)
15701 (setq minus (and (match-end 1)
15702 (equal (match-string 1 term) "-"))
15703 tag (match-string 2 term)
15704 re-p (equal (string-to-char tag) ?{)
15705 level-p (match-end 3)
15706 prop-p (match-end 4)
15707 mm (cond
15708 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15709 (level-p `(= level ,(string-to-number
15710 (match-string 3 term))))
15711 (prop-p
15712 (setq pn (match-string 4 term)
15713 pv (match-string 5 term)
15714 cat-p (equal pn "CATEGORY")
15715 re-p (equal (string-to-char pv) ?{)
15716 pv (substring pv 1 -1))
15717 (if (equal pn "CATEGORY")
15718 (setq gv '(get-text-property (point) 'org-category))
15719 (setq gv `(org-cached-entry-get nil ,pn)))
15720 (if re-p
15721 `(string-match ,pv (or ,gv ""))
15722 `(equal ,pv (or ,gv ""))))
15723 (t `(member ,(downcase tag) tags-list)))
15724 mm (if minus (list 'not mm) mm)
15725 term (substring term (match-end 0)))
15726 (push mm tagsmatcher))
15727 (push (if (> (length tagsmatcher) 1)
15728 (cons 'and tagsmatcher)
15729 (car tagsmatcher))
15730 orlist)
15731 (setq tagsmatcher nil))
15732 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15733 (setq tagsmatcher
15734 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15736 ;; Make the todo matcher
15737 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15738 (setq todomatcher t)
15739 (setq orterms (org-split-string todomatch "|") orlist nil)
15740 (while (setq term (pop orterms))
15741 (while (string-match re term)
15742 (setq minus (and (match-end 1)
15743 (equal (match-string 1 term) "-"))
15744 kwd (match-string 2 term)
15745 re-p (equal (string-to-char kwd) ?{)
15746 term (substring term (match-end 0))
15747 mm (if re-p
15748 `(string-match ,(substring kwd 1 -1) todo)
15749 (list 'equal 'todo kwd))
15750 mm (if minus (list 'not mm) mm))
15751 (push mm todomatcher))
15752 (push (if (> (length todomatcher) 1)
15753 (cons 'and todomatcher)
15754 (car todomatcher))
15755 orlist)
15756 (setq todomatcher nil))
15757 (setq todomatcher (if (> (length orlist) 1)
15758 (cons 'or orlist) (car orlist))))
15760 ;; Return the string and lisp forms of the matcher
15761 (setq matcher (if todomatcher
15762 (list 'and tagsmatcher todomatcher)
15763 tagsmatcher))
15764 (cons match0 matcher)))
15766 (defun org-match-any-p (re list)
15767 "Does re match any element of list?"
15768 (setq list (mapcar (lambda (x) (string-match re x)) list))
15769 (delq nil list))
15771 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15772 (defvar org-tags-overlay (org-make-overlay 1 1))
15773 (org-detach-overlay org-tags-overlay)
15775 (defun org-align-tags-here (to-col)
15776 ;; Assumes that this is a headline
15777 (let ((pos (point)) (col (current-column)) tags)
15778 (beginning-of-line 1)
15779 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15780 (< pos (match-beginning 2)))
15781 (progn
15782 (setq tags (match-string 2))
15783 (goto-char (match-beginning 1))
15784 (insert " ")
15785 (delete-region (point) (1+ (match-end 0)))
15786 (backward-char 1)
15787 (move-to-column
15788 (max (1+ (current-column))
15789 (1+ col)
15790 (if (> to-col 0)
15791 to-col
15792 (- (abs to-col) (length tags))))
15794 (insert tags)
15795 (move-to-column (min (current-column) col) t))
15796 (goto-char pos))))
15798 (defun org-set-tags (&optional arg just-align)
15799 "Set the tags for the current headline.
15800 With prefix ARG, realign all tags in headings in the current buffer."
15801 (interactive "P")
15802 (let* ((re (concat "^" outline-regexp))
15803 (current (org-get-tags-string))
15804 (col (current-column))
15805 (org-setting-tags t)
15806 table current-tags inherited-tags ; computed below when needed
15807 tags p0 c0 c1 rpl)
15808 (if arg
15809 (save-excursion
15810 (goto-char (point-min))
15811 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15812 (while (re-search-forward re nil t)
15813 (org-set-tags nil t)
15814 (end-of-line 1)))
15815 (message "All tags realigned to column %d" org-tags-column))
15816 (if just-align
15817 (setq tags current)
15818 ;; Get a new set of tags from the user
15819 (save-excursion
15820 (setq table (or org-tag-alist (org-get-buffer-tags))
15821 org-last-tags-completion-table table
15822 current-tags (org-split-string current ":")
15823 inherited-tags (nreverse
15824 (nthcdr (length current-tags)
15825 (nreverse (org-get-tags-at))))
15826 tags
15827 (if (or (eq t org-use-fast-tag-selection)
15828 (and org-use-fast-tag-selection
15829 (delq nil (mapcar 'cdr table))))
15830 (org-fast-tag-selection
15831 current-tags inherited-tags table
15832 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15833 (let ((org-add-colon-after-tag-completion t))
15834 (org-trim
15835 (org-without-partial-completion
15836 (completing-read "Tags: " 'org-tags-completion-function
15837 nil nil current 'org-tags-history)))))))
15838 (while (string-match "[-+&]+" tags)
15839 ;; No boolean logic, just a list
15840 (setq tags (replace-match ":" t t tags))))
15842 (if (string-match "\\`[\t ]*\\'" tags)
15843 (setq tags "")
15844 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15845 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15847 ;; Insert new tags at the correct column
15848 (beginning-of-line 1)
15849 (cond
15850 ((and (equal current "") (equal tags "")))
15851 ((re-search-forward
15852 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15853 (point-at-eol) t)
15854 (if (equal tags "")
15855 (setq rpl "")
15856 (goto-char (match-beginning 0))
15857 (setq c0 (current-column) p0 (point)
15858 c1 (max (1+ c0) (if (> org-tags-column 0)
15859 org-tags-column
15860 (- (- org-tags-column) (length tags))))
15861 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15862 (replace-match rpl t t)
15863 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15864 tags)
15865 (t (error "Tags alignment failed")))
15866 (move-to-column col)
15867 (unless just-align
15868 (run-hooks 'org-after-tags-change-hook)))))
15870 (defun org-change-tag-in-region (beg end tag off)
15871 "Add or remove TAG for each entry in the region.
15872 This works in the agenda, and also in an org-mode buffer."
15873 (interactive
15874 (list (region-beginning) (region-end)
15875 (let ((org-last-tags-completion-table
15876 (if (org-mode-p)
15877 (org-get-buffer-tags)
15878 (org-global-tags-completion-table))))
15879 (completing-read
15880 "Tag: " 'org-tags-completion-function nil nil nil
15881 'org-tags-history))
15882 (progn
15883 (message "[s]et or [r]emove? ")
15884 (equal (read-char-exclusive) ?r))))
15885 (if (fboundp 'deactivate-mark) (deactivate-mark))
15886 (let ((agendap (equal major-mode 'org-agenda-mode))
15887 l1 l2 m buf pos newhead (cnt 0))
15888 (goto-char end)
15889 (setq l2 (1- (org-current-line)))
15890 (goto-char beg)
15891 (setq l1 (org-current-line))
15892 (loop for l from l1 to l2 do
15893 (goto-line l)
15894 (setq m (get-text-property (point) 'org-hd-marker))
15895 (when (or (and (org-mode-p) (org-on-heading-p))
15896 (and agendap m))
15897 (setq buf (if agendap (marker-buffer m) (current-buffer))
15898 pos (if agendap m (point)))
15899 (with-current-buffer buf
15900 (save-excursion
15901 (save-restriction
15902 (goto-char pos)
15903 (setq cnt (1+ cnt))
15904 (org-toggle-tag tag (if off 'off 'on))
15905 (setq newhead (org-get-heading)))))
15906 (and agendap (org-agenda-change-all-lines newhead m))))
15907 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15909 (defun org-tags-completion-function (string predicate &optional flag)
15910 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15911 (confirm (lambda (x) (stringp (car x)))))
15912 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15913 (setq s1 (match-string 1 string)
15914 s2 (match-string 2 string))
15915 (setq s1 "" s2 string))
15916 (cond
15917 ((eq flag nil)
15918 ;; try completion
15919 (setq rtn (try-completion s2 ctable confirm))
15920 (if (stringp rtn)
15921 (setq rtn
15922 (concat s1 s2 (substring rtn (length s2))
15923 (if (and org-add-colon-after-tag-completion
15924 (assoc rtn ctable))
15925 ":" ""))))
15926 rtn)
15927 ((eq flag t)
15928 ;; all-completions
15929 (all-completions s2 ctable confirm)
15931 ((eq flag 'lambda)
15932 ;; exact match?
15933 (assoc s2 ctable)))
15936 (defun org-fast-tag-insert (kwd tags face &optional end)
15937 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15938 (insert (format "%-12s" (concat kwd ":"))
15939 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15940 (or end "")))
15942 (defun org-fast-tag-show-exit (flag)
15943 (save-excursion
15944 (goto-line 3)
15945 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15946 (replace-match ""))
15947 (when flag
15948 (end-of-line 1)
15949 (move-to-column (- (window-width) 19) t)
15950 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15952 (defun org-set-current-tags-overlay (current prefix)
15953 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15954 (if (featurep 'xemacs)
15955 (org-overlay-display org-tags-overlay (concat prefix s)
15956 'secondary-selection)
15957 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15958 (org-overlay-display org-tags-overlay (concat prefix s)))))
15960 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15961 "Fast tag selection with single keys.
15962 CURRENT is the current list of tags in the headline, INHERITED is the
15963 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15964 possibly with grouping information. TODO-TABLE is a similar table with
15965 TODO keywords, should these have keys assigned to them.
15966 If the keys are nil, a-z are automatically assigned.
15967 Returns the new tags string, or nil to not change the current settings."
15968 (let* ((fulltable (append table todo-table))
15969 (maxlen (apply 'max (mapcar
15970 (lambda (x)
15971 (if (stringp (car x)) (string-width (car x)) 0))
15972 fulltable)))
15973 (buf (current-buffer))
15974 (expert (eq org-fast-tag-selection-single-key 'expert))
15975 (buffer-tags nil)
15976 (fwidth (+ maxlen 3 1 3))
15977 (ncol (/ (- (window-width) 4) fwidth))
15978 (i-face 'org-done)
15979 (c-face 'org-todo)
15980 tg cnt e c char c1 c2 ntable tbl rtn
15981 ov-start ov-end ov-prefix
15982 (exit-after-next org-fast-tag-selection-single-key)
15983 (done-keywords org-done-keywords)
15984 groups ingroup)
15985 (save-excursion
15986 (beginning-of-line 1)
15987 (if (looking-at
15988 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15989 (setq ov-start (match-beginning 1)
15990 ov-end (match-end 1)
15991 ov-prefix "")
15992 (setq ov-start (1- (point-at-eol))
15993 ov-end (1+ ov-start))
15994 (skip-chars-forward "^\n\r")
15995 (setq ov-prefix
15996 (concat
15997 (buffer-substring (1- (point)) (point))
15998 (if (> (current-column) org-tags-column)
16000 (make-string (- org-tags-column (current-column)) ?\ ))))))
16001 (org-move-overlay org-tags-overlay ov-start ov-end)
16002 (save-window-excursion
16003 (if expert
16004 (set-buffer (get-buffer-create " *Org tags*"))
16005 (delete-other-windows)
16006 (split-window-vertically)
16007 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
16008 (erase-buffer)
16009 (org-set-local 'org-done-keywords done-keywords)
16010 (org-fast-tag-insert "Inherited" inherited i-face "\n")
16011 (org-fast-tag-insert "Current" current c-face "\n\n")
16012 (org-fast-tag-show-exit exit-after-next)
16013 (org-set-current-tags-overlay current ov-prefix)
16014 (setq tbl fulltable char ?a cnt 0)
16015 (while (setq e (pop tbl))
16016 (cond
16017 ((equal e '(:startgroup))
16018 (push '() groups) (setq ingroup t)
16019 (when (not (= cnt 0))
16020 (setq cnt 0)
16021 (insert "\n"))
16022 (insert "{ "))
16023 ((equal e '(:endgroup))
16024 (setq ingroup nil cnt 0)
16025 (insert "}\n"))
16027 (setq tg (car e) c2 nil)
16028 (if (cdr e)
16029 (setq c (cdr e))
16030 ;; automatically assign a character.
16031 (setq c1 (string-to-char
16032 (downcase (substring
16033 tg (if (= (string-to-char tg) ?@) 1 0)))))
16034 (if (or (rassoc c1 ntable) (rassoc c1 table))
16035 (while (or (rassoc char ntable) (rassoc char table))
16036 (setq char (1+ char)))
16037 (setq c2 c1))
16038 (setq c (or c2 char)))
16039 (if ingroup (push tg (car groups)))
16040 (setq tg (org-add-props tg nil 'face
16041 (cond
16042 ((not (assoc tg table))
16043 (org-get-todo-face tg))
16044 ((member tg current) c-face)
16045 ((member tg inherited) i-face)
16046 (t nil))))
16047 (if (and (= cnt 0) (not ingroup)) (insert " "))
16048 (insert "[" c "] " tg (make-string
16049 (- fwidth 4 (length tg)) ?\ ))
16050 (push (cons tg c) ntable)
16051 (when (= (setq cnt (1+ cnt)) ncol)
16052 (insert "\n")
16053 (if ingroup (insert " "))
16054 (setq cnt 0)))))
16055 (setq ntable (nreverse ntable))
16056 (insert "\n")
16057 (goto-char (point-min))
16058 (if (and (not expert) (fboundp 'fit-window-to-buffer))
16059 (fit-window-to-buffer))
16060 (setq rtn
16061 (catch 'exit
16062 (while t
16063 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
16064 (if groups " [!] no groups" " [!]groups")
16065 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
16066 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
16067 (cond
16068 ((= c ?\r) (throw 'exit t))
16069 ((= c ?!)
16070 (setq groups (not groups))
16071 (goto-char (point-min))
16072 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
16073 ((= c ?\C-c)
16074 (if (not expert)
16075 (org-fast-tag-show-exit
16076 (setq exit-after-next (not exit-after-next)))
16077 (setq expert nil)
16078 (delete-other-windows)
16079 (split-window-vertically)
16080 (org-switch-to-buffer-other-window " *Org tags*")
16081 (and (fboundp 'fit-window-to-buffer)
16082 (fit-window-to-buffer))))
16083 ((or (= c ?\C-g)
16084 (and (= c ?q) (not (rassoc c ntable))))
16085 (org-detach-overlay org-tags-overlay)
16086 (setq quit-flag t))
16087 ((= c ?\ )
16088 (setq current nil)
16089 (if exit-after-next (setq exit-after-next 'now)))
16090 ((= c ?\t)
16091 (condition-case nil
16092 (setq tg (completing-read
16093 "Tag: "
16094 (or buffer-tags
16095 (with-current-buffer buf
16096 (org-get-buffer-tags)))))
16097 (quit (setq tg "")))
16098 (when (string-match "\\S-" tg)
16099 (add-to-list 'buffer-tags (list tg))
16100 (if (member tg current)
16101 (setq current (delete tg current))
16102 (push tg current)))
16103 (if exit-after-next (setq exit-after-next 'now)))
16104 ((setq e (rassoc c todo-table) tg (car e))
16105 (with-current-buffer buf
16106 (save-excursion (org-todo tg)))
16107 (if exit-after-next (setq exit-after-next 'now)))
16108 ((setq e (rassoc c ntable) tg (car e))
16109 (if (member tg current)
16110 (setq current (delete tg current))
16111 (loop for g in groups do
16112 (if (member tg g)
16113 (mapc (lambda (x)
16114 (setq current (delete x current)))
16115 g)))
16116 (push tg current))
16117 (if exit-after-next (setq exit-after-next 'now))))
16119 ;; Create a sorted list
16120 (setq current
16121 (sort current
16122 (lambda (a b)
16123 (assoc b (cdr (memq (assoc a ntable) ntable))))))
16124 (if (eq exit-after-next 'now) (throw 'exit t))
16125 (goto-char (point-min))
16126 (beginning-of-line 2)
16127 (delete-region (point) (point-at-eol))
16128 (org-fast-tag-insert "Current" current c-face)
16129 (org-set-current-tags-overlay current ov-prefix)
16130 (while (re-search-forward
16131 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
16132 (setq tg (match-string 1))
16133 (add-text-properties
16134 (match-beginning 1) (match-end 1)
16135 (list 'face
16136 (cond
16137 ((member tg current) c-face)
16138 ((member tg inherited) i-face)
16139 (t (get-text-property (match-beginning 1) 'face))))))
16140 (goto-char (point-min)))))
16141 (org-detach-overlay org-tags-overlay)
16142 (if rtn
16143 (mapconcat 'identity current ":")
16144 nil))))
16146 (defun org-get-tags-string ()
16147 "Get the TAGS string in the current headline."
16148 (unless (org-on-heading-p t)
16149 (error "Not on a heading"))
16150 (save-excursion
16151 (beginning-of-line 1)
16152 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16153 (org-match-string-no-properties 1)
16154 "")))
16156 (defun org-get-tags ()
16157 "Get the list of tags specified in the current headline."
16158 (org-split-string (org-get-tags-string) ":"))
16160 (defun org-get-buffer-tags ()
16161 "Get a table of all tags used in the buffer, for completion."
16162 (let (tags)
16163 (save-excursion
16164 (goto-char (point-min))
16165 (while (re-search-forward
16166 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
16167 (when (equal (char-after (point-at-bol 0)) ?*)
16168 (mapc (lambda (x) (add-to-list 'tags x))
16169 (org-split-string (org-match-string-no-properties 1) ":")))))
16170 (mapcar 'list tags)))
16173 ;;;; Properties
16175 ;;; Setting and retrieving properties
16177 (defconst org-special-properties
16178 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
16179 "TIMESTAMP" "TIMESTAMP_IA")
16180 "The special properties valid in Org-mode.
16182 These are properties that are not defined in the property drawer,
16183 but in some other way.")
16185 (defconst org-default-properties
16186 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
16187 "LOCATION" "LOGGING" "COLUMNS")
16188 "Some properties that are used by Org-mode for various purposes.
16189 Being in this list makes sure that they are offered for completion.")
16191 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
16192 "Regular expression matching the first line of a property drawer.")
16194 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
16195 "Regular expression matching the first line of a property drawer.")
16197 (defun org-property-action ()
16198 "Do an action on properties."
16199 (interactive)
16200 (let (c)
16201 (org-at-property-p)
16202 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
16203 (setq c (read-char-exclusive))
16204 (cond
16205 ((equal c ?s)
16206 (call-interactively 'org-set-property))
16207 ((equal c ?d)
16208 (call-interactively 'org-delete-property))
16209 ((equal c ?D)
16210 (call-interactively 'org-delete-property-globally))
16211 ((equal c ?c)
16212 (call-interactively 'org-compute-property-at-point))
16213 (t (error "No such property action %c" c)))))
16215 (defun org-at-property-p ()
16216 "Is the cursor in a property line?"
16217 ;; FIXME: Does not check if we are actually in the drawer.
16218 ;; FIXME: also returns true on any drawers.....
16219 ;; This is used by C-c C-c for property action.
16220 (save-excursion
16221 (beginning-of-line 1)
16222 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
16224 (defmacro org-with-point-at (pom &rest body)
16225 "Move to buffer and point of point-or-marker POM for the duration of BODY."
16226 (declare (indent 1) (debug t))
16227 `(save-excursion
16228 (if (markerp pom) (set-buffer (marker-buffer pom)))
16229 (save-excursion
16230 (goto-char (or pom (point)))
16231 ,@body)))
16233 (defun org-get-property-block (&optional beg end force)
16234 "Return the (beg . end) range of the body of the property drawer.
16235 BEG and END can be beginning and end of subtree, if not given
16236 they will be found.
16237 If the drawer does not exist and FORCE is non-nil, create the drawer."
16238 (catch 'exit
16239 (save-excursion
16240 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
16241 (end (or end (progn (outline-next-heading) (point)))))
16242 (goto-char beg)
16243 (if (re-search-forward org-property-start-re end t)
16244 (setq beg (1+ (match-end 0)))
16245 (if force
16246 (save-excursion
16247 (org-insert-property-drawer)
16248 (setq end (progn (outline-next-heading) (point))))
16249 (throw 'exit nil))
16250 (goto-char beg)
16251 (if (re-search-forward org-property-start-re end t)
16252 (setq beg (1+ (match-end 0)))))
16253 (if (re-search-forward org-property-end-re end t)
16254 (setq end (match-beginning 0))
16255 (or force (throw 'exit nil))
16256 (goto-char beg)
16257 (setq end beg)
16258 (org-indent-line-function)
16259 (insert ":END:\n"))
16260 (cons beg end)))))
16262 (defun org-entry-properties (&optional pom which)
16263 "Get all properties of the entry at point-or-marker POM.
16264 This includes the TODO keyword, the tags, time strings for deadline,
16265 scheduled, and clocking, and any additional properties defined in the
16266 entry. The return value is an alist, keys may occur multiple times
16267 if the property key was used several times.
16268 POM may also be nil, in which case the current entry is used.
16269 If WHICH is nil or `all', get all properties. If WHICH is
16270 `special' or `standard', only get that subclass."
16271 (setq which (or which 'all))
16272 (org-with-point-at pom
16273 (let ((clockstr (substring org-clock-string 0 -1))
16274 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
16275 beg end range props sum-props key value string clocksum)
16276 (save-excursion
16277 (when (condition-case nil (org-back-to-heading t) (error nil))
16278 (setq beg (point))
16279 (setq sum-props (get-text-property (point) 'org-summaries))
16280 (setq clocksum (get-text-property (point) :org-clock-minutes))
16281 (outline-next-heading)
16282 (setq end (point))
16283 (when (memq which '(all special))
16284 ;; Get the special properties, like TODO and tags
16285 (goto-char beg)
16286 (when (and (looking-at org-todo-line-regexp) (match-end 2))
16287 (push (cons "TODO" (org-match-string-no-properties 2)) props))
16288 (when (looking-at org-priority-regexp)
16289 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16290 (when (and (setq value (org-get-tags-string))
16291 (string-match "\\S-" value))
16292 (push (cons "TAGS" value) props))
16293 (when (setq value (org-get-tags-at))
16294 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16295 props))
16296 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16297 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16298 string (if (equal key clockstr)
16299 (org-no-properties
16300 (org-trim
16301 (buffer-substring
16302 (match-beginning 3) (goto-char (point-at-eol)))))
16303 (substring (org-match-string-no-properties 3) 1 -1)))
16304 (unless key
16305 (if (= (char-after (match-beginning 3)) ?\[)
16306 (setq key "TIMESTAMP_IA")
16307 (setq key "TIMESTAMP")))
16308 (when (or (equal key clockstr) (not (assoc key props)))
16309 (push (cons key string) props)))
16313 (when (memq which '(all standard))
16314 ;; Get the standard properties, like :PORP: ...
16315 (setq range (org-get-property-block beg end))
16316 (when range
16317 (goto-char (car range))
16318 (while (re-search-forward
16319 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16320 (cdr range) t)
16321 (setq key (org-match-string-no-properties 1)
16322 value (org-trim (or (org-match-string-no-properties 2) "")))
16323 (unless (member key excluded)
16324 (push (cons key (or value "")) props)))))
16325 (if clocksum
16326 (push (cons "CLOCKSUM"
16327 (org-column-number-to-string (/ (float clocksum) 60.)
16328 'add_times))
16329 props))
16330 (append sum-props (nreverse props)))))))
16332 (defun org-entry-get (pom property &optional inherit)
16333 "Get value of PROPERTY for entry at point-or-marker POM.
16334 If INHERIT is non-nil and the entry does not have the property,
16335 then also check higher levels of the hierarchy.
16336 If the property is present but empty, the return value is the empty string.
16337 If the property is not present at all, nil is returned."
16338 (org-with-point-at pom
16339 (if inherit
16340 (org-entry-get-with-inheritance property)
16341 (if (member property org-special-properties)
16342 ;; We need a special property. Use brute force, get all properties.
16343 (cdr (assoc property (org-entry-properties nil 'special)))
16344 (let ((range (org-get-property-block)))
16345 (if (and range
16346 (goto-char (car range))
16347 (re-search-forward
16348 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16349 (cdr range) t))
16350 ;; Found the property, return it.
16351 (if (match-end 1)
16352 (org-match-string-no-properties 1)
16353 "")))))))
16355 (defun org-entry-delete (pom property)
16356 "Delete the property PROPERTY from entry at point-or-marker POM."
16357 (org-with-point-at pom
16358 (if (member property org-special-properties)
16359 nil ; cannot delete these properties.
16360 (let ((range (org-get-property-block)))
16361 (if (and range
16362 (goto-char (car range))
16363 (re-search-forward
16364 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16365 (cdr range) t))
16366 (progn
16367 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16369 nil)))))
16371 ;; Multi-values properties are properties that contain multiple values
16372 ;; These values are assumed to be single words, separated by whitespace.
16373 (defun org-entry-add-to-multivalued-property (pom property value)
16374 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16375 (let* ((old (org-entry-get pom property))
16376 (values (and old (org-split-string old "[ \t]"))))
16377 (unless (member value values)
16378 (setq values (cons value values))
16379 (org-entry-put pom property
16380 (mapconcat 'identity values " ")))))
16382 (defun org-entry-remove-from-multivalued-property (pom property value)
16383 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16384 (let* ((old (org-entry-get pom property))
16385 (values (and old (org-split-string old "[ \t]"))))
16386 (when (member value values)
16387 (setq values (delete value values))
16388 (org-entry-put pom property
16389 (mapconcat 'identity values " ")))))
16391 (defun org-entry-member-in-multivalued-property (pom property value)
16392 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16393 (let* ((old (org-entry-get pom property))
16394 (values (and old (org-split-string old "[ \t]"))))
16395 (member value values)))
16397 (defvar org-entry-property-inherited-from (make-marker))
16399 (defun org-entry-get-with-inheritance (property)
16400 "Get entry property, and search higher levels if not present."
16401 (let (tmp)
16402 (save-excursion
16403 (save-restriction
16404 (widen)
16405 (catch 'ex
16406 (while t
16407 (when (setq tmp (org-entry-get nil property))
16408 (org-back-to-heading t)
16409 (move-marker org-entry-property-inherited-from (point))
16410 (throw 'ex tmp))
16411 (or (org-up-heading-safe) (throw 'ex nil)))))
16412 (or tmp (cdr (assoc property org-local-properties))
16413 (cdr (assoc property org-global-properties))))))
16415 (defun org-entry-put (pom property value)
16416 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16417 (org-with-point-at pom
16418 (org-back-to-heading t)
16419 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16420 range)
16421 (cond
16422 ((equal property "TODO")
16423 (when (and (stringp value) (string-match "\\S-" value)
16424 (not (member value org-todo-keywords-1)))
16425 (error "\"%s\" is not a valid TODO state" value))
16426 (if (or (not value)
16427 (not (string-match "\\S-" value)))
16428 (setq value 'none))
16429 (org-todo value)
16430 (org-set-tags nil 'align))
16431 ((equal property "PRIORITY")
16432 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16433 (string-to-char value) ?\ ))
16434 (org-set-tags nil 'align))
16435 ((equal property "SCHEDULED")
16436 (if (re-search-forward org-scheduled-time-regexp end t)
16437 (cond
16438 ((eq value 'earlier) (org-timestamp-change -1 'day))
16439 ((eq value 'later) (org-timestamp-change 1 'day))
16440 (t (call-interactively 'org-schedule)))
16441 (call-interactively 'org-schedule)))
16442 ((equal property "DEADLINE")
16443 (if (re-search-forward org-deadline-time-regexp end t)
16444 (cond
16445 ((eq value 'earlier) (org-timestamp-change -1 'day))
16446 ((eq value 'later) (org-timestamp-change 1 'day))
16447 (t (call-interactively 'org-deadline)))
16448 (call-interactively 'org-deadline)))
16449 ((member property org-special-properties)
16450 (error "The %s property can not yet be set with `org-entry-put'"
16451 property))
16452 (t ; a non-special property
16453 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16454 (setq range (org-get-property-block beg end 'force))
16455 (goto-char (car range))
16456 (if (re-search-forward
16457 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16458 (progn
16459 (delete-region (match-beginning 1) (match-end 1))
16460 (goto-char (match-beginning 1)))
16461 (goto-char (cdr range))
16462 (insert "\n")
16463 (backward-char 1)
16464 (org-indent-line-function)
16465 (insert ":" property ":"))
16466 (and value (insert " " value))
16467 (org-indent-line-function)))))))
16469 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16470 "Get all property keys in the current buffer.
16471 With INCLUDE-SPECIALS, also list the special properties that relect things
16472 like tags and TODO state.
16473 With INCLUDE-DEFAULTS, also include properties that has special meaning
16474 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16475 With INCLUDE-COLUMNS, also include property names given in COLUMN
16476 formats in the current buffer."
16477 (let (rtn range cfmt cols s p)
16478 (save-excursion
16479 (save-restriction
16480 (widen)
16481 (goto-char (point-min))
16482 (while (re-search-forward org-property-start-re nil t)
16483 (setq range (org-get-property-block))
16484 (goto-char (car range))
16485 (while (re-search-forward
16486 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16487 (cdr range) t)
16488 (add-to-list 'rtn (org-match-string-no-properties 1)))
16489 (outline-next-heading))))
16491 (when include-specials
16492 (setq rtn (append org-special-properties rtn)))
16494 (when include-defaults
16495 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16497 (when include-columns
16498 (save-excursion
16499 (save-restriction
16500 (widen)
16501 (goto-char (point-min))
16502 (while (re-search-forward
16503 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16504 nil t)
16505 (setq cfmt (match-string 2) s 0)
16506 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16507 cfmt s)
16508 (setq s (match-end 0)
16509 p (match-string 1 cfmt))
16510 (unless (or (equal p "ITEM")
16511 (member p org-special-properties))
16512 (add-to-list 'rtn (match-string 1 cfmt))))))))
16514 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16516 (defun org-property-values (key)
16517 "Return a list of all values of property KEY."
16518 (save-excursion
16519 (save-restriction
16520 (widen)
16521 (goto-char (point-min))
16522 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16523 values)
16524 (while (re-search-forward re nil t)
16525 (add-to-list 'values (org-trim (match-string 1))))
16526 (delete "" values)))))
16528 (defun org-insert-property-drawer ()
16529 "Insert a property drawer into the current entry."
16530 (interactive)
16531 (org-back-to-heading t)
16532 (looking-at outline-regexp)
16533 (let ((indent (- (match-end 0)(match-beginning 0)))
16534 (beg (point))
16535 (re (concat "^[ \t]*" org-keyword-time-regexp))
16536 end hiddenp)
16537 (outline-next-heading)
16538 (setq end (point))
16539 (goto-char beg)
16540 (while (re-search-forward re end t))
16541 (setq hiddenp (org-invisible-p))
16542 (end-of-line 1)
16543 (and (equal (char-after) ?\n) (forward-char 1))
16544 (org-skip-over-state-notes)
16545 (skip-chars-backward " \t\n\r")
16546 (if (eq (char-before) ?*) (forward-char 1))
16547 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16548 (beginning-of-line 0)
16549 (indent-to-column indent)
16550 (beginning-of-line 2)
16551 (indent-to-column indent)
16552 (beginning-of-line 0)
16553 (if hiddenp
16554 (save-excursion
16555 (org-back-to-heading t)
16556 (hide-entry))
16557 (org-flag-drawer t))))
16559 (defun org-set-property (property value)
16560 "In the current entry, set PROPERTY to VALUE.
16561 When called interactively, this will prompt for a property name, offering
16562 completion on existing and default properties. And then it will prompt
16563 for a value, offering competion either on allowed values (via an inherited
16564 xxx_ALL property) or on existing values in other instances of this property
16565 in the current file."
16566 (interactive
16567 (let* ((prop (completing-read
16568 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16569 (cur (org-entry-get nil prop))
16570 (allowed (org-property-get-allowed-values nil prop 'table))
16571 (existing (mapcar 'list (org-property-values prop)))
16572 (val (if allowed
16573 (completing-read "Value: " allowed nil 'req-match)
16574 (completing-read
16575 (concat "Value" (if (and cur (string-match "\\S-" cur))
16576 (concat "[" cur "]") "")
16577 ": ")
16578 existing nil nil "" nil cur))))
16579 (list prop (if (equal val "") cur val))))
16580 (unless (equal (org-entry-get nil property) value)
16581 (org-entry-put nil property value)))
16583 (defun org-delete-property (property)
16584 "In the current entry, delete PROPERTY."
16585 (interactive
16586 (let* ((prop (completing-read
16587 "Property: " (org-entry-properties nil 'standard))))
16588 (list prop)))
16589 (message "Property %s %s" property
16590 (if (org-entry-delete nil property)
16591 "deleted"
16592 "was not present in the entry")))
16594 (defun org-delete-property-globally (property)
16595 "Remove PROPERTY globally, from all entries."
16596 (interactive
16597 (let* ((prop (completing-read
16598 "Globally remove property: "
16599 (mapcar 'list (org-buffer-property-keys)))))
16600 (list prop)))
16601 (save-excursion
16602 (save-restriction
16603 (widen)
16604 (goto-char (point-min))
16605 (let ((cnt 0))
16606 (while (re-search-forward
16607 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16608 nil t)
16609 (setq cnt (1+ cnt))
16610 (replace-match ""))
16611 (message "Property \"%s\" removed from %d entries" property cnt)))))
16613 (defvar org-columns-current-fmt-compiled) ; defined below
16615 (defun org-compute-property-at-point ()
16616 "Compute the property at point.
16617 This looks for an enclosing column format, extracts the operator and
16618 then applies it to the proerty in the column format's scope."
16619 (interactive)
16620 (unless (org-at-property-p)
16621 (error "Not at a property"))
16622 (let ((prop (org-match-string-no-properties 2)))
16623 (org-columns-get-format-and-top-level)
16624 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16625 (error "No operator defined for property %s" prop))
16626 (org-columns-compute prop)))
16628 (defun org-property-get-allowed-values (pom property &optional table)
16629 "Get allowed values for the property PROPERTY.
16630 When TABLE is non-nil, return an alist that can directly be used for
16631 completion."
16632 (let (vals)
16633 (cond
16634 ((equal property "TODO")
16635 (setq vals (org-with-point-at pom
16636 (append org-todo-keywords-1 '("")))))
16637 ((equal property "PRIORITY")
16638 (let ((n org-lowest-priority))
16639 (while (>= n org-highest-priority)
16640 (push (char-to-string n) vals)
16641 (setq n (1- n)))))
16642 ((member property org-special-properties))
16644 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16646 (when (and vals (string-match "\\S-" vals))
16647 (setq vals (car (read-from-string (concat "(" vals ")"))))
16648 (setq vals (mapcar (lambda (x)
16649 (cond ((stringp x) x)
16650 ((numberp x) (number-to-string x))
16651 ((symbolp x) (symbol-name x))
16652 (t "???")))
16653 vals)))))
16654 (if table (mapcar 'list vals) vals)))
16656 (defun org-property-previous-allowed-value (&optional previous)
16657 "Switch to the next allowed value for this property."
16658 (interactive)
16659 (org-property-next-allowed-value t))
16661 (defun org-property-next-allowed-value (&optional previous)
16662 "Switch to the next allowed value for this property."
16663 (interactive)
16664 (unless (org-at-property-p)
16665 (error "Not at a property"))
16666 (let* ((key (match-string 2))
16667 (value (match-string 3))
16668 (allowed (or (org-property-get-allowed-values (point) key)
16669 (and (member value '("[ ]" "[-]" "[X]"))
16670 '("[ ]" "[X]"))))
16671 nval)
16672 (unless allowed
16673 (error "Allowed values for this property have not been defined"))
16674 (if previous (setq allowed (reverse allowed)))
16675 (if (member value allowed)
16676 (setq nval (car (cdr (member value allowed)))))
16677 (setq nval (or nval (car allowed)))
16678 (if (equal nval value)
16679 (error "Only one allowed value for this property"))
16680 (org-at-property-p)
16681 (replace-match (concat " :" key ": " nval) t t)
16682 (org-indent-line-function)
16683 (beginning-of-line 1)
16684 (skip-chars-forward " \t")))
16686 (defun org-find-entry-with-id (ident)
16687 "Locate the entry that contains the ID property with exact value IDENT.
16688 IDENT can be a string, a symbol or a number, this function will search for
16689 the string representation of it.
16690 Return the position where this entry starts, or nil if there is no such entry."
16691 (let ((id (cond
16692 ((stringp ident) ident)
16693 ((symbol-name ident) (symbol-name ident))
16694 ((numberp ident) (number-to-string ident))
16695 (t (error "IDENT %s must be a string, symbol or number" ident))))
16696 (case-fold-search nil))
16697 (save-excursion
16698 (save-restriction
16699 (widen)
16700 (goto-char (point-min))
16701 (when (re-search-forward
16702 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16703 nil t)
16704 (org-back-to-heading)
16705 (point))))))
16707 ;;; Column View
16709 (defvar org-columns-overlays nil
16710 "Holds the list of current column overlays.")
16712 (defvar org-columns-current-fmt nil
16713 "Local variable, holds the currently active column format.")
16714 (defvar org-columns-current-fmt-compiled nil
16715 "Local variable, holds the currently active column format.
16716 This is the compiled version of the format.")
16717 (defvar org-columns-current-widths nil
16718 "Loval variable, holds the currently widths of fields.")
16719 (defvar org-columns-current-maxwidths nil
16720 "Loval variable, holds the currently active maximum column widths.")
16721 (defvar org-columns-begin-marker (make-marker)
16722 "Points to the position where last a column creation command was called.")
16723 (defvar org-columns-top-level-marker (make-marker)
16724 "Points to the position where current columns region starts.")
16726 (defvar org-columns-map (make-sparse-keymap)
16727 "The keymap valid in column display.")
16729 (defun org-columns-content ()
16730 "Switch to contents view while in columns view."
16731 (interactive)
16732 (org-overview)
16733 (org-content))
16735 (org-defkey org-columns-map "c" 'org-columns-content)
16736 (org-defkey org-columns-map "o" 'org-overview)
16737 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16738 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16739 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16740 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16741 (org-defkey org-columns-map "v" 'org-columns-show-value)
16742 (org-defkey org-columns-map "q" 'org-columns-quit)
16743 (org-defkey org-columns-map "r" 'org-columns-redo)
16744 (org-defkey org-columns-map "g" 'org-columns-redo)
16745 (org-defkey org-columns-map [left] 'backward-char)
16746 (org-defkey org-columns-map "\M-b" 'backward-char)
16747 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16748 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16749 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16750 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16751 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16752 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16753 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16754 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16755 (org-defkey org-columns-map "<" 'org-columns-narrow)
16756 (org-defkey org-columns-map ">" 'org-columns-widen)
16757 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16758 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16759 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16760 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16762 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16763 '("Column"
16764 ["Edit property" org-columns-edit-value t]
16765 ["Next allowed value" org-columns-next-allowed-value t]
16766 ["Previous allowed value" org-columns-previous-allowed-value t]
16767 ["Show full value" org-columns-show-value t]
16768 ["Edit allowed values" org-columns-edit-allowed t]
16769 "--"
16770 ["Edit column attributes" org-columns-edit-attributes t]
16771 ["Increase column width" org-columns-widen t]
16772 ["Decrease column width" org-columns-narrow t]
16773 "--"
16774 ["Move column right" org-columns-move-right t]
16775 ["Move column left" org-columns-move-left t]
16776 ["Add column" org-columns-new t]
16777 ["Delete column" org-columns-delete t]
16778 "--"
16779 ["CONTENTS" org-columns-content t]
16780 ["OVERVIEW" org-overview t]
16781 ["Refresh columns display" org-columns-redo t]
16782 "--"
16783 ["Open link" org-columns-open-link t]
16784 "--"
16785 ["Quit" org-columns-quit t]))
16787 (defun org-columns-new-overlay (beg end &optional string face)
16788 "Create a new column overlay and add it to the list."
16789 (let ((ov (org-make-overlay beg end)))
16790 (org-overlay-put ov 'face (or face 'secondary-selection))
16791 (org-overlay-display ov string face)
16792 (push ov org-columns-overlays)
16793 ov))
16795 (defun org-columns-display-here (&optional props)
16796 "Overlay the current line with column display."
16797 (interactive)
16798 (let* ((fmt org-columns-current-fmt-compiled)
16799 (beg (point-at-bol))
16800 (level-face (save-excursion
16801 (beginning-of-line 1)
16802 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16803 (org-get-level-face 2))))
16804 (color (list :foreground
16805 (face-attribute (or level-face 'default) :foreground)))
16806 props pom property ass width f string ov column val modval)
16807 ;; Check if the entry is in another buffer.
16808 (unless props
16809 (if (eq major-mode 'org-agenda-mode)
16810 (setq pom (or (get-text-property (point) 'org-hd-marker)
16811 (get-text-property (point) 'org-marker))
16812 props (if pom (org-entry-properties pom) nil))
16813 (setq props (org-entry-properties nil))))
16814 ;; Walk the format
16815 (while (setq column (pop fmt))
16816 (setq property (car column)
16817 ass (if (equal property "ITEM")
16818 (cons "ITEM"
16819 (save-match-data
16820 (org-no-properties
16821 (org-remove-tabs
16822 (buffer-substring-no-properties
16823 (point-at-bol) (point-at-eol))))))
16824 (assoc property props))
16825 width (or (cdr (assoc property org-columns-current-maxwidths))
16826 (nth 2 column)
16827 (length property))
16828 f (format "%%-%d.%ds | " width width)
16829 val (or (cdr ass) "")
16830 modval (if (equal property "ITEM")
16831 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16832 string (format f (or modval val)))
16833 ;; Create the overlay
16834 (org-unmodified
16835 (setq ov (org-columns-new-overlay
16836 beg (setq beg (1+ beg)) string
16837 (list color 'org-column)))
16838 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16839 (org-overlay-put ov 'keymap org-columns-map)
16840 (org-overlay-put ov 'org-columns-key property)
16841 (org-overlay-put ov 'org-columns-value (cdr ass))
16842 (org-overlay-put ov 'org-columns-value-modified modval)
16843 (org-overlay-put ov 'org-columns-pom pom)
16844 (org-overlay-put ov 'org-columns-format f))
16845 (if (or (not (char-after beg))
16846 (equal (char-after beg) ?\n))
16847 (let ((inhibit-read-only t))
16848 (save-excursion
16849 (goto-char beg)
16850 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16851 ;; Make the rest of the line disappear.
16852 (org-unmodified
16853 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16854 (org-overlay-put ov 'invisible t)
16855 (org-overlay-put ov 'keymap org-columns-map)
16856 (org-overlay-put ov 'intangible t)
16857 (push ov org-columns-overlays)
16858 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16859 (org-overlay-put ov 'keymap org-columns-map)
16860 (push ov org-columns-overlays)
16861 (let ((inhibit-read-only t))
16862 (put-text-property (max (point-min) (1- (point-at-bol)))
16863 (min (point-max) (1+ (point-at-eol)))
16864 'read-only "Type `e' to edit property")))))
16866 (defvar org-previous-header-line-format nil
16867 "The header line format before column view was turned on.")
16868 (defvar org-columns-inhibit-recalculation nil
16869 "Inhibit recomputing of columns on column view startup.")
16872 (defvar header-line-format)
16873 (defun org-columns-display-here-title ()
16874 "Overlay the newline before the current line with the table title."
16875 (interactive)
16876 (let ((fmt org-columns-current-fmt-compiled)
16877 string (title "")
16878 property width f column str widths)
16879 (while (setq column (pop fmt))
16880 (setq property (car column)
16881 str (or (nth 1 column) property)
16882 width (or (cdr (assoc property org-columns-current-maxwidths))
16883 (nth 2 column)
16884 (length str))
16885 widths (push width widths)
16886 f (format "%%-%d.%ds | " width width)
16887 string (format f str)
16888 title (concat title string)))
16889 (setq title (concat
16890 (org-add-props " " nil 'display '(space :align-to 0))
16891 (org-add-props title nil 'face '(:weight bold :underline t))))
16892 (org-set-local 'org-previous-header-line-format header-line-format)
16893 (org-set-local 'org-columns-current-widths (nreverse widths))
16894 (setq header-line-format title)))
16896 (defun org-columns-remove-overlays ()
16897 "Remove all currently active column overlays."
16898 (interactive)
16899 (when (marker-buffer org-columns-begin-marker)
16900 (with-current-buffer (marker-buffer org-columns-begin-marker)
16901 (when (local-variable-p 'org-previous-header-line-format)
16902 (setq header-line-format org-previous-header-line-format)
16903 (kill-local-variable 'org-previous-header-line-format))
16904 (move-marker org-columns-begin-marker nil)
16905 (move-marker org-columns-top-level-marker nil)
16906 (org-unmodified
16907 (mapc 'org-delete-overlay org-columns-overlays)
16908 (setq org-columns-overlays nil)
16909 (let ((inhibit-read-only t))
16910 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16912 (defun org-columns-cleanup-item (item fmt)
16913 "Remove from ITEM what is a column in the format FMT."
16914 (if (not org-complex-heading-regexp)
16915 item
16916 (when (string-match org-complex-heading-regexp item)
16917 (concat
16918 (org-add-props (concat (match-string 1 item) " ") nil
16919 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16920 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16921 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16922 " " (match-string 4 item)
16923 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16925 (defun org-columns-show-value ()
16926 "Show the full value of the property."
16927 (interactive)
16928 (let ((value (get-char-property (point) 'org-columns-value)))
16929 (message "Value is: %s" (or value ""))))
16931 (defun org-columns-quit ()
16932 "Remove the column overlays and in this way exit column editing."
16933 (interactive)
16934 (org-unmodified
16935 (org-columns-remove-overlays)
16936 (let ((inhibit-read-only t))
16937 (remove-text-properties (point-min) (point-max) '(read-only t))))
16938 (when (eq major-mode 'org-agenda-mode)
16939 (message
16940 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16942 (defun org-columns-check-computed ()
16943 "Check if this column value is computed.
16944 If yes, throw an error indicating that changing it does not make sense."
16945 (let ((val (get-char-property (point) 'org-columns-value)))
16946 (when (and (stringp val)
16947 (get-char-property 0 'org-computed val))
16948 (error "This value is computed from the entry's children"))))
16950 (defun org-columns-todo (&optional arg)
16951 "Change the TODO state during column view."
16952 (interactive "P")
16953 (org-columns-edit-value "TODO"))
16955 (defun org-columns-set-tags-or-toggle (&optional arg)
16956 "Toggle checkbox at point, or set tags for current headline."
16957 (interactive "P")
16958 (if (string-match "\\`\\[[ xX-]\\]\\'"
16959 (get-char-property (point) 'org-columns-value))
16960 (org-columns-next-allowed-value)
16961 (org-columns-edit-value "TAGS")))
16963 (defun org-columns-edit-value (&optional key)
16964 "Edit the value of the property at point in column view.
16965 Where possible, use the standard interface for changing this line."
16966 (interactive)
16967 (org-columns-check-computed)
16968 (let* ((external-key key)
16969 (col (current-column))
16970 (key (or key (get-char-property (point) 'org-columns-key)))
16971 (value (get-char-property (point) 'org-columns-value))
16972 (bol (point-at-bol)) (eol (point-at-eol))
16973 (pom (or (get-text-property bol 'org-hd-marker)
16974 (point))) ; keep despite of compiler waring
16975 (line-overlays
16976 (delq nil (mapcar (lambda (x)
16977 (and (eq (overlay-buffer x) (current-buffer))
16978 (>= (overlay-start x) bol)
16979 (<= (overlay-start x) eol)
16981 org-columns-overlays)))
16982 nval eval allowed)
16983 (cond
16984 ((equal key "CLOCKSUM")
16985 (error "This special column cannot be edited"))
16986 ((equal key "ITEM")
16987 (setq eval '(org-with-point-at pom
16988 (org-edit-headline))))
16989 ((equal key "TODO")
16990 (setq eval '(org-with-point-at pom
16991 (let ((current-prefix-arg
16992 (if external-key current-prefix-arg '(4))))
16993 (call-interactively 'org-todo)))))
16994 ((equal key "PRIORITY")
16995 (setq eval '(org-with-point-at pom
16996 (call-interactively 'org-priority))))
16997 ((equal key "TAGS")
16998 (setq eval '(org-with-point-at pom
16999 (let ((org-fast-tag-selection-single-key
17000 (if (eq org-fast-tag-selection-single-key 'expert)
17001 t org-fast-tag-selection-single-key)))
17002 (call-interactively 'org-set-tags)))))
17003 ((equal key "DEADLINE")
17004 (setq eval '(org-with-point-at pom
17005 (call-interactively 'org-deadline))))
17006 ((equal key "SCHEDULED")
17007 (setq eval '(org-with-point-at pom
17008 (call-interactively 'org-schedule))))
17010 (setq allowed (org-property-get-allowed-values pom key 'table))
17011 (if allowed
17012 (setq nval (completing-read "Value: " allowed nil t))
17013 (setq nval (read-string "Edit: " value)))
17014 (setq nval (org-trim nval))
17015 (when (not (equal nval value))
17016 (setq eval '(org-entry-put pom key nval)))))
17017 (when eval
17018 (let ((inhibit-read-only t))
17019 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
17020 (unwind-protect
17021 (progn
17022 (setq org-columns-overlays
17023 (org-delete-all line-overlays org-columns-overlays))
17024 (mapc 'org-delete-overlay line-overlays)
17025 (org-columns-eval eval))
17026 (org-columns-display-here))))
17027 (move-to-column col)
17028 (if (and (org-mode-p)
17029 (nth 3 (assoc key org-columns-current-fmt-compiled)))
17030 (org-columns-update key))))
17032 (defun org-edit-headline () ; FIXME: this is not columns specific
17033 "Edit the current headline, the part without TODO keyword, TAGS."
17034 (org-back-to-heading)
17035 (when (looking-at org-todo-line-regexp)
17036 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
17037 (txt (match-string 3))
17038 (post "")
17039 txt2)
17040 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
17041 (setq post (match-string 0 txt)
17042 txt (substring txt 0 (match-beginning 0))))
17043 (setq txt2 (read-string "Edit: " txt))
17044 (when (not (equal txt txt2))
17045 (beginning-of-line 1)
17046 (insert pre txt2 post)
17047 (delete-region (point) (point-at-eol))
17048 (org-set-tags nil t)))))
17050 (defun org-columns-edit-allowed ()
17051 "Edit the list of allowed values for the current property."
17052 (interactive)
17053 (let* ((key (get-char-property (point) 'org-columns-key))
17054 (key1 (concat key "_ALL"))
17055 (allowed (org-entry-get (point) key1 t))
17056 nval)
17057 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
17058 (setq nval (read-string "Allowed: " allowed))
17059 (org-entry-put
17060 (cond ((marker-position org-entry-property-inherited-from)
17061 org-entry-property-inherited-from)
17062 ((marker-position org-columns-top-level-marker)
17063 org-columns-top-level-marker))
17064 key1 nval)))
17066 (defmacro org-no-warnings (&rest body)
17067 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
17069 (defun org-columns-eval (form)
17070 (let (hidep)
17071 (save-excursion
17072 (beginning-of-line 1)
17073 ;; `next-line' is needed here, because it skips invisible line.
17074 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
17075 (setq hidep (org-on-heading-p 1)))
17076 (eval form)
17077 (and hidep (hide-entry))))
17079 (defun org-columns-previous-allowed-value ()
17080 "Switch to the previous allowed value for this column."
17081 (interactive)
17082 (org-columns-next-allowed-value t))
17084 (defun org-columns-next-allowed-value (&optional previous)
17085 "Switch to the next allowed value for this column."
17086 (interactive)
17087 (org-columns-check-computed)
17088 (let* ((col (current-column))
17089 (key (get-char-property (point) 'org-columns-key))
17090 (value (get-char-property (point) 'org-columns-value))
17091 (bol (point-at-bol)) (eol (point-at-eol))
17092 (pom (or (get-text-property bol 'org-hd-marker)
17093 (point))) ; keep despite of compiler waring
17094 (line-overlays
17095 (delq nil (mapcar (lambda (x)
17096 (and (eq (overlay-buffer x) (current-buffer))
17097 (>= (overlay-start x) bol)
17098 (<= (overlay-start x) eol)
17100 org-columns-overlays)))
17101 (allowed (or (org-property-get-allowed-values pom key)
17102 (and (memq
17103 (nth 4 (assoc key org-columns-current-fmt-compiled))
17104 '(checkbox checkbox-n-of-m checkbox-percent))
17105 '("[ ]" "[X]"))))
17106 nval)
17107 (when (equal key "ITEM")
17108 (error "Cannot edit item headline from here"))
17109 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
17110 (error "Allowed values for this property have not been defined"))
17111 (if (member key '("SCHEDULED" "DEADLINE"))
17112 (setq nval (if previous 'earlier 'later))
17113 (if previous (setq allowed (reverse allowed)))
17114 (if (member value allowed)
17115 (setq nval (car (cdr (member value allowed)))))
17116 (setq nval (or nval (car allowed)))
17117 (if (equal nval value)
17118 (error "Only one allowed value for this property")))
17119 (let ((inhibit-read-only t))
17120 (remove-text-properties (1- bol) eol '(read-only t))
17121 (unwind-protect
17122 (progn
17123 (setq org-columns-overlays
17124 (org-delete-all line-overlays org-columns-overlays))
17125 (mapc 'org-delete-overlay line-overlays)
17126 (org-columns-eval '(org-entry-put pom key nval)))
17127 (org-columns-display-here)))
17128 (move-to-column col)
17129 (if (and (org-mode-p)
17130 (nth 3 (assoc key org-columns-current-fmt-compiled)))
17131 (org-columns-update key))))
17133 (defun org-verify-version (task)
17134 (cond
17135 ((eq task 'columns)
17136 (if (or (featurep 'xemacs)
17137 (< emacs-major-version 22))
17138 (error "Emacs 22 is required for the columns feature")))))
17140 (defun org-columns-open-link (&optional arg)
17141 (interactive "P")
17142 (let ((value (get-char-property (point) 'org-columns-value)))
17143 (org-open-link-from-string value arg)))
17145 (defun org-open-link-from-string (s &optional arg)
17146 "Open a link in the string S, as if it was in Org-mode."
17147 (interactive)
17148 (with-temp-buffer
17149 (let ((org-inhibit-startup t))
17150 (org-mode)
17151 (insert s)
17152 (goto-char (point-min))
17153 (org-open-at-point arg))))
17155 (defun org-columns-get-format-and-top-level ()
17156 (let (fmt)
17157 (when (condition-case nil (org-back-to-heading) (error nil))
17158 (move-marker org-entry-property-inherited-from nil)
17159 (setq fmt (org-entry-get nil "COLUMNS" t)))
17160 (setq fmt (or fmt org-columns-default-format))
17161 (org-set-local 'org-columns-current-fmt fmt)
17162 (org-columns-compile-format fmt)
17163 (if (marker-position org-entry-property-inherited-from)
17164 (move-marker org-columns-top-level-marker
17165 org-entry-property-inherited-from)
17166 (move-marker org-columns-top-level-marker (point)))
17167 fmt))
17169 (defun org-columns ()
17170 "Turn on column view on an org-mode file."
17171 (interactive)
17172 (org-verify-version 'columns)
17173 (org-columns-remove-overlays)
17174 (move-marker org-columns-begin-marker (point))
17175 (let (beg end fmt cache maxwidths)
17176 (setq fmt (org-columns-get-format-and-top-level))
17177 (save-excursion
17178 (goto-char org-columns-top-level-marker)
17179 (setq beg (point))
17180 (unless org-columns-inhibit-recalculation
17181 (org-columns-compute-all))
17182 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
17183 (point-max)))
17184 ;; Get and cache the properties
17185 (goto-char beg)
17186 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
17187 (save-excursion
17188 (save-restriction
17189 (narrow-to-region beg end)
17190 (org-clock-sum))))
17191 (while (re-search-forward (concat "^" outline-regexp) end t)
17192 (push (cons (org-current-line) (org-entry-properties)) cache))
17193 (when cache
17194 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17195 (org-set-local 'org-columns-current-maxwidths maxwidths)
17196 (org-columns-display-here-title)
17197 (mapc (lambda (x)
17198 (goto-line (car x))
17199 (org-columns-display-here (cdr x)))
17200 cache)))))
17202 (defun org-columns-new (&optional prop title width op fmt &rest rest)
17203 "Insert a new column, to the leeft o the current column."
17204 (interactive)
17205 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
17206 cell)
17207 (setq prop (completing-read
17208 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
17209 nil nil prop))
17210 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
17211 (setq width (read-string "Column width: " (if width (number-to-string width))))
17212 (if (string-match "\\S-" width)
17213 (setq width (string-to-number width))
17214 (setq width nil))
17215 (setq fmt (completing-read "Summary [none]: "
17216 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
17217 nil t))
17218 (if (string-match "\\S-" fmt)
17219 (setq fmt (intern fmt))
17220 (setq fmt nil))
17221 (if (eq fmt 'none) (setq fmt nil))
17222 (if editp
17223 (progn
17224 (setcar editp prop)
17225 (setcdr editp (list title width nil fmt)))
17226 (setq cell (nthcdr (1- (current-column))
17227 org-columns-current-fmt-compiled))
17228 (setcdr cell (cons (list prop title width nil fmt)
17229 (cdr cell))))
17230 (org-columns-store-format)
17231 (org-columns-redo)))
17233 (defun org-columns-delete ()
17234 "Delete the column at point from columns view."
17235 (interactive)
17236 (let* ((n (current-column))
17237 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
17238 (when (y-or-n-p
17239 (format "Are you sure you want to remove column \"%s\"? " title))
17240 (setq org-columns-current-fmt-compiled
17241 (delq (nth n org-columns-current-fmt-compiled)
17242 org-columns-current-fmt-compiled))
17243 (org-columns-store-format)
17244 (org-columns-redo)
17245 (if (>= (current-column) (length org-columns-current-fmt-compiled))
17246 (backward-char 1)))))
17248 (defun org-columns-edit-attributes ()
17249 "Edit the attributes of the current column."
17250 (interactive)
17251 (let* ((n (current-column))
17252 (info (nth n org-columns-current-fmt-compiled)))
17253 (apply 'org-columns-new info)))
17255 (defun org-columns-widen (arg)
17256 "Make the column wider by ARG characters."
17257 (interactive "p")
17258 (let* ((n (current-column))
17259 (entry (nth n org-columns-current-fmt-compiled))
17260 (width (or (nth 2 entry)
17261 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
17262 (setq width (max 1 (+ width arg)))
17263 (setcar (nthcdr 2 entry) width)
17264 (org-columns-store-format)
17265 (org-columns-redo)))
17267 (defun org-columns-narrow (arg)
17268 "Make the column nrrower by ARG characters."
17269 (interactive "p")
17270 (org-columns-widen (- arg)))
17272 (defun org-columns-move-right ()
17273 "Swap this column with the one to the right."
17274 (interactive)
17275 (let* ((n (current-column))
17276 (cell (nthcdr n org-columns-current-fmt-compiled))
17278 (when (>= n (1- (length org-columns-current-fmt-compiled)))
17279 (error "Cannot shift this column further to the right"))
17280 (setq e (car cell))
17281 (setcar cell (car (cdr cell)))
17282 (setcdr cell (cons e (cdr (cdr cell))))
17283 (org-columns-store-format)
17284 (org-columns-redo)
17285 (forward-char 1)))
17287 (defun org-columns-move-left ()
17288 "Swap this column with the one to the left."
17289 (interactive)
17290 (let* ((n (current-column)))
17291 (when (= n 0)
17292 (error "Cannot shift this column further to the left"))
17293 (backward-char 1)
17294 (org-columns-move-right)
17295 (backward-char 1)))
17297 (defun org-columns-store-format ()
17298 "Store the text version of the current columns format in appropriate place.
17299 This is either in the COLUMNS property of the node starting the current column
17300 display, or in the #+COLUMNS line of the current buffer."
17301 (let (fmt (cnt 0))
17302 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17303 (org-set-local 'org-columns-current-fmt fmt)
17304 (if (marker-position org-columns-top-level-marker)
17305 (save-excursion
17306 (goto-char org-columns-top-level-marker)
17307 (if (and (org-at-heading-p)
17308 (org-entry-get nil "COLUMNS"))
17309 (org-entry-put nil "COLUMNS" fmt)
17310 (goto-char (point-min))
17311 ;; Overwrite all #+COLUMNS lines....
17312 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17313 (setq cnt (1+ cnt))
17314 (replace-match (concat "#+COLUMNS: " fmt) t t))
17315 (unless (> cnt 0)
17316 (goto-char (point-min))
17317 (or (org-on-heading-p t) (outline-next-heading))
17318 (let ((inhibit-read-only t))
17319 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17320 (org-set-local 'org-columns-default-format fmt))))))
17322 (defvar org-overriding-columns-format nil
17323 "When set, overrides any other definition.")
17324 (defvar org-agenda-view-columns-initially nil
17325 "When set, switch to columns view immediately after creating the agenda.")
17327 (defun org-agenda-columns ()
17328 "Turn on column view in the agenda."
17329 (interactive)
17330 (org-verify-version 'columns)
17331 (org-columns-remove-overlays)
17332 (move-marker org-columns-begin-marker (point))
17333 (let (fmt cache maxwidths m)
17334 (cond
17335 ((and (local-variable-p 'org-overriding-columns-format)
17336 org-overriding-columns-format)
17337 (setq fmt org-overriding-columns-format))
17338 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17339 (setq fmt (org-entry-get m "COLUMNS" t)))
17340 ((and (boundp 'org-columns-current-fmt)
17341 (local-variable-p 'org-columns-current-fmt)
17342 org-columns-current-fmt)
17343 (setq fmt org-columns-current-fmt))
17344 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17345 (setq m (get-text-property m 'org-hd-marker))
17346 (setq fmt (org-entry-get m "COLUMNS" t))))
17347 (setq fmt (or fmt org-columns-default-format))
17348 (org-set-local 'org-columns-current-fmt fmt)
17349 (org-columns-compile-format fmt)
17350 (save-excursion
17351 ;; Get and cache the properties
17352 (goto-char (point-min))
17353 (while (not (eobp))
17354 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17355 (get-text-property (point) 'org-marker)))
17356 (push (cons (org-current-line) (org-entry-properties m)) cache))
17357 (beginning-of-line 2))
17358 (when cache
17359 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17360 (org-set-local 'org-columns-current-maxwidths maxwidths)
17361 (org-columns-display-here-title)
17362 (mapc (lambda (x)
17363 (goto-line (car x))
17364 (org-columns-display-here (cdr x)))
17365 cache)))))
17367 (defun org-columns-get-autowidth-alist (s cache)
17368 "Derive the maximum column widths from the format and the cache."
17369 (let ((start 0) rtn)
17370 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17371 (push (cons (match-string 1 s) 1) rtn)
17372 (setq start (match-end 0)))
17373 (mapc (lambda (x)
17374 (setcdr x (apply 'max
17375 (mapcar
17376 (lambda (y)
17377 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17378 cache))))
17379 rtn)
17380 rtn))
17382 (defun org-columns-compute-all ()
17383 "Compute all columns that have operators defined."
17384 (org-unmodified
17385 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17386 (let ((columns org-columns-current-fmt-compiled) col)
17387 (while (setq col (pop columns))
17388 (when (nth 3 col)
17389 (save-excursion
17390 (org-columns-compute (car col)))))))
17392 (defun org-columns-update (property)
17393 "Recompute PROPERTY, and update the columns display for it."
17394 (org-columns-compute property)
17395 (let (fmt val pos)
17396 (save-excursion
17397 (mapc (lambda (ov)
17398 (when (equal (org-overlay-get ov 'org-columns-key) property)
17399 (setq pos (org-overlay-start ov))
17400 (goto-char pos)
17401 (when (setq val (cdr (assoc property
17402 (get-text-property
17403 (point-at-bol) 'org-summaries))))
17404 (setq fmt (org-overlay-get ov 'org-columns-format))
17405 (org-overlay-put ov 'org-columns-value val)
17406 (org-overlay-put ov 'display (format fmt val)))))
17407 org-columns-overlays))))
17409 (defun org-columns-compute (property)
17410 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17411 (interactive)
17412 (let* ((re (concat "^" outline-regexp))
17413 (lmax 30) ; Does anyone use deeper levels???
17414 (lsum (make-vector lmax 0))
17415 (lflag (make-vector lmax nil))
17416 (level 0)
17417 (ass (assoc property org-columns-current-fmt-compiled))
17418 (format (nth 4 ass))
17419 (printf (nth 5 ass))
17420 (beg org-columns-top-level-marker)
17421 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17422 (save-excursion
17423 ;; Find the region to compute
17424 (goto-char beg)
17425 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17426 (goto-char end)
17427 ;; Walk the tree from the back and do the computations
17428 (while (re-search-backward re beg t)
17429 (setq sumpos (match-beginning 0)
17430 last-level level
17431 level (org-outline-level)
17432 val (org-entry-get nil property)
17433 valflag (and val (string-match "\\S-" val)))
17434 (cond
17435 ((< level last-level)
17436 ;; put the sum of lower levels here as a property
17437 (setq sum (aref lsum last-level) ; current sum
17438 flag (aref lflag last-level) ; any valid entries from children?
17439 str (org-column-number-to-string sum format printf)
17440 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17441 useval (if flag str1 (if valflag val ""))
17442 sum-alist (get-text-property sumpos 'org-summaries))
17443 (if (assoc property sum-alist)
17444 (setcdr (assoc property sum-alist) useval)
17445 (push (cons property useval) sum-alist)
17446 (org-unmodified
17447 (add-text-properties sumpos (1+ sumpos)
17448 (list 'org-summaries sum-alist))))
17449 (when val
17450 (org-entry-put nil property (if flag str val)))
17451 ;; add current to current level accumulator
17452 (when (or flag valflag)
17453 (aset lsum level (+ (aref lsum level)
17454 (if flag sum (org-column-string-to-number
17455 (if flag str val) format))))
17456 (aset lflag level t))
17457 ;; clear accumulators for deeper levels
17458 (loop for l from (1+ level) to (1- lmax) do
17459 (aset lsum l 0)
17460 (aset lflag l nil)))
17461 ((>= level last-level)
17462 ;; add what we have here to the accumulator for this level
17463 (aset lsum level (+ (aref lsum level)
17464 (org-column-string-to-number (or val "0") format)))
17465 (and valflag (aset lflag level t)))
17466 (t (error "This should not happen")))))))
17468 (defun org-columns-redo ()
17469 "Construct the column display again."
17470 (interactive)
17471 (message "Recomputing columns...")
17472 (save-excursion
17473 (if (marker-position org-columns-begin-marker)
17474 (goto-char org-columns-begin-marker))
17475 (org-columns-remove-overlays)
17476 (if (org-mode-p)
17477 (call-interactively 'org-columns)
17478 (call-interactively 'org-agenda-columns)))
17479 (message "Recomputing columns...done"))
17481 (defun org-columns-not-in-agenda ()
17482 (if (eq major-mode 'org-agenda-mode)
17483 (error "This command is only allowed in Org-mode buffers")))
17486 (defun org-string-to-number (s)
17487 "Convert string to number, and interpret hh:mm:ss."
17488 (if (not (string-match ":" s))
17489 (string-to-number s)
17490 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17491 (while l
17492 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17493 sum)))
17495 (defun org-column-number-to-string (n fmt &optional printf)
17496 "Convert a computed column number to a string value, according to FMT."
17497 (cond
17498 ((eq fmt 'add_times)
17499 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17500 (format "%d:%02d" h m)))
17501 ((eq fmt 'checkbox)
17502 (cond ((= n (floor n)) "[X]")
17503 ((> n 1.) "[-]")
17504 (t "[ ]")))
17505 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17506 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17507 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17508 (printf (format printf n))
17509 ((eq fmt 'currency)
17510 (format "%.2f" n))
17511 (t (number-to-string n))))
17513 (defun org-nofm-to-completion (n m &optional percent)
17514 (if (not percent)
17515 (format "[%d/%d]" n m)
17516 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17518 (defun org-column-string-to-number (s fmt)
17519 "Convert a column value to a number that can be used for column computing."
17520 (cond
17521 ((string-match ":" s)
17522 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17523 (while l
17524 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17525 sum))
17526 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17527 (if (equal s "[X]") 1. 0.000001))
17528 (t (string-to-number s))))
17530 (defun org-columns-uncompile-format (cfmt)
17531 "Turn the compiled columns format back into a string representation."
17532 (let ((rtn "") e s prop title op width fmt printf)
17533 (while (setq e (pop cfmt))
17534 (setq prop (car e)
17535 title (nth 1 e)
17536 width (nth 2 e)
17537 op (nth 3 e)
17538 fmt (nth 4 e)
17539 printf (nth 5 e))
17540 (cond
17541 ((eq fmt 'add_times) (setq op ":"))
17542 ((eq fmt 'checkbox) (setq op "X"))
17543 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17544 ((eq fmt 'checkbox-percent) (setq op "X%"))
17545 ((eq fmt 'add_numbers) (setq op "+"))
17546 ((eq fmt 'currency) (setq op "$")))
17547 (if (and op printf) (setq op (concat op ";" printf)))
17548 (if (equal title prop) (setq title nil))
17549 (setq s (concat "%" (if width (number-to-string width))
17550 prop
17551 (if title (concat "(" title ")"))
17552 (if op (concat "{" op "}"))))
17553 (setq rtn (concat rtn " " s)))
17554 (org-trim rtn)))
17556 (defun org-columns-compile-format (fmt)
17557 "Turn a column format string into an alist of specifications.
17558 The alist has one entry for each column in the format. The elements of
17559 that list are:
17560 property the property
17561 title the title field for the columns
17562 width the column width in characters, can be nil for automatic
17563 operator the operator if any
17564 format the output format for computed results, derived from operator
17565 printf a printf format for computed values"
17566 (let ((start 0) width prop title op f printf)
17567 (setq org-columns-current-fmt-compiled nil)
17568 (while (string-match
17569 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17570 fmt start)
17571 (setq start (match-end 0)
17572 width (match-string 1 fmt)
17573 prop (match-string 2 fmt)
17574 title (or (match-string 3 fmt) prop)
17575 op (match-string 4 fmt)
17576 f nil
17577 printf nil)
17578 (if width (setq width (string-to-number width)))
17579 (when (and op (string-match ";" op))
17580 (setq printf (substring op (match-end 0))
17581 op (substring op 0 (match-beginning 0))))
17582 (cond
17583 ((equal op "+") (setq f 'add_numbers))
17584 ((equal op "$") (setq f 'currency))
17585 ((equal op ":") (setq f 'add_times))
17586 ((equal op "X") (setq f 'checkbox))
17587 ((equal op "X/") (setq f 'checkbox-n-of-m))
17588 ((equal op "X%") (setq f 'checkbox-percent))
17590 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17591 (setq org-columns-current-fmt-compiled
17592 (nreverse org-columns-current-fmt-compiled))))
17595 ;;; Dynamic block for Column view
17597 (defun org-columns-capture-view (&optional maxlevel skip-empty-rows)
17598 "Get the column view of the current buffer or subtree.
17599 The first optional argument MAXLEVEL sets the level limit. A
17600 second optional argument SKIP-EMPTY-ROWS tells whether to skip
17601 empty rows, an empty row being one where all the column view
17602 specifiers except ITEM are empty. This function returns a list
17603 containing the title row and all other rows. Each row is a list
17604 of fields."
17605 (save-excursion
17606 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17607 (n (length title)) row tbl)
17608 (goto-char (point-min))
17609 (while (and (re-search-forward "^\\(\\*+\\) " nil t)
17610 (or (null maxlevel)
17611 (>= maxlevel
17612 (if org-odd-levels-only
17613 (/ (1+ (length (match-string 1))) 2)
17614 (length (match-string 1))))))
17615 (when (get-char-property (match-beginning 0) 'org-columns-key)
17616 (setq row nil)
17617 (loop for i from 0 to (1- n) do
17618 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17619 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17621 row))
17622 (setq row (nreverse row))
17623 (unless (and skip-empty-rows
17624 (eq 1 (length (delete "" (delete-dups row)))))
17625 (push row tbl))))
17626 (append (list title 'hline) (nreverse tbl)))))
17628 (defun org-dblock-write:columnview (params)
17629 "Write the column view table.
17630 PARAMS is a property list of parameters:
17632 :width enforce same column widths with <N> specifiers.
17633 :id the :ID: property of the entry where the columns view
17634 should be built, as a string. When `local', call locally.
17635 When `global' call column view with the cursor at the beginning
17636 of the buffer (usually this means that the whole buffer switches
17637 to column view).
17638 :hlines When t, insert a hline before each item. When a number, insert
17639 a hline before each level <= that number.
17640 :vlines When t, make each column a colgroup to enforce vertical lines.
17641 :maxlevel When set to a number, don't capture headlines below this level.
17642 :skip-empty-rows
17643 When t, skip rows where all specifiers other than ITEM are empty."
17644 (let ((pos (move-marker (make-marker) (point)))
17645 (hlines (plist-get params :hlines))
17646 (vlines (plist-get params :vlines))
17647 (maxlevel (plist-get params :maxlevel))
17648 (skip-empty-rows (plist-get params :skip-empty-rows))
17649 tbl id idpos nfields tmp)
17650 (save-excursion
17651 (save-restriction
17652 (when (setq id (plist-get params :id))
17653 (cond ((not id) nil)
17654 ((eq id 'global) (goto-char (point-min)))
17655 ((eq id 'local) nil)
17656 ((setq idpos (org-find-entry-with-id id))
17657 (goto-char idpos))
17658 (t (error "Cannot find entry with :ID: %s" id))))
17659 (org-columns)
17660 (setq tbl (org-columns-capture-view maxlevel skip-empty-rows))
17661 (setq nfields (length (car tbl)))
17662 (org-columns-quit)))
17663 (goto-char pos)
17664 (move-marker pos nil)
17665 (when tbl
17666 (when (plist-get params :hlines)
17667 (setq tmp nil)
17668 (while tbl
17669 (if (eq (car tbl) 'hline)
17670 (push (pop tbl) tmp)
17671 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17672 (if (and (not (eq (car tmp) 'hline))
17673 (or (eq hlines t)
17674 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17675 (push 'hline tmp)))
17676 (push (pop tbl) tmp)))
17677 (setq tbl (nreverse tmp)))
17678 (when vlines
17679 (setq tbl (mapcar (lambda (x)
17680 (if (eq 'hline x) x (cons "" x)))
17681 tbl))
17682 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17683 (setq pos (point))
17684 (insert (org-listtable-to-string tbl))
17685 (when (plist-get params :width)
17686 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17687 org-columns-current-widths "|")))
17688 (goto-char pos)
17689 (org-table-align))))
17691 (defun org-listtable-to-string (tbl)
17692 "Convert a listtable TBL to a string that contains the Org-mode table.
17693 The table still need to be alligned. The resulting string has no leading
17694 and tailing newline characters."
17695 (mapconcat
17696 (lambda (x)
17697 (cond
17698 ((listp x)
17699 (concat "|" (mapconcat 'identity x "|") "|"))
17700 ((eq x 'hline) "|-|")
17701 (t (error "Garbage in listtable: %s" x))))
17702 tbl "\n"))
17704 (defun org-insert-columns-dblock ()
17705 "Create a dynamic block capturing a column view table."
17706 (interactive)
17707 (let ((defaults '(:name "columnview" :hlines 1))
17708 (id (completing-read
17709 "Capture columns (local, global, entry with :ID: property) [local]: "
17710 (append '(("global") ("local"))
17711 (mapcar 'list (org-property-values "ID"))))))
17712 (if (equal id "") (setq id 'local))
17713 (if (equal id "global") (setq id 'global))
17714 (setq defaults (append defaults (list :id id)))
17715 (org-create-dblock defaults)
17716 (org-update-dblock)))
17718 ;;;; Timestamps
17720 (defvar org-last-changed-timestamp nil)
17721 (defvar org-time-was-given) ; dynamically scoped parameter
17722 (defvar org-end-time-was-given) ; dynamically scoped parameter
17723 (defvar org-ts-what) ; dynamically scoped parameter
17725 (defun org-time-stamp (arg)
17726 "Prompt for a date/time and insert a time stamp.
17727 If the user specifies a time like HH:MM, or if this command is called
17728 with a prefix argument, the time stamp will contain date and time.
17729 Otherwise, only the date will be included. All parts of a date not
17730 specified by the user will be filled in from the current date/time.
17731 So if you press just return without typing anything, the time stamp
17732 will represent the current date/time. If there is already a timestamp
17733 at the cursor, it will be modified."
17734 (interactive "P")
17735 (let* ((ts nil)
17736 (default-time
17737 ;; Default time is either today, or, when entering a range,
17738 ;; the range start.
17739 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17740 (save-excursion
17741 (re-search-backward
17742 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17743 (- (point) 20) t)))
17744 (apply 'encode-time (org-parse-time-string (match-string 1)))
17745 (current-time)))
17746 (default-input (and ts (org-get-compact-tod ts)))
17747 org-time-was-given org-end-time-was-given time)
17748 (cond
17749 ((and (org-at-timestamp-p)
17750 (eq last-command 'org-time-stamp)
17751 (eq this-command 'org-time-stamp))
17752 (insert "--")
17753 (setq time (let ((this-command this-command))
17754 (org-read-date arg 'totime nil nil default-time default-input)))
17755 (org-insert-time-stamp time (or org-time-was-given arg)))
17756 ((org-at-timestamp-p)
17757 (setq time (let ((this-command this-command))
17758 (org-read-date arg 'totime nil nil default-time default-input)))
17759 (when (org-at-timestamp-p) ; just to get the match data
17760 (replace-match "")
17761 (setq org-last-changed-timestamp
17762 (org-insert-time-stamp
17763 time (or org-time-was-given arg)
17764 nil nil nil (list org-end-time-was-given))))
17765 (message "Timestamp updated"))
17767 (setq time (let ((this-command this-command))
17768 (org-read-date arg 'totime nil nil default-time default-input)))
17769 (org-insert-time-stamp time (or org-time-was-given arg)
17770 nil nil nil (list org-end-time-was-given))))))
17772 ;; FIXME: can we use this for something else????
17773 ;; like computing time differences?????
17774 (defun org-get-compact-tod (s)
17775 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17776 (let* ((t1 (match-string 1 s))
17777 (h1 (string-to-number (match-string 2 s)))
17778 (m1 (string-to-number (match-string 3 s)))
17779 (t2 (and (match-end 4) (match-string 5 s)))
17780 (h2 (and t2 (string-to-number (match-string 6 s))))
17781 (m2 (and t2 (string-to-number (match-string 7 s))))
17782 dh dm)
17783 (if (not t2)
17785 (setq dh (- h2 h1) dm (- m2 m1))
17786 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17787 (concat t1 "+" (number-to-string dh)
17788 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17790 (defun org-time-stamp-inactive (&optional arg)
17791 "Insert an inactive time stamp.
17792 An inactive time stamp is enclosed in square brackets instead of angle
17793 brackets. It is inactive in the sense that it does not trigger agenda entries,
17794 does not link to the calendar and cannot be changed with the S-cursor keys.
17795 So these are more for recording a certain time/date."
17796 (interactive "P")
17797 (let (org-time-was-given org-end-time-was-given time)
17798 (setq time (org-read-date arg 'totime))
17799 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17800 nil nil (list org-end-time-was-given))))
17802 (defvar org-date-ovl (org-make-overlay 1 1))
17803 (org-overlay-put org-date-ovl 'face 'org-warning)
17804 (org-detach-overlay org-date-ovl)
17806 (defvar org-ans1) ; dynamically scoped parameter
17807 (defvar org-ans2) ; dynamically scoped parameter
17809 (defvar org-plain-time-of-day-regexp) ; defined below
17811 (defvar org-read-date-overlay nil)
17812 (defvar org-dcst nil) ; dynamically scoped
17814 (defun org-read-date (&optional with-time to-time from-string prompt
17815 default-time default-input)
17816 "Read a date, possibly a time, and make things smooth for the user.
17817 The prompt will suggest to enter an ISO date, but you can also enter anything
17818 which will at least partially be understood by `parse-time-string'.
17819 Unrecognized parts of the date will default to the current day, month, year,
17820 hour and minute. If this command is called to replace a timestamp at point,
17821 of to enter the second timestamp of a range, the default time is taken from the
17822 existing stamp. For example,
17823 3-2-5 --> 2003-02-05
17824 feb 15 --> currentyear-02-15
17825 sep 12 9 --> 2009-09-12
17826 12:45 --> today 12:45
17827 22 sept 0:34 --> currentyear-09-22 0:34
17828 12 --> currentyear-currentmonth-12
17829 Fri --> nearest Friday (today or later)
17830 etc.
17832 Furthermore you can specify a relative date by giving, as the *first* thing
17833 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17834 change in days weeks, months, years.
17835 With a single plus or minus, the date is relative to today. With a double
17836 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17837 +4d --> four days from today
17838 +4 --> same as above
17839 +2w --> two weeks from today
17840 ++5 --> five days from default date
17842 The function understands only English month and weekday abbreviations,
17843 but this can be configured with the variables `parse-time-months' and
17844 `parse-time-weekdays'.
17846 While prompting, a calendar is popped up - you can also select the
17847 date with the mouse (button 1). The calendar shows a period of three
17848 months. To scroll it to other months, use the keys `>' and `<'.
17849 If you don't like the calendar, turn it off with
17850 \(setq org-read-date-popup-calendar nil)
17852 With optional argument TO-TIME, the date will immediately be converted
17853 to an internal time.
17854 With an optional argument WITH-TIME, the prompt will suggest to also
17855 insert a time. Note that when WITH-TIME is not set, you can still
17856 enter a time, and this function will inform the calling routine about
17857 this change. The calling routine may then choose to change the format
17858 used to insert the time stamp into the buffer to include the time.
17859 With optional argument FROM-STRING, read from this string instead from
17860 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17861 the time/date that is used for everything that is not specified by the
17862 user."
17863 (require 'parse-time)
17864 (let* ((org-time-stamp-rounding-minutes
17865 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
17866 (org-dcst org-display-custom-times)
17867 (ct (org-current-time))
17868 (def (or default-time ct))
17869 (defdecode (decode-time def))
17870 (dummy (progn
17871 (when (< (nth 2 defdecode) org-extend-today-until)
17872 (setcar (nthcdr 2 defdecode) -1)
17873 (setcar (nthcdr 1 defdecode) 59)
17874 (setq def (apply 'encode-time defdecode)
17875 defdecode (decode-time def)))))
17876 (calendar-move-hook nil)
17877 (view-diary-entries-initially nil)
17878 (view-calendar-holidays-initially nil)
17879 (timestr (format-time-string
17880 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17881 (prompt (concat (if prompt (concat prompt " ") "")
17882 (format "Date+time [%s]: " timestr)))
17883 ans (org-ans0 "") org-ans1 org-ans2 final)
17885 (cond
17886 (from-string (setq ans from-string))
17887 (org-read-date-popup-calendar
17888 (save-excursion
17889 (save-window-excursion
17890 (calendar)
17891 (calendar-forward-day (- (time-to-days def)
17892 (calendar-absolute-from-gregorian
17893 (calendar-current-date))))
17894 (org-eval-in-calendar nil t)
17895 (let* ((old-map (current-local-map))
17896 (map (copy-keymap calendar-mode-map))
17897 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17898 (org-defkey map (kbd "RET") 'org-calendar-select)
17899 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17900 'org-calendar-select-mouse)
17901 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17902 'org-calendar-select-mouse)
17903 (org-defkey minibuffer-local-map [(meta shift left)]
17904 (lambda () (interactive)
17905 (org-eval-in-calendar '(calendar-backward-month 1))))
17906 (org-defkey minibuffer-local-map [(meta shift right)]
17907 (lambda () (interactive)
17908 (org-eval-in-calendar '(calendar-forward-month 1))))
17909 (org-defkey minibuffer-local-map [(meta shift up)]
17910 (lambda () (interactive)
17911 (org-eval-in-calendar '(calendar-backward-year 1))))
17912 (org-defkey minibuffer-local-map [(meta shift down)]
17913 (lambda () (interactive)
17914 (org-eval-in-calendar '(calendar-forward-year 1))))
17915 (org-defkey minibuffer-local-map [(shift up)]
17916 (lambda () (interactive)
17917 (org-eval-in-calendar '(calendar-backward-week 1))))
17918 (org-defkey minibuffer-local-map [(shift down)]
17919 (lambda () (interactive)
17920 (org-eval-in-calendar '(calendar-forward-week 1))))
17921 (org-defkey minibuffer-local-map [(shift left)]
17922 (lambda () (interactive)
17923 (org-eval-in-calendar '(calendar-backward-day 1))))
17924 (org-defkey minibuffer-local-map [(shift right)]
17925 (lambda () (interactive)
17926 (org-eval-in-calendar '(calendar-forward-day 1))))
17927 (org-defkey minibuffer-local-map ">"
17928 (lambda () (interactive)
17929 (org-eval-in-calendar '(scroll-calendar-left 1))))
17930 (org-defkey minibuffer-local-map "<"
17931 (lambda () (interactive)
17932 (org-eval-in-calendar '(scroll-calendar-right 1))))
17933 (unwind-protect
17934 (progn
17935 (use-local-map map)
17936 (add-hook 'post-command-hook 'org-read-date-display)
17937 (setq org-ans0 (read-string prompt default-input nil nil))
17938 ;; org-ans0: from prompt
17939 ;; org-ans1: from mouse click
17940 ;; org-ans2: from calendar motion
17941 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17942 (remove-hook 'post-command-hook 'org-read-date-display)
17943 (use-local-map old-map)
17944 (when org-read-date-overlay
17945 (org-delete-overlay org-read-date-overlay)
17946 (setq org-read-date-overlay nil)))))))
17948 (t ; Naked prompt only
17949 (unwind-protect
17950 (setq ans (read-string prompt default-input nil timestr))
17951 (when org-read-date-overlay
17952 (org-delete-overlay org-read-date-overlay)
17953 (setq org-read-date-overlay nil)))))
17955 (setq final (org-read-date-analyze ans def defdecode))
17957 (if to-time
17958 (apply 'encode-time final)
17959 (if (and (boundp 'org-time-was-given) org-time-was-given)
17960 (format "%04d-%02d-%02d %02d:%02d"
17961 (nth 5 final) (nth 4 final) (nth 3 final)
17962 (nth 2 final) (nth 1 final))
17963 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17964 (defvar def)
17965 (defvar defdecode)
17966 (defvar with-time)
17967 (defun org-read-date-display ()
17968 "Display the currrent date prompt interpretation in the minibuffer."
17969 (when org-read-date-display-live
17970 (when org-read-date-overlay
17971 (org-delete-overlay org-read-date-overlay))
17972 (let ((p (point)))
17973 (end-of-line 1)
17974 (while (not (equal (buffer-substring
17975 (max (point-min) (- (point) 4)) (point))
17976 " "))
17977 (insert " "))
17978 (goto-char p))
17979 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17980 " " (or org-ans1 org-ans2)))
17981 (org-end-time-was-given nil)
17982 (f (org-read-date-analyze ans def defdecode))
17983 (fmts (if org-dcst
17984 org-time-stamp-custom-formats
17985 org-time-stamp-formats))
17986 (fmt (if (or with-time
17987 (and (boundp 'org-time-was-given) org-time-was-given))
17988 (cdr fmts)
17989 (car fmts)))
17990 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17991 (when (and org-end-time-was-given
17992 (string-match org-plain-time-of-day-regexp txt))
17993 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17994 org-end-time-was-given
17995 (substring txt (match-end 0)))))
17996 (setq org-read-date-overlay
17997 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17998 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
18000 (defun org-read-date-analyze (ans def defdecode)
18001 "Analyze the combined answer of the date prompt."
18002 ;; FIXME: cleanup and comment
18003 (let (delta deltan deltaw deltadef year month day
18004 hour minute second wday pm h2 m2 tl wday1)
18006 (when (setq delta (org-read-date-get-relative ans (current-time) def))
18007 (setq ans (replace-match "" t t ans)
18008 deltan (car delta)
18009 deltaw (nth 1 delta)
18010 deltadef (nth 2 delta)))
18012 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
18013 (when (string-match
18014 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
18015 (setq year (if (match-end 2)
18016 (string-to-number (match-string 2 ans))
18017 (string-to-number (format-time-string "%Y")))
18018 month (string-to-number (match-string 3 ans))
18019 day (string-to-number (match-string 4 ans)))
18020 (if (< year 100) (setq year (+ 2000 year)))
18021 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
18022 t nil ans)))
18023 ;; Help matching am/pm times, because `parse-time-string' does not do that.
18024 ;; If there is a time with am/pm, and *no* time without it, we convert
18025 ;; so that matching will be successful.
18026 (loop for i from 1 to 2 do ; twice, for end time as well
18027 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
18028 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
18029 (setq hour (string-to-number (match-string 1 ans))
18030 minute (if (match-end 3)
18031 (string-to-number (match-string 3 ans))
18033 pm (equal ?p
18034 (string-to-char (downcase (match-string 4 ans)))))
18035 (if (and (= hour 12) (not pm))
18036 (setq hour 0)
18037 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
18038 (setq ans (replace-match (format "%02d:%02d" hour minute)
18039 t t ans))))
18041 ;; Check if a time range is given as a duration
18042 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
18043 (setq hour (string-to-number (match-string 1 ans))
18044 h2 (+ hour (string-to-number (match-string 3 ans)))
18045 minute (string-to-number (match-string 2 ans))
18046 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
18047 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
18048 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
18050 ;; Check if there is a time range
18051 (when (boundp 'org-end-time-was-given)
18052 (setq org-time-was-given nil)
18053 (when (and (string-match org-plain-time-of-day-regexp ans)
18054 (match-end 8))
18055 (setq org-end-time-was-given (match-string 8 ans))
18056 (setq ans (concat (substring ans 0 (match-beginning 7))
18057 (substring ans (match-end 7))))))
18059 (setq tl (parse-time-string ans)
18060 day (or (nth 3 tl) (nth 3 defdecode))
18061 month (or (nth 4 tl)
18062 (if (and org-read-date-prefer-future
18063 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
18064 (1+ (nth 4 defdecode))
18065 (nth 4 defdecode)))
18066 year (or (nth 5 tl)
18067 (if (and org-read-date-prefer-future
18068 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
18069 (1+ (nth 5 defdecode))
18070 (nth 5 defdecode)))
18071 hour (or (nth 2 tl) (nth 2 defdecode))
18072 minute (or (nth 1 tl) (nth 1 defdecode))
18073 second (or (nth 0 tl) 0)
18074 wday (nth 6 tl))
18075 (when deltan
18076 (unless deltadef
18077 (let ((now (decode-time (current-time))))
18078 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
18079 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
18080 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
18081 ((equal deltaw "m") (setq month (+ month deltan)))
18082 ((equal deltaw "y") (setq year (+ year deltan)))))
18083 (when (and wday (not (nth 3 tl)))
18084 ;; Weekday was given, but no day, so pick that day in the week
18085 ;; on or after the derived date.
18086 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
18087 (unless (equal wday wday1)
18088 (setq day (+ day (% (- wday wday1 -7) 7)))))
18089 (if (and (boundp 'org-time-was-given)
18090 (nth 2 tl))
18091 (setq org-time-was-given t))
18092 (if (< year 100) (setq year (+ 2000 year)))
18093 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
18094 (list second minute hour day month year)))
18096 (defvar parse-time-weekdays)
18098 (defun org-read-date-get-relative (s today default)
18099 "Check string S for special relative date string.
18100 TODAY and DEFAULT are internal times, for today and for a default.
18101 Return shift list (N what def-flag)
18102 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
18103 N is the number of WHATs to shift.
18104 DEF-FLAG is t when a double ++ or -- indicates shift relative to
18105 the DEFAULT date rather than TODAY."
18106 (when (string-match
18107 (concat
18108 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
18109 "\\([0-9]+\\)?"
18110 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
18111 "\\([ \t]\\|$\\)") s)
18112 (let* ((dir (if (match-end 1)
18113 (string-to-char (substring (match-string 1 s) -1))
18114 ?+))
18115 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
18116 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
18117 (what (if (match-end 3) (match-string 3 s) "d"))
18118 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
18119 (date (if rel default today))
18120 (wday (nth 6 (decode-time date)))
18121 delta)
18122 (if wday1
18123 (progn
18124 (setq delta (mod (+ 7 (- wday1 wday)) 7))
18125 (if (= dir ?-) (setq delta (- delta 7)))
18126 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
18127 (list delta "d" rel))
18128 (list (* n (if (= dir ?-) -1 1)) what rel)))))
18130 (defun org-eval-in-calendar (form &optional keepdate)
18131 "Eval FORM in the calendar window and return to current window.
18132 Also, store the cursor date in variable org-ans2."
18133 (let ((sw (selected-window)))
18134 (select-window (get-buffer-window "*Calendar*"))
18135 (eval form)
18136 (when (and (not keepdate) (calendar-cursor-to-date))
18137 (let* ((date (calendar-cursor-to-date))
18138 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18139 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
18140 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
18141 (select-window sw)))
18143 ; ;; Update the prompt to show new default date
18144 ; (save-excursion
18145 ; (goto-char (point-min))
18146 ; (when (and org-ans2
18147 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
18148 ; (get-text-property (match-end 0) 'field))
18149 ; (let ((inhibit-read-only t))
18150 ; (replace-match (concat "[" org-ans2 "]") t t)
18151 ; (add-text-properties (point-min) (1+ (match-end 0))
18152 ; (text-properties-at (1+ (point-min)))))))))
18154 (defun org-calendar-select ()
18155 "Return to `org-read-date' with the date currently selected.
18156 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18157 (interactive)
18158 (when (calendar-cursor-to-date)
18159 (let* ((date (calendar-cursor-to-date))
18160 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18161 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18162 (if (active-minibuffer-window) (exit-minibuffer))))
18164 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
18165 "Insert a date stamp for the date given by the internal TIME.
18166 WITH-HM means, use the stamp format that includes the time of the day.
18167 INACTIVE means use square brackets instead of angular ones, so that the
18168 stamp will not contribute to the agenda.
18169 PRE and POST are optional strings to be inserted before and after the
18170 stamp.
18171 The command returns the inserted time stamp."
18172 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
18173 stamp)
18174 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
18175 (insert-before-markers (or pre ""))
18176 (insert-before-markers (setq stamp (format-time-string fmt time)))
18177 (when (listp extra)
18178 (setq extra (car extra))
18179 (if (and (stringp extra)
18180 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
18181 (setq extra (format "-%02d:%02d"
18182 (string-to-number (match-string 1 extra))
18183 (string-to-number (match-string 2 extra))))
18184 (setq extra nil)))
18185 (when extra
18186 (backward-char 1)
18187 (insert-before-markers extra)
18188 (forward-char 1))
18189 (insert-before-markers (or post ""))
18190 stamp))
18192 (defun org-toggle-time-stamp-overlays ()
18193 "Toggle the use of custom time stamp formats."
18194 (interactive)
18195 (setq org-display-custom-times (not org-display-custom-times))
18196 (unless org-display-custom-times
18197 (let ((p (point-min)) (bmp (buffer-modified-p)))
18198 (while (setq p (next-single-property-change p 'display))
18199 (if (and (get-text-property p 'display)
18200 (eq (get-text-property p 'face) 'org-date))
18201 (remove-text-properties
18202 p (setq p (next-single-property-change p 'display))
18203 '(display t))))
18204 (set-buffer-modified-p bmp)))
18205 (if (featurep 'xemacs)
18206 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
18207 (org-restart-font-lock)
18208 (setq org-table-may-need-update t)
18209 (if org-display-custom-times
18210 (message "Time stamps are overlayed with custom format")
18211 (message "Time stamp overlays removed")))
18213 (defun org-display-custom-time (beg end)
18214 "Overlay modified time stamp format over timestamp between BED and END."
18215 (let* ((ts (buffer-substring beg end))
18216 t1 w1 with-hm tf time str w2 (off 0))
18217 (save-match-data
18218 (setq t1 (org-parse-time-string ts t))
18219 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
18220 (setq off (- (match-end 0) (match-beginning 0)))))
18221 (setq end (- end off))
18222 (setq w1 (- end beg)
18223 with-hm (and (nth 1 t1) (nth 2 t1))
18224 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
18225 time (org-fix-decoded-time t1)
18226 str (org-add-props
18227 (format-time-string
18228 (substring tf 1 -1) (apply 'encode-time time))
18229 nil 'mouse-face 'highlight)
18230 w2 (length str))
18231 (if (not (= w2 w1))
18232 (add-text-properties (1+ beg) (+ 2 beg)
18233 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
18234 (if (featurep 'xemacs)
18235 (progn
18236 (put-text-property beg end 'invisible t)
18237 (put-text-property beg end 'end-glyph (make-glyph str)))
18238 (put-text-property beg end 'display str))))
18240 (defun org-translate-time (string)
18241 "Translate all timestamps in STRING to custom format.
18242 But do this only if the variable `org-display-custom-times' is set."
18243 (when org-display-custom-times
18244 (save-match-data
18245 (let* ((start 0)
18246 (re org-ts-regexp-both)
18247 t1 with-hm inactive tf time str beg end)
18248 (while (setq start (string-match re string start))
18249 (setq beg (match-beginning 0)
18250 end (match-end 0)
18251 t1 (save-match-data
18252 (org-parse-time-string (substring string beg end) t))
18253 with-hm (and (nth 1 t1) (nth 2 t1))
18254 inactive (equal (substring string beg (1+ beg)) "[")
18255 tf (funcall (if with-hm 'cdr 'car)
18256 org-time-stamp-custom-formats)
18257 time (org-fix-decoded-time t1)
18258 str (format-time-string
18259 (concat
18260 (if inactive "[" "<") (substring tf 1 -1)
18261 (if inactive "]" ">"))
18262 (apply 'encode-time time))
18263 string (replace-match str t t string)
18264 start (+ start (length str)))))))
18265 string)
18267 (defun org-fix-decoded-time (time)
18268 "Set 0 instead of nil for the first 6 elements of time.
18269 Don't touch the rest."
18270 (let ((n 0))
18271 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
18273 (defun org-days-to-time (timestamp-string)
18274 "Difference between TIMESTAMP-STRING and now in days."
18275 (- (time-to-days (org-time-string-to-time timestamp-string))
18276 (time-to-days (current-time))))
18278 (defun org-deadline-close (timestamp-string &optional ndays)
18279 "Is the time in TIMESTAMP-STRING close to the current date?"
18280 (setq ndays (or ndays (org-get-wdays timestamp-string)))
18281 (and (< (org-days-to-time timestamp-string) ndays)
18282 (not (org-entry-is-done-p))))
18284 (defun org-get-wdays (ts)
18285 "Get the deadline lead time appropriate for timestring TS."
18286 (cond
18287 ((<= org-deadline-warning-days 0)
18288 ;; 0 or negative, enforce this value no matter what
18289 (- org-deadline-warning-days))
18290 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
18291 ;; lead time is specified.
18292 (floor (* (string-to-number (match-string 1 ts))
18293 (cdr (assoc (match-string 2 ts)
18294 '(("d" . 1) ("w" . 7)
18295 ("m" . 30.4) ("y" . 365.25)))))))
18296 ;; go for the default.
18297 (t org-deadline-warning-days)))
18299 (defun org-calendar-select-mouse (ev)
18300 "Return to `org-read-date' with the date currently selected.
18301 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18302 (interactive "e")
18303 (mouse-set-point ev)
18304 (when (calendar-cursor-to-date)
18305 (let* ((date (calendar-cursor-to-date))
18306 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18307 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18308 (if (active-minibuffer-window) (exit-minibuffer))))
18310 (defun org-check-deadlines (ndays)
18311 "Check if there are any deadlines due or past due.
18312 A deadline is considered due if it happens within `org-deadline-warning-days'
18313 days from today's date. If the deadline appears in an entry marked DONE,
18314 it is not shown. The prefix arg NDAYS can be used to test that many
18315 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18316 (interactive "P")
18317 (let* ((org-warn-days
18318 (cond
18319 ((equal ndays '(4)) 100000)
18320 (ndays (prefix-numeric-value ndays))
18321 (t (abs org-deadline-warning-days))))
18322 (case-fold-search nil)
18323 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18324 (callback
18325 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18327 (message "%d deadlines past-due or due within %d days"
18328 (org-occur regexp nil callback)
18329 org-warn-days)))
18331 (defun org-check-before-date (date)
18332 "Check if there are deadlines or scheduled entries before DATE."
18333 (interactive (list (org-read-date)))
18334 (let ((case-fold-search nil)
18335 (regexp (concat "\\<\\(" org-deadline-string
18336 "\\|" org-scheduled-string
18337 "\\) *<\\([^>]+\\)>"))
18338 (callback
18339 (lambda () (time-less-p
18340 (org-time-string-to-time (match-string 2))
18341 (org-time-string-to-time date)))))
18342 (message "%d entries before %s"
18343 (org-occur regexp nil callback) date)))
18345 (defun org-evaluate-time-range (&optional to-buffer)
18346 "Evaluate a time range by computing the difference between start and end.
18347 Normally the result is just printed in the echo area, but with prefix arg
18348 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18349 If the time range is actually in a table, the result is inserted into the
18350 next column.
18351 For time difference computation, a year is assumed to be exactly 365
18352 days in order to avoid rounding problems."
18353 (interactive "P")
18355 (org-clock-update-time-maybe)
18356 (save-excursion
18357 (unless (org-at-date-range-p t)
18358 (goto-char (point-at-bol))
18359 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18360 (if (not (org-at-date-range-p t))
18361 (error "Not at a time-stamp range, and none found in current line")))
18362 (let* ((ts1 (match-string 1))
18363 (ts2 (match-string 2))
18364 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18365 (match-end (match-end 0))
18366 (time1 (org-time-string-to-time ts1))
18367 (time2 (org-time-string-to-time ts2))
18368 (t1 (time-to-seconds time1))
18369 (t2 (time-to-seconds time2))
18370 (diff (abs (- t2 t1)))
18371 (negative (< (- t2 t1) 0))
18372 ;; (ys (floor (* 365 24 60 60)))
18373 (ds (* 24 60 60))
18374 (hs (* 60 60))
18375 (fy "%dy %dd %02d:%02d")
18376 (fy1 "%dy %dd")
18377 (fd "%dd %02d:%02d")
18378 (fd1 "%dd")
18379 (fh "%02d:%02d")
18380 y d h m align)
18381 (if havetime
18382 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18384 d (floor (/ diff ds)) diff (mod diff ds)
18385 h (floor (/ diff hs)) diff (mod diff hs)
18386 m (floor (/ diff 60)))
18387 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18389 d (floor (+ (/ diff ds) 0.5))
18390 h 0 m 0))
18391 (if (not to-buffer)
18392 (message "%s" (org-make-tdiff-string y d h m))
18393 (if (org-at-table-p)
18394 (progn
18395 (goto-char match-end)
18396 (setq align t)
18397 (and (looking-at " *|") (goto-char (match-end 0))))
18398 (goto-char match-end))
18399 (if (looking-at
18400 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18401 (replace-match ""))
18402 (if negative (insert " -"))
18403 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18404 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18405 (insert " " (format fh h m))))
18406 (if align (org-table-align))
18407 (message "Time difference inserted")))))
18409 (defun org-make-tdiff-string (y d h m)
18410 (let ((fmt "")
18411 (l nil))
18412 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18413 l (push y l)))
18414 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18415 l (push d l)))
18416 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18417 l (push h l)))
18418 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18419 l (push m l)))
18420 (apply 'format fmt (nreverse l))))
18422 (defun org-time-string-to-time (s)
18423 (apply 'encode-time (org-parse-time-string s)))
18425 (defun org-time-string-to-absolute (s &optional daynr prefer)
18426 "Convert a time stamp to an absolute day number.
18427 If there is a specifyer for a cyclic time stamp, get the closest date to
18428 DAYNR."
18429 (cond
18430 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18431 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18432 daynr
18433 (+ daynr 1000)))
18434 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18435 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18436 (time-to-days (current-time))) (match-string 0 s)
18437 prefer))
18438 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18440 (defun org-time-from-absolute (d)
18441 "Return the time corresponding to date D.
18442 D may be an absolute day number, or a calendar-type list (month day year)."
18443 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18444 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18446 (defun org-calendar-holiday ()
18447 "List of holidays, for Diary display in Org-mode."
18448 (require 'holidays)
18449 (let ((hl (funcall
18450 (if (fboundp 'calendar-check-holidays)
18451 'calendar-check-holidays 'check-calendar-holidays) date)))
18452 (if hl (mapconcat 'identity hl "; "))))
18454 (defun org-diary-sexp-entry (sexp entry date)
18455 "Process a SEXP diary ENTRY for DATE."
18456 (require 'diary-lib)
18457 (let ((result (if calendar-debug-sexp
18458 (let ((stack-trace-on-error t))
18459 (eval (car (read-from-string sexp))))
18460 (condition-case nil
18461 (eval (car (read-from-string sexp)))
18462 (error
18463 (beep)
18464 (message "Bad sexp at line %d in %s: %s"
18465 (org-current-line)
18466 (buffer-file-name) sexp)
18467 (sleep-for 2))))))
18468 (cond ((stringp result) result)
18469 ((and (consp result)
18470 (stringp (cdr result))) (cdr result))
18471 (result entry)
18472 (t nil))))
18474 (defun org-diary-to-ical-string (frombuf)
18475 "Get iCalendar entries from diary entries in buffer FROMBUF.
18476 This uses the icalendar.el library."
18477 (let* ((tmpdir (if (featurep 'xemacs)
18478 (temp-directory)
18479 temporary-file-directory))
18480 (tmpfile (make-temp-name
18481 (expand-file-name "orgics" tmpdir)))
18482 buf rtn b e)
18483 (save-excursion
18484 (set-buffer frombuf)
18485 (icalendar-export-region (point-min) (point-max) tmpfile)
18486 (setq buf (find-buffer-visiting tmpfile))
18487 (set-buffer buf)
18488 (goto-char (point-min))
18489 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18490 (setq b (match-beginning 0)))
18491 (goto-char (point-max))
18492 (if (re-search-backward "^END:VEVENT" nil t)
18493 (setq e (match-end 0)))
18494 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18495 (kill-buffer buf)
18496 (kill-buffer frombuf)
18497 (delete-file tmpfile)
18498 rtn))
18500 (defun org-closest-date (start current change prefer)
18501 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18502 When PREFER is `past' return a date that is either CURRENT or past.
18503 When PREFER is `future', return a date that is either CURRENT or future."
18504 ;; Make the proper lists from the dates
18505 (catch 'exit
18506 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18507 dn dw sday cday n1 n2
18508 d m y y1 y2 date1 date2 nmonths nm ny m2)
18510 (setq start (org-date-to-gregorian start)
18511 current (org-date-to-gregorian
18512 (if org-agenda-repeating-timestamp-show-all
18513 current
18514 (time-to-days (current-time))))
18515 sday (calendar-absolute-from-gregorian start)
18516 cday (calendar-absolute-from-gregorian current))
18518 (if (<= cday sday) (throw 'exit sday))
18520 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18521 (setq dn (string-to-number (match-string 1 change))
18522 dw (cdr (assoc (match-string 2 change) a1)))
18523 (error "Invalid change specifyer: %s" change))
18524 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18525 (cond
18526 ((eq dw 'day)
18527 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18528 n2 (+ n1 dn)))
18529 ((eq dw 'year)
18530 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18531 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18532 (setq date1 (list m d y1)
18533 n1 (calendar-absolute-from-gregorian date1)
18534 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18535 n2 (calendar-absolute-from-gregorian date2)))
18536 ((eq dw 'month)
18537 ;; approx number of month between the tow dates
18538 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18539 ;; How often does dn fit in there?
18540 (setq d (nth 1 start) m (car start) y (nth 2 start)
18541 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18542 m (+ m nm)
18543 ny (floor (/ m 12))
18544 y (+ y ny)
18545 m (- m (* ny 12)))
18546 (while (> m 12) (setq m (- m 12) y (1+ y)))
18547 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18548 (setq m2 (+ m dn) y2 y)
18549 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18550 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18551 (while (< n2 cday)
18552 (setq n1 n2 m m2 y y2)
18553 (setq m2 (+ m dn) y2 y)
18554 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18555 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18557 (if org-agenda-repeating-timestamp-show-all
18558 (cond
18559 ((eq prefer 'past) n1)
18560 ((eq prefer 'future) (if (= cday n1) n1 n2))
18561 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18562 (cond
18563 ((eq prefer 'past) n1)
18564 ((eq prefer 'future) (if (= cday n1) n1 n2))
18565 (t (if (= cday n1) n1 n2)))))))
18567 (defun org-date-to-gregorian (date)
18568 "Turn any specification of DATE into a gregorian date for the calendar."
18569 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18570 ((and (listp date) (= (length date) 3)) date)
18571 ((stringp date)
18572 (setq date (org-parse-time-string date))
18573 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18574 ((listp date)
18575 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18577 (defun org-parse-time-string (s &optional nodefault)
18578 "Parse the standard Org-mode time string.
18579 This should be a lot faster than the normal `parse-time-string'.
18580 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18581 hour and minute fields will be nil if not given."
18582 (if (string-match org-ts-regexp0 s)
18583 (list 0
18584 (if (or (match-beginning 8) (not nodefault))
18585 (string-to-number (or (match-string 8 s) "0")))
18586 (if (or (match-beginning 7) (not nodefault))
18587 (string-to-number (or (match-string 7 s) "0")))
18588 (string-to-number (match-string 4 s))
18589 (string-to-number (match-string 3 s))
18590 (string-to-number (match-string 2 s))
18591 nil nil nil)
18592 (make-list 9 0)))
18594 (defun org-timestamp-up (&optional arg)
18595 "Increase the date item at the cursor by one.
18596 If the cursor is on the year, change the year. If it is on the month or
18597 the day, change that.
18598 With prefix ARG, change by that many units."
18599 (interactive "p")
18600 (org-timestamp-change (prefix-numeric-value arg)))
18602 (defun org-timestamp-down (&optional arg)
18603 "Decrease the date item at the cursor by one.
18604 If the cursor is on the year, change the year. If it is on the month or
18605 the day, change that.
18606 With prefix ARG, change by that many units."
18607 (interactive "p")
18608 (org-timestamp-change (- (prefix-numeric-value arg))))
18610 (defun org-timestamp-up-day (&optional arg)
18611 "Increase the date in the time stamp by one day.
18612 With prefix ARG, change that many days."
18613 (interactive "p")
18614 (if (and (not (org-at-timestamp-p t))
18615 (org-on-heading-p))
18616 (org-todo 'up)
18617 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18619 (defun org-timestamp-down-day (&optional arg)
18620 "Decrease the date in the time stamp by one day.
18621 With prefix ARG, change that many days."
18622 (interactive "p")
18623 (if (and (not (org-at-timestamp-p t))
18624 (org-on-heading-p))
18625 (org-todo 'down)
18626 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18628 (defsubst org-pos-in-match-range (pos n)
18629 (and (match-beginning n)
18630 (<= (match-beginning n) pos)
18631 (>= (match-end n) pos)))
18633 (defun org-at-timestamp-p (&optional inactive-ok)
18634 "Determine if the cursor is in or at a timestamp."
18635 (interactive)
18636 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18637 (pos (point))
18638 (ans (or (looking-at tsr)
18639 (save-excursion
18640 (skip-chars-backward "^[<\n\r\t")
18641 (if (> (point) (point-min)) (backward-char 1))
18642 (and (looking-at tsr)
18643 (> (- (match-end 0) pos) -1))))))
18644 (and ans
18645 (boundp 'org-ts-what)
18646 (setq org-ts-what
18647 (cond
18648 ((= pos (match-beginning 0)) 'bracket)
18649 ((= pos (1- (match-end 0))) 'bracket)
18650 ((org-pos-in-match-range pos 2) 'year)
18651 ((org-pos-in-match-range pos 3) 'month)
18652 ((org-pos-in-match-range pos 7) 'hour)
18653 ((org-pos-in-match-range pos 8) 'minute)
18654 ((or (org-pos-in-match-range pos 4)
18655 (org-pos-in-match-range pos 5)) 'day)
18656 ((and (> pos (or (match-end 8) (match-end 5)))
18657 (< pos (match-end 0)))
18658 (- pos (or (match-end 8) (match-end 5))))
18659 (t 'day))))
18660 ans))
18662 (defun org-toggle-timestamp-type ()
18663 "Toggle the type (<active> or [inactive]) of a time stamp."
18664 (interactive)
18665 (when (org-at-timestamp-p t)
18666 (save-excursion
18667 (goto-char (match-beginning 0))
18668 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18669 (goto-char (1- (match-end 0)))
18670 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18671 (message "Timestamp is now %sactive"
18672 (if (equal (char-before) ?>) "in" ""))))
18674 (defun org-timestamp-change (n &optional what)
18675 "Change the date in the time stamp at point.
18676 The date will be changed by N times WHAT. WHAT can be `day', `month',
18677 `year', `minute', `second'. If WHAT is not given, the cursor position
18678 in the timestamp determines what will be changed."
18679 (let ((pos (point))
18680 with-hm inactive
18681 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18682 org-ts-what
18683 extra rem
18684 ts time time0)
18685 (if (not (org-at-timestamp-p t))
18686 (error "Not at a timestamp"))
18687 (if (and (not what) (eq org-ts-what 'bracket))
18688 (org-toggle-timestamp-type)
18689 (if (and (not what) (not (eq org-ts-what 'day))
18690 org-display-custom-times
18691 (get-text-property (point) 'display)
18692 (not (get-text-property (1- (point)) 'display)))
18693 (setq org-ts-what 'day))
18694 (setq org-ts-what (or what org-ts-what)
18695 inactive (= (char-after (match-beginning 0)) ?\[)
18696 ts (match-string 0))
18697 (replace-match "")
18698 (if (string-match
18699 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18701 (setq extra (match-string 1 ts)))
18702 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18703 (setq with-hm t))
18704 (setq time0 (org-parse-time-string ts))
18705 (when (and (eq org-ts-what 'minute)
18706 (eq current-prefix-arg nil))
18707 (setq n (* dm (org-no-warnings (signum n))))
18708 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
18709 (setcar (cdr time0) (+ (nth 1 time0)
18710 (if (> n 0) (- rem) (- dm rem))))))
18711 (setq time
18712 (encode-time (or (car time0) 0)
18713 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18714 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18715 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18716 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18717 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18718 (nthcdr 6 time0)))
18719 (when (integerp org-ts-what)
18720 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18721 (if (eq what 'calendar)
18722 (let ((cal-date (org-get-date-from-calendar)))
18723 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18724 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18725 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18726 (setcar time0 (or (car time0) 0))
18727 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18728 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18729 (setq time (apply 'encode-time time0))))
18730 (setq org-last-changed-timestamp
18731 (org-insert-time-stamp time with-hm inactive nil nil extra))
18732 (org-clock-update-time-maybe)
18733 (goto-char pos)
18734 ;; Try to recenter the calendar window, if any
18735 (if (and org-calendar-follow-timestamp-change
18736 (get-buffer-window "*Calendar*" t)
18737 (memq org-ts-what '(day month year)))
18738 (org-recenter-calendar (time-to-days time))))))
18740 ;; FIXME: does not yet work for lead times
18741 (defun org-modify-ts-extra (s pos n)
18742 "Change the different parts of the lead-time and repeat fields in timestamp."
18743 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18744 ng h m new)
18745 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18746 (cond
18747 ((or (org-pos-in-match-range pos 2)
18748 (org-pos-in-match-range pos 3))
18749 (setq m (string-to-number (match-string 3 s))
18750 h (string-to-number (match-string 2 s)))
18751 (if (org-pos-in-match-range pos 2)
18752 (setq h (+ h n))
18753 (setq m (+ m n)))
18754 (if (< m 0) (setq m (+ m 60) h (1- h)))
18755 (if (> m 59) (setq m (- m 60) h (1+ h)))
18756 (setq h (min 24 (max 0 h)))
18757 (setq ng 1 new (format "-%02d:%02d" h m)))
18758 ((org-pos-in-match-range pos 6)
18759 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18760 ((org-pos-in-match-range pos 5)
18761 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18763 (when ng
18764 (setq s (concat
18765 (substring s 0 (match-beginning ng))
18767 (substring s (match-end ng))))))
18770 (defun org-recenter-calendar (date)
18771 "If the calendar is visible, recenter it to DATE."
18772 (let* ((win (selected-window))
18773 (cwin (get-buffer-window "*Calendar*" t))
18774 (calendar-move-hook nil))
18775 (when cwin
18776 (select-window cwin)
18777 (calendar-goto-date (if (listp date) date
18778 (calendar-gregorian-from-absolute date)))
18779 (select-window win))))
18781 (defun org-goto-calendar (&optional arg)
18782 "Go to the Emacs calendar at the current date.
18783 If there is a time stamp in the current line, go to that date.
18784 A prefix ARG can be used to force the current date."
18785 (interactive "P")
18786 (let ((tsr org-ts-regexp) diff
18787 (calendar-move-hook nil)
18788 (view-calendar-holidays-initially nil)
18789 (view-diary-entries-initially nil))
18790 (if (or (org-at-timestamp-p)
18791 (save-excursion
18792 (beginning-of-line 1)
18793 (looking-at (concat ".*" tsr))))
18794 (let ((d1 (time-to-days (current-time)))
18795 (d2 (time-to-days
18796 (org-time-string-to-time (match-string 1)))))
18797 (setq diff (- d2 d1))))
18798 (calendar)
18799 (calendar-goto-today)
18800 (if (and diff (not arg)) (calendar-forward-day diff))))
18802 (defun org-get-date-from-calendar ()
18803 "Return a list (month day year) of date at point in calendar."
18804 (with-current-buffer "*Calendar*"
18805 (save-match-data
18806 (calendar-cursor-to-date))))
18808 (defun org-date-from-calendar ()
18809 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18810 If there is already a time stamp at the cursor position, update it."
18811 (interactive)
18812 (if (org-at-timestamp-p t)
18813 (org-timestamp-change 0 'calendar)
18814 (let ((cal-date (org-get-date-from-calendar)))
18815 (org-insert-time-stamp
18816 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18818 (defvar appt-time-msg-list)
18820 ;;;###autoload
18821 (defun org-agenda-to-appt (&optional refresh filter)
18822 "Activate appointments found in `org-agenda-files'.
18823 With a \\[universal-argument] prefix, refresh the list of
18824 appointements.
18826 If FILTER is t, interactively prompt the user for a regular
18827 expression, and filter out entries that don't match it.
18829 If FILTER is a string, use this string as a regular expression
18830 for filtering entries out.
18832 FILTER can also be an alist with the car of each cell being
18833 either 'headline or 'category. For example:
18835 '((headline \"IMPORTANT\")
18836 (category \"Work\"))
18838 will only add headlines containing IMPORTANT or headlines
18839 belonging to the \"Work\" category."
18840 (interactive "P")
18841 (require 'calendar)
18842 (if refresh (setq appt-time-msg-list nil))
18843 (if (eq filter t)
18844 (setq filter (read-from-minibuffer "Regexp filter: ")))
18845 (let* ((cnt 0) ; count added events
18846 (org-agenda-new-buffers nil)
18847 (org-deadline-warning-days 0)
18848 (today (org-date-to-gregorian
18849 (time-to-days (current-time))))
18850 (files (org-agenda-files)) entries file)
18851 ;; Get all entries which may contain an appt
18852 (while (setq file (pop files))
18853 (setq entries
18854 (append entries
18855 (org-agenda-get-day-entries
18856 file today :timestamp :scheduled :deadline))))
18857 (setq entries (delq nil entries))
18858 ;; Map thru entries and find if we should filter them out
18859 (mapc
18860 (lambda(x)
18861 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18862 (cat (get-text-property 1 'org-category x))
18863 (tod (get-text-property 1 'time-of-day x))
18864 (ok (or (null filter)
18865 (and (stringp filter) (string-match filter evt))
18866 (and (listp filter)
18867 (or (string-match
18868 (cadr (assoc 'category filter)) cat)
18869 (string-match
18870 (cadr (assoc 'headline filter)) evt))))))
18871 ;; FIXME: Shall we remove text-properties for the appt text?
18872 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18873 (when (and ok tod)
18874 (setq tod (number-to-string tod)
18875 tod (when (string-match
18876 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18877 (concat (match-string 1 tod) ":"
18878 (match-string 2 tod))))
18879 (appt-add tod evt)
18880 (setq cnt (1+ cnt))))) entries)
18881 (org-release-buffers org-agenda-new-buffers)
18882 (if (eq cnt 0)
18883 (message "No event to add")
18884 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18886 ;;; The clock for measuring work time.
18888 (defvar org-mode-line-string "")
18889 (put 'org-mode-line-string 'risky-local-variable t)
18891 (defvar org-mode-line-timer nil)
18892 (defvar org-clock-heading "")
18893 (defvar org-clock-start-time "")
18895 (defun org-update-mode-line ()
18896 (let* ((delta (- (time-to-seconds (current-time))
18897 (time-to-seconds org-clock-start-time)))
18898 (h (floor delta 3600))
18899 (m (floor (- delta (* 3600 h)) 60)))
18900 (setq org-mode-line-string
18901 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18902 'help-echo "Org-mode clock is running"))
18903 (force-mode-line-update)))
18905 (defvar org-clock-marker (make-marker)
18906 "Marker recording the last clock-in.")
18907 (defvar org-clock-mode-line-entry nil
18908 "Information for the modeline about the running clock.")
18910 (defun org-clock-in ()
18911 "Start the clock on the current item.
18912 If necessary, clock-out of the currently active clock."
18913 (interactive)
18914 (org-clock-out t)
18915 (let (ts)
18916 (save-excursion
18917 (org-back-to-heading t)
18918 (when (and org-clock-in-switch-to-state
18919 (not (looking-at (concat outline-regexp "[ \t]*"
18920 org-clock-in-switch-to-state
18921 "\\>"))))
18922 (org-todo org-clock-in-switch-to-state))
18923 (if (and org-clock-heading-function
18924 (functionp org-clock-heading-function))
18925 (setq org-clock-heading (funcall org-clock-heading-function))
18926 (if (looking-at org-complex-heading-regexp)
18927 (setq org-clock-heading (match-string 4))
18928 (setq org-clock-heading "???")))
18929 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18930 (org-clock-find-position)
18932 (insert "\n") (backward-char 1)
18933 (indent-relative)
18934 (insert org-clock-string " ")
18935 (setq org-clock-start-time (current-time))
18936 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18937 (move-marker org-clock-marker (point) (buffer-base-buffer))
18938 (or global-mode-string (setq global-mode-string '("")))
18939 (or (memq 'org-mode-line-string global-mode-string)
18940 (setq global-mode-string
18941 (append global-mode-string '(org-mode-line-string))))
18942 (org-update-mode-line)
18943 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18944 (message "Clock started at %s" ts))))
18946 (defun org-clock-find-position ()
18947 "Find the location where the next clock line should be inserted."
18948 (org-back-to-heading t)
18949 (catch 'exit
18950 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18951 (re (concat "^[ \t]*" org-clock-string))
18952 (cnt 0)
18953 first last)
18954 (goto-char beg)
18955 (when (eobp) (newline) (setq end (max (point) end)))
18956 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18957 ;; we seem to have a CLOCK drawer, so go there.
18958 (beginning-of-line 2)
18959 (throw 'exit t))
18960 ;; Lets count the CLOCK lines
18961 (goto-char beg)
18962 (while (re-search-forward re end t)
18963 (setq first (or first (match-beginning 0))
18964 last (match-beginning 0)
18965 cnt (1+ cnt)))
18966 (when (and (integerp org-clock-into-drawer)
18967 (>= (1+ cnt) org-clock-into-drawer))
18968 ;; Wrap current entries into a new drawer
18969 (goto-char last)
18970 (beginning-of-line 2)
18971 (if (org-at-item-p) (org-end-of-item))
18972 (insert ":END:\n")
18973 (beginning-of-line 0)
18974 (org-indent-line-function)
18975 (goto-char first)
18976 (insert ":CLOCK:\n")
18977 (beginning-of-line 0)
18978 (org-indent-line-function)
18979 (org-flag-drawer t)
18980 (beginning-of-line 2)
18981 (throw 'exit nil))
18983 (goto-char beg)
18984 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18985 (not (equal (match-string 1) org-clock-string)))
18986 ;; Planning info, skip to after it
18987 (beginning-of-line 2)
18988 (or (bolp) (newline)))
18989 (when (eq t org-clock-into-drawer)
18990 (insert ":CLOCK:\n:END:\n")
18991 (beginning-of-line -1)
18992 (org-indent-line-function)
18993 (org-flag-drawer t)
18994 (beginning-of-line 2)
18995 (org-indent-line-function)))))
18997 (defun org-clock-out (&optional fail-quietly)
18998 "Stop the currently running clock.
18999 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
19000 (interactive)
19001 (catch 'exit
19002 (if (not (marker-buffer org-clock-marker))
19003 (if fail-quietly (throw 'exit t) (error "No active clock")))
19004 (let (ts te s h m)
19005 (save-excursion
19006 (set-buffer (marker-buffer org-clock-marker))
19007 (goto-char org-clock-marker)
19008 (beginning-of-line 1)
19009 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
19010 (equal (match-string 1) org-clock-string))
19011 (setq ts (match-string 2))
19012 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
19013 (goto-char (match-end 0))
19014 (delete-region (point) (point-at-eol))
19015 (insert "--")
19016 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
19017 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
19018 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
19019 h (floor (/ s 3600))
19020 s (- s (* 3600 h))
19021 m (floor (/ s 60))
19022 s (- s (* 60 s)))
19023 (insert " => " (format "%2d:%02d" h m))
19024 (move-marker org-clock-marker nil)
19025 (when org-log-note-clock-out
19026 (org-add-log-maybe 'clock-out))
19027 (when org-mode-line-timer
19028 (cancel-timer org-mode-line-timer)
19029 (setq org-mode-line-timer nil))
19030 (setq global-mode-string
19031 (delq 'org-mode-line-string global-mode-string))
19032 (force-mode-line-update)
19033 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
19035 (defun org-clock-cancel ()
19036 "Cancel the running clock be removing the start timestamp."
19037 (interactive)
19038 (if (not (marker-buffer org-clock-marker))
19039 (error "No active clock"))
19040 (save-excursion
19041 (set-buffer (marker-buffer org-clock-marker))
19042 (goto-char org-clock-marker)
19043 (delete-region (1- (point-at-bol)) (point-at-eol)))
19044 (setq global-mode-string
19045 (delq 'org-mode-line-string global-mode-string))
19046 (force-mode-line-update)
19047 (message "Clock canceled"))
19049 (defun org-clock-goto (&optional delete-windows)
19050 "Go to the currently clocked-in entry."
19051 (interactive "P")
19052 (if (not (marker-buffer org-clock-marker))
19053 (error "No active clock"))
19054 (switch-to-buffer-other-window
19055 (marker-buffer org-clock-marker))
19056 (if delete-windows (delete-other-windows))
19057 (goto-char org-clock-marker)
19058 (org-show-entry)
19059 (org-back-to-heading)
19060 (recenter))
19062 (defvar org-clock-file-total-minutes nil
19063 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
19064 (make-variable-buffer-local 'org-clock-file-total-minutes)
19066 (defun org-clock-sum (&optional tstart tend)
19067 "Sum the times for each subtree.
19068 Puts the resulting times in minutes as a text property on each headline."
19069 (interactive)
19070 (let* ((bmp (buffer-modified-p))
19071 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
19072 org-clock-string
19073 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
19074 (lmax 30)
19075 (ltimes (make-vector lmax 0))
19076 (t1 0)
19077 (level 0)
19078 ts te dt
19079 time)
19080 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
19081 (save-excursion
19082 (goto-char (point-max))
19083 (while (re-search-backward re nil t)
19084 (cond
19085 ((match-end 2)
19086 ;; Two time stamps
19087 (setq ts (match-string 2)
19088 te (match-string 3)
19089 ts (time-to-seconds
19090 (apply 'encode-time (org-parse-time-string ts)))
19091 te (time-to-seconds
19092 (apply 'encode-time (org-parse-time-string te)))
19093 ts (if tstart (max ts tstart) ts)
19094 te (if tend (min te tend) te)
19095 dt (- te ts)
19096 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
19097 ((match-end 4)
19098 ;; A naket time
19099 (setq t1 (+ t1 (string-to-number (match-string 5))
19100 (* 60 (string-to-number (match-string 4))))))
19101 (t ;; A headline
19102 (setq level (- (match-end 1) (match-beginning 1)))
19103 (when (or (> t1 0) (> (aref ltimes level) 0))
19104 (loop for l from 0 to level do
19105 (aset ltimes l (+ (aref ltimes l) t1)))
19106 (setq t1 0 time (aref ltimes level))
19107 (loop for l from level to (1- lmax) do
19108 (aset ltimes l 0))
19109 (goto-char (match-beginning 0))
19110 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
19111 (setq org-clock-file-total-minutes (aref ltimes 0)))
19112 (set-buffer-modified-p bmp)))
19114 (defun org-clock-display (&optional total-only)
19115 "Show subtree times in the entire buffer.
19116 If TOTAL-ONLY is non-nil, only show the total time for the entire file
19117 in the echo area."
19118 (interactive)
19119 (org-remove-clock-overlays)
19120 (let (time h m p)
19121 (org-clock-sum)
19122 (unless total-only
19123 (save-excursion
19124 (goto-char (point-min))
19125 (while (or (and (equal (setq p (point)) (point-min))
19126 (get-text-property p :org-clock-minutes))
19127 (setq p (next-single-property-change
19128 (point) :org-clock-minutes)))
19129 (goto-char p)
19130 (when (setq time (get-text-property p :org-clock-minutes))
19131 (org-put-clock-overlay time (funcall outline-level))))
19132 (setq h (/ org-clock-file-total-minutes 60)
19133 m (- org-clock-file-total-minutes (* 60 h)))
19134 ;; Arrange to remove the overlays upon next change.
19135 (when org-remove-highlights-with-change
19136 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
19137 nil 'local))))
19138 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
19140 (defvar org-clock-overlays nil)
19141 (make-variable-buffer-local 'org-clock-overlays)
19143 (defun org-put-clock-overlay (time &optional level)
19144 "Put an overlays on the current line, displaying TIME.
19145 If LEVEL is given, prefix time with a corresponding number of stars.
19146 This creates a new overlay and stores it in `org-clock-overlays', so that it
19147 will be easy to remove."
19148 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
19149 (l (if level (org-get-legal-level level 0) 0))
19150 (off 0)
19151 ov tx)
19152 (move-to-column c)
19153 (unless (eolp) (skip-chars-backward "^ \t"))
19154 (skip-chars-backward " \t")
19155 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
19156 tx (concat (buffer-substring (1- (point)) (point))
19157 (make-string (+ off (max 0 (- c (current-column)))) ?.)
19158 (org-add-props (format "%s %2d:%02d%s"
19159 (make-string l ?*) h m
19160 (make-string (- 16 l) ?\ ))
19161 '(face secondary-selection))
19162 ""))
19163 (if (not (featurep 'xemacs))
19164 (org-overlay-put ov 'display tx)
19165 (org-overlay-put ov 'invisible t)
19166 (org-overlay-put ov 'end-glyph (make-glyph tx)))
19167 (push ov org-clock-overlays)))
19169 (defun org-remove-clock-overlays (&optional beg end noremove)
19170 "Remove the occur highlights from the buffer.
19171 BEG and END are ignored. If NOREMOVE is nil, remove this function
19172 from the `before-change-functions' in the current buffer."
19173 (interactive)
19174 (unless org-inhibit-highlight-removal
19175 (mapc 'org-delete-overlay org-clock-overlays)
19176 (setq org-clock-overlays nil)
19177 (unless noremove
19178 (remove-hook 'before-change-functions
19179 'org-remove-clock-overlays 'local))))
19181 (defun org-clock-out-if-current ()
19182 "Clock out if the current entry contains the running clock.
19183 This is used to stop the clock after a TODO entry is marked DONE,
19184 and is only done if the variable `org-clock-out-when-done' is not nil."
19185 (when (and org-clock-out-when-done
19186 (member state org-done-keywords)
19187 (equal (marker-buffer org-clock-marker) (current-buffer))
19188 (< (point) org-clock-marker)
19189 (> (save-excursion (outline-next-heading) (point))
19190 org-clock-marker))
19191 ;; Clock out, but don't accept a logging message for this.
19192 (let ((org-log-note-clock-out nil))
19193 (org-clock-out))))
19195 (add-hook 'org-after-todo-state-change-hook
19196 'org-clock-out-if-current)
19198 (defun org-check-running-clock ()
19199 "Check if the current buffer contains the running clock.
19200 If yes, offer to stop it and to save the buffer with the changes."
19201 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
19202 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
19203 (buffer-name))))
19204 (org-clock-out)
19205 (when (y-or-n-p "Save changed buffer?")
19206 (save-buffer))))
19208 (defun org-clock-report (&optional arg)
19209 "Create a table containing a report about clocked time.
19210 If the cursor is inside an existing clocktable block, then the table
19211 will be updated. If not, a new clocktable will be inserted.
19212 When called with a prefix argument, move to the first clock table in the
19213 buffer and update it."
19214 (interactive "P")
19215 (org-remove-clock-overlays)
19216 (when arg
19217 (org-find-dblock "clocktable")
19218 (org-show-entry))
19219 (if (org-in-clocktable-p)
19220 (goto-char (org-in-clocktable-p))
19221 (org-create-dblock (list :name "clocktable"
19222 :maxlevel 2 :scope 'file)))
19223 (org-update-dblock))
19225 (defun org-in-clocktable-p ()
19226 "Check if the cursor is in a clocktable."
19227 (let ((pos (point)) start)
19228 (save-excursion
19229 (end-of-line 1)
19230 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
19231 (setq start (match-beginning 0))
19232 (re-search-forward "^#\\+END:.*" nil t)
19233 (>= (match-end 0) pos)
19234 start))))
19236 (defun org-clock-update-time-maybe ()
19237 "If this is a CLOCK line, update it and return t.
19238 Otherwise, return nil."
19239 (interactive)
19240 (save-excursion
19241 (beginning-of-line 1)
19242 (skip-chars-forward " \t")
19243 (when (looking-at org-clock-string)
19244 (let ((re (concat "[ \t]*" org-clock-string
19245 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
19246 "\\([ \t]*=>.*\\)?"))
19247 ts te h m s)
19248 (if (not (looking-at re))
19250 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
19251 (end-of-line 1)
19252 (setq ts (match-string 1)
19253 te (match-string 2))
19254 (setq s (- (time-to-seconds
19255 (apply 'encode-time (org-parse-time-string te)))
19256 (time-to-seconds
19257 (apply 'encode-time (org-parse-time-string ts))))
19258 h (floor (/ s 3600))
19259 s (- s (* 3600 h))
19260 m (floor (/ s 60))
19261 s (- s (* 60 s)))
19262 (insert " => " (format "%2d:%02d" h m))
19263 t)))))
19265 (defun org-clock-special-range (key &optional time as-strings)
19266 "Return two times bordering a special time range.
19267 Key is a symbol specifying the range and can be one of `today', `yesterday',
19268 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
19269 A week starts Monday 0:00 and ends Sunday 24:00.
19270 The range is determined relative to TIME. TIME defaults to the current time.
19271 The return value is a cons cell with two internal times like the ones
19272 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
19273 the returned times will be formatted strings."
19274 (let* ((tm (decode-time (or time (current-time))))
19275 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
19276 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
19277 (dow (nth 6 tm))
19278 s1 m1 h1 d1 month1 y1 diff ts te fm)
19279 (cond
19280 ((eq key 'today)
19281 (setq h 0 m 0 h1 24 m1 0))
19282 ((eq key 'yesterday)
19283 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19284 ((eq key 'thisweek)
19285 (setq diff (if (= dow 0) 6 (1- dow))
19286 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19287 ((eq key 'lastweek)
19288 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19289 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19290 ((eq key 'thismonth)
19291 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19292 ((eq key 'lastmonth)
19293 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19294 ((eq key 'thisyear)
19295 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19296 ((eq key 'lastyear)
19297 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19298 (t (error "No such time block %s" key)))
19299 (setq ts (encode-time s m h d month y)
19300 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19301 (or d1 d) (or month1 month) (or y1 y)))
19302 (setq fm (cdr org-time-stamp-formats))
19303 (if as-strings
19304 (cons (format-time-string fm ts) (format-time-string fm te))
19305 (cons ts te))))
19307 (defun org-dblock-write:clocktable (params)
19308 "Write the standard clocktable."
19309 (catch 'exit
19310 (let* ((hlchars '((1 . "*") (2 . "/")))
19311 (ins (make-marker))
19312 (total-time nil)
19313 (scope (plist-get params :scope))
19314 (tostring (plist-get params :tostring))
19315 (multifile (plist-get params :multifile))
19316 (header (plist-get params :header))
19317 (maxlevel (or (plist-get params :maxlevel) 3))
19318 (step (plist-get params :step))
19319 (emph (plist-get params :emphasize))
19320 (ts (plist-get params :tstart))
19321 (te (plist-get params :tend))
19322 (block (plist-get params :block))
19323 ipos time h m p level hlc hdl
19324 cc beg end pos tbl)
19325 (when step
19326 (org-clocktable-steps params)
19327 (throw 'exit nil))
19328 (when block
19329 (setq cc (org-clock-special-range block nil t)
19330 ts (car cc) te (cdr cc)))
19331 (if ts (setq ts (time-to-seconds
19332 (apply 'encode-time (org-parse-time-string ts)))))
19333 (if te (setq te (time-to-seconds
19334 (apply 'encode-time (org-parse-time-string te)))))
19335 (move-marker ins (point))
19336 (setq ipos (point))
19338 ;; Get the right scope
19339 (setq pos (point))
19340 (save-restriction
19341 (cond
19342 ((not scope))
19343 ((eq scope 'file) (widen))
19344 ((eq scope 'subtree) (org-narrow-to-subtree))
19345 ((eq scope 'tree)
19346 (while (org-up-heading-safe))
19347 (org-narrow-to-subtree))
19348 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19349 (symbol-name scope)))
19350 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19351 (catch 'exit
19352 (while (org-up-heading-safe)
19353 (looking-at outline-regexp)
19354 (if (<= (org-reduced-level (funcall outline-level)) level)
19355 (throw 'exit nil))))
19356 (org-narrow-to-subtree))
19357 ((or (listp scope) (eq scope 'agenda))
19358 (let* ((files (if (listp scope) scope (org-agenda-files)))
19359 (scope 'agenda)
19360 (p1 (copy-sequence params))
19361 file)
19362 (plist-put p1 :tostring t)
19363 (plist-put p1 :multifile t)
19364 (plist-put p1 :scope 'file)
19365 (org-prepare-agenda-buffers files)
19366 (while (setq file (pop files))
19367 (with-current-buffer (find-buffer-visiting file)
19368 (push (org-clocktable-add-file
19369 file (org-dblock-write:clocktable p1)) tbl)
19370 (setq total-time (+ (or total-time 0)
19371 org-clock-file-total-minutes)))))))
19372 (goto-char pos)
19374 (unless (eq scope 'agenda)
19375 (org-clock-sum ts te)
19376 (goto-char (point-min))
19377 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19378 (goto-char p)
19379 (when (setq time (get-text-property p :org-clock-minutes))
19380 (save-excursion
19381 (beginning-of-line 1)
19382 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19383 (setq level (org-reduced-level
19384 (- (match-end 1) (match-beginning 1))))
19385 (<= level maxlevel))
19386 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19387 hdl (match-string 2)
19388 h (/ time 60)
19389 m (- time (* 60 h)))
19390 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19391 (push (concat
19392 "| " (int-to-string level) "|" hlc hdl hlc " |"
19393 (make-string (1- level) ?|)
19394 hlc (format "%d:%02d" h m) hlc
19395 " |") tbl))))))
19396 (setq tbl (nreverse tbl))
19397 (if tostring
19398 (if tbl (mapconcat 'identity tbl "\n") nil)
19399 (goto-char ins)
19400 (insert-before-markers
19401 (or header
19402 (concat
19403 "Clock summary at ["
19404 (substring
19405 (format-time-string (cdr org-time-stamp-formats))
19406 1 -1)
19407 "]."
19408 (if block
19409 (format " Considered range is /%s/." block)
19411 "\n\n"))
19412 (if (eq scope 'agenda) "|File" "")
19413 "|L|Headline|Time|\n")
19414 (setq total-time (or total-time org-clock-file-total-minutes)
19415 h (/ total-time 60)
19416 m (- total-time (* 60 h)))
19417 (insert-before-markers
19418 "|-\n|"
19419 (if (eq scope 'agenda) "|" "")
19421 "*Total time*| "
19422 (format "*%d:%02d*" h m)
19423 "|\n|-\n")
19424 (setq tbl (delq nil tbl))
19425 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19426 (equal (substring (car tbl) 0 2) "|-"))
19427 (pop tbl))
19428 (insert-before-markers (mapconcat
19429 'identity (delq nil tbl)
19430 (if (eq scope 'agenda) "\n|-\n" "\n")))
19431 (backward-delete-char 1)
19432 (goto-char ipos)
19433 (skip-chars-forward "^|")
19434 (org-table-align))))))
19436 (defun org-clocktable-steps (params)
19437 (let* ((p1 (copy-sequence params))
19438 (ts (plist-get p1 :tstart))
19439 (te (plist-get p1 :tend))
19440 (step0 (plist-get p1 :step))
19441 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19442 (block (plist-get p1 :block))
19444 (when block
19445 (setq cc (org-clock-special-range block nil t)
19446 ts (car cc) te (cdr cc)))
19447 (if ts (setq ts (time-to-seconds
19448 (apply 'encode-time (org-parse-time-string ts)))))
19449 (if te (setq te (time-to-seconds
19450 (apply 'encode-time (org-parse-time-string te)))))
19451 (plist-put p1 :header "")
19452 (plist-put p1 :step nil)
19453 (plist-put p1 :block nil)
19454 (while (< ts te)
19455 (or (bolp) (insert "\n"))
19456 (plist-put p1 :tstart (format-time-string
19457 (car org-time-stamp-formats)
19458 (seconds-to-time ts)))
19459 (plist-put p1 :tend (format-time-string
19460 (car org-time-stamp-formats)
19461 (seconds-to-time (setq ts (+ ts step)))))
19462 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19463 (plist-get p1 :tstart) "\n")
19464 (org-dblock-write:clocktable p1)
19465 (re-search-forward "#\\+END:")
19466 (end-of-line 0))))
19469 (defun org-clocktable-add-file (file table)
19470 (if table
19471 (let ((lines (org-split-string table "\n"))
19472 (ff (file-name-nondirectory file)))
19473 (mapconcat 'identity
19474 (mapcar (lambda (x)
19475 (if (string-match org-table-dataline-regexp x)
19476 (concat "|" ff x)
19478 lines)
19479 "\n"))))
19481 ;; FIXME: I don't think anybody uses this, ask David
19482 (defun org-collect-clock-time-entries ()
19483 "Return an internal list with clocking information.
19484 This list has one entry for each CLOCK interval.
19485 FIXME: describe the elements."
19486 (interactive)
19487 (let ((re (concat "^[ \t]*" org-clock-string
19488 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19489 rtn beg end next cont level title total closedp leafp
19490 clockpos titlepos h m donep)
19491 (save-excursion
19492 (org-clock-sum)
19493 (goto-char (point-min))
19494 (while (re-search-forward re nil t)
19495 (setq clockpos (match-beginning 0)
19496 beg (match-string 1) end (match-string 2)
19497 cont (match-end 0))
19498 (setq beg (apply 'encode-time (org-parse-time-string beg))
19499 end (apply 'encode-time (org-parse-time-string end)))
19500 (org-back-to-heading t)
19501 (setq donep (org-entry-is-done-p))
19502 (setq titlepos (point)
19503 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19504 h (/ total 60) m (- total (* 60 h))
19505 total (cons h m))
19506 (looking-at "\\(\\*+\\) +\\(.*\\)")
19507 (setq level (- (match-end 1) (match-beginning 1))
19508 title (org-match-string-no-properties 2))
19509 (save-excursion (outline-next-heading) (setq next (point)))
19510 (setq closedp (re-search-forward org-closed-time-regexp next t))
19511 (goto-char next)
19512 (setq leafp (and (looking-at "^\\*+ ")
19513 (<= (- (match-end 0) (point)) level)))
19514 (push (list beg end clockpos closedp donep
19515 total title titlepos level leafp)
19516 rtn)
19517 (goto-char cont)))
19518 (nreverse rtn)))
19520 ;;;; Agenda, and Diary Integration
19522 ;;; Define the Org-agenda-mode
19524 (defvar org-agenda-mode-map (make-sparse-keymap)
19525 "Keymap for `org-agenda-mode'.")
19527 (defvar org-agenda-menu) ; defined later in this file.
19528 (defvar org-agenda-follow-mode nil)
19529 (defvar org-agenda-show-log nil)
19530 (defvar org-agenda-redo-command nil)
19531 (defvar org-agenda-query-string nil)
19532 (defvar org-agenda-mode-hook nil)
19533 (defvar org-agenda-type nil)
19534 (defvar org-agenda-force-single-file nil)
19536 (defun org-agenda-mode ()
19537 "Mode for time-sorted view on action items in Org-mode files.
19539 The following commands are available:
19541 \\{org-agenda-mode-map}"
19542 (interactive)
19543 (kill-all-local-variables)
19544 (setq org-agenda-undo-list nil
19545 org-agenda-pending-undo-list nil)
19546 (setq major-mode 'org-agenda-mode)
19547 ;; Keep global-font-lock-mode from turning on font-lock-mode
19548 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19549 (setq mode-name "Org-Agenda")
19550 (use-local-map org-agenda-mode-map)
19551 (easy-menu-add org-agenda-menu)
19552 (if org-startup-truncated (setq truncate-lines t))
19553 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19554 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19555 ;; Make sure properties are removed when copying text
19556 (when (boundp 'buffer-substring-filters)
19557 (org-set-local 'buffer-substring-filters
19558 (cons (lambda (x)
19559 (set-text-properties 0 (length x) nil x) x)
19560 buffer-substring-filters)))
19561 (unless org-agenda-keep-modes
19562 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19563 org-agenda-show-log nil))
19564 (easy-menu-change
19565 '("Agenda") "Agenda Files"
19566 (append
19567 (list
19568 (vector
19569 (if (get 'org-agenda-files 'org-restrict)
19570 "Restricted to single file"
19571 "Edit File List")
19572 '(org-edit-agenda-file-list)
19573 (not (get 'org-agenda-files 'org-restrict)))
19574 "--")
19575 (mapcar 'org-file-menu-entry (org-agenda-files))))
19576 (org-agenda-set-mode-name)
19577 (apply
19578 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19579 (list 'org-agenda-mode-hook)))
19581 (substitute-key-definition 'undo 'org-agenda-undo
19582 org-agenda-mode-map global-map)
19583 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19584 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19585 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19586 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19587 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19588 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19589 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19590 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19591 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19592 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19593 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19594 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19595 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19596 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19597 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19598 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19599 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19600 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19601 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19602 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19603 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19604 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19605 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19606 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19607 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19608 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19609 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19610 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19611 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19613 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19614 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19615 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19616 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19617 (while l (org-defkey org-agenda-mode-map
19618 (int-to-string (pop l)) 'digit-argument)))
19620 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19621 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19622 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19623 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19624 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19625 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19626 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19627 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19628 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19629 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19630 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19631 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19632 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19633 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19634 (org-defkey org-agenda-mode-map "n" 'next-line)
19635 (org-defkey org-agenda-mode-map "p" 'previous-line)
19636 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19637 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19638 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19639 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19640 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19641 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19642 (eval-after-load "calendar"
19643 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19644 'org-calendar-goto-agenda))
19645 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19646 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19647 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19648 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19649 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19650 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19651 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19652 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19653 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19654 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19655 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19656 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19657 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19658 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19659 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19660 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19661 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19662 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19663 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19664 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19665 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19666 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19668 (org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add)
19669 (org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract)
19670 (org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re)
19671 (org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re)
19673 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19674 "Local keymap for agenda entries from Org-mode.")
19676 (org-defkey org-agenda-keymap
19677 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19678 (org-defkey org-agenda-keymap
19679 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19680 (when org-agenda-mouse-1-follows-link
19681 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19682 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19683 '("Agenda"
19684 ("Agenda Files")
19685 "--"
19686 ["Show" org-agenda-show t]
19687 ["Go To (other window)" org-agenda-goto t]
19688 ["Go To (this window)" org-agenda-switch-to t]
19689 ["Follow Mode" org-agenda-follow-mode
19690 :style toggle :selected org-agenda-follow-mode :active t]
19691 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19692 "--"
19693 ["Cycle TODO" org-agenda-todo t]
19694 ["Archive subtree" org-agenda-archive t]
19695 ["Delete subtree" org-agenda-kill t]
19696 "--"
19697 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19698 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19699 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19700 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19701 "--"
19702 ("Tags and Properties"
19703 ["Show all Tags" org-agenda-show-tags t]
19704 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19705 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19706 "--"
19707 ["Column View" org-columns t])
19708 ("Date/Schedule"
19709 ["Schedule" org-agenda-schedule t]
19710 ["Set Deadline" org-agenda-deadline t]
19711 "--"
19712 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19713 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19714 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19715 ("Clock"
19716 ["Clock in" org-agenda-clock-in t]
19717 ["Clock out" org-agenda-clock-out t]
19718 ["Clock cancel" org-agenda-clock-cancel t]
19719 ["Goto running clock" org-clock-goto t])
19720 ("Priority"
19721 ["Set Priority" org-agenda-priority t]
19722 ["Increase Priority" org-agenda-priority-up t]
19723 ["Decrease Priority" org-agenda-priority-down t]
19724 ["Show Priority" org-agenda-show-priority t])
19725 ("Calendar/Diary"
19726 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19727 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19728 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19729 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19730 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19731 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19732 "--"
19733 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19734 "--"
19735 ("View"
19736 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19737 :style radio :selected (equal org-agenda-ndays 1)]
19738 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19739 :style radio :selected (equal org-agenda-ndays 7)]
19740 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19741 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19742 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19743 :style radio :selected (member org-agenda-ndays '(365 366))]
19744 "--"
19745 ["Show Logbook entries" org-agenda-log-mode
19746 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19747 ["Include Diary" org-agenda-toggle-diary
19748 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19749 ["Use Time Grid" org-agenda-toggle-time-grid
19750 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19751 ["Write view to file" org-write-agenda t]
19752 ["Rebuild buffer" org-agenda-redo t]
19753 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19754 "--"
19755 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19756 "--"
19757 ["Quit" org-agenda-quit t]
19758 ["Exit and Release Buffers" org-agenda-exit t]
19761 ;;; Agenda undo
19763 (defvar org-agenda-allow-remote-undo t
19764 "Non-nil means, allow remote undo from the agenda buffer.")
19765 (defvar org-agenda-undo-list nil
19766 "List of undoable operations in the agenda since last refresh.")
19767 (defvar org-agenda-undo-has-started-in nil
19768 "Buffers that have already seen `undo-start' in the current undo sequence.")
19769 (defvar org-agenda-pending-undo-list nil
19770 "In a series of undo commands, this is the list of remaning undo items.")
19772 (defmacro org-if-unprotected (&rest body)
19773 "Execute BODY if there is no `org-protected' text property at point."
19774 (declare (debug t))
19775 `(unless (get-text-property (point) 'org-protected)
19776 ,@body))
19778 (defmacro org-with-remote-undo (_buffer &rest _body)
19779 "Execute BODY while recording undo information in two buffers."
19780 (declare (indent 1) (debug t))
19781 `(let ((_cline (org-current-line))
19782 (_cmd this-command)
19783 (_buf1 (current-buffer))
19784 (_buf2 ,_buffer)
19785 (_undo1 buffer-undo-list)
19786 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19787 _c1 _c2)
19788 ,@_body
19789 (when org-agenda-allow-remote-undo
19790 (setq _c1 (org-verify-change-for-undo
19791 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19792 _c2 (org-verify-change-for-undo
19793 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19794 (when (or _c1 _c2)
19795 ;; make sure there are undo boundaries
19796 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19797 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19798 ;; remember which buffer to undo
19799 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19800 org-agenda-undo-list)))))
19802 (defun org-agenda-undo ()
19803 "Undo a remote editing step in the agenda.
19804 This undoes changes both in the agenda buffer and in the remote buffer
19805 that have been changed along."
19806 (interactive)
19807 (or org-agenda-allow-remote-undo
19808 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19809 (if (not (eq this-command last-command))
19810 (setq org-agenda-undo-has-started-in nil
19811 org-agenda-pending-undo-list org-agenda-undo-list))
19812 (if (not org-agenda-pending-undo-list)
19813 (error "No further undo information"))
19814 (let* ((entry (pop org-agenda-pending-undo-list))
19815 buf line cmd rembuf)
19816 (setq cmd (pop entry) line (pop entry))
19817 (setq rembuf (nth 2 entry))
19818 (org-with-remote-undo rembuf
19819 (while (bufferp (setq buf (pop entry)))
19820 (if (pop entry)
19821 (with-current-buffer buf
19822 (let ((last-undo-buffer buf)
19823 (inhibit-read-only t))
19824 (unless (memq buf org-agenda-undo-has-started-in)
19825 (push buf org-agenda-undo-has-started-in)
19826 (make-local-variable 'pending-undo-list)
19827 (undo-start))
19828 (while (and pending-undo-list
19829 (listp pending-undo-list)
19830 (not (car pending-undo-list)))
19831 (pop pending-undo-list))
19832 (undo-more 1))))))
19833 (goto-line line)
19834 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19836 (defun org-verify-change-for-undo (l1 l2)
19837 "Verify that a real change occurred between the undo lists L1 and L2."
19838 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19839 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19840 (not (eq l1 l2)))
19842 ;;; Agenda dispatch
19844 (defvar org-agenda-restrict nil)
19845 (defvar org-agenda-restrict-begin (make-marker))
19846 (defvar org-agenda-restrict-end (make-marker))
19847 (defvar org-agenda-last-dispatch-buffer nil)
19848 (defvar org-agenda-overriding-restriction nil)
19850 ;;;###autoload
19851 (defun org-agenda (arg &optional keys restriction)
19852 "Dispatch agenda commands to collect entries to the agenda buffer.
19853 Prompts for a command to execute. Any prefix arg will be passed
19854 on to the selected command. The default selections are:
19856 a Call `org-agenda-list' to display the agenda for current day or week.
19857 t Call `org-todo-list' to display the global todo list.
19858 T Call `org-todo-list' to display the global todo list, select only
19859 entries with a specific TODO keyword (the user gets a prompt).
19860 m Call `org-tags-view' to display headlines with tags matching
19861 a condition (the user is prompted for the condition).
19862 M Like `m', but select only TODO entries, no ordinary headlines.
19863 L Create a timeline for the current buffer.
19864 e Export views to associated files.
19866 More commands can be added by configuring the variable
19867 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19868 searches can be pre-defined in this way.
19870 If the current buffer is in Org-mode and visiting a file, you can also
19871 first press `<' once to indicate that the agenda should be temporarily
19872 \(until the next use of \\[org-agenda]) restricted to the current file.
19873 Pressing `<' twice means to restrict to the current subtree or region
19874 \(if active)."
19875 (interactive "P")
19876 (catch 'exit
19877 (let* ((prefix-descriptions nil)
19878 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19879 (org-agenda-custom-commands
19880 ;; normalize different versions
19881 (delq nil
19882 (mapcar
19883 (lambda (x)
19884 (cond ((stringp (cdr x))
19885 (push x prefix-descriptions)
19886 nil)
19887 ((stringp (nth 1 x)) x)
19888 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19889 (t (cons (car x) (cons "" (cdr x))))))
19890 org-agenda-custom-commands)))
19891 (buf (current-buffer))
19892 (bfn (buffer-file-name (buffer-base-buffer)))
19893 entry key type match lprops ans)
19894 ;; Turn off restriction unless there is an overriding one
19895 (unless org-agenda-overriding-restriction
19896 (put 'org-agenda-files 'org-restrict nil)
19897 (setq org-agenda-restrict nil)
19898 (move-marker org-agenda-restrict-begin nil)
19899 (move-marker org-agenda-restrict-end nil))
19900 ;; Delete old local properties
19901 (put 'org-agenda-redo-command 'org-lprops nil)
19902 ;; Remember where this call originated
19903 (setq org-agenda-last-dispatch-buffer (current-buffer))
19904 (unless keys
19905 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19906 keys (car ans)
19907 restriction (cdr ans)))
19908 ;; Estabish the restriction, if any
19909 (when (and (not org-agenda-overriding-restriction) restriction)
19910 (put 'org-agenda-files 'org-restrict (list bfn))
19911 (cond
19912 ((eq restriction 'region)
19913 (setq org-agenda-restrict t)
19914 (move-marker org-agenda-restrict-begin (region-beginning))
19915 (move-marker org-agenda-restrict-end (region-end)))
19916 ((eq restriction 'subtree)
19917 (save-excursion
19918 (setq org-agenda-restrict t)
19919 (org-back-to-heading t)
19920 (move-marker org-agenda-restrict-begin (point))
19921 (move-marker org-agenda-restrict-end
19922 (progn (org-end-of-subtree t)))))))
19924 (require 'calendar) ; FIXME: can we avoid this for some commands?
19925 ;; For example the todo list should not need it (but does...)
19926 (cond
19927 ((setq entry (assoc keys org-agenda-custom-commands))
19928 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19929 (progn
19930 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19931 (put 'org-agenda-redo-command 'org-lprops lprops)
19932 (cond
19933 ((eq type 'agenda)
19934 (org-let lprops '(org-agenda-list current-prefix-arg)))
19935 ((eq type 'alltodo)
19936 (org-let lprops '(org-todo-list current-prefix-arg)))
19937 ((eq type 'search)
19938 (org-let lprops '(org-search-view current-prefix-arg match)))
19939 ((eq type 'stuck)
19940 (org-let lprops '(org-agenda-list-stuck-projects
19941 current-prefix-arg)))
19942 ((eq type 'tags)
19943 (org-let lprops '(org-tags-view current-prefix-arg match)))
19944 ((eq type 'tags-todo)
19945 (org-let lprops '(org-tags-view '(4) match)))
19946 ((eq type 'todo)
19947 (org-let lprops '(org-todo-list match)))
19948 ((eq type 'tags-tree)
19949 (org-check-for-org-mode)
19950 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19951 ((eq type 'todo-tree)
19952 (org-check-for-org-mode)
19953 (org-let lprops
19954 '(org-occur (concat "^" outline-regexp "[ \t]*"
19955 (regexp-quote match) "\\>"))))
19956 ((eq type 'occur-tree)
19957 (org-check-for-org-mode)
19958 (org-let lprops '(org-occur match)))
19959 ((functionp type)
19960 (org-let lprops '(funcall type match)))
19961 ((fboundp type)
19962 (org-let lprops '(funcall type match)))
19963 (t (error "Invalid custom agenda command type %s" type))))
19964 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19965 ((equal keys "C")
19966 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19967 (customize-variable 'org-agenda-custom-commands))
19968 ((equal keys "a") (call-interactively 'org-agenda-list))
19969 ((equal keys "s") (call-interactively 'org-search-view))
19970 ((equal keys "t") (call-interactively 'org-todo-list))
19971 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19972 ((equal keys "m") (call-interactively 'org-tags-view))
19973 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19974 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19975 ((equal keys "L")
19976 (unless (org-mode-p)
19977 (error "This is not an Org-mode file"))
19978 (unless restriction
19979 (put 'org-agenda-files 'org-restrict (list bfn))
19980 (org-call-with-arg 'org-timeline arg)))
19981 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19982 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19983 ((equal keys "!") (customize-variable 'org-stuck-projects))
19984 (t (error "Invalid agenda key"))))))
19986 (defun org-agenda-normalize-custom-commands (cmds)
19987 (delq nil
19988 (mapcar
19989 (lambda (x)
19990 (cond ((stringp (cdr x)) nil)
19991 ((stringp (nth 1 x)) x)
19992 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19993 (t (cons (car x) (cons "" (cdr x))))))
19994 cmds)))
19996 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19997 "The user interface for selecting an agenda command."
19998 (catch 'exit
19999 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
20000 (restrict-ok (and bfn (org-mode-p)))
20001 (region-p (org-region-active-p))
20002 (custom org-agenda-custom-commands)
20003 (selstring "")
20004 restriction second-time
20005 c entry key type match prefixes rmheader header-end custom1 desc)
20006 (save-window-excursion
20007 (delete-other-windows)
20008 (org-switch-to-buffer-other-window " *Agenda Commands*")
20009 (erase-buffer)
20010 (insert (eval-when-compile
20011 (let ((header
20013 Press key for an agenda command: < Buffer,subtree/region restriction
20014 -------------------------------- > Remove restriction
20015 a Agenda for current week or day e Export agenda views
20016 t List of all TODO entries T Entries with special TODO kwd
20017 m Match a TAGS query M Like m, but only TODO entries
20018 L Timeline for current buffer # List stuck projects (!=configure)
20019 s Search for keywords C Configure custom agenda commands
20020 / Multi-occur
20022 (start 0))
20023 (while (string-match
20024 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
20025 header start)
20026 (setq start (match-end 0))
20027 (add-text-properties (match-beginning 2) (match-end 2)
20028 '(face bold) header))
20029 header)))
20030 (setq header-end (move-marker (make-marker) (point)))
20031 (while t
20032 (setq custom1 custom)
20033 (when (eq rmheader t)
20034 (goto-line 1)
20035 (re-search-forward ":" nil t)
20036 (delete-region (match-end 0) (point-at-eol))
20037 (forward-char 1)
20038 (looking-at "-+")
20039 (delete-region (match-end 0) (point-at-eol))
20040 (move-marker header-end (match-end 0)))
20041 (goto-char header-end)
20042 (delete-region (point) (point-max))
20043 (while (setq entry (pop custom1))
20044 (setq key (car entry) desc (nth 1 entry)
20045 type (nth 2 entry) match (nth 3 entry))
20046 (if (> (length key) 1)
20047 (add-to-list 'prefixes (string-to-char key))
20048 (insert
20049 (format
20050 "\n%-4s%-14s: %s"
20051 (org-add-props (copy-sequence key)
20052 '(face bold))
20053 (cond
20054 ((string-match "\\S-" desc) desc)
20055 ((eq type 'agenda) "Agenda for current week or day")
20056 ((eq type 'alltodo) "List of all TODO entries")
20057 ((eq type 'search) "Word search")
20058 ((eq type 'stuck) "List of stuck projects")
20059 ((eq type 'todo) "TODO keyword")
20060 ((eq type 'tags) "Tags query")
20061 ((eq type 'tags-todo) "Tags (TODO)")
20062 ((eq type 'tags-tree) "Tags tree")
20063 ((eq type 'todo-tree) "TODO kwd tree")
20064 ((eq type 'occur-tree) "Occur tree")
20065 ((functionp type) (if (symbolp type)
20066 (symbol-name type)
20067 "Lambda expression"))
20068 (t "???"))
20069 (cond
20070 ((stringp match)
20071 (org-add-props match nil 'face 'org-warning))
20072 (match
20073 (format "set of %d commands" (length match)))
20074 (t ""))))))
20075 (when prefixes
20076 (mapc (lambda (x)
20077 (insert
20078 (format "\n%s %s"
20079 (org-add-props (char-to-string x)
20080 nil 'face 'bold)
20081 (or (cdr (assoc (concat selstring (char-to-string x))
20082 prefix-descriptions))
20083 "Prefix key"))))
20084 prefixes))
20085 (goto-char (point-min))
20086 (when (fboundp 'fit-window-to-buffer)
20087 (if second-time
20088 (if (not (pos-visible-in-window-p (point-max)))
20089 (fit-window-to-buffer))
20090 (setq second-time t)
20091 (fit-window-to-buffer)))
20092 (message "Press key for agenda command%s:"
20093 (if (or restrict-ok org-agenda-overriding-restriction)
20094 (if org-agenda-overriding-restriction
20095 " (restriction lock active)"
20096 (if restriction
20097 (format " (restricted to %s)" restriction)
20098 " (unrestricted)"))
20099 ""))
20100 (setq c (read-char-exclusive))
20101 (message "")
20102 (cond
20103 ((assoc (char-to-string c) custom)
20104 (setq selstring (concat selstring (char-to-string c)))
20105 (throw 'exit (cons selstring restriction)))
20106 ((memq c prefixes)
20107 (setq selstring (concat selstring (char-to-string c))
20108 prefixes nil
20109 rmheader (or rmheader t)
20110 custom (delq nil (mapcar
20111 (lambda (x)
20112 (if (or (= (length (car x)) 1)
20113 (/= (string-to-char (car x)) c))
20115 (cons (substring (car x) 1) (cdr x))))
20116 custom))))
20117 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
20118 (message "Restriction is only possible in Org-mode buffers")
20119 (ding) (sit-for 1))
20120 ((eq c ?1)
20121 (org-agenda-remove-restriction-lock 'noupdate)
20122 (setq restriction 'buffer))
20123 ((eq c ?0)
20124 (org-agenda-remove-restriction-lock 'noupdate)
20125 (setq restriction (if region-p 'region 'subtree)))
20126 ((eq c ?<)
20127 (org-agenda-remove-restriction-lock 'noupdate)
20128 (setq restriction
20129 (cond
20130 ((eq restriction 'buffer)
20131 (if region-p 'region 'subtree))
20132 ((memq restriction '(subtree region))
20133 nil)
20134 (t 'buffer))))
20135 ((eq c ?>)
20136 (org-agenda-remove-restriction-lock 'noupdate)
20137 (setq restriction nil))
20138 ((and (equal selstring "") (memq c '(?s ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
20139 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
20140 ((and (> (length selstring) 0) (eq c ?\d))
20141 (delete-window)
20142 (org-agenda-get-restriction-and-command prefix-descriptions))
20144 ((equal c ?q) (error "Abort"))
20145 (t (error "Invalid key %c" c))))))))
20147 (defun org-run-agenda-series (name series)
20148 (org-prepare-agenda name)
20149 (let* ((org-agenda-multi t)
20150 (redo (list 'org-run-agenda-series name (list 'quote series)))
20151 (cmds (car series))
20152 (gprops (nth 1 series))
20153 match ;; The byte compiler incorrectly complains about this. Keep it!
20154 cmd type lprops)
20155 (while (setq cmd (pop cmds))
20156 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
20157 (cond
20158 ((eq type 'agenda)
20159 (org-let2 gprops lprops
20160 '(call-interactively 'org-agenda-list)))
20161 ((eq type 'alltodo)
20162 (org-let2 gprops lprops
20163 '(call-interactively 'org-todo-list)))
20164 ((eq type 'search)
20165 (org-let2 gprops lprops
20166 '(org-search-view current-prefix-arg match)))
20167 ((eq type 'stuck)
20168 (org-let2 gprops lprops
20169 '(call-interactively 'org-agenda-list-stuck-projects)))
20170 ((eq type 'tags)
20171 (org-let2 gprops lprops
20172 '(org-tags-view current-prefix-arg match)))
20173 ((eq type 'tags-todo)
20174 (org-let2 gprops lprops
20175 '(org-tags-view '(4) match)))
20176 ((eq type 'todo)
20177 (org-let2 gprops lprops
20178 '(org-todo-list match)))
20179 ((fboundp type)
20180 (org-let2 gprops lprops
20181 '(funcall type match)))
20182 (t (error "Invalid type in command series"))))
20183 (widen)
20184 (setq org-agenda-redo-command redo)
20185 (goto-char (point-min)))
20186 (org-finalize-agenda))
20188 ;;;###autoload
20189 (defmacro org-batch-agenda (cmd-key &rest parameters)
20190 "Run an agenda command in batch mode and send the result to STDOUT.
20191 If CMD-KEY is a string of length 1, it is used as a key in
20192 `org-agenda-custom-commands' and triggers this command. If it is a
20193 longer string it is used as a tags/todo match string.
20194 Paramters are alternating variable names and values that will be bound
20195 before running the agenda command."
20196 (let (pars)
20197 (while parameters
20198 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20199 (if (> (length cmd-key) 2)
20200 (eval (list 'let (nreverse pars)
20201 (list 'org-tags-view nil cmd-key)))
20202 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20203 (set-buffer org-agenda-buffer-name)
20204 (princ (org-encode-for-stdout (buffer-string)))))
20206 (defun org-encode-for-stdout (string)
20207 (if (fboundp 'encode-coding-string)
20208 (encode-coding-string string buffer-file-coding-system)
20209 string))
20211 (defvar org-agenda-info nil)
20213 ;;;###autoload
20214 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
20215 "Run an agenda command in batch mode and send the result to STDOUT.
20216 If CMD-KEY is a string of length 1, it is used as a key in
20217 `org-agenda-custom-commands' and triggers this command. If it is a
20218 longer string it is used as a tags/todo match string.
20219 Paramters are alternating variable names and values that will be bound
20220 before running the agenda command.
20222 The output gives a line for each selected agenda item. Each
20223 item is a list of comma-separated values, like this:
20225 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
20227 category The category of the item
20228 head The headline, without TODO kwd, TAGS and PRIORITY
20229 type The type of the agenda entry, can be
20230 todo selected in TODO match
20231 tagsmatch selected in tags match
20232 diary imported from diary
20233 deadline a deadline on given date
20234 scheduled scheduled on given date
20235 timestamp entry has timestamp on given date
20236 closed entry was closed on given date
20237 upcoming-deadline warning about deadline
20238 past-scheduled forwarded scheduled item
20239 block entry has date block including g. date
20240 todo The todo keyword, if any
20241 tags All tags including inherited ones, separated by colons
20242 date The relevant date, like 2007-2-14
20243 time The time, like 15:00-16:50
20244 extra Sting with extra planning info
20245 priority-l The priority letter if any was given
20246 priority-n The computed numerical priority
20247 agenda-day The day in the agenda where this is listed"
20249 (let (pars)
20250 (while parameters
20251 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20252 (push (list 'org-agenda-remove-tags t) pars)
20253 (if (> (length cmd-key) 2)
20254 (eval (list 'let (nreverse pars)
20255 (list 'org-tags-view nil cmd-key)))
20256 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20257 (set-buffer org-agenda-buffer-name)
20258 (let* ((lines (org-split-string (buffer-string) "\n"))
20259 line)
20260 (while (setq line (pop lines))
20261 (catch 'next
20262 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
20263 (setq org-agenda-info
20264 (org-fix-agenda-info (text-properties-at 0 line)))
20265 (princ
20266 (org-encode-for-stdout
20267 (mapconcat 'org-agenda-export-csv-mapper
20268 '(org-category txt type todo tags date time-of-day extra
20269 priority-letter priority agenda-day)
20270 ",")))
20271 (princ "\n"))))))
20273 (defun org-fix-agenda-info (props)
20274 "Make sure all properties on an agenda item have a canonical form,
20275 so the export commands can easily use it."
20276 (let (tmp re)
20277 (when (setq tmp (plist-get props 'tags))
20278 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20279 (when (setq tmp (plist-get props 'date))
20280 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20281 (let ((calendar-date-display-form '(year "-" month "-" day)))
20282 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20284 (setq tmp (calendar-date-string tmp)))
20285 (setq props (plist-put props 'date tmp)))
20286 (when (setq tmp (plist-get props 'day))
20287 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20288 (let ((calendar-date-display-form '(year "-" month "-" day)))
20289 (setq tmp (calendar-date-string tmp)))
20290 (setq props (plist-put props 'day tmp))
20291 (setq props (plist-put props 'agenda-day tmp)))
20292 (when (setq tmp (plist-get props 'txt))
20293 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20294 (plist-put props 'priority-letter (match-string 1 tmp))
20295 (setq tmp (replace-match "" t t tmp)))
20296 (when (and (setq re (plist-get props 'org-todo-regexp))
20297 (setq re (concat "\\`\\.*" re " ?"))
20298 (string-match re tmp))
20299 (plist-put props 'todo (match-string 1 tmp))
20300 (setq tmp (replace-match "" t t tmp)))
20301 (plist-put props 'txt tmp)))
20302 props)
20304 (defun org-agenda-export-csv-mapper (prop)
20305 (let ((res (plist-get org-agenda-info prop)))
20306 (setq res
20307 (cond
20308 ((not res) "")
20309 ((stringp res) res)
20310 (t (prin1-to-string res))))
20311 (while (string-match "," res)
20312 (setq res (replace-match ";" t t res)))
20313 (org-trim res)))
20316 ;;;###autoload
20317 (defun org-store-agenda-views (&rest parameters)
20318 (interactive)
20319 (eval (list 'org-batch-store-agenda-views)))
20321 ;; FIXME, why is this a macro?????
20322 ;;;###autoload
20323 (defmacro org-batch-store-agenda-views (&rest parameters)
20324 "Run all custom agenda commands that have a file argument."
20325 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20326 (pop-up-frames nil)
20327 (dir default-directory)
20328 pars cmd thiscmdkey files opts)
20329 (while parameters
20330 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20331 (setq pars (reverse pars))
20332 (save-window-excursion
20333 (while cmds
20334 (setq cmd (pop cmds)
20335 thiscmdkey (car cmd)
20336 opts (nth 4 cmd)
20337 files (nth 5 cmd))
20338 (if (stringp files) (setq files (list files)))
20339 (when files
20340 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20341 (list 'org-agenda nil thiscmdkey)))
20342 (set-buffer org-agenda-buffer-name)
20343 (while files
20344 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20345 (list 'org-write-agenda
20346 (expand-file-name (pop files) dir) t))))
20347 (and (get-buffer org-agenda-buffer-name)
20348 (kill-buffer org-agenda-buffer-name)))))))
20350 (defun org-write-agenda (file &optional nosettings)
20351 "Write the current buffer (an agenda view) as a file.
20352 Depending on the extension of the file name, plain text (.txt),
20353 HTML (.html or .htm) or Postscript (.ps) is produced.
20354 If NOSETTINGS is given, do not scope the settings of
20355 `org-agenda-exporter-settings' into the export commands. This is used when
20356 the settings have already been scoped and we do not wish to overrule other,
20357 higher priority settings."
20358 (interactive "FWrite agenda to file: ")
20359 (if (not (file-writable-p file))
20360 (error "Cannot write agenda to file %s" file))
20361 (cond
20362 ((string-match "\\.html?\\'" file) (require 'htmlize))
20363 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20364 (org-let (if nosettings nil org-agenda-exporter-settings)
20365 '(save-excursion
20366 (save-window-excursion
20367 (cond
20368 ((string-match "\\.html?\\'" file)
20369 (set-buffer (htmlize-buffer (current-buffer)))
20371 (when (and org-agenda-export-html-style
20372 (string-match "<style>" org-agenda-export-html-style))
20373 ;; replace <style> section with org-agenda-export-html-style
20374 (goto-char (point-min))
20375 (kill-region (- (search-forward "<style") 6)
20376 (search-forward "</style>"))
20377 (insert org-agenda-export-html-style))
20378 (write-file file)
20379 (kill-buffer (current-buffer))
20380 (message "HTML written to %s" file))
20381 ((string-match "\\.ps\\'" file)
20382 (ps-print-buffer-with-faces file)
20383 (message "Postscript written to %s" file))
20385 (let ((bs (buffer-string)))
20386 (find-file file)
20387 (insert bs)
20388 (save-buffer 0)
20389 (kill-buffer (current-buffer))
20390 (message "Plain text written to %s" file))))))
20391 (set-buffer org-agenda-buffer-name)))
20393 (defmacro org-no-read-only (&rest body)
20394 "Inhibit read-only for BODY."
20395 `(let ((inhibit-read-only t)) ,@body))
20397 (defun org-check-for-org-mode ()
20398 "Make sure current buffer is in org-mode. Error if not."
20399 (or (org-mode-p)
20400 (error "Cannot execute org-mode agenda command on buffer in %s."
20401 major-mode)))
20403 (defun org-fit-agenda-window ()
20404 "Fit the window to the buffer size."
20405 (and (memq org-agenda-window-setup '(reorganize-frame))
20406 (fboundp 'fit-window-to-buffer)
20407 (fit-window-to-buffer
20409 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20410 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20412 ;;; Agenda file list
20414 (defun org-agenda-files (&optional unrestricted)
20415 "Get the list of agenda files.
20416 Optional UNRESTRICTED means return the full list even if a restriction
20417 is currently in place."
20418 (let ((files
20419 (cond
20420 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20421 ((stringp org-agenda-files) (org-read-agenda-file-list))
20422 ((listp org-agenda-files) org-agenda-files)
20423 (t (error "Invalid value of `org-agenda-files'")))))
20424 (setq files (apply 'append
20425 (mapcar (lambda (f)
20426 (if (file-directory-p f)
20427 (directory-files f t
20428 org-agenda-file-regexp)
20429 (list f)))
20430 files)))
20431 (if org-agenda-skip-unavailable-files
20432 (delq nil
20433 (mapcar (function
20434 (lambda (file)
20435 (and (file-readable-p file) file)))
20436 files))
20437 files))) ; `org-check-agenda-file' will remove them from the list
20439 (defun org-edit-agenda-file-list ()
20440 "Edit the list of agenda files.
20441 Depending on setup, this either uses customize to edit the variable
20442 `org-agenda-files', or it visits the file that is holding the list. In the
20443 latter case, the buffer is set up in a way that saving it automatically kills
20444 the buffer and restores the previous window configuration."
20445 (interactive)
20446 (if (stringp org-agenda-files)
20447 (let ((cw (current-window-configuration)))
20448 (find-file org-agenda-files)
20449 (org-set-local 'org-window-configuration cw)
20450 (org-add-hook 'after-save-hook
20451 (lambda ()
20452 (set-window-configuration
20453 (prog1 org-window-configuration
20454 (kill-buffer (current-buffer))))
20455 (org-install-agenda-files-menu)
20456 (message "New agenda file list installed"))
20457 nil 'local)
20458 (message "%s" (substitute-command-keys
20459 "Edit list and finish with \\[save-buffer]")))
20460 (customize-variable 'org-agenda-files)))
20462 (defun org-store-new-agenda-file-list (list)
20463 "Set new value for the agenda file list and save it correcly."
20464 (if (stringp org-agenda-files)
20465 (let ((f org-agenda-files) b)
20466 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20467 (with-temp-file f
20468 (insert (mapconcat 'identity list "\n") "\n")))
20469 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20470 (setq org-agenda-files list)
20471 (customize-save-variable 'org-agenda-files org-agenda-files))))
20473 (defun org-read-agenda-file-list ()
20474 "Read the list of agenda files from a file."
20475 (when (stringp org-agenda-files)
20476 (with-temp-buffer
20477 (insert-file-contents org-agenda-files)
20478 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20481 ;;;###autoload
20482 (defun org-cycle-agenda-files ()
20483 "Cycle through the files in `org-agenda-files'.
20484 If the current buffer visits an agenda file, find the next one in the list.
20485 If the current buffer does not, find the first agenda file."
20486 (interactive)
20487 (let* ((fs (org-agenda-files t))
20488 (files (append fs (list (car fs))))
20489 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20490 file)
20491 (unless files (error "No agenda files"))
20492 (catch 'exit
20493 (while (setq file (pop files))
20494 (if (equal (file-truename file) tcf)
20495 (when (car files)
20496 (find-file (car files))
20497 (throw 'exit t))))
20498 (find-file (car fs)))
20499 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20501 (defun org-agenda-file-to-front (&optional to-end)
20502 "Move/add the current file to the top of the agenda file list.
20503 If the file is not present in the list, it is added to the front. If it is
20504 present, it is moved there. With optional argument TO-END, add/move to the
20505 end of the list."
20506 (interactive "P")
20507 (let ((org-agenda-skip-unavailable-files nil)
20508 (file-alist (mapcar (lambda (x)
20509 (cons (file-truename x) x))
20510 (org-agenda-files t)))
20511 (ctf (file-truename buffer-file-name))
20512 x had)
20513 (setq x (assoc ctf file-alist) had x)
20515 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20516 (if to-end
20517 (setq file-alist (append (delq x file-alist) (list x)))
20518 (setq file-alist (cons x (delq x file-alist))))
20519 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20520 (org-install-agenda-files-menu)
20521 (message "File %s to %s of agenda file list"
20522 (if had "moved" "added") (if to-end "end" "front"))))
20524 (defun org-remove-file (&optional file)
20525 "Remove current file from the list of files in variable `org-agenda-files'.
20526 These are the files which are being checked for agenda entries.
20527 Optional argument FILE means, use this file instead of the current."
20528 (interactive)
20529 (let* ((org-agenda-skip-unavailable-files nil)
20530 (file (or file buffer-file-name))
20531 (true-file (file-truename file))
20532 (afile (abbreviate-file-name file))
20533 (files (delq nil (mapcar
20534 (lambda (x)
20535 (if (equal true-file
20536 (file-truename x))
20537 nil x))
20538 (org-agenda-files t)))))
20539 (if (not (= (length files) (length (org-agenda-files t))))
20540 (progn
20541 (org-store-new-agenda-file-list files)
20542 (org-install-agenda-files-menu)
20543 (message "Removed file: %s" afile))
20544 (message "File was not in list: %s (not removed)" afile))))
20546 (defun org-file-menu-entry (file)
20547 (vector file (list 'find-file file) t))
20549 (defun org-check-agenda-file (file)
20550 "Make sure FILE exists. If not, ask user what to do."
20551 (when (not (file-exists-p file))
20552 (message "non-existent file %s. [R]emove from list or [A]bort?"
20553 (abbreviate-file-name file))
20554 (let ((r (downcase (read-char-exclusive))))
20555 (cond
20556 ((equal r ?r)
20557 (org-remove-file file)
20558 (throw 'nextfile t))
20559 (t (error "Abort"))))))
20561 ;;; Agenda prepare and finalize
20563 (defvar org-agenda-multi nil) ; dynammically scoped
20564 (defvar org-agenda-buffer-name "*Org Agenda*")
20565 (defvar org-pre-agenda-window-conf nil)
20566 (defvar org-agenda-name nil)
20567 (defun org-prepare-agenda (&optional name)
20568 (setq org-todo-keywords-for-agenda nil)
20569 (setq org-done-keywords-for-agenda nil)
20570 (if org-agenda-multi
20571 (progn
20572 (setq buffer-read-only nil)
20573 (goto-char (point-max))
20574 (unless (or (bobp) org-agenda-compact-blocks)
20575 (insert "\n" (make-string (window-width) ?=) "\n"))
20576 (narrow-to-region (point) (point-max)))
20577 (org-agenda-reset-markers)
20578 (org-prepare-agenda-buffers (org-agenda-files))
20579 (setq org-todo-keywords-for-agenda
20580 (org-uniquify org-todo-keywords-for-agenda))
20581 (setq org-done-keywords-for-agenda
20582 (org-uniquify org-done-keywords-for-agenda))
20583 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20584 (awin (get-buffer-window abuf)))
20585 (cond
20586 ((equal (current-buffer) abuf) nil)
20587 (awin (select-window awin))
20588 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20589 ((equal org-agenda-window-setup 'current-window)
20590 (switch-to-buffer abuf))
20591 ((equal org-agenda-window-setup 'other-window)
20592 (org-switch-to-buffer-other-window abuf))
20593 ((equal org-agenda-window-setup 'other-frame)
20594 (switch-to-buffer-other-frame abuf))
20595 ((equal org-agenda-window-setup 'reorganize-frame)
20596 (delete-other-windows)
20597 (org-switch-to-buffer-other-window abuf))))
20598 (setq buffer-read-only nil)
20599 (erase-buffer)
20600 (org-agenda-mode)
20601 (and name (not org-agenda-name)
20602 (org-set-local 'org-agenda-name name)))
20603 (setq buffer-read-only nil))
20605 (defun org-finalize-agenda ()
20606 "Finishing touch for the agenda buffer, called just before displaying it."
20607 (unless org-agenda-multi
20608 (save-excursion
20609 (let ((inhibit-read-only t))
20610 (goto-char (point-min))
20611 (while (org-activate-bracket-links (point-max))
20612 (add-text-properties (match-beginning 0) (match-end 0)
20613 '(face org-link)))
20614 (org-agenda-align-tags)
20615 (unless org-agenda-with-colors
20616 (remove-text-properties (point-min) (point-max) '(face nil))))
20617 (if (and (boundp 'org-overriding-columns-format)
20618 org-overriding-columns-format)
20619 (org-set-local 'org-overriding-columns-format
20620 org-overriding-columns-format))
20621 (if (and (boundp 'org-agenda-view-columns-initially)
20622 org-agenda-view-columns-initially)
20623 (org-agenda-columns))
20624 (when org-agenda-fontify-priorities
20625 (org-fontify-priorities))
20626 (run-hooks 'org-finalize-agenda-hook)
20627 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20630 (defun org-fontify-priorities ()
20631 "Make highest priority lines bold, and lowest italic."
20632 (interactive)
20633 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20634 (org-delete-overlay o)))
20635 (org-overlays-in (point-min) (point-max)))
20636 (save-excursion
20637 (let ((inhibit-read-only t)
20638 b e p ov h l)
20639 (goto-char (point-min))
20640 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20641 (setq h (or (get-char-property (point) 'org-highest-priority)
20642 org-highest-priority)
20643 l (or (get-char-property (point) 'org-lowest-priority)
20644 org-lowest-priority)
20645 p (string-to-char (match-string 1))
20646 b (match-beginning 0) e (point-at-eol)
20647 ov (org-make-overlay b e))
20648 (org-overlay-put
20649 ov 'face
20650 (cond ((listp org-agenda-fontify-priorities)
20651 (cdr (assoc p org-agenda-fontify-priorities)))
20652 ((equal p l) 'italic)
20653 ((equal p h) 'bold)))
20654 (org-overlay-put ov 'org-type 'org-priority)))))
20656 (defun org-prepare-agenda-buffers (files)
20657 "Create buffers for all agenda files, protect archived trees and comments."
20658 (interactive)
20659 (let ((pa '(:org-archived t))
20660 (pc '(:org-comment t))
20661 (pall '(:org-archived t :org-comment t))
20662 (inhibit-read-only t)
20663 (rea (concat ":" org-archive-tag ":"))
20664 bmp file re)
20665 (save-excursion
20666 (save-restriction
20667 (while (setq file (pop files))
20668 (if (bufferp file)
20669 (set-buffer file)
20670 (org-check-agenda-file file)
20671 (set-buffer (org-get-agenda-file-buffer file)))
20672 (widen)
20673 (setq bmp (buffer-modified-p))
20674 (org-refresh-category-properties)
20675 (setq org-todo-keywords-for-agenda
20676 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20677 (setq org-done-keywords-for-agenda
20678 (append org-done-keywords-for-agenda org-done-keywords))
20679 (save-excursion
20680 (remove-text-properties (point-min) (point-max) pall)
20681 (when org-agenda-skip-archived-trees
20682 (goto-char (point-min))
20683 (while (re-search-forward rea nil t)
20684 (if (org-on-heading-p t)
20685 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20686 (goto-char (point-min))
20687 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20688 (while (re-search-forward re nil t)
20689 (add-text-properties
20690 (match-beginning 0) (org-end-of-subtree t) pc)))
20691 (set-buffer-modified-p bmp))))))
20693 (defvar org-agenda-skip-function nil
20694 "Function to be called at each match during agenda construction.
20695 If this function returns nil, the current match should not be skipped.
20696 Otherwise, the function must return a position from where the search
20697 should be continued.
20698 This may also be a Lisp form, it will be evaluated.
20699 Never set this variable using `setq' or so, because then it will apply
20700 to all future agenda commands. Instead, bind it with `let' to scope
20701 it dynamically into the agenda-constructing command. A good way to set
20702 it is through options in org-agenda-custom-commands.")
20704 (defun org-agenda-skip ()
20705 "Throw to `:skip' in places that should be skipped.
20706 Also moves point to the end of the skipped region, so that search can
20707 continue from there."
20708 (let ((p (point-at-bol)) to fp)
20709 (and org-agenda-skip-archived-trees
20710 (get-text-property p :org-archived)
20711 (org-end-of-subtree t)
20712 (throw :skip t))
20713 (and (get-text-property p :org-comment)
20714 (org-end-of-subtree t)
20715 (throw :skip t))
20716 (if (equal (char-after p) ?#) (throw :skip t))
20717 (when (and (or (setq fp (functionp org-agenda-skip-function))
20718 (consp org-agenda-skip-function))
20719 (setq to (save-excursion
20720 (save-match-data
20721 (if fp
20722 (funcall org-agenda-skip-function)
20723 (eval org-agenda-skip-function))))))
20724 (goto-char to)
20725 (throw :skip t))))
20727 (defvar org-agenda-markers nil
20728 "List of all currently active markers created by `org-agenda'.")
20729 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20730 "Creation time of the last agenda marker.")
20732 (defun org-agenda-new-marker (&optional pos)
20733 "Return a new agenda marker.
20734 Org-mode keeps a list of these markers and resets them when they are
20735 no longer in use."
20736 (let ((m (copy-marker (or pos (point)))))
20737 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20738 (push m org-agenda-markers)
20741 (defun org-agenda-reset-markers ()
20742 "Reset markers created by `org-agenda'."
20743 (while org-agenda-markers
20744 (move-marker (pop org-agenda-markers) nil)))
20746 (defun org-get-agenda-file-buffer (file)
20747 "Get a buffer visiting FILE. If the buffer needs to be created, add
20748 it to the list of buffers which might be released later."
20749 (let ((buf (org-find-base-buffer-visiting file)))
20750 (if buf
20751 buf ; just return it
20752 ;; Make a new buffer and remember it
20753 (setq buf (find-file-noselect file))
20754 (if buf (push buf org-agenda-new-buffers))
20755 buf)))
20757 (defun org-release-buffers (blist)
20758 "Release all buffers in list, asking the user for confirmation when needed.
20759 When a buffer is unmodified, it is just killed. When modified, it is saved
20760 \(if the user agrees) and then killed."
20761 (let (buf file)
20762 (while (setq buf (pop blist))
20763 (setq file (buffer-file-name buf))
20764 (when (and (buffer-modified-p buf)
20765 file
20766 (y-or-n-p (format "Save file %s? " file)))
20767 (with-current-buffer buf (save-buffer)))
20768 (kill-buffer buf))))
20770 (defun org-get-category (&optional pos)
20771 "Get the category applying to position POS."
20772 (get-text-property (or pos (point)) 'org-category))
20774 ;;; Agenda timeline
20776 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20778 (defun org-timeline (&optional include-all)
20779 "Show a time-sorted view of the entries in the current org file.
20780 Only entries with a time stamp of today or later will be listed. With
20781 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20782 under the current date.
20783 If the buffer contains an active region, only check the region for
20784 dates."
20785 (interactive "P")
20786 (require 'calendar)
20787 (org-compile-prefix-format 'timeline)
20788 (org-set-sorting-strategy 'timeline)
20789 (let* ((dopast t)
20790 (dotodo include-all)
20791 (doclosed org-agenda-show-log)
20792 (entry buffer-file-name)
20793 (date (calendar-current-date))
20794 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20795 (end (if (org-region-active-p) (region-end) (point-max)))
20796 (day-numbers (org-get-all-dates beg end 'no-ranges
20797 t doclosed ; always include today
20798 org-timeline-show-empty-dates))
20799 (org-deadline-warning-days 0)
20800 (org-agenda-only-exact-dates t)
20801 (today (time-to-days (current-time)))
20802 (past t)
20803 args
20804 s e rtn d emptyp)
20805 (setq org-agenda-redo-command
20806 (list 'progn
20807 (list 'org-switch-to-buffer-other-window (current-buffer))
20808 (list 'org-timeline (list 'quote include-all))))
20809 (if (not dopast)
20810 ;; Remove past dates from the list of dates.
20811 (setq day-numbers (delq nil (mapcar (lambda(x)
20812 (if (>= x today) x nil))
20813 day-numbers))))
20814 (org-prepare-agenda (concat "Timeline "
20815 (file-name-nondirectory buffer-file-name)))
20816 (if doclosed (push :closed args))
20817 (push :timestamp args)
20818 (push :deadline args)
20819 (push :scheduled args)
20820 (push :sexp args)
20821 (if dotodo (push :todo args))
20822 (while (setq d (pop day-numbers))
20823 (if (and (listp d) (eq (car d) :omitted))
20824 (progn
20825 (setq s (point))
20826 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20827 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20828 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20829 (if (and (>= d today)
20830 dopast
20831 past)
20832 (progn
20833 (setq past nil)
20834 (insert (make-string 79 ?-) "\n")))
20835 (setq date (calendar-gregorian-from-absolute d))
20836 (setq s (point))
20837 (setq rtn (and (not emptyp)
20838 (apply 'org-agenda-get-day-entries entry
20839 date args)))
20840 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20841 (progn
20842 (insert
20843 (if (stringp org-agenda-format-date)
20844 (format-time-string org-agenda-format-date
20845 (org-time-from-absolute date))
20846 (funcall org-agenda-format-date date))
20847 "\n")
20848 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20849 (put-text-property s (1- (point)) 'org-date-line t)
20850 (if (equal d today)
20851 (put-text-property s (1- (point)) 'org-today t))
20852 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20853 (put-text-property s (1- (point)) 'day d)))))
20854 (goto-char (point-min))
20855 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20856 (point-min)))
20857 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20858 (org-finalize-agenda)
20859 (setq buffer-read-only t)))
20861 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20862 "Return a list of all relevant day numbers from BEG to END buffer positions.
20863 If NO-RANGES is non-nil, include only the start and end dates of a range,
20864 not every single day in the range. If FORCE-TODAY is non-nil, make
20865 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20866 inactive time stamps (those in square brackets) are included.
20867 When EMPTY is non-nil, also include days without any entries."
20868 (let ((re (concat
20869 (if pre-re pre-re "")
20870 (if inactive org-ts-regexp-both org-ts-regexp)))
20871 dates dates1 date day day1 day2 ts1 ts2)
20872 (if force-today
20873 (setq dates (list (time-to-days (current-time)))))
20874 (save-excursion
20875 (goto-char beg)
20876 (while (re-search-forward re end t)
20877 (setq day (time-to-days (org-time-string-to-time
20878 (substring (match-string 1) 0 10))))
20879 (or (memq day dates) (push day dates)))
20880 (unless no-ranges
20881 (goto-char beg)
20882 (while (re-search-forward org-tr-regexp end t)
20883 (setq ts1 (substring (match-string 1) 0 10)
20884 ts2 (substring (match-string 2) 0 10)
20885 day1 (time-to-days (org-time-string-to-time ts1))
20886 day2 (time-to-days (org-time-string-to-time ts2)))
20887 (while (< (setq day1 (1+ day1)) day2)
20888 (or (memq day1 dates) (push day1 dates)))))
20889 (setq dates (sort dates '<))
20890 (when empty
20891 (while (setq day (pop dates))
20892 (setq day2 (car dates))
20893 (push day dates1)
20894 (when (and day2 empty)
20895 (if (or (eq empty t)
20896 (and (numberp empty) (<= (- day2 day) empty)))
20897 (while (< (setq day (1+ day)) day2)
20898 (push (list day) dates1))
20899 (push (cons :omitted (- day2 day)) dates1))))
20900 (setq dates (nreverse dates1)))
20901 dates)))
20903 ;;; Agenda Daily/Weekly
20905 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20906 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20907 (defvar org-agenda-last-arguments nil
20908 "The arguments of the previous call to org-agenda")
20909 (defvar org-starting-day nil) ; local variable in the agenda buffer
20910 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20911 (defvar org-include-all-loc nil) ; local variable
20912 (defvar org-agenda-remove-date nil) ; dynamically scoped FIXME: not used???
20914 ;;;###autoload
20915 (defun org-agenda-list (&optional include-all start-day ndays)
20916 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20917 The view will be for the current day or week, but from the overview buffer
20918 you will be able to go to other days/weeks.
20920 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20921 all unfinished TODO items will also be shown, before the agenda.
20922 This feature is considered obsolete, please use the TODO list or a block
20923 agenda instead.
20925 With a numeric prefix argument in an interactive call, the agenda will
20926 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20927 the number of days. NDAYS defaults to `org-agenda-ndays'.
20929 START-DAY defaults to TODAY, or to the most recent match for the weekday
20930 given in `org-agenda-start-on-weekday'."
20931 (interactive "P")
20932 (if (and (integerp include-all) (> include-all 0))
20933 (setq ndays include-all include-all nil))
20934 (setq ndays (or ndays org-agenda-ndays)
20935 start-day (or start-day org-agenda-start-day))
20936 (if org-agenda-overriding-arguments
20937 (setq include-all (car org-agenda-overriding-arguments)
20938 start-day (nth 1 org-agenda-overriding-arguments)
20939 ndays (nth 2 org-agenda-overriding-arguments)))
20940 (if (stringp start-day)
20941 ;; Convert to an absolute day number
20942 (setq start-day (time-to-days (org-read-date nil t start-day))))
20943 (setq org-agenda-last-arguments (list include-all start-day ndays))
20944 (org-compile-prefix-format 'agenda)
20945 (org-set-sorting-strategy 'agenda)
20946 (require 'calendar)
20947 (let* ((org-agenda-start-on-weekday
20948 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20949 org-agenda-start-on-weekday nil))
20950 (thefiles (org-agenda-files))
20951 (files thefiles)
20952 (today (time-to-days
20953 (time-subtract (current-time)
20954 (list 0 (* 3600 org-extend-today-until) 0))))
20955 (sd (or start-day today))
20956 (start (if (or (null org-agenda-start-on-weekday)
20957 (< org-agenda-ndays 7))
20959 (let* ((nt (calendar-day-of-week
20960 (calendar-gregorian-from-absolute sd)))
20961 (n1 org-agenda-start-on-weekday)
20962 (d (- nt n1)))
20963 (- sd (+ (if (< d 0) 7 0) d)))))
20964 (day-numbers (list start))
20965 (day-cnt 0)
20966 (inhibit-redisplay (not debug-on-error))
20967 s e rtn rtnall file date d start-pos end-pos todayp nd)
20968 (setq org-agenda-redo-command
20969 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20970 ;; Make the list of days
20971 (setq ndays (or ndays org-agenda-ndays)
20972 nd ndays)
20973 (while (> ndays 1)
20974 (push (1+ (car day-numbers)) day-numbers)
20975 (setq ndays (1- ndays)))
20976 (setq day-numbers (nreverse day-numbers))
20977 (org-prepare-agenda "Day/Week")
20978 (org-set-local 'org-starting-day (car day-numbers))
20979 (org-set-local 'org-include-all-loc include-all)
20980 (org-set-local 'org-agenda-span
20981 (org-agenda-ndays-to-span nd))
20982 (when (and (or include-all org-agenda-include-all-todo)
20983 (member today day-numbers))
20984 (setq files thefiles
20985 rtnall nil)
20986 (while (setq file (pop files))
20987 (catch 'nextfile
20988 (org-check-agenda-file file)
20989 (setq date (calendar-gregorian-from-absolute today)
20990 rtn (org-agenda-get-day-entries
20991 file date :todo))
20992 (setq rtnall (append rtnall rtn))))
20993 (when rtnall
20994 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20995 (add-text-properties (point-min) (1- (point))
20996 (list 'face 'org-agenda-structure))
20997 (insert (org-finalize-agenda-entries rtnall) "\n")))
20998 (unless org-agenda-compact-blocks
20999 (setq s (point))
21000 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
21001 "-agenda:\n")
21002 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
21003 'org-date-line t)))
21004 (while (setq d (pop day-numbers))
21005 (setq date (calendar-gregorian-from-absolute d)
21006 s (point))
21007 (if (or (setq todayp (= d today))
21008 (and (not start-pos) (= d sd)))
21009 (setq start-pos (point))
21010 (if (and start-pos (not end-pos))
21011 (setq end-pos (point))))
21012 (setq files thefiles
21013 rtnall nil)
21014 (while (setq file (pop files))
21015 (catch 'nextfile
21016 (org-check-agenda-file file)
21017 (if org-agenda-show-log
21018 (setq rtn (org-agenda-get-day-entries
21019 file date
21020 :deadline :scheduled :timestamp :sexp :closed))
21021 (setq rtn (org-agenda-get-day-entries
21022 file date
21023 :deadline :scheduled :sexp :timestamp)))
21024 (setq rtnall (append rtnall rtn))))
21025 (if org-agenda-include-diary
21026 (progn
21027 (require 'diary-lib)
21028 (setq rtn (org-get-entries-from-diary date))
21029 (setq rtnall (append rtnall rtn))))
21030 (if (or rtnall org-agenda-show-all-dates)
21031 (progn
21032 (setq day-cnt (1+ day-cnt))
21033 (insert
21034 (if (stringp org-agenda-format-date)
21035 (format-time-string org-agenda-format-date
21036 (org-time-from-absolute date))
21037 (funcall org-agenda-format-date date))
21038 "\n")
21039 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
21040 (put-text-property s (1- (point)) 'org-date-line t)
21041 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
21042 (if todayp (put-text-property s (1- (point)) 'org-today t))
21043 (if rtnall (insert
21044 (org-finalize-agenda-entries
21045 (org-agenda-add-time-grid-maybe
21046 rtnall nd todayp))
21047 "\n"))
21048 (put-text-property s (1- (point)) 'day d)
21049 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
21050 (goto-char (point-min))
21051 (org-fit-agenda-window)
21052 (unless (and (pos-visible-in-window-p (point-min))
21053 (pos-visible-in-window-p (point-max)))
21054 (goto-char (1- (point-max)))
21055 (recenter -1)
21056 (if (not (pos-visible-in-window-p (or start-pos 1)))
21057 (progn
21058 (goto-char (or start-pos 1))
21059 (recenter 1))))
21060 (goto-char (or start-pos 1))
21061 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
21062 (org-finalize-agenda)
21063 (setq buffer-read-only t)
21064 (message "")))
21066 (defun org-agenda-ndays-to-span (n)
21067 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
21069 ;;; Agenda word search
21071 (defvar org-agenda-search-history nil)
21073 ;;;###autoload
21074 (defun org-search-view (&optional arg string)
21075 "Show all entries that contain words or regular expressions.
21076 If the first character of the search string is an asterisks,
21077 search only the headlines.
21079 The search string is broken into \"words\" by splitting at whitespace.
21080 The individual words are then interpreted as a boolean expression with
21081 logical AND. Words prefixed with a minus must not occur in the entry.
21082 Words without a prefix or prefixed with a plus must occur in the entry.
21083 Matching is case-insensitive and the words are enclosed by word delimiters.
21085 Words enclosed by curly braces are interpreted as regular expressions
21086 that must or must not match in the entry.
21088 This command searches the agenda files, and in addition the files listed
21089 in `org-agenda-text-search-extra-files'."
21090 (interactive "P")
21091 (org-compile-prefix-format 'search)
21092 (org-set-sorting-strategy 'search)
21093 (org-prepare-agenda "SEARCH")
21094 (let* ((props (list 'face nil
21095 'done-face 'org-done
21096 'org-not-done-regexp org-not-done-regexp
21097 'org-todo-regexp org-todo-regexp
21098 'mouse-face 'highlight
21099 'keymap org-agenda-keymap
21100 'help-echo (format "mouse-2 or RET jump to location")))
21101 regexp rtn rtnall files file pos
21102 marker priority category tags c neg re
21103 ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
21104 (unless (and (not arg)
21105 (stringp string)
21106 (string-match "\\S-" string))
21107 (setq string (read-string "[+-]Word/{Regexp} ...: "
21108 (cond
21109 ((integerp arg) (cons string arg))
21110 (arg string))
21111 'org-agenda-search-history)))
21112 (setq org-agenda-redo-command
21113 (list 'org-search-view 'current-prefix-arg string))
21114 (setq org-agenda-query-string string)
21116 (if (equal (string-to-char string) ?*)
21117 (setq hdl-only t
21118 words (substring string 1))
21119 (setq words string))
21120 (setq words (org-split-string words))
21121 (mapc (lambda (w)
21122 (setq c (string-to-char w))
21123 (if (equal c ?-)
21124 (setq neg t w (substring w 1))
21125 (if (equal c ?+)
21126 (setq neg nil w (substring w 1))
21127 (setq neg nil)))
21128 (if (string-match "\\`{.*}\\'" w)
21129 (setq re (substring w 1 -1))
21130 (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>")))
21131 (if neg (push re regexps-) (push re regexps+)))
21132 words)
21133 (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b)))))
21134 (if (not regexps+)
21135 (setq regexp (concat "^" org-outline-regexp))
21136 (setq regexp (pop regexps+))
21137 (if hdl-only (setq regexp (concat "^" org-outline-regexp ".*?"
21138 regexp))))
21139 (setq files (append (org-agenda-files) org-agenda-text-search-extra-files)
21140 rtnall nil)
21141 (while (setq file (pop files))
21142 (setq ee nil)
21143 (catch 'nextfile
21144 (org-check-agenda-file file)
21145 (setq buffer (if (file-exists-p file)
21146 (org-get-agenda-file-buffer file)
21147 (error "No such file %s" file)))
21148 (if (not buffer)
21149 ;; If file does not exist, make sure an error message is sent
21150 (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s"
21151 file))))
21152 (with-current-buffer buffer
21153 (unless (org-mode-p)
21154 (error "Agenda file %s is not in `org-mode'" file))
21155 (let ((case-fold-search t))
21156 (save-excursion
21157 (save-restriction
21158 (if org-agenda-restrict
21159 (narrow-to-region org-agenda-restrict-begin
21160 org-agenda-restrict-end)
21161 (widen))
21162 (goto-char (point-min))
21163 (unless (or (org-on-heading-p)
21164 (outline-next-heading))
21165 (throw 'nextfile t))
21166 (goto-char (max (point-min) (1- (point))))
21167 (while (re-search-forward regexp nil t)
21168 (org-back-to-heading t)
21169 (skip-chars-forward "* ")
21170 (setq beg (point-at-bol)
21171 beg1 (point)
21172 end (progn (outline-next-heading) (point)))
21173 (catch :skip
21174 (goto-char beg)
21175 (org-agenda-skip)
21176 (setq str (buffer-substring-no-properties
21177 (point-at-bol)
21178 (if hdl-only (point-at-eol) end)))
21179 (mapc (lambda (wr) (when (string-match wr str)
21180 (goto-char (1- end))
21181 (throw :skip t)))
21182 regexps-)
21183 (mapc (lambda (wr) (unless (string-match wr str)
21184 (goto-char (1- end))
21185 (throw :skip t)))
21186 regexps+)
21187 (goto-char beg)
21188 (setq marker (org-agenda-new-marker (point))
21189 category (org-get-category)
21190 tags (org-get-tags-at (point))
21191 txt (org-format-agenda-item
21193 (buffer-substring-no-properties
21194 beg1 (point-at-eol))
21195 category tags))
21196 (org-add-props txt props
21197 'org-marker marker 'org-hd-marker marker
21198 'priority 1000 'org-category category
21199 'type "search")
21200 (push txt ee)
21201 (goto-char (1- end)))))))))
21202 (setq rtn (nreverse ee))
21203 (setq rtnall (append rtnall rtn)))
21204 (if org-agenda-overriding-header
21205 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21206 nil 'face 'org-agenda-structure) "\n")
21207 (insert "Search words: ")
21208 (add-text-properties (point-min) (1- (point))
21209 (list 'face 'org-agenda-structure))
21210 (setq pos (point))
21211 (insert string "\n")
21212 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21213 (setq pos (point))
21214 (unless org-agenda-multi
21215 (insert "Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit\n")
21216 (add-text-properties pos (1- (point))
21217 (list 'face 'org-agenda-structure))))
21218 (when rtnall
21219 (insert (org-finalize-agenda-entries rtnall) "\n"))
21220 (goto-char (point-min))
21221 (org-fit-agenda-window)
21222 (add-text-properties (point-min) (point-max) '(org-agenda-type search))
21223 (org-finalize-agenda)
21224 (setq buffer-read-only t)))
21226 ;;; Agenda TODO list
21228 (defvar org-select-this-todo-keyword nil)
21229 (defvar org-last-arg nil)
21231 ;;;###autoload
21232 (defun org-todo-list (arg)
21233 "Show all TODO entries from all agenda file in a single list.
21234 The prefix arg can be used to select a specific TODO keyword and limit
21235 the list to these. When using \\[universal-argument], you will be prompted
21236 for a keyword. A numeric prefix directly selects the Nth keyword in
21237 `org-todo-keywords-1'."
21238 (interactive "P")
21239 (require 'calendar)
21240 (org-compile-prefix-format 'todo)
21241 (org-set-sorting-strategy 'todo)
21242 (org-prepare-agenda "TODO")
21243 (let* ((today (time-to-days (current-time)))
21244 (date (calendar-gregorian-from-absolute today))
21245 (kwds org-todo-keywords-for-agenda)
21246 (completion-ignore-case t)
21247 (org-select-this-todo-keyword
21248 (if (stringp arg) arg
21249 (and arg (integerp arg) (> arg 0)
21250 (nth (1- arg) kwds))))
21251 rtn rtnall files file pos)
21252 (when (equal arg '(4))
21253 (setq org-select-this-todo-keyword
21254 (completing-read "Keyword (or KWD1|K2D2|...): "
21255 (mapcar 'list kwds) nil nil)))
21256 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
21257 (org-set-local 'org-last-arg arg)
21258 (setq org-agenda-redo-command
21259 '(org-todo-list (or current-prefix-arg org-last-arg)))
21260 (setq files (org-agenda-files)
21261 rtnall nil)
21262 (while (setq file (pop files))
21263 (catch 'nextfile
21264 (org-check-agenda-file file)
21265 (setq rtn (org-agenda-get-day-entries file date :todo))
21266 (setq rtnall (append rtnall rtn))))
21267 (if org-agenda-overriding-header
21268 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21269 nil 'face 'org-agenda-structure) "\n")
21270 (insert "Global list of TODO items of type: ")
21271 (add-text-properties (point-min) (1- (point))
21272 (list 'face 'org-agenda-structure))
21273 (setq pos (point))
21274 (insert (or org-select-this-todo-keyword "ALL") "\n")
21275 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21276 (setq pos (point))
21277 (unless org-agenda-multi
21278 (insert "Available with `N r': (0)ALL")
21279 (let ((n 0) s)
21280 (mapc (lambda (x)
21281 (setq s (format "(%d)%s" (setq n (1+ n)) x))
21282 (if (> (+ (current-column) (string-width s) 1) (frame-width))
21283 (insert "\n "))
21284 (insert " " s))
21285 kwds))
21286 (insert "\n"))
21287 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21288 (when rtnall
21289 (insert (org-finalize-agenda-entries rtnall) "\n"))
21290 (goto-char (point-min))
21291 (org-fit-agenda-window)
21292 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
21293 (org-finalize-agenda)
21294 (setq buffer-read-only t)))
21296 ;;; Agenda tags match
21298 ;;;###autoload
21299 (defun org-tags-view (&optional todo-only match)
21300 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
21301 The prefix arg TODO-ONLY limits the search to TODO entries."
21302 (interactive "P")
21303 (org-compile-prefix-format 'tags)
21304 (org-set-sorting-strategy 'tags)
21305 (let* ((org-tags-match-list-sublevels
21306 (if todo-only t org-tags-match-list-sublevels))
21307 (completion-ignore-case t)
21308 rtn rtnall files file pos matcher
21309 buffer)
21310 (setq matcher (org-make-tags-matcher match)
21311 match (car matcher) matcher (cdr matcher))
21312 (org-prepare-agenda (concat "TAGS " match))
21313 (setq org-agenda-query-string match)
21314 (setq org-agenda-redo-command
21315 (list 'org-tags-view (list 'quote todo-only)
21316 (list 'if 'current-prefix-arg nil 'org-agenda-query-string)))
21317 (setq files (org-agenda-files)
21318 rtnall nil)
21319 (while (setq file (pop files))
21320 (catch 'nextfile
21321 (org-check-agenda-file file)
21322 (setq buffer (if (file-exists-p file)
21323 (org-get-agenda-file-buffer file)
21324 (error "No such file %s" file)))
21325 (if (not buffer)
21326 ;; If file does not exist, merror message to agenda
21327 (setq rtn (list
21328 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21329 rtnall (append rtnall rtn))
21330 (with-current-buffer buffer
21331 (unless (org-mode-p)
21332 (error "Agenda file %s is not in `org-mode'" file))
21333 (save-excursion
21334 (save-restriction
21335 (if org-agenda-restrict
21336 (narrow-to-region org-agenda-restrict-begin
21337 org-agenda-restrict-end)
21338 (widen))
21339 (setq rtn (org-scan-tags 'agenda matcher todo-only))
21340 (setq rtnall (append rtnall rtn))))))))
21341 (if org-agenda-overriding-header
21342 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21343 nil 'face 'org-agenda-structure) "\n")
21344 (insert "Headlines with TAGS match: ")
21345 (add-text-properties (point-min) (1- (point))
21346 (list 'face 'org-agenda-structure))
21347 (setq pos (point))
21348 (insert match "\n")
21349 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21350 (setq pos (point))
21351 (unless org-agenda-multi
21352 (insert "Press `C-u r' to search again with new search string\n"))
21353 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21354 (when rtnall
21355 (insert (org-finalize-agenda-entries rtnall) "\n"))
21356 (goto-char (point-min))
21357 (org-fit-agenda-window)
21358 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
21359 (org-finalize-agenda)
21360 (setq buffer-read-only t)))
21362 ;;; Agenda Finding stuck projects
21364 (defvar org-agenda-skip-regexp nil
21365 "Regular expression used in skipping subtrees for the agenda.
21366 This is basically a temporary global variable that can be set and then
21367 used by user-defined selections using `org-agenda-skip-function'.")
21369 (defvar org-agenda-overriding-header nil
21370 "When this is set during todo and tags searches, will replace header.")
21372 (defun org-agenda-skip-subtree-when-regexp-matches ()
21373 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
21374 If yes, it returns the end position of this tree, causing agenda commands
21375 to skip this subtree. This is a function that can be put into
21376 `org-agenda-skip-function' for the duration of a command."
21377 (let ((end (save-excursion (org-end-of-subtree t)))
21378 skip)
21379 (save-excursion
21380 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
21381 (and skip end)))
21383 (defun org-agenda-skip-entry-if (&rest conditions)
21384 "Skip entry if any of CONDITIONS is true.
21385 See `org-agenda-skip-if' for details."
21386 (org-agenda-skip-if nil conditions))
21388 (defun org-agenda-skip-subtree-if (&rest conditions)
21389 "Skip entry if any of CONDITIONS is true.
21390 See `org-agenda-skip-if' for details."
21391 (org-agenda-skip-if t conditions))
21393 (defun org-agenda-skip-if (subtree conditions)
21394 "Checks current entity for CONDITIONS.
21395 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21396 the entry, i.e. the text before the next heading is checked.
21398 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21399 from different tests. Valid conditions are:
21401 scheduled Check if there is a scheduled cookie
21402 notscheduled Check if there is no scheduled cookie
21403 deadline Check if there is a deadline
21404 notdeadline Check if there is no deadline
21405 regexp Check if regexp matches
21406 notregexp Check if regexp does not match.
21408 The regexp is taken from the conditions list, it must come right after
21409 the `regexp' or `notregexp' element.
21411 If any of these conditions is met, this function returns the end point of
21412 the entity, causing the search to continue from there. This is a function
21413 that can be put into `org-agenda-skip-function' for the duration of a command."
21414 (let (beg end m)
21415 (org-back-to-heading t)
21416 (setq beg (point)
21417 end (if subtree
21418 (progn (org-end-of-subtree t) (point))
21419 (progn (outline-next-heading) (1- (point)))))
21420 (goto-char beg)
21421 (and
21423 (and (memq 'scheduled conditions)
21424 (re-search-forward org-scheduled-time-regexp end t))
21425 (and (memq 'notscheduled conditions)
21426 (not (re-search-forward org-scheduled-time-regexp end t)))
21427 (and (memq 'deadline conditions)
21428 (re-search-forward org-deadline-time-regexp end t))
21429 (and (memq 'notdeadline conditions)
21430 (not (re-search-forward org-deadline-time-regexp end t)))
21431 (and (setq m (memq 'regexp conditions))
21432 (stringp (nth 1 m))
21433 (re-search-forward (nth 1 m) end t))
21434 (and (setq m (memq 'notregexp conditions))
21435 (stringp (nth 1 m))
21436 (not (re-search-forward (nth 1 m) end t))))
21437 end)))
21439 ;;;###autoload
21440 (defun org-agenda-list-stuck-projects (&rest ignore)
21441 "Create agenda view for projects that are stuck.
21442 Stuck projects are project that have no next actions. For the definitions
21443 of what a project is and how to check if it stuck, customize the variable
21444 `org-stuck-projects'.
21445 MATCH is being ignored."
21446 (interactive)
21447 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21448 ;; FIXME: we could have used org-agenda-skip-if here.
21449 (org-agenda-overriding-header "List of stuck projects: ")
21450 (matcher (nth 0 org-stuck-projects))
21451 (todo (nth 1 org-stuck-projects))
21452 (todo-wds (if (member "*" todo)
21453 (progn
21454 (org-prepare-agenda-buffers (org-agenda-files))
21455 (org-delete-all
21456 org-done-keywords-for-agenda
21457 (copy-sequence org-todo-keywords-for-agenda)))
21458 todo))
21459 (todo-re (concat "^\\*+[ \t]+\\("
21460 (mapconcat 'identity todo-wds "\\|")
21461 "\\)\\>"))
21462 (tags (nth 2 org-stuck-projects))
21463 (tags-re (if (member "*" tags)
21464 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21465 (concat "^\\*+ .*:\\("
21466 (mapconcat 'identity tags "\\|")
21467 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21468 (gen-re (nth 3 org-stuck-projects))
21469 (re-list
21470 (delq nil
21471 (list
21472 (if todo todo-re)
21473 (if tags tags-re)
21474 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21475 gen-re)))))
21476 (setq org-agenda-skip-regexp
21477 (if re-list
21478 (mapconcat 'identity re-list "\\|")
21479 (error "No information how to identify unstuck projects")))
21480 (org-tags-view nil matcher)
21481 (with-current-buffer org-agenda-buffer-name
21482 (setq org-agenda-redo-command
21483 '(org-agenda-list-stuck-projects
21484 (or current-prefix-arg org-last-arg))))))
21486 ;;; Diary integration
21488 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21490 (defun org-get-entries-from-diary (date)
21491 "Get the (Emacs Calendar) diary entries for DATE."
21492 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21493 (diary-display-hook '(fancy-diary-display))
21494 (pop-up-frames nil)
21495 (list-diary-entries-hook
21496 (cons 'org-diary-default-entry list-diary-entries-hook))
21497 (diary-file-name-prefix-function nil) ; turn this feature off
21498 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21499 entries
21500 (org-disable-agenda-to-diary t))
21501 (save-excursion
21502 (save-window-excursion
21503 (funcall (if (fboundp 'diary-list-entries)
21504 'diary-list-entries 'list-diary-entries)
21505 date 1)))
21506 (if (not (get-buffer fancy-diary-buffer))
21507 (setq entries nil)
21508 (with-current-buffer fancy-diary-buffer
21509 (setq buffer-read-only nil)
21510 (if (zerop (buffer-size))
21511 ;; No entries
21512 (setq entries nil)
21513 ;; Omit the date and other unnecessary stuff
21514 (org-agenda-cleanup-fancy-diary)
21515 ;; Add prefix to each line and extend the text properties
21516 (if (zerop (buffer-size))
21517 (setq entries nil)
21518 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21519 (set-buffer-modified-p nil)
21520 (kill-buffer fancy-diary-buffer)))
21521 (when entries
21522 (setq entries (org-split-string entries "\n"))
21523 (setq entries
21524 (mapcar
21525 (lambda (x)
21526 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21527 ;; Extend the text properties to the beginning of the line
21528 (org-add-props x (text-properties-at (1- (length x)) x)
21529 'type "diary" 'date date))
21530 entries)))))
21532 (defun org-agenda-cleanup-fancy-diary ()
21533 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21534 This gets rid of the date, the underline under the date, and
21535 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21536 date. It also removes lines that contain only whitespace."
21537 (goto-char (point-min))
21538 (if (looking-at ".*?:[ \t]*")
21539 (progn
21540 (replace-match "")
21541 (re-search-forward "\n=+$" nil t)
21542 (replace-match "")
21543 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21544 (re-search-forward "\n=+$" nil t)
21545 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21546 (goto-char (point-min))
21547 (while (re-search-forward "^ +\n" nil t)
21548 (replace-match ""))
21549 (goto-char (point-min))
21550 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21551 (replace-match "")))
21553 ;; Make sure entries from the diary have the right text properties.
21554 (eval-after-load "diary-lib"
21555 '(if (boundp 'diary-modify-entry-list-string-function)
21556 ;; We can rely on the hook, nothing to do
21558 ;; Hook not avaiable, must use advice to make this work
21559 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21560 "Make the position visible."
21561 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21562 (stringp string)
21563 buffer-file-name)
21564 (setq string (org-modify-diary-entry-string string))))))
21566 (defun org-modify-diary-entry-string (string)
21567 "Add text properties to string, allowing org-mode to act on it."
21568 (org-add-props string nil
21569 'mouse-face 'highlight
21570 'keymap org-agenda-keymap
21571 'help-echo (if buffer-file-name
21572 (format "mouse-2 or RET jump to diary file %s"
21573 (abbreviate-file-name buffer-file-name))
21575 'org-agenda-diary-link t
21576 'org-marker (org-agenda-new-marker (point-at-bol))))
21578 (defun org-diary-default-entry ()
21579 "Add a dummy entry to the diary.
21580 Needed to avoid empty dates which mess up holiday display."
21581 ;; Catch the error if dealing with the new add-to-diary-alist
21582 (when org-disable-agenda-to-diary
21583 (condition-case nil
21584 (add-to-diary-list original-date "Org-mode dummy" "")
21585 (error
21586 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21588 ;;;###autoload
21589 (defun org-diary (&rest args)
21590 "Return diary information from org-files.
21591 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21592 It accesses org files and extracts information from those files to be
21593 listed in the diary. The function accepts arguments specifying what
21594 items should be listed. The following arguments are allowed:
21596 :timestamp List the headlines of items containing a date stamp or
21597 date range matching the selected date. Deadlines will
21598 also be listed, on the expiration day.
21600 :sexp List entries resulting from diary-like sexps.
21602 :deadline List any deadlines past due, or due within
21603 `org-deadline-warning-days'. The listing occurs only
21604 in the diary for *today*, not at any other date. If
21605 an entry is marked DONE, it is no longer listed.
21607 :scheduled List all items which are scheduled for the given date.
21608 The diary for *today* also contains items which were
21609 scheduled earlier and are not yet marked DONE.
21611 :todo List all TODO items from the org-file. This may be a
21612 long list - so this is not turned on by default.
21613 Like deadlines, these entries only show up in the
21614 diary for *today*, not at any other date.
21616 The call in the diary file should look like this:
21618 &%%(org-diary) ~/path/to/some/orgfile.org
21620 Use a separate line for each org file to check. Or, if you omit the file name,
21621 all files listed in `org-agenda-files' will be checked automatically:
21623 &%%(org-diary)
21625 If you don't give any arguments (as in the example above), the default
21626 arguments (:deadline :scheduled :timestamp :sexp) are used.
21627 So the example above may also be written as
21629 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21631 The function expects the lisp variables `entry' and `date' to be provided
21632 by the caller, because this is how the calendar works. Don't use this
21633 function from a program - use `org-agenda-get-day-entries' instead."
21634 (when (> (- (time-to-seconds (current-time))
21635 org-agenda-last-marker-time)
21637 (org-agenda-reset-markers))
21638 (org-compile-prefix-format 'agenda)
21639 (org-set-sorting-strategy 'agenda)
21640 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21641 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21642 (list entry)
21643 (org-agenda-files t)))
21644 file rtn results)
21645 (org-prepare-agenda-buffers files)
21646 ;; If this is called during org-agenda, don't return any entries to
21647 ;; the calendar. Org Agenda will list these entries itself.
21648 (if org-disable-agenda-to-diary (setq files nil))
21649 (while (setq file (pop files))
21650 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21651 (setq results (append results rtn)))
21652 (if results
21653 (concat (org-finalize-agenda-entries results) "\n"))))
21655 ;;; Agenda entry finders
21657 (defun org-agenda-get-day-entries (file date &rest args)
21658 "Does the work for `org-diary' and `org-agenda'.
21659 FILE is the path to a file to be checked for entries. DATE is date like
21660 the one returned by `calendar-current-date'. ARGS are symbols indicating
21661 which kind of entries should be extracted. For details about these, see
21662 the documentation of `org-diary'."
21663 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21664 (let* ((org-startup-folded nil)
21665 (org-startup-align-all-tables nil)
21666 (buffer (if (file-exists-p file)
21667 (org-get-agenda-file-buffer file)
21668 (error "No such file %s" file)))
21669 arg results rtn)
21670 (if (not buffer)
21671 ;; If file does not exist, make sure an error message ends up in diary
21672 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21673 (with-current-buffer buffer
21674 (unless (org-mode-p)
21675 (error "Agenda file %s is not in `org-mode'" file))
21676 (let ((case-fold-search nil))
21677 (save-excursion
21678 (save-restriction
21679 (if org-agenda-restrict
21680 (narrow-to-region org-agenda-restrict-begin
21681 org-agenda-restrict-end)
21682 (widen))
21683 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21684 (while (setq arg (pop args))
21685 (cond
21686 ((and (eq arg :todo)
21687 (equal date (calendar-current-date)))
21688 (setq rtn (org-agenda-get-todos))
21689 (setq results (append results rtn)))
21690 ((eq arg :timestamp)
21691 (setq rtn (org-agenda-get-blocks))
21692 (setq results (append results rtn))
21693 (setq rtn (org-agenda-get-timestamps))
21694 (setq results (append results rtn)))
21695 ((eq arg :sexp)
21696 (setq rtn (org-agenda-get-sexps))
21697 (setq results (append results rtn)))
21698 ((eq arg :scheduled)
21699 (setq rtn (org-agenda-get-scheduled))
21700 (setq results (append results rtn)))
21701 ((eq arg :closed)
21702 (setq rtn (org-agenda-get-closed))
21703 (setq results (append results rtn)))
21704 ((eq arg :deadline)
21705 (setq rtn (org-agenda-get-deadlines))
21706 (setq results (append results rtn))))))))
21707 results))))
21709 (defun org-entry-is-todo-p ()
21710 (member (org-get-todo-state) org-not-done-keywords))
21712 (defun org-entry-is-done-p ()
21713 (member (org-get-todo-state) org-done-keywords))
21715 (defun org-get-todo-state ()
21716 (save-excursion
21717 (org-back-to-heading t)
21718 (and (looking-at org-todo-line-regexp)
21719 (match-end 2)
21720 (match-string 2))))
21722 (defun org-at-date-range-p (&optional inactive-ok)
21723 "Is the cursor inside a date range?"
21724 (interactive)
21725 (save-excursion
21726 (catch 'exit
21727 (let ((pos (point)))
21728 (skip-chars-backward "^[<\r\n")
21729 (skip-chars-backward "<[")
21730 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21731 (>= (match-end 0) pos)
21732 (throw 'exit t))
21733 (skip-chars-backward "^<[\r\n")
21734 (skip-chars-backward "<[")
21735 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21736 (>= (match-end 0) pos)
21737 (throw 'exit t)))
21738 nil)))
21740 (defun org-agenda-get-todos ()
21741 "Return the TODO information for agenda display."
21742 (let* ((props (list 'face nil
21743 'done-face 'org-done
21744 'org-not-done-regexp org-not-done-regexp
21745 'org-todo-regexp org-todo-regexp
21746 'mouse-face 'highlight
21747 'keymap org-agenda-keymap
21748 'help-echo
21749 (format "mouse-2 or RET jump to org file %s"
21750 (abbreviate-file-name buffer-file-name))))
21751 ;; FIXME: get rid of the \n at some point but watch out
21752 (regexp (concat "^\\*+[ \t]+\\("
21753 (if org-select-this-todo-keyword
21754 (if (equal org-select-this-todo-keyword "*")
21755 org-todo-regexp
21756 (concat "\\<\\("
21757 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21758 "\\)\\>"))
21759 org-not-done-regexp)
21760 "[^\n\r]*\\)"))
21761 marker priority category tags
21762 ee txt beg end)
21763 (goto-char (point-min))
21764 (while (re-search-forward regexp nil t)
21765 (catch :skip
21766 (save-match-data
21767 (beginning-of-line)
21768 (setq beg (point) end (progn (outline-next-heading) (point)))
21769 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21770 (re-search-forward org-ts-regexp end t))
21771 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21772 (re-search-forward org-scheduled-time-regexp end t))
21773 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21774 (re-search-forward org-deadline-time-regexp end t)
21775 (org-deadline-close (match-string 1))))
21776 (goto-char (1+ beg))
21777 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21778 (throw :skip nil)))
21779 (goto-char beg)
21780 (org-agenda-skip)
21781 (goto-char (match-beginning 1))
21782 (setq marker (org-agenda-new-marker (match-beginning 0))
21783 category (org-get-category)
21784 tags (org-get-tags-at (point))
21785 txt (org-format-agenda-item "" (match-string 1) category tags)
21786 priority (1+ (org-get-priority txt)))
21787 (org-add-props txt props
21788 'org-marker marker 'org-hd-marker marker
21789 'priority priority 'org-category category
21790 'type "todo")
21791 (push txt ee)
21792 (if org-agenda-todo-list-sublevels
21793 (goto-char (match-end 1))
21794 (org-end-of-subtree 'invisible))))
21795 (nreverse ee)))
21797 (defconst org-agenda-no-heading-message
21798 "No heading for this item in buffer or region.")
21800 (defun org-agenda-get-timestamps ()
21801 "Return the date stamp information for agenda display."
21802 (let* ((props (list 'face nil
21803 'org-not-done-regexp org-not-done-regexp
21804 'org-todo-regexp org-todo-regexp
21805 'mouse-face 'highlight
21806 'keymap org-agenda-keymap
21807 'help-echo
21808 (format "mouse-2 or RET jump to org file %s"
21809 (abbreviate-file-name buffer-file-name))))
21810 (d1 (calendar-absolute-from-gregorian date))
21811 (remove-re
21812 (concat
21813 (regexp-quote
21814 (format-time-string
21815 "<%Y-%m-%d"
21816 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21817 ".*?>"))
21818 (regexp
21819 (concat
21820 (regexp-quote
21821 (substring
21822 (format-time-string
21823 (car org-time-stamp-formats)
21824 (apply 'encode-time ; DATE bound by calendar
21825 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21826 0 11))
21827 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21828 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21829 marker hdmarker deadlinep scheduledp donep tmp priority category
21830 ee txt timestr tags b0 b3 e3 head)
21831 (goto-char (point-min))
21832 (while (re-search-forward regexp nil t)
21833 (setq b0 (match-beginning 0)
21834 b3 (match-beginning 3) e3 (match-end 3))
21835 (catch :skip
21836 (and (org-at-date-range-p) (throw :skip nil))
21837 (org-agenda-skip)
21838 (if (and (match-end 1)
21839 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21840 (throw :skip nil))
21841 (if (and e3
21842 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21843 (throw :skip nil))
21844 (setq marker (org-agenda-new-marker b0)
21845 category (org-get-category b0)
21846 tmp (buffer-substring (max (point-min)
21847 (- b0 org-ds-keyword-length))
21849 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21850 deadlinep (string-match org-deadline-regexp tmp)
21851 scheduledp (string-match org-scheduled-regexp tmp)
21852 donep (org-entry-is-done-p))
21853 (if (or scheduledp deadlinep) (throw :skip t))
21854 (if (string-match ">" timestr)
21855 ;; substring should only run to end of time stamp
21856 (setq timestr (substring timestr 0 (match-end 0))))
21857 (save-excursion
21858 (if (re-search-backward "^\\*+ " nil t)
21859 (progn
21860 (goto-char (match-beginning 0))
21861 (setq hdmarker (org-agenda-new-marker)
21862 tags (org-get-tags-at))
21863 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21864 (setq head (match-string 1))
21865 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21866 (setq txt (org-format-agenda-item
21867 nil head category tags timestr nil
21868 remove-re)))
21869 (setq txt org-agenda-no-heading-message))
21870 (setq priority (org-get-priority txt))
21871 (org-add-props txt props
21872 'org-marker marker 'org-hd-marker hdmarker)
21873 (org-add-props txt nil 'priority priority
21874 'org-category category 'date date
21875 'type "timestamp")
21876 (push txt ee))
21877 (outline-next-heading)))
21878 (nreverse ee)))
21880 (defun org-agenda-get-sexps ()
21881 "Return the sexp information for agenda display."
21882 (require 'diary-lib)
21883 (let* ((props (list 'face nil
21884 'mouse-face 'highlight
21885 'keymap org-agenda-keymap
21886 'help-echo
21887 (format "mouse-2 or RET jump to org file %s"
21888 (abbreviate-file-name buffer-file-name))))
21889 (regexp "^&?%%(")
21890 marker category ee txt tags entry result beg b sexp sexp-entry)
21891 (goto-char (point-min))
21892 (while (re-search-forward regexp nil t)
21893 (catch :skip
21894 (org-agenda-skip)
21895 (setq beg (match-beginning 0))
21896 (goto-char (1- (match-end 0)))
21897 (setq b (point))
21898 (forward-sexp 1)
21899 (setq sexp (buffer-substring b (point)))
21900 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21901 (org-trim (match-string 1))
21902 ""))
21903 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21904 (when result
21905 (setq marker (org-agenda-new-marker beg)
21906 category (org-get-category beg))
21908 (if (string-match "\\S-" result)
21909 (setq txt result)
21910 (setq txt "SEXP entry returned empty string"))
21912 (setq txt (org-format-agenda-item
21913 "" txt category tags 'time))
21914 (org-add-props txt props 'org-marker marker)
21915 (org-add-props txt nil
21916 'org-category category 'date date
21917 'type "sexp")
21918 (push txt ee))))
21919 (nreverse ee)))
21921 (defun org-agenda-get-closed ()
21922 "Return the logged TODO entries for agenda display."
21923 (let* ((props (list 'mouse-face 'highlight
21924 'org-not-done-regexp org-not-done-regexp
21925 'org-todo-regexp org-todo-regexp
21926 'keymap org-agenda-keymap
21927 'help-echo
21928 (format "mouse-2 or RET jump to org file %s"
21929 (abbreviate-file-name buffer-file-name))))
21930 (regexp (concat
21931 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21932 (regexp-quote
21933 (substring
21934 (format-time-string
21935 (car org-time-stamp-formats)
21936 (apply 'encode-time ; DATE bound by calendar
21937 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21938 1 11))))
21939 marker hdmarker priority category tags closedp
21940 ee txt timestr)
21941 (goto-char (point-min))
21942 (while (re-search-forward regexp nil t)
21943 (catch :skip
21944 (org-agenda-skip)
21945 (setq marker (org-agenda-new-marker (match-beginning 0))
21946 closedp (equal (match-string 1) org-closed-string)
21947 category (org-get-category (match-beginning 0))
21948 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21949 ;; donep (org-entry-is-done-p)
21951 (if (string-match "\\]" timestr)
21952 ;; substring should only run to end of time stamp
21953 (setq timestr (substring timestr 0 (match-end 0))))
21954 (save-excursion
21955 (if (re-search-backward "^\\*+ " nil t)
21956 (progn
21957 (goto-char (match-beginning 0))
21958 (setq hdmarker (org-agenda-new-marker)
21959 tags (org-get-tags-at))
21960 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21961 (setq txt (org-format-agenda-item
21962 (if closedp "Closed: " "Clocked: ")
21963 (match-string 1) category tags timestr)))
21964 (setq txt org-agenda-no-heading-message))
21965 (setq priority 100000)
21966 (org-add-props txt props
21967 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21968 'priority priority 'org-category category
21969 'type "closed" 'date date
21970 'undone-face 'org-warning 'done-face 'org-done)
21971 (push txt ee))
21972 (goto-char (point-at-eol))))
21973 (nreverse ee)))
21975 (defun org-agenda-get-deadlines ()
21976 "Return the deadline information for agenda display."
21977 (let* ((props (list 'mouse-face 'highlight
21978 'org-not-done-regexp org-not-done-regexp
21979 'org-todo-regexp org-todo-regexp
21980 'keymap org-agenda-keymap
21981 'help-echo
21982 (format "mouse-2 or RET jump to org file %s"
21983 (abbreviate-file-name buffer-file-name))))
21984 (regexp org-deadline-time-regexp)
21985 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21986 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21987 d2 diff dfrac wdays pos pos1 category tags
21988 ee txt head face s upcomingp donep timestr)
21989 (goto-char (point-min))
21990 (while (re-search-forward regexp nil t)
21991 (catch :skip
21992 (org-agenda-skip)
21993 (setq s (match-string 1)
21994 pos (1- (match-beginning 1))
21995 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21996 diff (- d2 d1)
21997 wdays (org-get-wdays s)
21998 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21999 upcomingp (and todayp (> diff 0)))
22000 ;; When to show a deadline in the calendar:
22001 ;; If the expiration is within wdays warning time.
22002 ;; Past-due deadlines are only shown on the current date
22003 (if (or (and (<= diff wdays)
22004 (and todayp (not org-agenda-only-exact-dates)))
22005 (= diff 0))
22006 (save-excursion
22007 (setq category (org-get-category))
22008 (if (re-search-backward "^\\*+[ \t]+" nil t)
22009 (progn
22010 (goto-char (match-end 0))
22011 (setq pos1 (match-beginning 0))
22012 (setq tags (org-get-tags-at pos1))
22013 (setq head (buffer-substring-no-properties
22014 (point)
22015 (progn (skip-chars-forward "^\r\n")
22016 (point))))
22017 (setq donep (string-match org-looking-at-done-regexp head))
22018 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
22019 (setq timestr
22020 (concat (substring s (match-beginning 1)) " "))
22021 (setq timestr 'time))
22022 (if (and donep
22023 (or org-agenda-skip-deadline-if-done
22024 (not (= diff 0))))
22025 (setq txt nil)
22026 (setq txt (org-format-agenda-item
22027 (if (= diff 0)
22028 (car org-agenda-deadline-leaders)
22029 (format (nth 1 org-agenda-deadline-leaders)
22030 diff))
22031 head category tags timestr))))
22032 (setq txt org-agenda-no-heading-message))
22033 (when txt
22034 (setq face (org-agenda-deadline-face dfrac wdays))
22035 (org-add-props txt props
22036 'org-marker (org-agenda-new-marker pos)
22037 'org-hd-marker (org-agenda-new-marker pos1)
22038 'priority (+ (- diff)
22039 (org-get-priority txt))
22040 'org-category category
22041 'type (if upcomingp "upcoming-deadline" "deadline")
22042 'date (if upcomingp date d2)
22043 'face (if donep 'org-done face)
22044 'undone-face face 'done-face 'org-done)
22045 (push txt ee))))))
22046 (nreverse ee)))
22048 (defun org-agenda-deadline-face (fraction &optional wdays)
22049 "Return the face to displaying a deadline item.
22050 FRACTION is what fraction of the head-warning time has passed."
22051 (if (equal wdays 0) (setq fraction 1.))
22052 (let ((faces org-agenda-deadline-faces) f)
22053 (catch 'exit
22054 (while (setq f (pop faces))
22055 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
22057 (defun org-agenda-get-scheduled ()
22058 "Return the scheduled information for agenda display."
22059 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
22060 'org-todo-regexp org-todo-regexp
22061 'done-face 'org-done
22062 'mouse-face 'highlight
22063 'keymap org-agenda-keymap
22064 'help-echo
22065 (format "mouse-2 or RET jump to org file %s"
22066 (abbreviate-file-name buffer-file-name))))
22067 (regexp org-scheduled-time-regexp)
22068 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
22069 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
22070 d2 diff pos pos1 category tags
22071 ee txt head pastschedp donep face timestr s)
22072 (goto-char (point-min))
22073 (while (re-search-forward regexp nil t)
22074 (catch :skip
22075 (org-agenda-skip)
22076 (setq s (match-string 1)
22077 pos (1- (match-beginning 1))
22078 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
22079 ;;; is this right?
22080 ;;; do we need to do this for deadleine too????
22081 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
22082 diff (- d2 d1))
22083 (setq pastschedp (and todayp (< diff 0)))
22084 ;; When to show a scheduled item in the calendar:
22085 ;; If it is on or past the date.
22086 (if (or (and (< diff 0)
22087 (and todayp (not org-agenda-only-exact-dates)))
22088 (= diff 0))
22089 (save-excursion
22090 (setq category (org-get-category))
22091 (if (re-search-backward "^\\*+[ \t]+" nil t)
22092 (progn
22093 (goto-char (match-end 0))
22094 (setq pos1 (match-beginning 0))
22095 (setq tags (org-get-tags-at))
22096 (setq head (buffer-substring-no-properties
22097 (point)
22098 (progn (skip-chars-forward "^\r\n") (point))))
22099 (setq donep (string-match org-looking-at-done-regexp head))
22100 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
22101 (setq timestr
22102 (concat (substring s (match-beginning 1)) " "))
22103 (setq timestr 'time))
22104 (if (and donep
22105 (or org-agenda-skip-scheduled-if-done
22106 (not (= diff 0))))
22107 (setq txt nil)
22108 (setq txt (org-format-agenda-item
22109 (if (= diff 0)
22110 (car org-agenda-scheduled-leaders)
22111 (format (nth 1 org-agenda-scheduled-leaders)
22112 (- 1 diff)))
22113 head category tags timestr))))
22114 (setq txt org-agenda-no-heading-message))
22115 (when txt
22116 (setq face (if pastschedp
22117 'org-scheduled-previously
22118 'org-scheduled-today))
22119 (org-add-props txt props
22120 'undone-face face
22121 'face (if donep 'org-done face)
22122 'org-marker (org-agenda-new-marker pos)
22123 'org-hd-marker (org-agenda-new-marker pos1)
22124 'type (if pastschedp "past-scheduled" "scheduled")
22125 'date (if pastschedp d2 date)
22126 'priority (+ 94 (- 5 diff) (org-get-priority txt))
22127 'org-category category)
22128 (push txt ee))))))
22129 (nreverse ee)))
22131 (defun org-agenda-get-blocks ()
22132 "Return the date-range information for agenda display."
22133 (let* ((props (list 'face nil
22134 'org-not-done-regexp org-not-done-regexp
22135 'org-todo-regexp org-todo-regexp
22136 'mouse-face 'highlight
22137 'keymap org-agenda-keymap
22138 'help-echo
22139 (format "mouse-2 or RET jump to org file %s"
22140 (abbreviate-file-name buffer-file-name))))
22141 (regexp org-tr-regexp)
22142 (d0 (calendar-absolute-from-gregorian date))
22143 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
22144 donep head)
22145 (goto-char (point-min))
22146 (while (re-search-forward regexp nil t)
22147 (catch :skip
22148 (org-agenda-skip)
22149 (setq pos (point))
22150 (setq timestr (match-string 0)
22151 s1 (match-string 1)
22152 s2 (match-string 2)
22153 d1 (time-to-days (org-time-string-to-time s1))
22154 d2 (time-to-days (org-time-string-to-time s2)))
22155 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
22156 ;; Only allow days between the limits, because the normal
22157 ;; date stamps will catch the limits.
22158 (save-excursion
22159 (setq marker (org-agenda-new-marker (point)))
22160 (setq category (org-get-category))
22161 (if (re-search-backward "^\\*+ " nil t)
22162 (progn
22163 (goto-char (match-beginning 0))
22164 (setq hdmarker (org-agenda-new-marker (point)))
22165 (setq tags (org-get-tags-at))
22166 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
22167 (setq head (match-string 1))
22168 (and org-agenda-skip-timestamp-if-done
22169 (org-entry-is-done-p)
22170 (throw :skip t))
22171 (setq txt (org-format-agenda-item
22172 (format (if (= d1 d2) "" "(%d/%d): ")
22173 (1+ (- d0 d1)) (1+ (- d2 d1)))
22174 head category tags
22175 (if (= d0 d1) timestr))))
22176 (setq txt org-agenda-no-heading-message))
22177 (org-add-props txt props
22178 'org-marker marker 'org-hd-marker hdmarker
22179 'type "block" 'date date
22180 'priority (org-get-priority txt) 'org-category category)
22181 (push txt ee)))
22182 (goto-char pos)))
22183 ;; Sort the entries by expiration date.
22184 (nreverse ee)))
22186 ;;; Agenda presentation and sorting
22188 (defconst org-plain-time-of-day-regexp
22189 (concat
22190 "\\(\\<[012]?[0-9]"
22191 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22192 "\\(--?"
22193 "\\(\\<[012]?[0-9]"
22194 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22195 "\\)?")
22196 "Regular expression to match a plain time or time range.
22197 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22198 groups carry important information:
22199 0 the full match
22200 1 the first time, range or not
22201 8 the second time, if it is a range.")
22203 (defconst org-plain-time-extension-regexp
22204 (concat
22205 "\\(\\<[012]?[0-9]"
22206 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22207 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
22208 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
22209 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22210 groups carry important information:
22211 0 the full match
22212 7 hours of duration
22213 9 minutes of duration")
22215 (defconst org-stamp-time-of-day-regexp
22216 (concat
22217 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
22218 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
22219 "\\(--?"
22220 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
22221 "Regular expression to match a timestamp time or time range.
22222 After a match, the following groups carry important information:
22223 0 the full match
22224 1 date plus weekday, for backreferencing to make sure both times on same day
22225 2 the first time, range or not
22226 4 the second time, if it is a range.")
22228 (defvar org-prefix-has-time nil
22229 "A flag, set by `org-compile-prefix-format'.
22230 The flag is set if the currently compiled format contains a `%t'.")
22231 (defvar org-prefix-has-tag nil
22232 "A flag, set by `org-compile-prefix-format'.
22233 The flag is set if the currently compiled format contains a `%T'.")
22235 (defun org-format-agenda-item (extra txt &optional category tags dotime
22236 noprefix remove-re)
22237 "Format TXT to be inserted into the agenda buffer.
22238 In particular, it adds the prefix and corresponding text properties. EXTRA
22239 must be a string and replaces the `%s' specifier in the prefix format.
22240 CATEGORY (string, symbol or nil) may be used to overrule the default
22241 category taken from local variable or file name. It will replace the `%c'
22242 specifier in the format. DOTIME, when non-nil, indicates that a
22243 time-of-day should be extracted from TXT for sorting of this entry, and for
22244 the `%t' specifier in the format. When DOTIME is a string, this string is
22245 searched for a time before TXT is. NOPREFIX is a flag and indicates that
22246 only the correctly processes TXT should be returned - this is used by
22247 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
22248 Any match of REMOVE-RE will be removed from TXT."
22249 (save-match-data
22250 ;; Diary entries sometimes have extra whitespace at the beginning
22251 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
22252 (let* ((category (or category
22253 org-category
22254 (if buffer-file-name
22255 (file-name-sans-extension
22256 (file-name-nondirectory buffer-file-name))
22257 "")))
22258 (tag (if tags (nth (1- (length tags)) tags) ""))
22259 time ; time and tag are needed for the eval of the prefix format
22260 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
22261 (time-of-day (and dotime (org-get-time-of-day ts)))
22262 stamp plain s0 s1 s2 rtn srp)
22263 (when (and dotime time-of-day org-prefix-has-time)
22264 ;; Extract starting and ending time and move them to prefix
22265 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
22266 (setq plain (string-match org-plain-time-of-day-regexp ts)))
22267 (setq s0 (match-string 0 ts)
22268 srp (and stamp (match-end 3))
22269 s1 (match-string (if plain 1 2) ts)
22270 s2 (match-string (if plain 8 (if srp 4 6)) ts))
22272 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
22273 ;; them, we might want to remove them there to avoid duplication.
22274 ;; The user can turn this off with a variable.
22275 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
22276 (string-match (concat (regexp-quote s0) " *") txt)
22277 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
22278 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
22279 (= (match-beginning 0) 0)
22281 (setq txt (replace-match "" nil nil txt))))
22282 ;; Normalize the time(s) to 24 hour
22283 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
22284 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
22286 (when (and s1 (not s2) org-agenda-default-appointment-duration
22287 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
22288 (let ((m (+ (string-to-number (match-string 2 s1))
22289 (* 60 (string-to-number (match-string 1 s1)))
22290 org-agenda-default-appointment-duration))
22292 (setq h (/ m 60) m (- m (* h 60)))
22293 (setq s2 (format "%02d:%02d" h m))))
22295 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22296 txt)
22297 ;; Tags are in the string
22298 (if (or (eq org-agenda-remove-tags t)
22299 (and org-agenda-remove-tags
22300 org-prefix-has-tag))
22301 (setq txt (replace-match "" t t txt))
22302 (setq txt (replace-match
22303 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
22304 (match-string 2 txt))
22305 t t txt))))
22307 (when remove-re
22308 (while (string-match remove-re txt)
22309 (setq txt (replace-match "" t t txt))))
22311 ;; Create the final string
22312 (if noprefix
22313 (setq rtn txt)
22314 ;; Prepare the variables needed in the eval of the compiled format
22315 (setq time (cond (s2 (concat s1 "-" s2))
22316 (s1 (concat s1 "......"))
22317 (t ""))
22318 extra (or extra "")
22319 category (if (symbolp category) (symbol-name category) category))
22320 ;; Evaluate the compiled format
22321 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
22323 ;; And finally add the text properties
22324 (org-add-props rtn nil
22325 'org-category (downcase category) 'tags tags
22326 'org-highest-priority org-highest-priority
22327 'org-lowest-priority org-lowest-priority
22328 'prefix-length (- (length rtn) (length txt))
22329 'time-of-day time-of-day
22330 'txt txt
22331 'time time
22332 'extra extra
22333 'dotime dotime))))
22335 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
22336 (defvar org-agenda-sorting-strategy-selected nil)
22338 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
22339 (catch 'exit
22340 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
22341 ((and todayp (member 'today (car org-agenda-time-grid))))
22342 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
22343 ((member 'weekly (car org-agenda-time-grid)))
22344 (t (throw 'exit list)))
22345 (let* ((have (delq nil (mapcar
22346 (lambda (x) (get-text-property 1 'time-of-day x))
22347 list)))
22348 (string (nth 1 org-agenda-time-grid))
22349 (gridtimes (nth 2 org-agenda-time-grid))
22350 (req (car org-agenda-time-grid))
22351 (remove (member 'remove-match req))
22352 new time)
22353 (if (and (member 'require-timed req) (not have))
22354 ;; don't show empty grid
22355 (throw 'exit list))
22356 (while (setq time (pop gridtimes))
22357 (unless (and remove (member time have))
22358 (setq time (int-to-string time))
22359 (push (org-format-agenda-item
22360 nil string "" nil
22361 (concat (substring time 0 -2) ":" (substring time -2)))
22362 new)
22363 (put-text-property
22364 1 (length (car new)) 'face 'org-time-grid (car new))))
22365 (if (member 'time-up org-agenda-sorting-strategy-selected)
22366 (append new list)
22367 (append list new)))))
22369 (defun org-compile-prefix-format (key)
22370 "Compile the prefix format into a Lisp form that can be evaluated.
22371 The resulting form is returned and stored in the variable
22372 `org-prefix-format-compiled'."
22373 (setq org-prefix-has-time nil org-prefix-has-tag nil)
22374 (let ((s (cond
22375 ((stringp org-agenda-prefix-format)
22376 org-agenda-prefix-format)
22377 ((assq key org-agenda-prefix-format)
22378 (cdr (assq key org-agenda-prefix-format)))
22379 (t " %-12:c%?-12t% s")))
22380 (start 0)
22381 varform vars var e c f opt)
22382 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
22383 s start)
22384 (setq var (cdr (assoc (match-string 4 s)
22385 '(("c" . category) ("t" . time) ("s" . extra)
22386 ("T" . tag))))
22387 c (or (match-string 3 s) "")
22388 opt (match-beginning 1)
22389 start (1+ (match-beginning 0)))
22390 (if (equal var 'time) (setq org-prefix-has-time t))
22391 (if (equal var 'tag) (setq org-prefix-has-tag t))
22392 (setq f (concat "%" (match-string 2 s) "s"))
22393 (if opt
22394 (setq varform
22395 `(if (equal "" ,var)
22397 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22398 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22399 (setq s (replace-match "%s" t nil s))
22400 (push varform vars))
22401 (setq vars (nreverse vars))
22402 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22404 (defun org-set-sorting-strategy (key)
22405 (if (symbolp (car org-agenda-sorting-strategy))
22406 ;; the old format
22407 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22408 (setq org-agenda-sorting-strategy-selected
22409 (or (cdr (assq key org-agenda-sorting-strategy))
22410 (cdr (assq 'agenda org-agenda-sorting-strategy))
22411 '(time-up category-keep priority-down)))))
22413 (defun org-get-time-of-day (s &optional string mod24)
22414 "Check string S for a time of day.
22415 If found, return it as a military time number between 0 and 2400.
22416 If not found, return nil.
22417 The optional STRING argument forces conversion into a 5 character wide string
22418 HH:MM."
22419 (save-match-data
22420 (when
22421 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22422 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22423 (let* ((h (string-to-number (match-string 1 s)))
22424 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22425 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22426 (am-p (equal ampm "am"))
22427 (h1 (cond ((not ampm) h)
22428 ((= h 12) (if am-p 0 12))
22429 (t (+ h (if am-p 0 12)))))
22430 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22431 (mod h1 24) h1))
22432 (t0 (+ (* 100 h2) m))
22433 (t1 (concat (if (>= h1 24) "+" " ")
22434 (if (< t0 100) "0" "")
22435 (if (< t0 10) "0" "")
22436 (int-to-string t0))))
22437 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22439 (defun org-finalize-agenda-entries (list &optional nosort)
22440 "Sort and concatenate the agenda items."
22441 (setq list (mapcar 'org-agenda-highlight-todo list))
22442 (if nosort
22443 list
22444 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22446 (defun org-agenda-highlight-todo (x)
22447 (let (re pl)
22448 (if (eq x 'line)
22449 (save-excursion
22450 (beginning-of-line 1)
22451 (setq re (get-text-property (point) 'org-todo-regexp))
22452 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22453 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22454 (add-text-properties (match-beginning 0) (match-end 0)
22455 (list 'face (org-get-todo-face 0)))
22456 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22457 (delete-region (match-beginning 1) (1- (match-end 0)))
22458 (goto-char (match-beginning 1))
22459 (insert (format org-agenda-todo-keyword-format s)))))
22460 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22461 pl (get-text-property 0 'prefix-length x))
22462 (when (and re
22463 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22464 x (or pl 0)) pl))
22465 (add-text-properties
22466 (or (match-end 1) (match-end 0)) (match-end 0)
22467 (list 'face (org-get-todo-face (match-string 2 x)))
22469 (setq x (concat (substring x 0 (match-end 1))
22470 (format org-agenda-todo-keyword-format
22471 (match-string 2 x))
22473 (substring x (match-end 3)))))
22474 x)))
22476 (defsubst org-cmp-priority (a b)
22477 "Compare the priorities of string A and B."
22478 (let ((pa (or (get-text-property 1 'priority a) 0))
22479 (pb (or (get-text-property 1 'priority b) 0)))
22480 (cond ((> pa pb) +1)
22481 ((< pa pb) -1)
22482 (t nil))))
22484 (defsubst org-cmp-category (a b)
22485 "Compare the string values of categories of strings A and B."
22486 (let ((ca (or (get-text-property 1 'org-category a) ""))
22487 (cb (or (get-text-property 1 'org-category b) "")))
22488 (cond ((string-lessp ca cb) -1)
22489 ((string-lessp cb ca) +1)
22490 (t nil))))
22492 (defsubst org-cmp-tag (a b)
22493 "Compare the string values of categories of strings A and B."
22494 (let ((ta (car (last (get-text-property 1 'tags a))))
22495 (tb (car (last (get-text-property 1 'tags b)))))
22496 (cond ((not ta) +1)
22497 ((not tb) -1)
22498 ((string-lessp ta tb) -1)
22499 ((string-lessp tb ta) +1)
22500 (t nil))))
22502 (defsubst org-cmp-time (a b)
22503 "Compare the time-of-day values of strings A and B."
22504 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22505 (ta (or (get-text-property 1 'time-of-day a) def))
22506 (tb (or (get-text-property 1 'time-of-day b) def)))
22507 (cond ((< ta tb) -1)
22508 ((< tb ta) +1)
22509 (t nil))))
22511 (defun org-entries-lessp (a b)
22512 "Predicate for sorting agenda entries."
22513 ;; The following variables will be used when the form is evaluated.
22514 ;; So even though the compiler complains, keep them.
22515 (let* ((time-up (org-cmp-time a b))
22516 (time-down (if time-up (- time-up) nil))
22517 (priority-up (org-cmp-priority a b))
22518 (priority-down (if priority-up (- priority-up) nil))
22519 (category-up (org-cmp-category a b))
22520 (category-down (if category-up (- category-up) nil))
22521 (category-keep (if category-up +1 nil))
22522 (tag-up (org-cmp-tag a b))
22523 (tag-down (if tag-up (- tag-up) nil)))
22524 (cdr (assoc
22525 (eval (cons 'or org-agenda-sorting-strategy-selected))
22526 '((-1 . t) (1 . nil) (nil . nil))))))
22528 ;;; Agenda restriction lock
22530 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22531 "Overlay to mark the headline to which arenda commands are restricted.")
22532 (org-overlay-put org-agenda-restriction-lock-overlay
22533 'face 'org-agenda-restriction-lock)
22534 (org-overlay-put org-agenda-restriction-lock-overlay
22535 'help-echo "Agendas are currently limited to this subtree.")
22536 (org-detach-overlay org-agenda-restriction-lock-overlay)
22537 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22538 "Overlay marking the agenda restriction line in speedbar.")
22539 (org-overlay-put org-speedbar-restriction-lock-overlay
22540 'face 'org-agenda-restriction-lock)
22541 (org-overlay-put org-speedbar-restriction-lock-overlay
22542 'help-echo "Agendas are currently limited to this item.")
22543 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22545 (defun org-agenda-set-restriction-lock (&optional type)
22546 "Set restriction lock for agenda, to current subtree or file.
22547 Restriction will be the file if TYPE is `file', or if type is the
22548 universal prefix '(4), or if the cursor is before the first headline
22549 in the file. Otherwise, restriction will be to the current subtree."
22550 (interactive "P")
22551 (and (equal type '(4)) (setq type 'file))
22552 (setq type (cond
22553 (type type)
22554 ((org-at-heading-p) 'subtree)
22555 ((condition-case nil (org-back-to-heading t) (error nil))
22556 'subtree)
22557 (t 'file)))
22558 (if (eq type 'subtree)
22559 (progn
22560 (setq org-agenda-restrict t)
22561 (setq org-agenda-overriding-restriction 'subtree)
22562 (put 'org-agenda-files 'org-restrict
22563 (list (buffer-file-name (buffer-base-buffer))))
22564 (org-back-to-heading t)
22565 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22566 (move-marker org-agenda-restrict-begin (point))
22567 (move-marker org-agenda-restrict-end
22568 (save-excursion (org-end-of-subtree t)))
22569 (message "Locking agenda restriction to subtree"))
22570 (put 'org-agenda-files 'org-restrict
22571 (list (buffer-file-name (buffer-base-buffer))))
22572 (setq org-agenda-restrict nil)
22573 (setq org-agenda-overriding-restriction 'file)
22574 (move-marker org-agenda-restrict-begin nil)
22575 (move-marker org-agenda-restrict-end nil)
22576 (message "Locking agenda restriction to file"))
22577 (setq current-prefix-arg nil)
22578 (org-agenda-maybe-redo))
22580 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22581 "Remove the agenda restriction lock."
22582 (interactive "P")
22583 (org-detach-overlay org-agenda-restriction-lock-overlay)
22584 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22585 (setq org-agenda-overriding-restriction nil)
22586 (setq org-agenda-restrict nil)
22587 (put 'org-agenda-files 'org-restrict nil)
22588 (move-marker org-agenda-restrict-begin nil)
22589 (move-marker org-agenda-restrict-end nil)
22590 (setq current-prefix-arg nil)
22591 (message "Agenda restriction lock removed")
22592 (or noupdate (org-agenda-maybe-redo)))
22594 (defun org-agenda-maybe-redo ()
22595 "If there is any window showing the agenda view, update it."
22596 (let ((w (get-buffer-window org-agenda-buffer-name t))
22597 (w0 (selected-window)))
22598 (when w
22599 (select-window w)
22600 (org-agenda-redo)
22601 (select-window w0)
22602 (if org-agenda-overriding-restriction
22603 (message "Agenda view shifted to new %s restriction"
22604 org-agenda-overriding-restriction)
22605 (message "Agenda restriction lock removed")))))
22607 ;;; Agenda commands
22609 (defun org-agenda-check-type (error &rest types)
22610 "Check if agenda buffer is of allowed type.
22611 If ERROR is non-nil, throw an error, otherwise just return nil."
22612 (if (memq org-agenda-type types)
22614 (if error
22615 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22616 nil)))
22618 (defun org-agenda-quit ()
22619 "Exit agenda by removing the window or the buffer."
22620 (interactive)
22621 (let ((buf (current-buffer)))
22622 (if (not (one-window-p)) (delete-window))
22623 (kill-buffer buf)
22624 (org-agenda-reset-markers)
22625 (org-columns-remove-overlays))
22626 ;; Maybe restore the pre-agenda window configuration.
22627 (and org-agenda-restore-windows-after-quit
22628 (not (eq org-agenda-window-setup 'other-frame))
22629 org-pre-agenda-window-conf
22630 (set-window-configuration org-pre-agenda-window-conf)))
22632 (defun org-agenda-exit ()
22633 "Exit agenda by removing the window or the buffer.
22634 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22635 Org-mode buffers visited directly by the user will not be touched."
22636 (interactive)
22637 (org-release-buffers org-agenda-new-buffers)
22638 (setq org-agenda-new-buffers nil)
22639 (org-agenda-quit))
22641 (defun org-agenda-execute (arg)
22642 "Execute another agenda command, keeping same window.\\<global-map>
22643 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22644 (interactive "P")
22645 (let ((org-agenda-window-setup 'current-window))
22646 (org-agenda arg)))
22648 (defun org-save-all-org-buffers ()
22649 "Save all Org-mode buffers without user confirmation."
22650 (interactive)
22651 (message "Saving all Org-mode buffers...")
22652 (save-some-buffers t 'org-mode-p)
22653 (message "Saving all Org-mode buffers... done"))
22655 (defun org-agenda-redo ()
22656 "Rebuild Agenda.
22657 When this is the global TODO list, a prefix argument will be interpreted."
22658 (interactive)
22659 (let* ((org-agenda-keep-modes t)
22660 (line (org-current-line))
22661 (window-line (- line (org-current-line (window-start))))
22662 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22663 (message "Rebuilding agenda buffer...")
22664 (org-let lprops '(eval org-agenda-redo-command))
22665 (setq org-agenda-undo-list nil
22666 org-agenda-pending-undo-list nil)
22667 (message "Rebuilding agenda buffer...done")
22668 (goto-line line)
22669 (recenter window-line)))
22671 (defun org-agenda-manipulate-query-add ()
22672 "Manipulate the query by adding a search term with positive selection.
22673 Positive selection means, the term must be matched for selection of an entry."
22674 (interactive)
22675 (org-agenda-manipulate-query ?\[))
22676 (defun org-agenda-manipulate-query-subtract ()
22677 "Manipulate the query by adding a search term with negative selection.
22678 Negative selection means, term must not be matched for selection of an entry."
22679 (interactive)
22680 (org-agenda-manipulate-query ?\]))
22681 (defun org-agenda-manipulate-query-add-re ()
22682 "Manipulate the query by adding a search regexp with positive selection.
22683 Positive selection means, the regexp must match for selection of an entry."
22684 (interactive)
22685 (org-agenda-manipulate-query ?\{))
22686 (defun org-agenda-manipulate-query-subtract-re ()
22687 "Manipulate the query by adding a search regexp with negative selection.
22688 Negative selection means, regexp must not match for selection of an entry."
22689 (interactive)
22690 (org-agenda-manipulate-query ?\}))
22691 (defun org-agenda-manipulate-query (char)
22692 (cond
22693 ((eq org-agenda-type 'search)
22694 (org-add-to-string
22695 'org-agenda-query-string
22696 (cdr (assoc char '((?\[ . " +") (?\] . " -")
22697 (?\{ . " +{}") (?\} . " -{}")))))
22698 (setq org-agenda-redo-command
22699 (list 'org-search-view
22700 (+ (length org-agenda-query-string)
22701 (if (member char '(?\{ ?\})) 0 1))
22702 org-agenda-query-string))
22703 (set-register org-agenda-query-register org-agenda-query-string)
22704 (org-agenda-redo))
22705 (t (error "Canot manipulate query for %s-type agenda buffers"
22706 org-agenda-type))))
22708 (defun org-add-to-string (var string)
22709 (set var (concat (symbol-value var) string)))
22711 (defun org-agenda-goto-date (date)
22712 "Jump to DATE in agenda."
22713 (interactive (list (org-read-date)))
22714 (org-agenda-list nil date))
22716 (defun org-agenda-goto-today ()
22717 "Go to today."
22718 (interactive)
22719 (org-agenda-check-type t 'timeline 'agenda)
22720 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22721 (cond
22722 (tdpos (goto-char tdpos))
22723 ((eq org-agenda-type 'agenda)
22724 (let* ((sd (time-to-days
22725 (time-subtract (current-time)
22726 (list 0 (* 3600 org-extend-today-until) 0))))
22727 (comp (org-agenda-compute-time-span sd org-agenda-span))
22728 (org-agenda-overriding-arguments org-agenda-last-arguments))
22729 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22730 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22731 (org-agenda-redo)
22732 (org-agenda-find-same-or-today-or-agenda)))
22733 (t (error "Cannot find today")))))
22735 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22736 (goto-char
22737 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22738 (text-property-any (point-min) (point-max) 'org-today t)
22739 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22740 (point-min))))
22742 (defun org-agenda-later (arg)
22743 "Go forward in time by thee current span.
22744 With prefix ARG, go forward that many times the current span."
22745 (interactive "p")
22746 (org-agenda-check-type t 'agenda)
22747 (let* ((span org-agenda-span)
22748 (sd org-starting-day)
22749 (greg (calendar-gregorian-from-absolute sd))
22750 (cnt (get-text-property (point) 'org-day-cnt))
22751 greg2 nd)
22752 (cond
22753 ((eq span 'day)
22754 (setq sd (+ arg sd) nd 1))
22755 ((eq span 'week)
22756 (setq sd (+ (* 7 arg) sd) nd 7))
22757 ((eq span 'month)
22758 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22759 sd (calendar-absolute-from-gregorian greg2))
22760 (setcar greg2 (1+ (car greg2)))
22761 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22762 ((eq span 'year)
22763 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22764 sd (calendar-absolute-from-gregorian greg2))
22765 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22766 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22767 (let ((org-agenda-overriding-arguments
22768 (list (car org-agenda-last-arguments) sd nd t)))
22769 (org-agenda-redo)
22770 (org-agenda-find-same-or-today-or-agenda cnt))))
22772 (defun org-agenda-earlier (arg)
22773 "Go backward in time by the current span.
22774 With prefix ARG, go backward that many times the current span."
22775 (interactive "p")
22776 (org-agenda-later (- arg)))
22778 (defun org-agenda-day-view ()
22779 "Switch to daily view for agenda."
22780 (interactive)
22781 (setq org-agenda-ndays 1)
22782 (org-agenda-change-time-span 'day))
22783 (defun org-agenda-week-view ()
22784 "Switch to daily view for agenda."
22785 (interactive)
22786 (setq org-agenda-ndays 7)
22787 (org-agenda-change-time-span 'week))
22788 (defun org-agenda-month-view ()
22789 "Switch to daily view for agenda."
22790 (interactive)
22791 (org-agenda-change-time-span 'month))
22792 (defun org-agenda-year-view ()
22793 "Switch to daily view for agenda."
22794 (interactive)
22795 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22796 (org-agenda-change-time-span 'year)
22797 (error "Abort")))
22799 (defun org-agenda-change-time-span (span)
22800 "Change the agenda view to SPAN.
22801 SPAN may be `day', `week', `month', `year'."
22802 (org-agenda-check-type t 'agenda)
22803 (if (equal org-agenda-span span)
22804 (error "Viewing span is already \"%s\"" span))
22805 (let* ((sd (or (get-text-property (point) 'day)
22806 org-starting-day))
22807 (computed (org-agenda-compute-time-span sd span))
22808 (org-agenda-overriding-arguments
22809 (list (car org-agenda-last-arguments)
22810 (car computed) (cdr computed) t)))
22811 (org-agenda-redo)
22812 (org-agenda-find-same-or-today-or-agenda))
22813 (org-agenda-set-mode-name)
22814 (message "Switched to %s view" span))
22816 (defun org-agenda-compute-time-span (sd span)
22817 "Compute starting date and number of days for agenda.
22818 SPAN may be `day', `week', `month', `year'. The return value
22819 is a cons cell with the starting date and the number of days,
22820 so that the date SD will be in that range."
22821 (let* ((greg (calendar-gregorian-from-absolute sd))
22823 (cond
22824 ((eq span 'day)
22825 (setq nd 1))
22826 ((eq span 'week)
22827 (let* ((nt (calendar-day-of-week
22828 (calendar-gregorian-from-absolute sd)))
22829 (d (if org-agenda-start-on-weekday
22830 (- nt org-agenda-start-on-weekday)
22831 0)))
22832 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22833 (setq nd 7)))
22834 ((eq span 'month)
22835 (setq sd (calendar-absolute-from-gregorian
22836 (list (car greg) 1 (nth 2 greg)))
22837 nd (- (calendar-absolute-from-gregorian
22838 (list (1+ (car greg)) 1 (nth 2 greg)))
22839 sd)))
22840 ((eq span 'year)
22841 (setq sd (calendar-absolute-from-gregorian
22842 (list 1 1 (nth 2 greg)))
22843 nd (- (calendar-absolute-from-gregorian
22844 (list 1 1 (1+ (nth 2 greg))))
22845 sd))))
22846 (cons sd nd)))
22848 ;; FIXME: does not work if user makes date format that starts with a blank
22849 (defun org-agenda-next-date-line (&optional arg)
22850 "Jump to the next line indicating a date in agenda buffer."
22851 (interactive "p")
22852 (org-agenda-check-type t 'agenda 'timeline)
22853 (beginning-of-line 1)
22854 (if (looking-at "^\\S-") (forward-char 1))
22855 (if (not (re-search-forward "^\\S-" nil t arg))
22856 (progn
22857 (backward-char 1)
22858 (error "No next date after this line in this buffer")))
22859 (goto-char (match-beginning 0)))
22861 (defun org-agenda-previous-date-line (&optional arg)
22862 "Jump to the previous line indicating a date in agenda buffer."
22863 (interactive "p")
22864 (org-agenda-check-type t 'agenda 'timeline)
22865 (beginning-of-line 1)
22866 (if (not (re-search-backward "^\\S-" nil t arg))
22867 (error "No previous date before this line in this buffer")))
22869 ;; Initialize the highlight
22870 (defvar org-hl (org-make-overlay 1 1))
22871 (org-overlay-put org-hl 'face 'highlight)
22873 (defun org-highlight (begin end &optional buffer)
22874 "Highlight a region with overlay."
22875 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22876 org-hl begin end (or buffer (current-buffer))))
22878 (defun org-unhighlight ()
22879 "Detach overlay INDEX."
22880 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22882 ;; FIXME this is currently not used.
22883 (defun org-highlight-until-next-command (beg end &optional buffer)
22884 (org-highlight beg end buffer)
22885 (add-hook 'pre-command-hook 'org-unhighlight-once))
22886 (defun org-unhighlight-once ()
22887 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22888 (org-unhighlight))
22890 (defun org-agenda-follow-mode ()
22891 "Toggle follow mode in an agenda buffer."
22892 (interactive)
22893 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22894 (org-agenda-set-mode-name)
22895 (message "Follow mode is %s"
22896 (if org-agenda-follow-mode "on" "off")))
22898 (defun org-agenda-log-mode ()
22899 "Toggle log mode in an agenda buffer."
22900 (interactive)
22901 (org-agenda-check-type t 'agenda 'timeline)
22902 (setq org-agenda-show-log (not org-agenda-show-log))
22903 (org-agenda-set-mode-name)
22904 (org-agenda-redo)
22905 (message "Log mode is %s"
22906 (if org-agenda-show-log "on" "off")))
22908 (defun org-agenda-toggle-diary ()
22909 "Toggle diary inclusion in an agenda buffer."
22910 (interactive)
22911 (org-agenda-check-type t 'agenda)
22912 (setq org-agenda-include-diary (not org-agenda-include-diary))
22913 (org-agenda-redo)
22914 (org-agenda-set-mode-name)
22915 (message "Diary inclusion turned %s"
22916 (if org-agenda-include-diary "on" "off")))
22918 (defun org-agenda-toggle-time-grid ()
22919 "Toggle time grid in an agenda buffer."
22920 (interactive)
22921 (org-agenda-check-type t 'agenda)
22922 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22923 (org-agenda-redo)
22924 (org-agenda-set-mode-name)
22925 (message "Time-grid turned %s"
22926 (if org-agenda-use-time-grid "on" "off")))
22928 (defun org-agenda-set-mode-name ()
22929 "Set the mode name to indicate all the small mode settings."
22930 (setq mode-name
22931 (concat "Org-Agenda"
22932 (if (equal org-agenda-ndays 1) " Day" "")
22933 (if (equal org-agenda-ndays 7) " Week" "")
22934 (if org-agenda-follow-mode " Follow" "")
22935 (if org-agenda-include-diary " Diary" "")
22936 (if org-agenda-use-time-grid " Grid" "")
22937 (if org-agenda-show-log " Log" "")))
22938 (force-mode-line-update))
22940 (defun org-agenda-post-command-hook ()
22941 (and (eolp) (not (bolp)) (backward-char 1))
22942 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22943 (if (and org-agenda-follow-mode
22944 (get-text-property (point) 'org-marker))
22945 (org-agenda-show)))
22947 (defun org-agenda-show-priority ()
22948 "Show the priority of the current item.
22949 This priority is composed of the main priority given with the [#A] cookies,
22950 and by additional input from the age of a schedules or deadline entry."
22951 (interactive)
22952 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22953 (message "Priority is %d" (if pri pri -1000))))
22955 (defun org-agenda-show-tags ()
22956 "Show the tags applicable to the current item."
22957 (interactive)
22958 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22959 (if tags
22960 (message "Tags are :%s:"
22961 (org-no-properties (mapconcat 'identity tags ":")))
22962 (message "No tags associated with this line"))))
22964 (defun org-agenda-goto (&optional highlight)
22965 "Go to the Org-mode file which contains the item at point."
22966 (interactive)
22967 (let* ((marker (or (get-text-property (point) 'org-marker)
22968 (org-agenda-error)))
22969 (buffer (marker-buffer marker))
22970 (pos (marker-position marker)))
22971 (switch-to-buffer-other-window buffer)
22972 (widen)
22973 (goto-char pos)
22974 (when (org-mode-p)
22975 (org-show-context 'agenda)
22976 (save-excursion
22977 (and (outline-next-heading)
22978 (org-flag-heading nil)))) ; show the next heading
22979 (recenter (/ (window-height) 2))
22980 (run-hooks 'org-agenda-after-show-hook)
22981 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22983 (defvar org-agenda-after-show-hook nil
22984 "Normal hook run after an item has been shown from the agenda.
22985 Point is in the buffer where the item originated.")
22987 (defun org-agenda-kill ()
22988 "Kill the entry or subtree belonging to the current agenda entry."
22989 (interactive)
22990 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22991 (let* ((marker (or (get-text-property (point) 'org-marker)
22992 (org-agenda-error)))
22993 (buffer (marker-buffer marker))
22994 (pos (marker-position marker))
22995 (type (get-text-property (point) 'type))
22996 dbeg dend (n 0) conf)
22997 (org-with-remote-undo buffer
22998 (with-current-buffer buffer
22999 (save-excursion
23000 (goto-char pos)
23001 (if (and (org-mode-p) (not (member type '("sexp"))))
23002 (setq dbeg (progn (org-back-to-heading t) (point))
23003 dend (org-end-of-subtree t t))
23004 (setq dbeg (point-at-bol)
23005 dend (min (point-max) (1+ (point-at-eol)))))
23006 (goto-char dbeg)
23007 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
23008 (setq conf (or (eq t org-agenda-confirm-kill)
23009 (and (numberp org-agenda-confirm-kill)
23010 (> n org-agenda-confirm-kill))))
23011 (and conf
23012 (not (y-or-n-p
23013 (format "Delete entry with %d lines in buffer \"%s\"? "
23014 n (buffer-name buffer))))
23015 (error "Abort"))
23016 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
23017 (with-current-buffer buffer (delete-region dbeg dend))
23018 (message "Agenda item and source killed"))))
23020 (defun org-agenda-archive ()
23021 "Kill the entry or subtree belonging to the current agenda entry."
23022 (interactive)
23023 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
23024 (let* ((marker (or (get-text-property (point) 'org-marker)
23025 (org-agenda-error)))
23026 (buffer (marker-buffer marker))
23027 (pos (marker-position marker)))
23028 (org-with-remote-undo buffer
23029 (with-current-buffer buffer
23030 (if (org-mode-p)
23031 (save-excursion
23032 (goto-char pos)
23033 (org-remove-subtree-entries-from-agenda)
23034 (org-back-to-heading t)
23035 (org-archive-subtree))
23036 (error "Archiving works only in Org-mode files"))))))
23038 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
23039 "Remove all lines in the agenda that correspond to a given subtree.
23040 The subtree is the one in buffer BUF, starting at BEG and ending at END.
23041 If this information is not given, the function uses the tree at point."
23042 (let ((buf (or buf (current-buffer))) m p)
23043 (save-excursion
23044 (unless (and beg end)
23045 (org-back-to-heading t)
23046 (setq beg (point))
23047 (org-end-of-subtree t)
23048 (setq end (point)))
23049 (set-buffer (get-buffer org-agenda-buffer-name))
23050 (save-excursion
23051 (goto-char (point-max))
23052 (beginning-of-line 1)
23053 (while (not (bobp))
23054 (when (and (setq m (get-text-property (point) 'org-marker))
23055 (equal buf (marker-buffer m))
23056 (setq p (marker-position m))
23057 (>= p beg)
23058 (<= p end))
23059 (let ((inhibit-read-only t))
23060 (delete-region (point-at-bol) (1+ (point-at-eol)))))
23061 (beginning-of-line 0))))))
23063 (defun org-agenda-open-link ()
23064 "Follow the link in the current line, if any."
23065 (interactive)
23066 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
23067 (save-excursion
23068 (save-restriction
23069 (narrow-to-region (point-at-bol) (point-at-eol))
23070 (org-open-at-point))))
23072 (defun org-agenda-copy-local-variable (var)
23073 "Get a variable from a referenced buffer and install it here."
23074 (let ((m (get-text-property (point) 'org-marker)))
23075 (when (and m (buffer-live-p (marker-buffer m)))
23076 (org-set-local var (with-current-buffer (marker-buffer m)
23077 (symbol-value var))))))
23079 (defun org-agenda-switch-to (&optional delete-other-windows)
23080 "Go to the Org-mode file which contains the item at point."
23081 (interactive)
23082 (let* ((marker (or (get-text-property (point) 'org-marker)
23083 (org-agenda-error)))
23084 (buffer (marker-buffer marker))
23085 (pos (marker-position marker)))
23086 (switch-to-buffer buffer)
23087 (and delete-other-windows (delete-other-windows))
23088 (widen)
23089 (goto-char pos)
23090 (when (org-mode-p)
23091 (org-show-context 'agenda)
23092 (save-excursion
23093 (and (outline-next-heading)
23094 (org-flag-heading nil)))))) ; show the next heading
23096 (defun org-agenda-goto-mouse (ev)
23097 "Go to the Org-mode file which contains the item at the mouse click."
23098 (interactive "e")
23099 (mouse-set-point ev)
23100 (org-agenda-goto))
23102 (defun org-agenda-show ()
23103 "Display the Org-mode file which contains the item at point."
23104 (interactive)
23105 (let ((win (selected-window)))
23106 (org-agenda-goto t)
23107 (select-window win)))
23109 (defun org-agenda-recenter (arg)
23110 "Display the Org-mode file which contains the item at point and recenter."
23111 (interactive "P")
23112 (let ((win (selected-window)))
23113 (org-agenda-goto t)
23114 (recenter arg)
23115 (select-window win)))
23117 (defun org-agenda-show-mouse (ev)
23118 "Display the Org-mode file which contains the item at the mouse click."
23119 (interactive "e")
23120 (mouse-set-point ev)
23121 (org-agenda-show))
23123 (defun org-agenda-check-no-diary ()
23124 "Check if the entry is a diary link and abort if yes."
23125 (if (get-text-property (point) 'org-agenda-diary-link)
23126 (org-agenda-error)))
23128 (defun org-agenda-error ()
23129 (error "Command not allowed in this line"))
23131 (defun org-agenda-tree-to-indirect-buffer ()
23132 "Show the subtree corresponding to the current entry in an indirect buffer.
23133 This calls the command `org-tree-to-indirect-buffer' from the original
23134 Org-mode buffer.
23135 With numerical prefix arg ARG, go up to this level and then take that tree.
23136 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
23137 dedicated frame)."
23138 (interactive)
23139 (org-agenda-check-no-diary)
23140 (let* ((marker (or (get-text-property (point) 'org-marker)
23141 (org-agenda-error)))
23142 (buffer (marker-buffer marker))
23143 (pos (marker-position marker)))
23144 (with-current-buffer buffer
23145 (save-excursion
23146 (goto-char pos)
23147 (call-interactively 'org-tree-to-indirect-buffer)))))
23149 (defvar org-last-heading-marker (make-marker)
23150 "Marker pointing to the headline that last changed its TODO state
23151 by a remote command from the agenda.")
23153 (defun org-agenda-todo-nextset ()
23154 "Switch TODO entry to next sequence."
23155 (interactive)
23156 (org-agenda-todo 'nextset))
23158 (defun org-agenda-todo-previousset ()
23159 "Switch TODO entry to previous sequence."
23160 (interactive)
23161 (org-agenda-todo 'previousset))
23163 (defun org-agenda-todo (&optional arg)
23164 "Cycle TODO state of line at point, also in Org-mode file.
23165 This changes the line at point, all other lines in the agenda referring to
23166 the same tree node, and the headline of the tree node in the Org-mode file."
23167 (interactive "P")
23168 (org-agenda-check-no-diary)
23169 (let* ((col (current-column))
23170 (marker (or (get-text-property (point) 'org-marker)
23171 (org-agenda-error)))
23172 (buffer (marker-buffer marker))
23173 (pos (marker-position marker))
23174 (hdmarker (get-text-property (point) 'org-hd-marker))
23175 (inhibit-read-only t)
23176 newhead)
23177 (org-with-remote-undo buffer
23178 (with-current-buffer buffer
23179 (widen)
23180 (goto-char pos)
23181 (org-show-context 'agenda)
23182 (save-excursion
23183 (and (outline-next-heading)
23184 (org-flag-heading nil))) ; show the next heading
23185 (org-todo arg)
23186 (and (bolp) (forward-char 1))
23187 (setq newhead (org-get-heading))
23188 (save-excursion
23189 (org-back-to-heading)
23190 (move-marker org-last-heading-marker (point))))
23191 (beginning-of-line 1)
23192 (save-excursion
23193 (org-agenda-change-all-lines newhead hdmarker 'fixface))
23194 (move-to-column col))))
23196 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
23197 "Change all lines in the agenda buffer which match HDMARKER.
23198 The new content of the line will be NEWHEAD (as modified by
23199 `org-format-agenda-item'). HDMARKER is checked with
23200 `equal' against all `org-hd-marker' text properties in the file.
23201 If FIXFACE is non-nil, the face of each item is modified acording to
23202 the new TODO state."
23203 (let* ((inhibit-read-only t)
23204 props m pl undone-face done-face finish new dotime cat tags)
23205 (save-excursion
23206 (goto-char (point-max))
23207 (beginning-of-line 1)
23208 (while (not finish)
23209 (setq finish (bobp))
23210 (when (and (setq m (get-text-property (point) 'org-hd-marker))
23211 (equal m hdmarker))
23212 (setq props (text-properties-at (point))
23213 dotime (get-text-property (point) 'dotime)
23214 cat (get-text-property (point) 'org-category)
23215 tags (get-text-property (point) 'tags)
23216 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
23217 pl (get-text-property (point) 'prefix-length)
23218 undone-face (get-text-property (point) 'undone-face)
23219 done-face (get-text-property (point) 'done-face))
23220 (move-to-column pl)
23221 (cond
23222 ((equal new "")
23223 (beginning-of-line 1)
23224 (and (looking-at ".*\n?") (replace-match "")))
23225 ((looking-at ".*")
23226 (replace-match new t t)
23227 (beginning-of-line 1)
23228 (add-text-properties (point-at-bol) (point-at-eol) props)
23229 (when fixface
23230 (add-text-properties
23231 (point-at-bol) (point-at-eol)
23232 (list 'face
23233 (if org-last-todo-state-is-todo
23234 undone-face done-face))))
23235 (org-agenda-highlight-todo 'line)
23236 (beginning-of-line 1))
23237 (t (error "Line update did not work"))))
23238 (beginning-of-line 0)))
23239 (org-finalize-agenda)))
23241 (defun org-agenda-align-tags (&optional line)
23242 "Align all tags in agenda items to `org-agenda-tags-column'."
23243 (let ((inhibit-read-only t) l c)
23244 (save-excursion
23245 (goto-char (if line (point-at-bol) (point-min)))
23246 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
23247 (if line (point-at-eol) nil) t)
23248 (add-text-properties
23249 (match-beginning 2) (match-end 2)
23250 (list 'face (delq nil (list 'org-tag (get-text-property
23251 (match-beginning 2) 'face)))))
23252 (setq l (- (match-end 2) (match-beginning 2))
23253 c (if (< org-agenda-tags-column 0)
23254 (- (abs org-agenda-tags-column) l)
23255 org-agenda-tags-column))
23256 (delete-region (match-beginning 1) (match-end 1))
23257 (goto-char (match-beginning 1))
23258 (insert (org-add-props
23259 (make-string (max 1 (- c (current-column))) ?\ )
23260 (text-properties-at (point))))))))
23262 (defun org-agenda-priority-up ()
23263 "Increase the priority of line at point, also in Org-mode file."
23264 (interactive)
23265 (org-agenda-priority 'up))
23267 (defun org-agenda-priority-down ()
23268 "Decrease the priority of line at point, also in Org-mode file."
23269 (interactive)
23270 (org-agenda-priority 'down))
23272 (defun org-agenda-priority (&optional force-direction)
23273 "Set the priority of line at point, also in Org-mode file.
23274 This changes the line at point, all other lines in the agenda referring to
23275 the same tree node, and the headline of the tree node in the Org-mode file."
23276 (interactive)
23277 (org-agenda-check-no-diary)
23278 (let* ((marker (or (get-text-property (point) 'org-marker)
23279 (org-agenda-error)))
23280 (hdmarker (get-text-property (point) 'org-hd-marker))
23281 (buffer (marker-buffer hdmarker))
23282 (pos (marker-position hdmarker))
23283 (inhibit-read-only t)
23284 newhead)
23285 (org-with-remote-undo buffer
23286 (with-current-buffer buffer
23287 (widen)
23288 (goto-char pos)
23289 (org-show-context 'agenda)
23290 (save-excursion
23291 (and (outline-next-heading)
23292 (org-flag-heading nil))) ; show the next heading
23293 (funcall 'org-priority force-direction)
23294 (end-of-line 1)
23295 (setq newhead (org-get-heading)))
23296 (org-agenda-change-all-lines newhead hdmarker)
23297 (beginning-of-line 1))))
23299 (defun org-get-tags-at (&optional pos)
23300 "Get a list of all headline tags applicable at POS.
23301 POS defaults to point. If tags are inherited, the list contains
23302 the targets in the same sequence as the headlines appear, i.e.
23303 the tags of the current headline come last."
23304 (interactive)
23305 (let (tags lastpos)
23306 (save-excursion
23307 (save-restriction
23308 (widen)
23309 (goto-char (or pos (point)))
23310 (save-match-data
23311 (org-back-to-heading t)
23312 (condition-case nil
23313 (while (not (equal lastpos (point)))
23314 (setq lastpos (point))
23315 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
23316 (setq tags (append (org-split-string
23317 (org-match-string-no-properties 1) ":")
23318 tags)))
23319 (or org-use-tag-inheritance (error ""))
23320 (org-up-heading-all 1))
23321 (error nil))))
23322 tags)))
23324 ;; FIXME: should fix the tags property of the agenda line.
23325 (defun org-agenda-set-tags ()
23326 "Set tags for the current headline."
23327 (interactive)
23328 (org-agenda-check-no-diary)
23329 (if (and (org-region-active-p) (interactive-p))
23330 (call-interactively 'org-change-tag-in-region)
23331 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23332 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23333 (org-agenda-error)))
23334 (buffer (marker-buffer hdmarker))
23335 (pos (marker-position hdmarker))
23336 (inhibit-read-only t)
23337 newhead)
23338 (org-with-remote-undo buffer
23339 (with-current-buffer buffer
23340 (widen)
23341 (goto-char pos)
23342 (save-excursion
23343 (org-show-context 'agenda))
23344 (save-excursion
23345 (and (outline-next-heading)
23346 (org-flag-heading nil))) ; show the next heading
23347 (goto-char pos)
23348 (call-interactively 'org-set-tags)
23349 (end-of-line 1)
23350 (setq newhead (org-get-heading)))
23351 (org-agenda-change-all-lines newhead hdmarker)
23352 (beginning-of-line 1)))))
23354 (defun org-agenda-toggle-archive-tag ()
23355 "Toggle the archive tag for the current entry."
23356 (interactive)
23357 (org-agenda-check-no-diary)
23358 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23359 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23360 (org-agenda-error)))
23361 (buffer (marker-buffer hdmarker))
23362 (pos (marker-position hdmarker))
23363 (inhibit-read-only t)
23364 newhead)
23365 (org-with-remote-undo buffer
23366 (with-current-buffer buffer
23367 (widen)
23368 (goto-char pos)
23369 (org-show-context 'agenda)
23370 (save-excursion
23371 (and (outline-next-heading)
23372 (org-flag-heading nil))) ; show the next heading
23373 (call-interactively 'org-toggle-archive-tag)
23374 (end-of-line 1)
23375 (setq newhead (org-get-heading)))
23376 (org-agenda-change-all-lines newhead hdmarker)
23377 (beginning-of-line 1))))
23379 (defun org-agenda-date-later (arg &optional what)
23380 "Change the date of this item to one day later."
23381 (interactive "p")
23382 (org-agenda-check-type t 'agenda 'timeline)
23383 (org-agenda-check-no-diary)
23384 (let* ((marker (or (get-text-property (point) 'org-marker)
23385 (org-agenda-error)))
23386 (buffer (marker-buffer marker))
23387 (pos (marker-position marker)))
23388 (org-with-remote-undo buffer
23389 (with-current-buffer buffer
23390 (widen)
23391 (goto-char pos)
23392 (if (not (org-at-timestamp-p))
23393 (error "Cannot find time stamp"))
23394 (org-timestamp-change arg (or what 'day)))
23395 (org-agenda-show-new-time marker org-last-changed-timestamp))
23396 (message "Time stamp changed to %s" org-last-changed-timestamp)))
23398 (defun org-agenda-date-earlier (arg &optional what)
23399 "Change the date of this item to one day earlier."
23400 (interactive "p")
23401 (org-agenda-date-later (- arg) what))
23403 (defun org-agenda-show-new-time (marker stamp &optional prefix)
23404 "Show new date stamp via text properties."
23405 ;; We use text properties to make this undoable
23406 (let ((inhibit-read-only t))
23407 (setq stamp (concat " " prefix " => " stamp))
23408 (save-excursion
23409 (goto-char (point-max))
23410 (while (not (bobp))
23411 (when (equal marker (get-text-property (point) 'org-marker))
23412 (move-to-column (- (window-width) (length stamp)) t)
23413 (if (featurep 'xemacs)
23414 ;; Use `duplicable' property to trigger undo recording
23415 (let ((ex (make-extent nil nil))
23416 (gl (make-glyph stamp)))
23417 (set-glyph-face gl 'secondary-selection)
23418 (set-extent-properties
23419 ex (list 'invisible t 'end-glyph gl 'duplicable t))
23420 (insert-extent ex (1- (point)) (point-at-eol)))
23421 (add-text-properties
23422 (1- (point)) (point-at-eol)
23423 (list 'display (org-add-props stamp nil
23424 'face 'secondary-selection))))
23425 (beginning-of-line 1))
23426 (beginning-of-line 0)))))
23428 (defun org-agenda-date-prompt (arg)
23429 "Change the date of this item. Date is prompted for, with default today.
23430 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23431 be used to request time specification in the time stamp."
23432 (interactive "P")
23433 (org-agenda-check-type t 'agenda 'timeline)
23434 (org-agenda-check-no-diary)
23435 (let* ((marker (or (get-text-property (point) 'org-marker)
23436 (org-agenda-error)))
23437 (buffer (marker-buffer marker))
23438 (pos (marker-position marker)))
23439 (org-with-remote-undo buffer
23440 (with-current-buffer buffer
23441 (widen)
23442 (goto-char pos)
23443 (if (not (org-at-timestamp-p))
23444 (error "Cannot find time stamp"))
23445 (org-time-stamp arg)
23446 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23448 (defun org-agenda-schedule (arg)
23449 "Schedule the item at point."
23450 (interactive "P")
23451 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23452 (org-agenda-check-no-diary)
23453 (let* ((marker (or (get-text-property (point) 'org-marker)
23454 (org-agenda-error)))
23455 (type (marker-insertion-type marker))
23456 (buffer (marker-buffer marker))
23457 (pos (marker-position marker))
23458 (org-insert-labeled-timestamps-at-point nil)
23460 (when type (message "%s" type) (sit-for 3))
23461 (set-marker-insertion-type marker t)
23462 (org-with-remote-undo buffer
23463 (with-current-buffer buffer
23464 (widen)
23465 (goto-char pos)
23466 (setq ts (org-schedule arg)))
23467 (org-agenda-show-new-time marker ts "S"))
23468 (message "Item scheduled for %s" ts)))
23470 (defun org-agenda-deadline (arg)
23471 "Schedule the item at point."
23472 (interactive "P")
23473 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23474 (org-agenda-check-no-diary)
23475 (let* ((marker (or (get-text-property (point) 'org-marker)
23476 (org-agenda-error)))
23477 (buffer (marker-buffer marker))
23478 (pos (marker-position marker))
23479 (org-insert-labeled-timestamps-at-point nil)
23481 (org-with-remote-undo buffer
23482 (with-current-buffer buffer
23483 (widen)
23484 (goto-char pos)
23485 (setq ts (org-deadline arg)))
23486 (org-agenda-show-new-time marker ts "S"))
23487 (message "Deadline for this item set to %s" ts)))
23489 (defun org-get-heading (&optional no-tags)
23490 "Return the heading of the current entry, without the stars."
23491 (save-excursion
23492 (org-back-to-heading t)
23493 (if (looking-at
23494 (if no-tags
23495 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23496 "\\*+[ \t]+\\([^\r\n]*\\)"))
23497 (match-string 1) "")))
23499 (defun org-agenda-clock-in (&optional arg)
23500 "Start the clock on the currently selected item."
23501 (interactive "P")
23502 (org-agenda-check-no-diary)
23503 (let* ((marker (or (get-text-property (point) 'org-marker)
23504 (org-agenda-error)))
23505 (pos (marker-position marker)))
23506 (org-with-remote-undo (marker-buffer marker)
23507 (with-current-buffer (marker-buffer marker)
23508 (widen)
23509 (goto-char pos)
23510 (org-clock-in)))))
23512 (defun org-agenda-clock-out (&optional arg)
23513 "Stop the currently running clock."
23514 (interactive "P")
23515 (unless (marker-buffer org-clock-marker)
23516 (error "No running clock"))
23517 (org-with-remote-undo (marker-buffer org-clock-marker)
23518 (org-clock-out)))
23520 (defun org-agenda-clock-cancel (&optional arg)
23521 "Cancel the currently running clock."
23522 (interactive "P")
23523 (unless (marker-buffer org-clock-marker)
23524 (error "No running clock"))
23525 (org-with-remote-undo (marker-buffer org-clock-marker)
23526 (org-clock-cancel)))
23528 (defun org-agenda-diary-entry ()
23529 "Make a diary entry, like the `i' command from the calendar.
23530 All the standard commands work: block, weekly etc."
23531 (interactive)
23532 (org-agenda-check-type t 'agenda 'timeline)
23533 (require 'diary-lib)
23534 (let* ((char (progn
23535 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23536 (read-char-exclusive)))
23537 (cmd (cdr (assoc char
23538 '((?d . insert-diary-entry)
23539 (?w . insert-weekly-diary-entry)
23540 (?m . insert-monthly-diary-entry)
23541 (?y . insert-yearly-diary-entry)
23542 (?a . insert-anniversary-diary-entry)
23543 (?b . insert-block-diary-entry)
23544 (?c . insert-cyclic-diary-entry)))))
23545 (oldf (symbol-function 'calendar-cursor-to-date))
23546 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23547 (point (point))
23548 (mark (or (mark t) (point))))
23549 (unless cmd
23550 (error "No command associated with <%c>" char))
23551 (unless (and (get-text-property point 'day)
23552 (or (not (equal ?b char))
23553 (get-text-property mark 'day)))
23554 (error "Don't know which date to use for diary entry"))
23555 ;; We implement this by hacking the `calendar-cursor-to-date' function
23556 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23557 (let ((calendar-mark-ring
23558 (list (calendar-gregorian-from-absolute
23559 (or (get-text-property mark 'day)
23560 (get-text-property point 'day))))))
23561 (unwind-protect
23562 (progn
23563 (fset 'calendar-cursor-to-date
23564 (lambda (&optional error)
23565 (calendar-gregorian-from-absolute
23566 (get-text-property point 'day))))
23567 (call-interactively cmd))
23568 (fset 'calendar-cursor-to-date oldf)))))
23571 (defun org-agenda-execute-calendar-command (cmd)
23572 "Execute a calendar command from the agenda, with the date associated to
23573 the cursor position."
23574 (org-agenda-check-type t 'agenda 'timeline)
23575 (require 'diary-lib)
23576 (unless (get-text-property (point) 'day)
23577 (error "Don't know which date to use for calendar command"))
23578 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23579 (point (point))
23580 (date (calendar-gregorian-from-absolute
23581 (get-text-property point 'day)))
23582 ;; the following 3 vars are needed in the calendar
23583 (displayed-day (extract-calendar-day date))
23584 (displayed-month (extract-calendar-month date))
23585 (displayed-year (extract-calendar-year date)))
23586 (unwind-protect
23587 (progn
23588 (fset 'calendar-cursor-to-date
23589 (lambda (&optional error)
23590 (calendar-gregorian-from-absolute
23591 (get-text-property point 'day))))
23592 (call-interactively cmd))
23593 (fset 'calendar-cursor-to-date oldf))))
23595 (defun org-agenda-phases-of-moon ()
23596 "Display the phases of the moon for the 3 months around the cursor date."
23597 (interactive)
23598 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23600 (defun org-agenda-holidays ()
23601 "Display the holidays for the 3 months around the cursor date."
23602 (interactive)
23603 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23605 (defun org-agenda-sunrise-sunset (arg)
23606 "Display sunrise and sunset for the cursor date.
23607 Latitude and longitude can be specified with the variables
23608 `calendar-latitude' and `calendar-longitude'. When called with prefix
23609 argument, latitude and longitude will be prompted for."
23610 (interactive "P")
23611 (let ((calendar-longitude (if arg nil calendar-longitude))
23612 (calendar-latitude (if arg nil calendar-latitude))
23613 (calendar-location-name
23614 (if arg "the given coordinates" calendar-location-name)))
23615 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23617 (defun org-agenda-goto-calendar ()
23618 "Open the Emacs calendar with the date at the cursor."
23619 (interactive)
23620 (org-agenda-check-type t 'agenda 'timeline)
23621 (let* ((day (or (get-text-property (point) 'day)
23622 (error "Don't know which date to open in calendar")))
23623 (date (calendar-gregorian-from-absolute day))
23624 (calendar-move-hook nil)
23625 (view-calendar-holidays-initially nil)
23626 (view-diary-entries-initially nil))
23627 (calendar)
23628 (calendar-goto-date date)))
23630 (defun org-calendar-goto-agenda ()
23631 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23632 This is a command that has to be installed in `calendar-mode-map'."
23633 (interactive)
23634 (org-agenda-list nil (calendar-absolute-from-gregorian
23635 (calendar-cursor-to-date))
23636 nil))
23638 (defun org-agenda-convert-date ()
23639 (interactive)
23640 (org-agenda-check-type t 'agenda 'timeline)
23641 (let ((day (get-text-property (point) 'day))
23642 date s)
23643 (unless day
23644 (error "Don't know which date to convert"))
23645 (setq date (calendar-gregorian-from-absolute day))
23646 (setq s (concat
23647 "Gregorian: " (calendar-date-string date) "\n"
23648 "ISO: " (calendar-iso-date-string date) "\n"
23649 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23650 "Julian: " (calendar-julian-date-string date) "\n"
23651 "Astron. JD: " (calendar-astro-date-string date)
23652 " (Julian date number at noon UTC)\n"
23653 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23654 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23655 "French: " (calendar-french-date-string date) "\n"
23656 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23657 "Mayan: " (calendar-mayan-date-string date) "\n"
23658 "Coptic: " (calendar-coptic-date-string date) "\n"
23659 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23660 "Persian: " (calendar-persian-date-string date) "\n"
23661 "Chinese: " (calendar-chinese-date-string date) "\n"))
23662 (with-output-to-temp-buffer "*Dates*"
23663 (princ s))
23664 (if (fboundp 'fit-window-to-buffer)
23665 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23668 ;;;; Embedded LaTeX
23670 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23671 "Keymap for the minor `org-cdlatex-mode'.")
23673 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23674 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23675 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23676 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23677 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23679 (defvar org-cdlatex-texmathp-advice-is-done nil
23680 "Flag remembering if we have applied the advice to texmathp already.")
23682 (define-minor-mode org-cdlatex-mode
23683 "Toggle the minor `org-cdlatex-mode'.
23684 This mode supports entering LaTeX environment and math in LaTeX fragments
23685 in Org-mode.
23686 \\{org-cdlatex-mode-map}"
23687 nil " OCDL" nil
23688 (when org-cdlatex-mode (require 'cdlatex))
23689 (unless org-cdlatex-texmathp-advice-is-done
23690 (setq org-cdlatex-texmathp-advice-is-done t)
23691 (defadvice texmathp (around org-math-always-on activate)
23692 "Always return t in org-mode buffers.
23693 This is because we want to insert math symbols without dollars even outside
23694 the LaTeX math segments. If Orgmode thinks that point is actually inside
23695 en embedded LaTeX fragement, let texmathp do its job.
23696 \\[org-cdlatex-mode-map]"
23697 (interactive)
23698 (let (p)
23699 (cond
23700 ((not (org-mode-p)) ad-do-it)
23701 ((eq this-command 'cdlatex-math-symbol)
23702 (setq ad-return-value t
23703 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23705 (let ((p (org-inside-LaTeX-fragment-p)))
23706 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23707 (setq ad-return-value t
23708 texmathp-why '("Org-mode embedded math" . 0))
23709 (if p ad-do-it)))))))))
23711 (defun turn-on-org-cdlatex ()
23712 "Unconditionally turn on `org-cdlatex-mode'."
23713 (org-cdlatex-mode 1))
23715 (defun org-inside-LaTeX-fragment-p ()
23716 "Test if point is inside a LaTeX fragment.
23717 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23718 sequence appearing also before point.
23719 Even though the matchers for math are configurable, this function assumes
23720 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23721 delimiters are skipped when they have been removed by customization.
23722 The return value is nil, or a cons cell with the delimiter and
23723 and the position of this delimiter.
23725 This function does a reasonably good job, but can locally be fooled by
23726 for example currency specifications. For example it will assume being in
23727 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23728 fragments that are properly closed, but during editing, we have to live
23729 with the uncertainty caused by missing closing delimiters. This function
23730 looks only before point, not after."
23731 (catch 'exit
23732 (let ((pos (point))
23733 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23734 (lim (progn
23735 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23736 (point)))
23737 dd-on str (start 0) m re)
23738 (goto-char pos)
23739 (when dodollar
23740 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23741 re (nth 1 (assoc "$" org-latex-regexps)))
23742 (while (string-match re str start)
23743 (cond
23744 ((= (match-end 0) (length str))
23745 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23746 ((= (match-end 0) (- (length str) 5))
23747 (throw 'exit nil))
23748 (t (setq start (match-end 0))))))
23749 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23750 (goto-char pos)
23751 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23752 (and (match-beginning 2) (throw 'exit nil))
23753 ;; count $$
23754 (while (re-search-backward "\\$\\$" lim t)
23755 (setq dd-on (not dd-on)))
23756 (goto-char pos)
23757 (if dd-on (cons "$$" m))))))
23760 (defun org-try-cdlatex-tab ()
23761 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23762 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23763 - inside a LaTeX fragment, or
23764 - after the first word in a line, where an abbreviation expansion could
23765 insert a LaTeX environment."
23766 (when org-cdlatex-mode
23767 (cond
23768 ((save-excursion
23769 (skip-chars-backward "a-zA-Z0-9*")
23770 (skip-chars-backward " \t")
23771 (bolp))
23772 (cdlatex-tab) t)
23773 ((org-inside-LaTeX-fragment-p)
23774 (cdlatex-tab) t)
23775 (t nil))))
23777 (defun org-cdlatex-underscore-caret (&optional arg)
23778 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23779 Revert to the normal definition outside of these fragments."
23780 (interactive "P")
23781 (if (org-inside-LaTeX-fragment-p)
23782 (call-interactively 'cdlatex-sub-superscript)
23783 (let (org-cdlatex-mode)
23784 (call-interactively (key-binding (vector last-input-event))))))
23786 (defun org-cdlatex-math-modify (&optional arg)
23787 "Execute `cdlatex-math-modify' in LaTeX fragments.
23788 Revert to the normal definition outside of these fragments."
23789 (interactive "P")
23790 (if (org-inside-LaTeX-fragment-p)
23791 (call-interactively 'cdlatex-math-modify)
23792 (let (org-cdlatex-mode)
23793 (call-interactively (key-binding (vector last-input-event))))))
23795 (defvar org-latex-fragment-image-overlays nil
23796 "List of overlays carrying the images of latex fragments.")
23797 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23799 (defun org-remove-latex-fragment-image-overlays ()
23800 "Remove all overlays with LaTeX fragment images in current buffer."
23801 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23802 (setq org-latex-fragment-image-overlays nil))
23804 (defun org-preview-latex-fragment (&optional subtree)
23805 "Preview the LaTeX fragment at point, or all locally or globally.
23806 If the cursor is in a LaTeX fragment, create the image and overlay
23807 it over the source code. If there is no fragment at point, display
23808 all fragments in the current text, from one headline to the next. With
23809 prefix SUBTREE, display all fragments in the current subtree. With a
23810 double prefix `C-u C-u', or when the cursor is before the first headline,
23811 display all fragments in the buffer.
23812 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23813 (interactive "P")
23814 (org-remove-latex-fragment-image-overlays)
23815 (save-excursion
23816 (save-restriction
23817 (let (beg end at msg)
23818 (cond
23819 ((or (equal subtree '(16))
23820 (not (save-excursion
23821 (re-search-backward (concat "^" outline-regexp) nil t))))
23822 (setq beg (point-min) end (point-max)
23823 msg "Creating images for buffer...%s"))
23824 ((equal subtree '(4))
23825 (org-back-to-heading)
23826 (setq beg (point) end (org-end-of-subtree t)
23827 msg "Creating images for subtree...%s"))
23829 (if (setq at (org-inside-LaTeX-fragment-p))
23830 (goto-char (max (point-min) (- (cdr at) 2)))
23831 (org-back-to-heading))
23832 (setq beg (point) end (progn (outline-next-heading) (point))
23833 msg (if at "Creating image...%s"
23834 "Creating images for entry...%s"))))
23835 (message msg "")
23836 (narrow-to-region beg end)
23837 (goto-char beg)
23838 (org-format-latex
23839 (concat "ltxpng/" (file-name-sans-extension
23840 (file-name-nondirectory
23841 buffer-file-name)))
23842 default-directory 'overlays msg at 'forbuffer)
23843 (message msg "done. Use `C-c C-c' to remove images.")))))
23845 (defvar org-latex-regexps
23846 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23847 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23848 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23849 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23850 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23851 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23852 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23853 "Regular expressions for matching embedded LaTeX.")
23855 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23856 "Replace LaTeX fragments with links to an image, and produce images."
23857 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23858 (let* ((prefixnodir (file-name-nondirectory prefix))
23859 (absprefix (expand-file-name prefix dir))
23860 (todir (file-name-directory absprefix))
23861 (opt org-format-latex-options)
23862 (matchers (plist-get opt :matchers))
23863 (re-list org-latex-regexps)
23864 (cnt 0) txt link beg end re e checkdir
23865 m n block linkfile movefile ov)
23866 ;; Check if there are old images files with this prefix, and remove them
23867 (when (file-directory-p todir)
23868 (mapc 'delete-file
23869 (directory-files
23870 todir 'full
23871 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23872 ;; Check the different regular expressions
23873 (while (setq e (pop re-list))
23874 (setq m (car e) re (nth 1 e) n (nth 2 e)
23875 block (if (nth 3 e) "\n\n" ""))
23876 (when (member m matchers)
23877 (goto-char (point-min))
23878 (while (re-search-forward re nil t)
23879 (when (or (not at) (equal (cdr at) (match-beginning n)))
23880 (setq txt (match-string n)
23881 beg (match-beginning n) end (match-end n)
23882 cnt (1+ cnt)
23883 linkfile (format "%s_%04d.png" prefix cnt)
23884 movefile (format "%s_%04d.png" absprefix cnt)
23885 link (concat block "[[file:" linkfile "]]" block))
23886 (if msg (message msg cnt))
23887 (goto-char beg)
23888 (unless checkdir ; make sure the directory exists
23889 (setq checkdir t)
23890 (or (file-directory-p todir) (make-directory todir)))
23891 (org-create-formula-image
23892 txt movefile opt forbuffer)
23893 (if overlays
23894 (progn
23895 (setq ov (org-make-overlay beg end))
23896 (if (featurep 'xemacs)
23897 (progn
23898 (org-overlay-put ov 'invisible t)
23899 (org-overlay-put
23900 ov 'end-glyph
23901 (make-glyph (vector 'png :file movefile))))
23902 (org-overlay-put
23903 ov 'display
23904 (list 'image :type 'png :file movefile :ascent 'center)))
23905 (push ov org-latex-fragment-image-overlays)
23906 (goto-char end))
23907 (delete-region beg end)
23908 (insert link))))))))
23910 ;; This function borrows from Ganesh Swami's latex2png.el
23911 (defun org-create-formula-image (string tofile options buffer)
23912 (let* ((tmpdir (if (featurep 'xemacs)
23913 (temp-directory)
23914 temporary-file-directory))
23915 (texfilebase (make-temp-name
23916 (expand-file-name "orgtex" tmpdir)))
23917 (texfile (concat texfilebase ".tex"))
23918 (dvifile (concat texfilebase ".dvi"))
23919 (pngfile (concat texfilebase ".png"))
23920 (fnh (face-attribute 'default :height nil))
23921 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23922 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23923 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23924 "Black"))
23925 (bg (or (plist-get options (if buffer :background :html-background))
23926 "Transparent")))
23927 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23928 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23929 (with-temp-file texfile
23930 (insert org-format-latex-header
23931 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23932 (let ((dir default-directory))
23933 (condition-case nil
23934 (progn
23935 (cd tmpdir)
23936 (call-process "latex" nil nil nil texfile))
23937 (error nil))
23938 (cd dir))
23939 (if (not (file-exists-p dvifile))
23940 (progn (message "Failed to create dvi file from %s" texfile) nil)
23941 (call-process "dvipng" nil nil nil
23942 "-E" "-fg" fg "-bg" bg
23943 "-D" dpi
23944 ;;"-x" scale "-y" scale
23945 "-T" "tight"
23946 "-o" pngfile
23947 dvifile)
23948 (if (not (file-exists-p pngfile))
23949 (progn (message "Failed to create png file from %s" texfile) nil)
23950 ;; Use the requested file name and clean up
23951 (copy-file pngfile tofile 'replace)
23952 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23953 (delete-file (concat texfilebase e)))
23954 pngfile))))
23956 (defun org-dvipng-color (attr)
23957 "Return an rgb color specification for dvipng."
23958 (apply 'format "rgb %s %s %s"
23959 (mapcar 'org-normalize-color
23960 (color-values (face-attribute 'default attr nil)))))
23962 (defun org-normalize-color (value)
23963 "Return string to be used as color value for an RGB component."
23964 (format "%g" (/ value 65535.0)))
23966 ;;;; Exporting
23968 ;;; Variables, constants, and parameter plists
23970 (defconst org-level-max 20)
23972 (defvar org-export-html-preamble nil
23973 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23974 (defvar org-export-html-postamble nil
23975 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23976 (defvar org-export-html-auto-preamble t
23977 "Should default preamble be inserted? Set by publishing functions.")
23978 (defvar org-export-html-auto-postamble t
23979 "Should default postamble be inserted? Set by publishing functions.")
23980 (defvar org-current-export-file nil) ; dynamically scoped parameter
23981 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23984 (defconst org-export-plist-vars
23985 '((:language . org-export-default-language)
23986 (:customtime . org-display-custom-times)
23987 (:headline-levels . org-export-headline-levels)
23988 (:section-numbers . org-export-with-section-numbers)
23989 (:table-of-contents . org-export-with-toc)
23990 (:preserve-breaks . org-export-preserve-breaks)
23991 (:archived-trees . org-export-with-archived-trees)
23992 (:emphasize . org-export-with-emphasize)
23993 (:sub-superscript . org-export-with-sub-superscripts)
23994 (:special-strings . org-export-with-special-strings)
23995 (:footnotes . org-export-with-footnotes)
23996 (:drawers . org-export-with-drawers)
23997 (:tags . org-export-with-tags)
23998 (:TeX-macros . org-export-with-TeX-macros)
23999 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
24000 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
24001 (:fixed-width . org-export-with-fixed-width)
24002 (:timestamps . org-export-with-timestamps)
24003 (:author-info . org-export-author-info)
24004 (:time-stamp-file . org-export-time-stamp-file)
24005 (:tables . org-export-with-tables)
24006 (:table-auto-headline . org-export-highlight-first-table-line)
24007 (:style . org-export-html-style)
24008 (:agenda-style . org-agenda-export-html-style)
24009 (:convert-org-links . org-export-html-link-org-files-as-html)
24010 (:inline-images . org-export-html-inline-images)
24011 (:html-extension . org-export-html-extension)
24012 (:html-table-tag . org-export-html-table-tag)
24013 (:expand-quoted-html . org-export-html-expand)
24014 (:timestamp . org-export-html-with-timestamp)
24015 (:publishing-directory . org-export-publishing-directory)
24016 (:preamble . org-export-html-preamble)
24017 (:postamble . org-export-html-postamble)
24018 (:auto-preamble . org-export-html-auto-preamble)
24019 (:auto-postamble . org-export-html-auto-postamble)
24020 (:author . user-full-name)
24021 (:email . user-mail-address)))
24023 (defun org-default-export-plist ()
24024 "Return the property list with default settings for the export variables."
24025 (let ((l org-export-plist-vars) rtn e)
24026 (while (setq e (pop l))
24027 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
24028 rtn))
24030 (defun org-infile-export-plist ()
24031 "Return the property list with file-local settings for export."
24032 (save-excursion
24033 (save-restriction
24034 (widen)
24035 (goto-char 0)
24036 (let ((re (org-make-options-regexp
24037 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
24038 p key val text options)
24039 (while (re-search-forward re nil t)
24040 (setq key (org-match-string-no-properties 1)
24041 val (org-match-string-no-properties 2))
24042 (cond
24043 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
24044 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
24045 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
24046 ((string-equal key "DATE") (setq p (plist-put p :date val)))
24047 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
24048 ((string-equal key "TEXT")
24049 (setq text (if text (concat text "\n" val) val)))
24050 ((string-equal key "OPTIONS") (setq options val))))
24051 (setq p (plist-put p :text text))
24052 (when options
24053 (let ((op '(("H" . :headline-levels)
24054 ("num" . :section-numbers)
24055 ("toc" . :table-of-contents)
24056 ("\\n" . :preserve-breaks)
24057 ("@" . :expand-quoted-html)
24058 (":" . :fixed-width)
24059 ("|" . :tables)
24060 ("^" . :sub-superscript)
24061 ("-" . :special-strings)
24062 ("f" . :footnotes)
24063 ("d" . :drawers)
24064 ("tags" . :tags)
24065 ("*" . :emphasize)
24066 ("TeX" . :TeX-macros)
24067 ("LaTeX" . :LaTeX-fragments)
24068 ("skip" . :skip-before-1st-heading)
24069 ("author" . :author-info)
24070 ("timestamp" . :time-stamp-file)))
24072 (while (setq o (pop op))
24073 (if (string-match (concat (regexp-quote (car o))
24074 ":\\([^ \t\n\r;,.]*\\)")
24075 options)
24076 (setq p (plist-put p (cdr o)
24077 (car (read-from-string
24078 (match-string 1 options)))))))))
24079 p))))
24081 (defun org-export-directory (type plist)
24082 (let* ((val (plist-get plist :publishing-directory))
24083 (dir (if (listp val)
24084 (or (cdr (assoc type val)) ".")
24085 val)))
24086 dir))
24088 (defun org-skip-comments (lines)
24089 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
24090 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
24091 (re2 "^\\(\\*+\\)[ \t\n\r]")
24092 (case-fold-search nil)
24093 rtn line level)
24094 (while (setq line (pop lines))
24095 (cond
24096 ((and (string-match re1 line)
24097 (setq level (- (match-end 1) (match-beginning 1))))
24098 ;; Beginning of a COMMENT subtree. Skip it.
24099 (while (and (setq line (pop lines))
24100 (or (not (string-match re2 line))
24101 (> (- (match-end 1) (match-beginning 1)) level))))
24102 (setq lines (cons line lines)))
24103 ((string-match "^#" line)
24104 ;; an ordinary comment line
24106 ((and org-export-table-remove-special-lines
24107 (string-match "^[ \t]*|" line)
24108 (or (string-match "^[ \t]*| *[!_^] *|" line)
24109 (and (string-match "| *<[0-9]+> *|" line)
24110 (not (string-match "| *[^ <|]" line)))))
24111 ;; a special table line that should be removed
24113 (t (setq rtn (cons line rtn)))))
24114 (nreverse rtn)))
24116 (defun org-export (&optional arg)
24117 (interactive)
24118 (let ((help "[t] insert the export option template
24119 \[v] limit export to visible part of outline tree
24121 \[a] export as ASCII
24123 \[h] export as HTML
24124 \[H] export as HTML to temporary buffer
24125 \[R] export region as HTML
24126 \[b] export as HTML and browse immediately
24127 \[x] export as XOXO
24129 \[l] export as LaTeX
24130 \[L] export as LaTeX to temporary buffer
24132 \[i] export current file as iCalendar file
24133 \[I] export all agenda files as iCalendar files
24134 \[c] export agenda files into combined iCalendar file
24136 \[F] publish current file
24137 \[P] publish current project
24138 \[X] publish... (project will be prompted for)
24139 \[A] publish all projects")
24140 (cmds
24141 '((?t . org-insert-export-options-template)
24142 (?v . org-export-visible)
24143 (?a . org-export-as-ascii)
24144 (?h . org-export-as-html)
24145 (?b . org-export-as-html-and-open)
24146 (?H . org-export-as-html-to-buffer)
24147 (?R . org-export-region-as-html)
24148 (?x . org-export-as-xoxo)
24149 (?l . org-export-as-latex)
24150 (?L . org-export-as-latex-to-buffer)
24151 (?i . org-export-icalendar-this-file)
24152 (?I . org-export-icalendar-all-agenda-files)
24153 (?c . org-export-icalendar-combine-agenda-files)
24154 (?F . org-publish-current-file)
24155 (?P . org-publish-current-project)
24156 (?X . org-publish)
24157 (?A . org-publish-all)))
24158 r1 r2 ass)
24159 (save-window-excursion
24160 (delete-other-windows)
24161 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
24162 (princ help))
24163 (message "Select command: ")
24164 (setq r1 (read-char-exclusive)))
24165 (setq r2 (if (< r1 27) (+ r1 96) r1))
24166 (if (setq ass (assq r2 cmds))
24167 (call-interactively (cdr ass))
24168 (error "No command associated with key %c" r1))))
24170 (defconst org-html-entities
24171 '(("nbsp")
24172 ("iexcl")
24173 ("cent")
24174 ("pound")
24175 ("curren")
24176 ("yen")
24177 ("brvbar")
24178 ("vert" . "&#124;")
24179 ("sect")
24180 ("uml")
24181 ("copy")
24182 ("ordf")
24183 ("laquo")
24184 ("not")
24185 ("shy")
24186 ("reg")
24187 ("macr")
24188 ("deg")
24189 ("plusmn")
24190 ("sup2")
24191 ("sup3")
24192 ("acute")
24193 ("micro")
24194 ("para")
24195 ("middot")
24196 ("odot"."o")
24197 ("star"."*")
24198 ("cedil")
24199 ("sup1")
24200 ("ordm")
24201 ("raquo")
24202 ("frac14")
24203 ("frac12")
24204 ("frac34")
24205 ("iquest")
24206 ("Agrave")
24207 ("Aacute")
24208 ("Acirc")
24209 ("Atilde")
24210 ("Auml")
24211 ("Aring") ("AA"."&Aring;")
24212 ("AElig")
24213 ("Ccedil")
24214 ("Egrave")
24215 ("Eacute")
24216 ("Ecirc")
24217 ("Euml")
24218 ("Igrave")
24219 ("Iacute")
24220 ("Icirc")
24221 ("Iuml")
24222 ("ETH")
24223 ("Ntilde")
24224 ("Ograve")
24225 ("Oacute")
24226 ("Ocirc")
24227 ("Otilde")
24228 ("Ouml")
24229 ("times")
24230 ("Oslash")
24231 ("Ugrave")
24232 ("Uacute")
24233 ("Ucirc")
24234 ("Uuml")
24235 ("Yacute")
24236 ("THORN")
24237 ("szlig")
24238 ("agrave")
24239 ("aacute")
24240 ("acirc")
24241 ("atilde")
24242 ("auml")
24243 ("aring")
24244 ("aelig")
24245 ("ccedil")
24246 ("egrave")
24247 ("eacute")
24248 ("ecirc")
24249 ("euml")
24250 ("igrave")
24251 ("iacute")
24252 ("icirc")
24253 ("iuml")
24254 ("eth")
24255 ("ntilde")
24256 ("ograve")
24257 ("oacute")
24258 ("ocirc")
24259 ("otilde")
24260 ("ouml")
24261 ("divide")
24262 ("oslash")
24263 ("ugrave")
24264 ("uacute")
24265 ("ucirc")
24266 ("uuml")
24267 ("yacute")
24268 ("thorn")
24269 ("yuml")
24270 ("fnof")
24271 ("Alpha")
24272 ("Beta")
24273 ("Gamma")
24274 ("Delta")
24275 ("Epsilon")
24276 ("Zeta")
24277 ("Eta")
24278 ("Theta")
24279 ("Iota")
24280 ("Kappa")
24281 ("Lambda")
24282 ("Mu")
24283 ("Nu")
24284 ("Xi")
24285 ("Omicron")
24286 ("Pi")
24287 ("Rho")
24288 ("Sigma")
24289 ("Tau")
24290 ("Upsilon")
24291 ("Phi")
24292 ("Chi")
24293 ("Psi")
24294 ("Omega")
24295 ("alpha")
24296 ("beta")
24297 ("gamma")
24298 ("delta")
24299 ("epsilon")
24300 ("varepsilon"."&epsilon;")
24301 ("zeta")
24302 ("eta")
24303 ("theta")
24304 ("iota")
24305 ("kappa")
24306 ("lambda")
24307 ("mu")
24308 ("nu")
24309 ("xi")
24310 ("omicron")
24311 ("pi")
24312 ("rho")
24313 ("sigmaf") ("varsigma"."&sigmaf;")
24314 ("sigma")
24315 ("tau")
24316 ("upsilon")
24317 ("phi")
24318 ("chi")
24319 ("psi")
24320 ("omega")
24321 ("thetasym") ("vartheta"."&thetasym;")
24322 ("upsih")
24323 ("piv")
24324 ("bull") ("bullet"."&bull;")
24325 ("hellip") ("dots"."&hellip;")
24326 ("prime")
24327 ("Prime")
24328 ("oline")
24329 ("frasl")
24330 ("weierp")
24331 ("image")
24332 ("real")
24333 ("trade")
24334 ("alefsym")
24335 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
24336 ("uarr") ("uparrow"."&uarr;")
24337 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
24338 ("darr")("downarrow"."&darr;")
24339 ("harr") ("leftrightarrow"."&harr;")
24340 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
24341 ("lArr") ("Leftarrow"."&lArr;")
24342 ("uArr") ("Uparrow"."&uArr;")
24343 ("rArr") ("Rightarrow"."&rArr;")
24344 ("dArr") ("Downarrow"."&dArr;")
24345 ("hArr") ("Leftrightarrow"."&hArr;")
24346 ("forall")
24347 ("part") ("partial"."&part;")
24348 ("exist") ("exists"."&exist;")
24349 ("empty") ("emptyset"."&empty;")
24350 ("nabla")
24351 ("isin") ("in"."&isin;")
24352 ("notin")
24353 ("ni")
24354 ("prod")
24355 ("sum")
24356 ("minus")
24357 ("lowast") ("ast"."&lowast;")
24358 ("radic")
24359 ("prop") ("proptp"."&prop;")
24360 ("infin") ("infty"."&infin;")
24361 ("ang") ("angle"."&ang;")
24362 ("and") ("wedge"."&and;")
24363 ("or") ("vee"."&or;")
24364 ("cap")
24365 ("cup")
24366 ("int")
24367 ("there4")
24368 ("sim")
24369 ("cong") ("simeq"."&cong;")
24370 ("asymp")("approx"."&asymp;")
24371 ("ne") ("neq"."&ne;")
24372 ("equiv")
24373 ("le")
24374 ("ge")
24375 ("sub") ("subset"."&sub;")
24376 ("sup") ("supset"."&sup;")
24377 ("nsub")
24378 ("sube")
24379 ("supe")
24380 ("oplus")
24381 ("otimes")
24382 ("perp")
24383 ("sdot") ("cdot"."&sdot;")
24384 ("lceil")
24385 ("rceil")
24386 ("lfloor")
24387 ("rfloor")
24388 ("lang")
24389 ("rang")
24390 ("loz") ("Diamond"."&loz;")
24391 ("spades") ("spadesuit"."&spades;")
24392 ("clubs") ("clubsuit"."&clubs;")
24393 ("hearts") ("diamondsuit"."&hearts;")
24394 ("diams") ("diamondsuit"."&diams;")
24395 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
24396 ("quot")
24397 ("amp")
24398 ("lt")
24399 ("gt")
24400 ("OElig")
24401 ("oelig")
24402 ("Scaron")
24403 ("scaron")
24404 ("Yuml")
24405 ("circ")
24406 ("tilde")
24407 ("ensp")
24408 ("emsp")
24409 ("thinsp")
24410 ("zwnj")
24411 ("zwj")
24412 ("lrm")
24413 ("rlm")
24414 ("ndash")
24415 ("mdash")
24416 ("lsquo")
24417 ("rsquo")
24418 ("sbquo")
24419 ("ldquo")
24420 ("rdquo")
24421 ("bdquo")
24422 ("dagger")
24423 ("Dagger")
24424 ("permil")
24425 ("lsaquo")
24426 ("rsaquo")
24427 ("euro")
24429 ("arccos"."arccos")
24430 ("arcsin"."arcsin")
24431 ("arctan"."arctan")
24432 ("arg"."arg")
24433 ("cos"."cos")
24434 ("cosh"."cosh")
24435 ("cot"."cot")
24436 ("coth"."coth")
24437 ("csc"."csc")
24438 ("deg"."deg")
24439 ("det"."det")
24440 ("dim"."dim")
24441 ("exp"."exp")
24442 ("gcd"."gcd")
24443 ("hom"."hom")
24444 ("inf"."inf")
24445 ("ker"."ker")
24446 ("lg"."lg")
24447 ("lim"."lim")
24448 ("liminf"."liminf")
24449 ("limsup"."limsup")
24450 ("ln"."ln")
24451 ("log"."log")
24452 ("max"."max")
24453 ("min"."min")
24454 ("Pr"."Pr")
24455 ("sec"."sec")
24456 ("sin"."sin")
24457 ("sinh"."sinh")
24458 ("sup"."sup")
24459 ("tan"."tan")
24460 ("tanh"."tanh")
24462 "Entities for TeX->HTML translation.
24463 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24464 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24465 In that case, \"\\ent\" will be translated to \"&other;\".
24466 The list contains HTML entities for Latin-1, Greek and other symbols.
24467 It is supplemented by a number of commonly used TeX macros with appropriate
24468 translations. There is currently no way for users to extend this.")
24470 ;;; General functions for all backends
24472 (defun org-cleaned-string-for-export (string &rest parameters)
24473 "Cleanup a buffer STRING so that links can be created safely."
24474 (interactive)
24475 (let* ((re-radio (and org-target-link-regexp
24476 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24477 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24478 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24479 (re-archive (concat ":" org-archive-tag ":"))
24480 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24481 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24482 (htmlp (plist-get parameters :for-html))
24483 (asciip (plist-get parameters :for-ascii))
24484 (latexp (plist-get parameters :for-LaTeX))
24485 (commentsp (plist-get parameters :comments))
24486 (archived-trees (plist-get parameters :archived-trees))
24487 (inhibit-read-only t)
24488 (drawers org-drawers)
24489 (exp-drawers (plist-get parameters :drawers))
24490 (outline-regexp "\\*+ ")
24491 a b xx
24492 rtn p)
24493 (with-current-buffer (get-buffer-create " org-mode-tmp")
24494 (erase-buffer)
24495 (insert string)
24496 ;; Remove license-to-kill stuff
24497 (while (setq p (text-property-any (point-min) (point-max)
24498 :org-license-to-kill t))
24499 (delete-region p (next-single-property-change p :org-license-to-kill)))
24501 (let ((org-inhibit-startup t)) (org-mode))
24502 (untabify (point-min) (point-max))
24504 ;; Get rid of drawers
24505 (unless (eq t exp-drawers)
24506 (goto-char (point-min))
24507 (let ((re (concat "^[ \t]*:\\("
24508 (mapconcat
24509 'identity
24510 (org-delete-all exp-drawers
24511 (copy-sequence drawers))
24512 "\\|")
24513 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24514 (while (re-search-forward re nil t)
24515 (replace-match ""))))
24517 ;; Get the correct stuff before the first headline
24518 (when (plist-get parameters :skip-before-1st-heading)
24519 (goto-char (point-min))
24520 (when (re-search-forward "^\\*+[ \t]" nil t)
24521 (delete-region (point-min) (match-beginning 0))
24522 (goto-char (point-min))
24523 (insert "\n")))
24524 (when (plist-get parameters :add-text)
24525 (goto-char (point-min))
24526 (insert (plist-get parameters :add-text) "\n"))
24528 ;; Get rid of archived trees
24529 (when (not (eq archived-trees t))
24530 (goto-char (point-min))
24531 (while (re-search-forward re-archive nil t)
24532 (if (not (org-on-heading-p t))
24533 (org-end-of-subtree t)
24534 (beginning-of-line 1)
24535 (setq a (if archived-trees
24536 (1+ (point-at-eol)) (point))
24537 b (org-end-of-subtree t))
24538 (if (> b a) (delete-region a b)))))
24540 ;; Find targets in comments and move them out of comments,
24541 ;; but mark them as targets that should be invisible
24542 (goto-char (point-min))
24543 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24544 (replace-match "\\1(INVISIBLE)"))
24546 ;; Protect backend specific stuff, throw away the others.
24547 (let ((formatters
24548 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24549 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24550 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24551 fmt)
24552 (goto-char (point-min))
24553 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24554 (goto-char (match-end 0))
24555 (while (not (looking-at "#\\+END_EXAMPLE"))
24556 (insert ": ")
24557 (beginning-of-line 2)))
24558 (goto-char (point-min))
24559 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24560 (add-text-properties (match-beginning 0) (match-end 0)
24561 '(org-protected t)))
24562 (while formatters
24563 (setq fmt (pop formatters))
24564 (when (car fmt)
24565 (goto-char (point-min))
24566 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24567 ":[ \t]*\\(.*\\)") nil t)
24568 (replace-match "\\1" t)
24569 (add-text-properties
24570 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24571 '(org-protected t))))
24572 (goto-char (point-min))
24573 (while (re-search-forward
24574 (concat "^#\\+"
24575 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24576 (cadddr fmt) "\\>.*\n?") nil t)
24577 (if (car fmt)
24578 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24579 '(org-protected t))
24580 (delete-region (match-beginning 0) (match-end 0))))))
24582 ;; Protect quoted subtrees
24583 (goto-char (point-min))
24584 (while (re-search-forward re-quote nil t)
24585 (goto-char (match-beginning 0))
24586 (end-of-line 1)
24587 (add-text-properties (point) (org-end-of-subtree t)
24588 '(org-protected t)))
24590 ;; Protect verbatim elements
24591 (goto-char (point-min))
24592 (while (re-search-forward org-verbatim-re nil t)
24593 (add-text-properties (match-beginning 4) (match-end 4)
24594 '(org-protected t))
24595 (goto-char (1+ (match-end 4))))
24597 ;; Remove subtrees that are commented
24598 (goto-char (point-min))
24599 (while (re-search-forward re-commented nil t)
24600 (goto-char (match-beginning 0))
24601 (delete-region (point) (org-end-of-subtree t)))
24603 ;; Remove special table lines
24604 (when org-export-table-remove-special-lines
24605 (goto-char (point-min))
24606 (while (re-search-forward "^[ \t]*|" nil t)
24607 (beginning-of-line 1)
24608 (if (or (looking-at "[ \t]*| *[!_^] *|")
24609 (and (looking-at ".*?| *<[0-9]+> *|")
24610 (not (looking-at ".*?| *[^ <|]"))))
24611 (delete-region (max (point-min) (1- (point-at-bol)))
24612 (point-at-eol))
24613 (end-of-line 1))))
24615 ;; Specific LaTeX stuff
24616 (when latexp
24617 (require 'org-export-latex nil)
24618 (org-export-latex-cleaned-string))
24620 (when asciip
24621 (org-export-ascii-clean-string))
24623 ;; Specific HTML stuff
24624 (when htmlp
24625 ;; Convert LaTeX fragments to images
24626 (when (plist-get parameters :LaTeX-fragments)
24627 (org-format-latex
24628 (concat "ltxpng/" (file-name-sans-extension
24629 (file-name-nondirectory
24630 org-current-export-file)))
24631 org-current-export-dir nil "Creating LaTeX image %s"))
24632 (message "Exporting..."))
24634 ;; Remove or replace comments
24635 (goto-char (point-min))
24636 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24637 (if commentsp
24638 (progn (add-text-properties
24639 (match-beginning 0) (match-end 0) '(org-protected t))
24640 (replace-match (format commentsp (match-string 1)) t t))
24641 (replace-match "")))
24643 ;; Find matches for radio targets and turn them into internal links
24644 (goto-char (point-min))
24645 (when re-radio
24646 (while (re-search-forward re-radio nil t)
24647 (org-if-unprotected
24648 (replace-match "\\1[[\\2]]"))))
24650 ;; Find all links that contain a newline and put them into a single line
24651 (goto-char (point-min))
24652 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24653 (org-if-unprotected
24654 (replace-match "\\1 \\3")
24655 (goto-char (match-beginning 0))))
24658 ;; Normalize links: Convert angle and plain links into bracket links
24659 ;; Expand link abbreviations
24660 (goto-char (point-min))
24661 (while (re-search-forward re-plain-link nil t)
24662 (goto-char (1- (match-end 0)))
24663 (org-if-unprotected
24664 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24665 ":" (match-string 3) "]]")))
24666 ;; added 'org-link face to links
24667 (put-text-property 0 (length s) 'face 'org-link s)
24668 (replace-match s t t))))
24669 (goto-char (point-min))
24670 (while (re-search-forward re-angle-link nil t)
24671 (goto-char (1- (match-end 0)))
24672 (org-if-unprotected
24673 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24674 ":" (match-string 3) "]]")))
24675 (put-text-property 0 (length s) 'face 'org-link s)
24676 (replace-match s t t))))
24677 (goto-char (point-min))
24678 (while (re-search-forward org-bracket-link-regexp nil t)
24679 (org-if-unprotected
24680 (let* ((s (concat "[[" (setq xx (save-match-data
24681 (org-link-expand-abbrev (match-string 1))))
24683 (if (match-end 3)
24684 (match-string 2)
24685 (concat "[" xx "]"))
24686 "]")))
24687 (put-text-property 0 (length s) 'face 'org-link s)
24688 (replace-match s t t))))
24690 ;; Find multiline emphasis and put them into single line
24691 (when (plist-get parameters :emph-multiline)
24692 (goto-char (point-min))
24693 (while (re-search-forward org-emph-re nil t)
24694 (if (not (= (char-after (match-beginning 3))
24695 (char-after (match-beginning 4))))
24696 (org-if-unprotected
24697 (subst-char-in-region (match-beginning 0) (match-end 0)
24698 ?\n ?\ t)
24699 (goto-char (1- (match-end 0))))
24700 (goto-char (1+ (match-beginning 0))))))
24702 (setq rtn (buffer-string)))
24703 (kill-buffer " org-mode-tmp")
24704 rtn))
24706 (defun org-export-grab-title-from-buffer ()
24707 "Get a title for the current document, from looking at the buffer."
24708 (let ((inhibit-read-only t))
24709 (save-excursion
24710 (goto-char (point-min))
24711 (let ((end (save-excursion (outline-next-heading) (point))))
24712 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24713 ;; Mark the line so that it will not be exported as normal text.
24714 (org-unmodified
24715 (add-text-properties (match-beginning 0) (match-end 0)
24716 (list :org-license-to-kill t)))
24717 ;; Return the title string
24718 (org-trim (match-string 0)))))))
24720 (defun org-export-get-title-from-subtree ()
24721 "Return subtree title and exclude it from export."
24722 (let (title (m (mark)))
24723 (save-excursion
24724 (goto-char (region-beginning))
24725 (when (and (org-at-heading-p)
24726 (>= (org-end-of-subtree t t) (region-end)))
24727 ;; This is a subtree, we take the title from the first heading
24728 (goto-char (region-beginning))
24729 (looking-at org-todo-line-regexp)
24730 (setq title (match-string 3))
24731 (org-unmodified
24732 (add-text-properties (point) (1+ (point-at-eol))
24733 (list :org-license-to-kill t)))))
24734 title))
24736 (defun org-solidify-link-text (s &optional alist)
24737 "Take link text and make a safe target out of it."
24738 (save-match-data
24739 (let* ((rtn
24740 (mapconcat
24741 'identity
24742 (org-split-string s "[ \t\r\n]+") "--"))
24743 (a (assoc rtn alist)))
24744 (or (cdr a) rtn))))
24746 (defun org-get-min-level (lines)
24747 "Get the minimum level in LINES."
24748 (let ((re "^\\(\\*+\\) ") l min)
24749 (catch 'exit
24750 (while (setq l (pop lines))
24751 (if (string-match re l)
24752 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24753 1)))
24755 ;; Variable holding the vector with section numbers
24756 (defvar org-section-numbers (make-vector org-level-max 0))
24758 (defun org-init-section-numbers ()
24759 "Initialize the vector for the section numbers."
24760 (let* ((level -1)
24761 (numbers (nreverse (org-split-string "" "\\.")))
24762 (depth (1- (length org-section-numbers)))
24763 (i depth) number-string)
24764 (while (>= i 0)
24765 (if (> i level)
24766 (aset org-section-numbers i 0)
24767 (setq number-string (or (car numbers) "0"))
24768 (if (string-match "\\`[A-Z]\\'" number-string)
24769 (aset org-section-numbers i
24770 (- (string-to-char number-string) ?A -1))
24771 (aset org-section-numbers i (string-to-number number-string)))
24772 (pop numbers))
24773 (setq i (1- i)))))
24775 (defun org-section-number (&optional level)
24776 "Return a string with the current section number.
24777 When LEVEL is non-nil, increase section numbers on that level."
24778 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24779 (when level
24780 (when (> level -1)
24781 (aset org-section-numbers
24782 level (1+ (aref org-section-numbers level))))
24783 (setq idx (1+ level))
24784 (while (<= idx depth)
24785 (if (not (= idx 1))
24786 (aset org-section-numbers idx 0))
24787 (setq idx (1+ idx))))
24788 (setq idx 0)
24789 (while (<= idx depth)
24790 (setq n (aref org-section-numbers idx))
24791 (setq string (concat string (if (not (string= string "")) "." "")
24792 (int-to-string n)))
24793 (setq idx (1+ idx)))
24794 (save-match-data
24795 (if (string-match "\\`\\([@0]\\.\\)+" string)
24796 (setq string (replace-match "" t nil string)))
24797 (if (string-match "\\(\\.0\\)+\\'" string)
24798 (setq string (replace-match "" t nil string))))
24799 string))
24801 ;;; ASCII export
24803 (defvar org-last-level nil) ; dynamically scoped variable
24804 (defvar org-min-level nil) ; dynamically scoped variable
24805 (defvar org-levels-open nil) ; dynamically scoped parameter
24806 (defvar org-ascii-current-indentation nil) ; For communication
24808 (defun org-export-as-ascii (arg)
24809 "Export the outline as a pretty ASCII file.
24810 If there is an active region, export only the region.
24811 The prefix ARG specifies how many levels of the outline should become
24812 underlined headlines. The default is 3."
24813 (interactive "P")
24814 (setq-default org-todo-line-regexp org-todo-line-regexp)
24815 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24816 (org-infile-export-plist)))
24817 (region-p (org-region-active-p))
24818 (subtree-p
24819 (when region-p
24820 (save-excursion
24821 (goto-char (region-beginning))
24822 (and (org-at-heading-p)
24823 (>= (org-end-of-subtree t t) (region-end))))))
24824 (custom-times org-display-custom-times)
24825 (org-ascii-current-indentation '(0 . 0))
24826 (level 0) line txt
24827 (umax nil)
24828 (umax-toc nil)
24829 (case-fold-search nil)
24830 (filename (concat (file-name-as-directory
24831 (org-export-directory :ascii opt-plist))
24832 (file-name-sans-extension
24833 (or (and subtree-p
24834 (org-entry-get (region-beginning)
24835 "EXPORT_FILE_NAME" t))
24836 (file-name-nondirectory buffer-file-name)))
24837 ".txt"))
24838 (filename (if (equal (file-truename filename)
24839 (file-truename buffer-file-name))
24840 (concat filename ".txt")
24841 filename))
24842 (buffer (find-file-noselect filename))
24843 (org-levels-open (make-vector org-level-max nil))
24844 (odd org-odd-levels-only)
24845 (date (plist-get opt-plist :date))
24846 (author (plist-get opt-plist :author))
24847 (title (or (and subtree-p (org-export-get-title-from-subtree))
24848 (plist-get opt-plist :title)
24849 (and (not
24850 (plist-get opt-plist :skip-before-1st-heading))
24851 (org-export-grab-title-from-buffer))
24852 (file-name-sans-extension
24853 (file-name-nondirectory buffer-file-name))))
24854 (email (plist-get opt-plist :email))
24855 (language (plist-get opt-plist :language))
24856 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24857 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24858 (todo nil)
24859 (lang-words nil)
24860 (region
24861 (buffer-substring
24862 (if (org-region-active-p) (region-beginning) (point-min))
24863 (if (org-region-active-p) (region-end) (point-max))))
24864 (lines (org-split-string
24865 (org-cleaned-string-for-export
24866 region
24867 :for-ascii t
24868 :skip-before-1st-heading
24869 (plist-get opt-plist :skip-before-1st-heading)
24870 :drawers (plist-get opt-plist :drawers)
24871 :verbatim-multiline t
24872 :archived-trees
24873 (plist-get opt-plist :archived-trees)
24874 :add-text (plist-get opt-plist :text))
24875 "\n"))
24876 thetoc have-headings first-heading-pos
24877 table-open table-buffer)
24879 (let ((inhibit-read-only t))
24880 (org-unmodified
24881 (remove-text-properties (point-min) (point-max)
24882 '(:org-license-to-kill t))))
24884 (setq org-min-level (org-get-min-level lines))
24885 (setq org-last-level org-min-level)
24886 (org-init-section-numbers)
24888 (find-file-noselect filename)
24890 (setq lang-words (or (assoc language org-export-language-setup)
24891 (assoc "en" org-export-language-setup)))
24892 (switch-to-buffer-other-window buffer)
24893 (erase-buffer)
24894 (fundamental-mode)
24895 ;; create local variables for all options, to make sure all called
24896 ;; functions get the correct information
24897 (mapc (lambda (x)
24898 (set (make-local-variable (cdr x))
24899 (plist-get opt-plist (car x))))
24900 org-export-plist-vars)
24901 (org-set-local 'org-odd-levels-only odd)
24902 (setq umax (if arg (prefix-numeric-value arg)
24903 org-export-headline-levels))
24904 (setq umax-toc (if (integerp org-export-with-toc)
24905 (min org-export-with-toc umax)
24906 umax))
24908 ;; File header
24909 (if title (org-insert-centered title ?=))
24910 (insert "\n")
24911 (if (and (or author email)
24912 org-export-author-info)
24913 (insert (concat (nth 1 lang-words) ": " (or author "")
24914 (if email (concat " <" email ">") "")
24915 "\n")))
24917 (cond
24918 ((and date (string-match "%" date))
24919 (setq date (format-time-string date (current-time))))
24920 (date)
24921 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24923 (if (and date org-export-time-stamp-file)
24924 (insert (concat (nth 2 lang-words) ": " date"\n")))
24926 (insert "\n\n")
24928 (if org-export-with-toc
24929 (progn
24930 (push (concat (nth 3 lang-words) "\n") thetoc)
24931 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24932 (mapc '(lambda (line)
24933 (if (string-match org-todo-line-regexp
24934 line)
24935 ;; This is a headline
24936 (progn
24937 (setq have-headings t)
24938 (setq level (- (match-end 1) (match-beginning 1))
24939 level (org-tr-level level)
24940 txt (match-string 3 line)
24941 todo
24942 (or (and org-export-mark-todo-in-toc
24943 (match-beginning 2)
24944 (not (member (match-string 2 line)
24945 org-done-keywords)))
24946 ; TODO, not DONE
24947 (and org-export-mark-todo-in-toc
24948 (= level umax-toc)
24949 (org-search-todo-below
24950 line lines level))))
24951 (setq txt (org-html-expand-for-ascii txt))
24953 (while (string-match org-bracket-link-regexp txt)
24954 (setq txt
24955 (replace-match
24956 (match-string (if (match-end 2) 3 1) txt)
24957 t t txt)))
24959 (if (and (memq org-export-with-tags '(not-in-toc nil))
24960 (string-match
24961 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24962 txt))
24963 (setq txt (replace-match "" t t txt)))
24964 (if (string-match quote-re0 txt)
24965 (setq txt (replace-match "" t t txt)))
24967 (if org-export-with-section-numbers
24968 (setq txt (concat (org-section-number level)
24969 " " txt)))
24970 (if (<= level umax-toc)
24971 (progn
24972 (push
24973 (concat
24974 (make-string
24975 (* (max 0 (- level org-min-level)) 4) ?\ )
24976 (format (if todo "%s (*)\n" "%s\n") txt))
24977 thetoc)
24978 (setq org-last-level level))
24979 ))))
24980 lines)
24981 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24983 (org-init-section-numbers)
24984 (while (setq line (pop lines))
24985 ;; Remove the quoted HTML tags.
24986 (setq line (org-html-expand-for-ascii line))
24987 ;; Remove targets
24988 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24989 (setq line (replace-match "" t t line)))
24990 ;; Replace internal links
24991 (while (string-match org-bracket-link-regexp line)
24992 (setq line (replace-match
24993 (if (match-end 3) "[\\3]" "[\\1]")
24994 t nil line)))
24995 (when custom-times
24996 (setq line (org-translate-time line)))
24997 (cond
24998 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24999 ;; a Headline
25000 (setq first-heading-pos (or first-heading-pos (point)))
25001 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25002 txt (match-string 2 line))
25003 (org-ascii-level-start level txt umax lines))
25005 ((and org-export-with-tables
25006 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25007 (if (not table-open)
25008 ;; New table starts
25009 (setq table-open t table-buffer nil))
25010 ;; Accumulate lines
25011 (setq table-buffer (cons line table-buffer))
25012 (when (or (not lines)
25013 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25014 (car lines))))
25015 (setq table-open nil
25016 table-buffer (nreverse table-buffer))
25017 (insert (mapconcat
25018 (lambda (x)
25019 (org-fix-indentation x org-ascii-current-indentation))
25020 (org-format-table-ascii table-buffer)
25021 "\n") "\n")))
25023 (setq line (org-fix-indentation line org-ascii-current-indentation))
25024 (if (and org-export-with-fixed-width
25025 (string-match "^\\([ \t]*\\)\\(:\\)" line))
25026 (setq line (replace-match "\\1" nil nil line)))
25027 (insert line "\n"))))
25029 (normal-mode)
25031 ;; insert the table of contents
25032 (when thetoc
25033 (goto-char (point-min))
25034 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
25035 (progn
25036 (goto-char (match-beginning 0))
25037 (replace-match ""))
25038 (goto-char first-heading-pos))
25039 (mapc 'insert thetoc)
25040 (or (looking-at "[ \t]*\n[ \t]*\n")
25041 (insert "\n\n")))
25043 ;; Convert whitespace place holders
25044 (goto-char (point-min))
25045 (let (beg end)
25046 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25047 (setq end (next-single-property-change beg 'org-whitespace))
25048 (goto-char beg)
25049 (delete-region beg end)
25050 (insert (make-string (- end beg) ?\ ))))
25052 (save-buffer)
25053 ;; remove display and invisible chars
25054 (let (beg end)
25055 (goto-char (point-min))
25056 (while (setq beg (next-single-property-change (point) 'display))
25057 (setq end (next-single-property-change beg 'display))
25058 (delete-region beg end)
25059 (goto-char beg)
25060 (insert "=>"))
25061 (goto-char (point-min))
25062 (while (setq beg (next-single-property-change (point) 'org-cwidth))
25063 (setq end (next-single-property-change beg 'org-cwidth))
25064 (delete-region beg end)
25065 (goto-char beg)))
25066 (goto-char (point-min))))
25068 (defun org-export-ascii-clean-string ()
25069 "Do extra work for ASCII export"
25070 (goto-char (point-min))
25071 (while (re-search-forward org-verbatim-re nil t)
25072 (goto-char (match-end 2))
25073 (backward-delete-char 1) (insert "'")
25074 (goto-char (match-beginning 2))
25075 (delete-char 1) (insert "`")
25076 (goto-char (match-end 2))))
25078 (defun org-search-todo-below (line lines level)
25079 "Search the subtree below LINE for any TODO entries."
25080 (let ((rest (cdr (memq line lines)))
25081 (re org-todo-line-regexp)
25082 line lv todo)
25083 (catch 'exit
25084 (while (setq line (pop rest))
25085 (if (string-match re line)
25086 (progn
25087 (setq lv (- (match-end 1) (match-beginning 1))
25088 todo (and (match-beginning 2)
25089 (not (member (match-string 2 line)
25090 org-done-keywords))))
25091 ; TODO, not DONE
25092 (if (<= lv level) (throw 'exit nil))
25093 (if todo (throw 'exit t))))))))
25095 (defun org-html-expand-for-ascii (line)
25096 "Handle quoted HTML for ASCII export."
25097 (if org-export-html-expand
25098 (while (string-match "@<[^<>\n]*>" line)
25099 ;; We just remove the tags for now.
25100 (setq line (replace-match "" nil nil line))))
25101 line)
25103 (defun org-insert-centered (s &optional underline)
25104 "Insert the string S centered and underline it with character UNDERLINE."
25105 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
25106 (insert (make-string ind ?\ ) s "\n")
25107 (if underline
25108 (insert (make-string ind ?\ )
25109 (make-string (string-width s) underline)
25110 "\n"))))
25112 (defun org-ascii-level-start (level title umax &optional lines)
25113 "Insert a new level in ASCII export."
25114 (let (char (n (- level umax 1)) (ind 0))
25115 (if (> level umax)
25116 (progn
25117 (insert (make-string (* 2 n) ?\ )
25118 (char-to-string (nth (% n (length org-export-ascii-bullets))
25119 org-export-ascii-bullets))
25120 " " title "\n")
25121 ;; find the indentation of the next non-empty line
25122 (catch 'stop
25123 (while lines
25124 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
25125 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
25126 (throw 'stop (setq ind (org-get-indentation (car lines)))))
25127 (pop lines)))
25128 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
25129 (if (or (not (equal (char-before) ?\n))
25130 (not (equal (char-before (1- (point))) ?\n)))
25131 (insert "\n"))
25132 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
25133 (unless org-export-with-tags
25134 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25135 (setq title (replace-match "" t t title))))
25136 (if org-export-with-section-numbers
25137 (setq title (concat (org-section-number level) " " title)))
25138 (insert title "\n" (make-string (string-width title) char) "\n")
25139 (setq org-ascii-current-indentation '(0 . 0)))))
25141 (defun org-export-visible (type arg)
25142 "Create a copy of the visible part of the current buffer, and export it.
25143 The copy is created in a temporary buffer and removed after use.
25144 TYPE is the final key (as a string) that also select the export command in
25145 the `C-c C-e' export dispatcher.
25146 As a special case, if the you type SPC at the prompt, the temporary
25147 org-mode file will not be removed but presented to you so that you can
25148 continue to use it. The prefix arg ARG is passed through to the exporting
25149 command."
25150 (interactive
25151 (list (progn
25152 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
25153 (read-char-exclusive))
25154 current-prefix-arg))
25155 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
25156 (error "Invalid export key"))
25157 (let* ((binding (cdr (assoc type
25158 '((?a . org-export-as-ascii)
25159 (?\C-a . org-export-as-ascii)
25160 (?b . org-export-as-html-and-open)
25161 (?\C-b . org-export-as-html-and-open)
25162 (?h . org-export-as-html)
25163 (?H . org-export-as-html-to-buffer)
25164 (?R . org-export-region-as-html)
25165 (?x . org-export-as-xoxo)))))
25166 (keepp (equal type ?\ ))
25167 (file buffer-file-name)
25168 (buffer (get-buffer-create "*Org Export Visible*"))
25169 s e)
25170 ;; Need to hack the drawers here.
25171 (save-excursion
25172 (goto-char (point-min))
25173 (while (re-search-forward org-drawer-regexp nil t)
25174 (goto-char (match-beginning 1))
25175 (or (org-invisible-p) (org-flag-drawer nil))))
25176 (with-current-buffer buffer (erase-buffer))
25177 (save-excursion
25178 (setq s (goto-char (point-min)))
25179 (while (not (= (point) (point-max)))
25180 (goto-char (org-find-invisible))
25181 (append-to-buffer buffer s (point))
25182 (setq s (goto-char (org-find-visible))))
25183 (org-cycle-hide-drawers 'all)
25184 (goto-char (point-min))
25185 (unless keepp
25186 ;; Copy all comment lines to the end, to make sure #+ settings are
25187 ;; still available for the second export step. Kind of a hack, but
25188 ;; does do the trick.
25189 (if (looking-at "#[^\r\n]*")
25190 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
25191 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
25192 (append-to-buffer buffer (1+ (match-beginning 0))
25193 (min (point-max) (1+ (match-end 0))))))
25194 (set-buffer buffer)
25195 (let ((buffer-file-name file)
25196 (org-inhibit-startup t))
25197 (org-mode)
25198 (show-all)
25199 (unless keepp (funcall binding arg))))
25200 (if (not keepp)
25201 (kill-buffer buffer)
25202 (switch-to-buffer-other-window buffer)
25203 (goto-char (point-min)))))
25205 (defun org-find-visible ()
25206 (let ((s (point)))
25207 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25208 (get-char-property s 'invisible)))
25210 (defun org-find-invisible ()
25211 (let ((s (point)))
25212 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25213 (not (get-char-property s 'invisible))))
25216 ;;; HTML export
25218 (defun org-get-current-options ()
25219 "Return a string with current options as keyword options.
25220 Does include HTML export options as well as TODO and CATEGORY stuff."
25221 (format
25222 "#+TITLE: %s
25223 #+AUTHOR: %s
25224 #+EMAIL: %s
25225 #+LANGUAGE: %s
25226 #+TEXT: Some descriptive text to be emitted. Several lines OK.
25227 #+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
25228 #+CATEGORY: %s
25229 #+SEQ_TODO: %s
25230 #+TYP_TODO: %s
25231 #+PRIORITIES: %c %c %c
25232 #+DRAWERS: %s
25233 #+STARTUP: %s %s %s %s %s
25234 #+TAGS: %s
25235 #+ARCHIVE: %s
25236 #+LINK: %s
25238 (buffer-name) (user-full-name) user-mail-address org-export-default-language
25239 org-export-headline-levels
25240 org-export-with-section-numbers
25241 org-export-with-toc
25242 org-export-preserve-breaks
25243 org-export-html-expand
25244 org-export-with-fixed-width
25245 org-export-with-tables
25246 org-export-with-sub-superscripts
25247 org-export-with-special-strings
25248 org-export-with-footnotes
25249 org-export-with-emphasize
25250 org-export-with-TeX-macros
25251 org-export-with-LaTeX-fragments
25252 org-export-skip-text-before-1st-heading
25253 org-export-with-drawers
25254 org-export-with-tags
25255 (file-name-nondirectory buffer-file-name)
25256 "TODO FEEDBACK VERIFY DONE"
25257 "Me Jason Marie DONE"
25258 org-highest-priority org-lowest-priority org-default-priority
25259 (mapconcat 'identity org-drawers " ")
25260 (cdr (assoc org-startup-folded
25261 '((nil . "showall") (t . "overview") (content . "content"))))
25262 (if org-odd-levels-only "odd" "oddeven")
25263 (if org-hide-leading-stars "hidestars" "showstars")
25264 (if org-startup-align-all-tables "align" "noalign")
25265 (cond ((eq org-log-done t) "logdone")
25266 ((equal org-log-done 'note) "lognotedone")
25267 ((not org-log-done) "nologdone"))
25268 (or (mapconcat (lambda (x)
25269 (cond
25270 ((equal '(:startgroup) x) "{")
25271 ((equal '(:endgroup) x) "}")
25272 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
25273 (t (car x))))
25274 (or org-tag-alist (org-get-buffer-tags)) " ") "")
25275 org-archive-location
25276 "org file:~/org/%s.org"
25279 (defun org-insert-export-options-template ()
25280 "Insert into the buffer a template with information for exporting."
25281 (interactive)
25282 (if (not (bolp)) (newline))
25283 (let ((s (org-get-current-options)))
25284 (and (string-match "#\\+CATEGORY" s)
25285 (setq s (substring s 0 (match-beginning 0))))
25286 (insert s)))
25288 (defun org-toggle-fixed-width-section (arg)
25289 "Toggle the fixed-width export.
25290 If there is no active region, the QUOTE keyword at the current headline is
25291 inserted or removed. When present, it causes the text between this headline
25292 and the next to be exported as fixed-width text, and unmodified.
25293 If there is an active region, this command adds or removes a colon as the
25294 first character of this line. If the first character of a line is a colon,
25295 this line is also exported in fixed-width font."
25296 (interactive "P")
25297 (let* ((cc 0)
25298 (regionp (org-region-active-p))
25299 (beg (if regionp (region-beginning) (point)))
25300 (end (if regionp (region-end)))
25301 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
25302 (case-fold-search nil)
25303 (re "[ \t]*\\(:\\)")
25304 off)
25305 (if regionp
25306 (save-excursion
25307 (goto-char beg)
25308 (setq cc (current-column))
25309 (beginning-of-line 1)
25310 (setq off (looking-at re))
25311 (while (> nlines 0)
25312 (setq nlines (1- nlines))
25313 (beginning-of-line 1)
25314 (cond
25315 (arg
25316 (move-to-column cc t)
25317 (insert ":\n")
25318 (forward-line -1))
25319 ((and off (looking-at re))
25320 (replace-match "" t t nil 1))
25321 ((not off) (move-to-column cc t) (insert ":")))
25322 (forward-line 1)))
25323 (save-excursion
25324 (org-back-to-heading)
25325 (if (looking-at (concat outline-regexp
25326 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
25327 (replace-match "" t t nil 1)
25328 (if (looking-at outline-regexp)
25329 (progn
25330 (goto-char (match-end 0))
25331 (insert org-quote-string " "))))))))
25333 (defun org-export-as-html-and-open (arg)
25334 "Export the outline as HTML and immediately open it with a browser.
25335 If there is an active region, export only the region.
25336 The prefix ARG specifies how many levels of the outline should become
25337 headlines. The default is 3. Lower levels will become bulleted lists."
25338 (interactive "P")
25339 (org-export-as-html arg 'hidden)
25340 (org-open-file buffer-file-name))
25342 (defun org-export-as-html-batch ()
25343 "Call `org-export-as-html', may be used in batch processing as
25344 emacs --batch
25345 --load=$HOME/lib/emacs/org.el
25346 --eval \"(setq org-export-headline-levels 2)\"
25347 --visit=MyFile --funcall org-export-as-html-batch"
25348 (org-export-as-html org-export-headline-levels 'hidden))
25350 (defun org-export-as-html-to-buffer (arg)
25351 "Call `org-exort-as-html` with output to a temporary buffer.
25352 No file is created. The prefix ARG is passed through to `org-export-as-html'."
25353 (interactive "P")
25354 (org-export-as-html arg nil nil "*Org HTML Export*")
25355 (switch-to-buffer-other-window "*Org HTML Export*"))
25357 (defun org-replace-region-by-html (beg end)
25358 "Assume the current region has org-mode syntax, and convert it to HTML.
25359 This can be used in any buffer. For example, you could write an
25360 itemized list in org-mode syntax in an HTML buffer and then use this
25361 command to convert it."
25362 (interactive "r")
25363 (let (reg html buf pop-up-frames)
25364 (save-window-excursion
25365 (if (org-mode-p)
25366 (setq html (org-export-region-as-html
25367 beg end t 'string))
25368 (setq reg (buffer-substring beg end)
25369 buf (get-buffer-create "*Org tmp*"))
25370 (with-current-buffer buf
25371 (erase-buffer)
25372 (insert reg)
25373 (org-mode)
25374 (setq html (org-export-region-as-html
25375 (point-min) (point-max) t 'string)))
25376 (kill-buffer buf)))
25377 (delete-region beg end)
25378 (insert html)))
25380 (defun org-export-region-as-html (beg end &optional body-only buffer)
25381 "Convert region from BEG to END in org-mode buffer to HTML.
25382 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
25383 contents, and only produce the region of converted text, useful for
25384 cut-and-paste operations.
25385 If BUFFER is a buffer or a string, use/create that buffer as a target
25386 of the converted HTML. If BUFFER is the symbol `string', return the
25387 produced HTML as a string and leave not buffer behind. For example,
25388 a Lisp program could call this function in the following way:
25390 (setq html (org-export-region-as-html beg end t 'string))
25392 When called interactively, the output buffer is selected, and shown
25393 in a window. A non-interactive call will only retunr the buffer."
25394 (interactive "r\nP")
25395 (when (interactive-p)
25396 (setq buffer "*Org HTML Export*"))
25397 (let ((transient-mark-mode t) (zmacs-regions t)
25398 rtn)
25399 (goto-char end)
25400 (set-mark (point)) ;; to activate the region
25401 (goto-char beg)
25402 (setq rtn (org-export-as-html
25403 nil nil nil
25404 buffer body-only))
25405 (if (fboundp 'deactivate-mark) (deactivate-mark))
25406 (if (and (interactive-p) (bufferp rtn))
25407 (switch-to-buffer-other-window rtn)
25408 rtn)))
25410 (defvar html-table-tag nil) ; dynamically scoped into this.
25411 (defun org-export-as-html (arg &optional hidden ext-plist
25412 to-buffer body-only pub-dir)
25413 "Export the outline as a pretty HTML file.
25414 If there is an active region, export only the region. The prefix
25415 ARG specifies how many levels of the outline should become
25416 headlines. The default is 3. Lower levels will become bulleted
25417 lists. When HIDDEN is non-nil, don't display the HTML buffer.
25418 EXT-PLIST is a property list with external parameters overriding
25419 org-mode's default settings, but still inferior to file-local
25420 settings. When TO-BUFFER is non-nil, create a buffer with that
25421 name and export to that buffer. If TO-BUFFER is the symbol
25422 `string', don't leave any buffer behind but just return the
25423 resulting HTML as a string. When BODY-ONLY is set, don't produce
25424 the file header and footer, simply return the content of
25425 <body>...</body>, without even the body tags themselves. When
25426 PUB-DIR is set, use this as the publishing directory."
25427 (interactive "P")
25429 ;; Make sure we have a file name when we need it.
25430 (when (and (not (or to-buffer body-only))
25431 (not buffer-file-name))
25432 (if (buffer-base-buffer)
25433 (org-set-local 'buffer-file-name
25434 (with-current-buffer (buffer-base-buffer)
25435 buffer-file-name))
25436 (error "Need a file name to be able to export.")))
25438 (message "Exporting...")
25439 (setq-default org-todo-line-regexp org-todo-line-regexp)
25440 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25441 (setq-default org-done-keywords org-done-keywords)
25442 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25443 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25444 ext-plist
25445 (org-infile-export-plist)))
25447 (style (plist-get opt-plist :style))
25448 (html-extension (plist-get opt-plist :html-extension))
25449 (link-validate (plist-get opt-plist :link-validation-function))
25450 valid thetoc have-headings first-heading-pos
25451 (odd org-odd-levels-only)
25452 (region-p (org-region-active-p))
25453 (subtree-p
25454 (when region-p
25455 (save-excursion
25456 (goto-char (region-beginning))
25457 (and (org-at-heading-p)
25458 (>= (org-end-of-subtree t t) (region-end))))))
25459 ;; The following two are dynamically scoped into other
25460 ;; routines below.
25461 (org-current-export-dir
25462 (or pub-dir (org-export-directory :html opt-plist)))
25463 (org-current-export-file buffer-file-name)
25464 (level 0) (line "") (origline "") txt todo
25465 (umax nil)
25466 (umax-toc nil)
25467 (filename (if to-buffer nil
25468 (expand-file-name
25469 (concat
25470 (file-name-sans-extension
25471 (or (and subtree-p
25472 (org-entry-get (region-beginning)
25473 "EXPORT_FILE_NAME" t))
25474 (file-name-nondirectory buffer-file-name)))
25475 "." html-extension)
25476 (file-name-as-directory
25477 (or pub-dir (org-export-directory :html opt-plist))))))
25478 (current-dir (if buffer-file-name
25479 (file-name-directory buffer-file-name)
25480 default-directory))
25481 (buffer (if to-buffer
25482 (cond
25483 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25484 (t (get-buffer-create to-buffer)))
25485 (find-file-noselect filename)))
25486 (org-levels-open (make-vector org-level-max nil))
25487 (date (plist-get opt-plist :date))
25488 (author (plist-get opt-plist :author))
25489 (title (or (and subtree-p (org-export-get-title-from-subtree))
25490 (plist-get opt-plist :title)
25491 (and (not
25492 (plist-get opt-plist :skip-before-1st-heading))
25493 (org-export-grab-title-from-buffer))
25494 (and buffer-file-name
25495 (file-name-sans-extension
25496 (file-name-nondirectory buffer-file-name)))
25497 "UNTITLED"))
25498 (html-table-tag (plist-get opt-plist :html-table-tag))
25499 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25500 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25501 (inquote nil)
25502 (infixed nil)
25503 (in-local-list nil)
25504 (local-list-num nil)
25505 (local-list-indent nil)
25506 (llt org-plain-list-ordered-item-terminator)
25507 (email (plist-get opt-plist :email))
25508 (language (plist-get opt-plist :language))
25509 (lang-words nil)
25510 (target-alist nil) tg
25511 (head-count 0) cnt
25512 (start 0)
25513 (coding-system (and (boundp 'buffer-file-coding-system)
25514 buffer-file-coding-system))
25515 (coding-system-for-write (or org-export-html-coding-system
25516 coding-system))
25517 (save-buffer-coding-system (or org-export-html-coding-system
25518 coding-system))
25519 (charset (and coding-system-for-write
25520 (fboundp 'coding-system-get)
25521 (coding-system-get coding-system-for-write
25522 'mime-charset)))
25523 (region
25524 (buffer-substring
25525 (if region-p (region-beginning) (point-min))
25526 (if region-p (region-end) (point-max))))
25527 (lines
25528 (org-split-string
25529 (org-cleaned-string-for-export
25530 region
25531 :emph-multiline t
25532 :for-html t
25533 :skip-before-1st-heading
25534 (plist-get opt-plist :skip-before-1st-heading)
25535 :drawers (plist-get opt-plist :drawers)
25536 :archived-trees
25537 (plist-get opt-plist :archived-trees)
25538 :add-text
25539 (plist-get opt-plist :text)
25540 :LaTeX-fragments
25541 (plist-get opt-plist :LaTeX-fragments))
25542 "[\r\n]"))
25543 table-open type
25544 table-buffer table-orig-buffer
25545 ind start-is-num starter didclose
25546 rpl path desc descp desc1 desc2 link
25549 (let ((inhibit-read-only t))
25550 (org-unmodified
25551 (remove-text-properties (point-min) (point-max)
25552 '(:org-license-to-kill t))))
25554 (message "Exporting...")
25556 (setq org-min-level (org-get-min-level lines))
25557 (setq org-last-level org-min-level)
25558 (org-init-section-numbers)
25560 (cond
25561 ((and date (string-match "%" date))
25562 (setq date (format-time-string date (current-time))))
25563 (date)
25564 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25566 ;; Get the language-dependent settings
25567 (setq lang-words (or (assoc language org-export-language-setup)
25568 (assoc "en" org-export-language-setup)))
25570 ;; Switch to the output buffer
25571 (set-buffer buffer)
25572 (let ((inhibit-read-only t)) (erase-buffer))
25573 (fundamental-mode)
25575 (and (fboundp 'set-buffer-file-coding-system)
25576 (set-buffer-file-coding-system coding-system-for-write))
25578 (let ((case-fold-search nil)
25579 (org-odd-levels-only odd))
25580 ;; create local variables for all options, to make sure all called
25581 ;; functions get the correct information
25582 (mapc (lambda (x)
25583 (set (make-local-variable (cdr x))
25584 (plist-get opt-plist (car x))))
25585 org-export-plist-vars)
25586 (setq umax (if arg (prefix-numeric-value arg)
25587 org-export-headline-levels))
25588 (setq umax-toc (if (integerp org-export-with-toc)
25589 (min org-export-with-toc umax)
25590 umax))
25591 (unless body-only
25592 ;; File header
25593 (insert (format
25594 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25595 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25596 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25597 lang=\"%s\" xml:lang=\"%s\">
25598 <head>
25599 <title>%s</title>
25600 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25601 <meta name=\"generator\" content=\"Org-mode\"/>
25602 <meta name=\"generated\" content=\"%s\"/>
25603 <meta name=\"author\" content=\"%s\"/>
25605 </head><body>
25607 language language (org-html-expand title)
25608 (or charset "iso-8859-1") date author style))
25610 (insert (or (plist-get opt-plist :preamble) ""))
25612 (when (plist-get opt-plist :auto-preamble)
25613 (if title (insert (format org-export-html-title-format
25614 (org-html-expand title))))))
25616 (if (and org-export-with-toc (not body-only))
25617 (progn
25618 (push (format "<h%d>%s</h%d>\n"
25619 org-export-html-toplevel-hlevel
25620 (nth 3 lang-words)
25621 org-export-html-toplevel-hlevel)
25622 thetoc)
25623 (push "<ul>\n<li>" thetoc)
25624 (setq lines
25625 (mapcar '(lambda (line)
25626 (if (string-match org-todo-line-regexp line)
25627 ;; This is a headline
25628 (progn
25629 (setq have-headings t)
25630 (setq level (- (match-end 1) (match-beginning 1))
25631 level (org-tr-level level)
25632 txt (save-match-data
25633 (org-html-expand
25634 (org-export-cleanup-toc-line
25635 (match-string 3 line))))
25636 todo
25637 (or (and org-export-mark-todo-in-toc
25638 (match-beginning 2)
25639 (not (member (match-string 2 line)
25640 org-done-keywords)))
25641 ; TODO, not DONE
25642 (and org-export-mark-todo-in-toc
25643 (= level umax-toc)
25644 (org-search-todo-below
25645 line lines level))))
25646 (if (string-match
25647 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25648 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25649 (if (string-match quote-re0 txt)
25650 (setq txt (replace-match "" t t txt)))
25651 (if org-export-with-section-numbers
25652 (setq txt (concat (org-section-number level)
25653 " " txt)))
25654 (if (<= level (max umax umax-toc))
25655 (setq head-count (+ head-count 1)))
25656 (if (<= level umax-toc)
25657 (progn
25658 (if (> level org-last-level)
25659 (progn
25660 (setq cnt (- level org-last-level))
25661 (while (>= (setq cnt (1- cnt)) 0)
25662 (push "\n<ul>\n<li>" thetoc))
25663 (push "\n" thetoc)))
25664 (if (< level org-last-level)
25665 (progn
25666 (setq cnt (- org-last-level level))
25667 (while (>= (setq cnt (1- cnt)) 0)
25668 (push "</li>\n</ul>" thetoc))
25669 (push "\n" thetoc)))
25670 ;; Check for targets
25671 (while (string-match org-target-regexp line)
25672 (setq tg (match-string 1 line)
25673 line (replace-match
25674 (concat "@<span class=\"target\">" tg "@</span> ")
25675 t t line))
25676 (push (cons (org-solidify-link-text tg)
25677 (format "sec-%d" head-count))
25678 target-alist))
25679 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25680 (setq txt (replace-match "" t t txt)))
25681 (push
25682 (format
25683 (if todo
25684 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25685 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25686 head-count txt) thetoc)
25688 (setq org-last-level level))
25690 line)
25691 lines))
25692 (while (> org-last-level (1- org-min-level))
25693 (setq org-last-level (1- org-last-level))
25694 (push "</li>\n</ul>\n" thetoc))
25695 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25697 (setq head-count 0)
25698 (org-init-section-numbers)
25700 (while (setq line (pop lines) origline line)
25701 (catch 'nextline
25703 ;; end of quote section?
25704 (when (and inquote (string-match "^\\*+ " line))
25705 (insert "</pre>\n")
25706 (setq inquote nil))
25707 ;; inside a quote section?
25708 (when inquote
25709 (insert (org-html-protect line) "\n")
25710 (throw 'nextline nil))
25712 ;; verbatim lines
25713 (when (and org-export-with-fixed-width
25714 (string-match "^[ \t]*:\\(.*\\)" line))
25715 (when (not infixed)
25716 (setq infixed t)
25717 (insert "<pre>\n"))
25718 (insert (org-html-protect (match-string 1 line)) "\n")
25719 (when (and lines
25720 (not (string-match "^[ \t]*\\(:.*\\)"
25721 (car lines))))
25722 (setq infixed nil)
25723 (insert "</pre>\n"))
25724 (throw 'nextline nil))
25726 ;; Protected HTML
25727 (when (get-text-property 0 'org-protected line)
25728 (let (par)
25729 (when (re-search-backward
25730 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25731 (setq par (match-string 1))
25732 (replace-match "\\2\n"))
25733 (insert line "\n")
25734 (while (and lines
25735 (or (= (length (car lines)) 0)
25736 (get-text-property 0 'org-protected (car lines))))
25737 (insert (pop lines) "\n"))
25738 (and par (insert "<p>\n")))
25739 (throw 'nextline nil))
25741 ;; Horizontal line
25742 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25743 (insert "\n<hr/>\n")
25744 (throw 'nextline nil))
25746 ;; make targets to anchors
25747 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25748 (cond
25749 ((match-end 2)
25750 (setq line (replace-match
25751 (concat "@<a name=\""
25752 (org-solidify-link-text (match-string 1 line))
25753 "\">\\nbsp@</a>")
25754 t t line)))
25755 ((and org-export-with-toc (equal (string-to-char line) ?*))
25756 (setq line (replace-match
25757 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25758 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25759 t t line)))
25761 (setq line (replace-match
25762 (concat "@<a name=\""
25763 (org-solidify-link-text (match-string 1 line))
25764 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25765 t t line)))))
25767 (setq line (org-html-handle-time-stamps line))
25769 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25770 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25771 ;; Also handle sub_superscripts and checkboxes
25772 (or (string-match org-table-hline-regexp line)
25773 (setq line (org-html-expand line)))
25775 ;; Format the links
25776 (setq start 0)
25777 (while (string-match org-bracket-link-analytic-regexp line start)
25778 (setq start (match-beginning 0))
25779 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25780 (setq path (match-string 3 line))
25781 (setq desc1 (if (match-end 5) (match-string 5 line))
25782 desc2 (if (match-end 2) (concat type ":" path) path)
25783 descp (and desc1 (not (equal desc1 desc2)))
25784 desc (or desc1 desc2))
25785 ;; Make an image out of the description if that is so wanted
25786 (when (and descp (org-file-image-p desc))
25787 (save-match-data
25788 (if (string-match "^file:" desc)
25789 (setq desc (substring desc (match-end 0)))))
25790 (setq desc (concat "<img src=\"" desc "\"/>")))
25791 ;; FIXME: do we need to unescape here somewhere?
25792 (cond
25793 ((equal type "internal")
25794 (setq rpl
25795 (concat
25796 "<a href=\"#"
25797 (org-solidify-link-text
25798 (save-match-data (org-link-unescape path)) target-alist)
25799 "\">" desc "</a>")))
25800 ((member type '("http" "https"))
25801 ;; standard URL, just check if we need to inline an image
25802 (if (and (or (eq t org-export-html-inline-images)
25803 (and org-export-html-inline-images (not descp)))
25804 (org-file-image-p path))
25805 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25806 (setq link (concat type ":" path))
25807 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25808 ((member type '("ftp" "mailto" "news"))
25809 ;; standard URL
25810 (setq link (concat type ":" path))
25811 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25812 ((string= type "file")
25813 ;; FILE link
25814 (let* ((filename path)
25815 (abs-p (file-name-absolute-p filename))
25816 thefile file-is-image-p search)
25817 (save-match-data
25818 (if (string-match "::\\(.*\\)" filename)
25819 (setq search (match-string 1 filename)
25820 filename (replace-match "" t nil filename)))
25821 (setq valid
25822 (if (functionp link-validate)
25823 (funcall link-validate filename current-dir)
25825 (setq file-is-image-p (org-file-image-p filename))
25826 (setq thefile (if abs-p (expand-file-name filename) filename))
25827 (when (and org-export-html-link-org-files-as-html
25828 (string-match "\\.org$" thefile))
25829 (setq thefile (concat (substring thefile 0
25830 (match-beginning 0))
25831 "." html-extension))
25832 (if (and search
25833 ;; make sure this is can be used as target search
25834 (not (string-match "^[0-9]*$" search))
25835 (not (string-match "^\\*" search))
25836 (not (string-match "^/.*/$" search)))
25837 (setq thefile (concat thefile "#"
25838 (org-solidify-link-text
25839 (org-link-unescape search)))))
25840 (when (string-match "^file:" desc)
25841 (setq desc (replace-match "" t t desc))
25842 (if (string-match "\\.org$" desc)
25843 (setq desc (replace-match "" t t desc))))))
25844 (setq rpl (if (and file-is-image-p
25845 (or (eq t org-export-html-inline-images)
25846 (and org-export-html-inline-images
25847 (not descp))))
25848 (concat "<img src=\"" thefile "\"/>")
25849 (concat "<a href=\"" thefile "\">" desc "</a>")))
25850 (if (not valid) (setq rpl desc))))
25851 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25852 (setq rpl (concat "<i>&lt;" type ":"
25853 (save-match-data (org-link-unescape path))
25854 "&gt;</i>"))))
25855 (setq line (replace-match rpl t t line)
25856 start (+ start (length rpl))))
25858 ;; TODO items
25859 (if (and (string-match org-todo-line-regexp line)
25860 (match-beginning 2))
25862 (setq line
25863 (concat (substring line 0 (match-beginning 2))
25864 "<span class=\""
25865 (if (member (match-string 2 line)
25866 org-done-keywords)
25867 "done" "todo")
25868 "\">" (match-string 2 line)
25869 "</span>" (substring line (match-end 2)))))
25871 ;; Does this contain a reference to a footnote?
25872 (when org-export-with-footnotes
25873 (setq start 0)
25874 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25875 (if (get-text-property (match-beginning 2) 'org-protected line)
25876 (setq start (match-end 2))
25877 (let ((n (match-string 2 line)))
25878 (setq line
25879 (replace-match
25880 (format
25881 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25882 (match-string 1 line) n n n)
25883 t t line))))))
25885 (cond
25886 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25887 ;; This is a headline
25888 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25889 txt (match-string 2 line))
25890 (if (string-match quote-re0 txt)
25891 (setq txt (replace-match "" t t txt)))
25892 (if (<= level (max umax umax-toc))
25893 (setq head-count (+ head-count 1)))
25894 (when in-local-list
25895 ;; Close any local lists before inserting a new header line
25896 (while local-list-num
25897 (org-close-li)
25898 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25899 (pop local-list-num))
25900 (setq local-list-indent nil
25901 in-local-list nil))
25902 (setq first-heading-pos (or first-heading-pos (point)))
25903 (org-html-level-start level txt umax
25904 (and org-export-with-toc (<= level umax))
25905 head-count)
25906 ;; QUOTES
25907 (when (string-match quote-re line)
25908 (insert "<pre>")
25909 (setq inquote t)))
25911 ((and org-export-with-tables
25912 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25913 (if (not table-open)
25914 ;; New table starts
25915 (setq table-open t table-buffer nil table-orig-buffer nil))
25916 ;; Accumulate lines
25917 (setq table-buffer (cons line table-buffer)
25918 table-orig-buffer (cons origline table-orig-buffer))
25919 (when (or (not lines)
25920 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25921 (car lines))))
25922 (setq table-open nil
25923 table-buffer (nreverse table-buffer)
25924 table-orig-buffer (nreverse table-orig-buffer))
25925 (org-close-par-maybe)
25926 (insert (org-format-table-html table-buffer table-orig-buffer))))
25928 ;; Normal lines
25929 (when (string-match
25930 (cond
25931 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25932 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25933 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25934 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25935 line)
25936 (setq ind (org-get-string-indentation line)
25937 start-is-num (match-beginning 4)
25938 starter (if (match-beginning 2)
25939 (substring (match-string 2 line) 0 -1))
25940 line (substring line (match-beginning 5)))
25941 (unless (string-match "[^ \t]" line)
25942 ;; empty line. Pretend indentation is large.
25943 (setq ind (if org-empty-line-terminates-plain-lists
25945 (1+ (or (car local-list-indent) 1)))))
25946 (setq didclose nil)
25947 (while (and in-local-list
25948 (or (and (= ind (car local-list-indent))
25949 (not starter))
25950 (< ind (car local-list-indent))))
25951 (setq didclose t)
25952 (org-close-li)
25953 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25954 (pop local-list-num) (pop local-list-indent)
25955 (setq in-local-list local-list-indent))
25956 (cond
25957 ((and starter
25958 (or (not in-local-list)
25959 (> ind (car local-list-indent))))
25960 ;; Start new (level of) list
25961 (org-close-par-maybe)
25962 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25963 (push start-is-num local-list-num)
25964 (push ind local-list-indent)
25965 (setq in-local-list t))
25966 (starter
25967 ;; continue current list
25968 (org-close-li)
25969 (insert "<li>\n"))
25970 (didclose
25971 ;; we did close a list, normal text follows: need <p>
25972 (org-open-par)))
25973 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25974 (setq line
25975 (replace-match
25976 (if (equal (match-string 1 line) "X")
25977 "<b>[X]</b>"
25978 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25979 t t line))))
25981 ;; Empty lines start a new paragraph. If hand-formatted lists
25982 ;; are not fully interpreted, lines starting with "-", "+", "*"
25983 ;; also start a new paragraph.
25984 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25986 ;; Is this the start of a footnote?
25987 (when org-export-with-footnotes
25988 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25989 (org-close-par-maybe)
25990 (let ((n (match-string 1 line)))
25991 (setq line (replace-match
25992 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25994 ;; Check if the line break needs to be conserved
25995 (cond
25996 ((string-match "\\\\\\\\[ \t]*$" line)
25997 (setq line (replace-match "<br/>" t t line)))
25998 (org-export-preserve-breaks
25999 (setq line (concat line "<br/>"))))
26001 (insert line "\n")))))
26003 ;; Properly close all local lists and other lists
26004 (when inquote (insert "</pre>\n"))
26005 (when in-local-list
26006 ;; Close any local lists before inserting a new header line
26007 (while local-list-num
26008 (org-close-li)
26009 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
26010 (pop local-list-num))
26011 (setq local-list-indent nil
26012 in-local-list nil))
26013 (org-html-level-start 1 nil umax
26014 (and org-export-with-toc (<= level umax))
26015 head-count)
26017 (unless body-only
26018 (when (plist-get opt-plist :auto-postamble)
26019 (insert "<div id=\"postamble\">")
26020 (when (and org-export-author-info author)
26021 (insert "<p class=\"author\"> "
26022 (nth 1 lang-words) ": " author "\n")
26023 (when email
26024 (if (listp (split-string email ",+ *"))
26025 (mapc (lambda(e)
26026 (insert "<a href=\"mailto:" e "\">&lt;"
26027 e "&gt;</a>\n"))
26028 (split-string email ",+ *"))
26029 (insert "<a href=\"mailto:" email "\">&lt;"
26030 email "&gt;</a>\n")))
26031 (insert "</p>\n"))
26032 (when (and date org-export-time-stamp-file)
26033 (insert "<p class=\"date\"> "
26034 (nth 2 lang-words) ": "
26035 date "</p>\n"))
26036 (insert "</div>"))
26038 (if org-export-html-with-timestamp
26039 (insert org-export-html-html-helper-timestamp))
26040 (insert (or (plist-get opt-plist :postamble) ""))
26041 (insert "</body>\n</html>\n"))
26043 (normal-mode)
26044 (if (eq major-mode default-major-mode) (html-mode))
26046 ;; insert the table of contents
26047 (goto-char (point-min))
26048 (when thetoc
26049 (if (or (re-search-forward
26050 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
26051 (re-search-forward
26052 "\\[TABLE-OF-CONTENTS\\]" nil t))
26053 (progn
26054 (goto-char (match-beginning 0))
26055 (replace-match ""))
26056 (goto-char first-heading-pos)
26057 (when (looking-at "\\s-*</p>")
26058 (goto-char (match-end 0))
26059 (insert "\n")))
26060 (insert "<div id=\"table-of-contents\">\n")
26061 (mapc 'insert thetoc)
26062 (insert "</div>\n"))
26063 ;; remove empty paragraphs and lists
26064 (goto-char (point-min))
26065 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
26066 (replace-match ""))
26067 (goto-char (point-min))
26068 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
26069 (replace-match ""))
26070 (goto-char (point-min))
26071 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
26072 (replace-match ""))
26073 ;; Convert whitespace place holders
26074 (goto-char (point-min))
26075 (let (beg end n)
26076 (while (setq beg (next-single-property-change (point) 'org-whitespace))
26077 (setq n (get-text-property beg 'org-whitespace)
26078 end (next-single-property-change beg 'org-whitespace))
26079 (goto-char beg)
26080 (delete-region beg end)
26081 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
26082 (make-string n ?x)))))
26084 (or to-buffer (progn (save-buffer) (kill-buffer (current-buffer))))
26085 (goto-char (point-min))
26086 (message "Exporting... done")
26087 (if (eq to-buffer 'string)
26088 (prog1 (buffer-substring (point-min) (point-max))
26089 (kill-buffer (current-buffer)))
26090 (current-buffer)))))
26092 (defvar org-table-colgroup-info nil)
26093 (defun org-format-table-ascii (lines)
26094 "Format a table for ascii export."
26095 (if (stringp lines)
26096 (setq lines (org-split-string lines "\n")))
26097 (if (not (string-match "^[ \t]*|" (car lines)))
26098 ;; Table made by table.el - test for spanning
26099 lines
26101 ;; A normal org table
26102 ;; Get rid of hlines at beginning and end
26103 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26104 (setq lines (nreverse lines))
26105 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26106 (setq lines (nreverse lines))
26107 (when org-export-table-remove-special-lines
26108 ;; Check if the table has a marking column. If yes remove the
26109 ;; column and the special lines
26110 (setq lines (org-table-clean-before-export lines)))
26111 ;; Get rid of the vertical lines except for grouping
26112 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
26113 rtn line vl1 start)
26114 (while (setq line (pop lines))
26115 (if (string-match org-table-hline-regexp line)
26116 (and (string-match "|\\(.*\\)|" line)
26117 (setq line (replace-match " \\1" t nil line)))
26118 (setq start 0 vl1 vl)
26119 (while (string-match "|" line start)
26120 (setq start (match-end 0))
26121 (or (pop vl1) (setq line (replace-match " " t t line)))))
26122 (push line rtn))
26123 (nreverse rtn))))
26125 (defun org-colgroup-info-to-vline-list (info)
26126 (let (vl new last)
26127 (while info
26128 (setq last new new (pop info))
26129 (if (or (memq last '(:end :startend))
26130 (memq new '(:start :startend)))
26131 (push t vl)
26132 (push nil vl)))
26133 (setq vl (nreverse vl))
26134 (and vl (setcar vl nil))
26135 vl))
26137 (defun org-format-table-html (lines olines)
26138 "Find out which HTML converter to use and return the HTML code."
26139 (if (stringp lines)
26140 (setq lines (org-split-string lines "\n")))
26141 (if (string-match "^[ \t]*|" (car lines))
26142 ;; A normal org table
26143 (org-format-org-table-html lines)
26144 ;; Table made by table.el - test for spanning
26145 (let* ((hlines (delq nil (mapcar
26146 (lambda (x)
26147 (if (string-match "^[ \t]*\\+-" x) x
26148 nil))
26149 lines)))
26150 (first (car hlines))
26151 (ll (and (string-match "\\S-+" first)
26152 (match-string 0 first)))
26153 (re (concat "^[ \t]*" (regexp-quote ll)))
26154 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
26155 hlines))))
26156 (if (and (not spanning)
26157 (not org-export-prefer-native-exporter-for-tables))
26158 ;; We can use my own converter with HTML conversions
26159 (org-format-table-table-html lines)
26160 ;; Need to use the code generator in table.el, with the original text.
26161 (org-format-table-table-html-using-table-generate-source olines)))))
26163 (defun org-format-org-table-html (lines &optional splice)
26164 "Format a table into HTML."
26165 ;; Get rid of hlines at beginning and end
26166 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26167 (setq lines (nreverse lines))
26168 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26169 (setq lines (nreverse lines))
26170 (when org-export-table-remove-special-lines
26171 ;; Check if the table has a marking column. If yes remove the
26172 ;; column and the special lines
26173 (setq lines (org-table-clean-before-export lines)))
26175 (let ((head (and org-export-highlight-first-table-line
26176 (delq nil (mapcar
26177 (lambda (x) (string-match "^[ \t]*|-" x))
26178 (cdr lines)))))
26179 (nlines 0) fnum i
26180 tbopen line fields html gr colgropen)
26181 (if splice (setq head nil))
26182 (unless splice (push (if head "<thead>" "<tbody>") html))
26183 (setq tbopen t)
26184 (while (setq line (pop lines))
26185 (catch 'next-line
26186 (if (string-match "^[ \t]*|-" line)
26187 (progn
26188 (unless splice
26189 (push (if head "</thead>" "</tbody>") html)
26190 (if lines (push "<tbody>" html) (setq tbopen nil)))
26191 (setq head nil) ;; head ends here, first time around
26192 ;; ignore this line
26193 (throw 'next-line t)))
26194 ;; Break the line into fields
26195 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26196 (unless fnum (setq fnum (make-vector (length fields) 0)))
26197 (setq nlines (1+ nlines) i -1)
26198 (push (concat "<tr>"
26199 (mapconcat
26200 (lambda (x)
26201 (setq i (1+ i))
26202 (if (and (< i nlines)
26203 (string-match org-table-number-regexp x))
26204 (incf (aref fnum i)))
26205 (if head
26206 (concat (car org-export-table-header-tags) x
26207 (cdr org-export-table-header-tags))
26208 (concat (car org-export-table-data-tags) x
26209 (cdr org-export-table-data-tags))))
26210 fields "")
26211 "</tr>")
26212 html)))
26213 (unless splice (if tbopen (push "</tbody>" html)))
26214 (unless splice (push "</table>\n" html))
26215 (setq html (nreverse html))
26216 (unless splice
26217 ;; Put in col tags with the alignment (unfortuntely often ignored...)
26218 (push (mapconcat
26219 (lambda (x)
26220 (setq gr (pop org-table-colgroup-info))
26221 (format "%s<col align=\"%s\"></col>%s"
26222 (if (memq gr '(:start :startend))
26223 (prog1
26224 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
26225 (setq colgropen t))
26227 (if (> (/ (float x) nlines) org-table-number-fraction)
26228 "right" "left")
26229 (if (memq gr '(:end :startend))
26230 (progn (setq colgropen nil) "</colgroup>")
26231 "")))
26232 fnum "")
26233 html)
26234 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
26235 (push html-table-tag html))
26236 (concat (mapconcat 'identity html "\n") "\n")))
26238 (defun org-table-clean-before-export (lines)
26239 "Check if the table has a marking column.
26240 If yes remove the column and the special lines."
26241 (setq org-table-colgroup-info nil)
26242 (if (memq nil
26243 (mapcar
26244 (lambda (x) (or (string-match "^[ \t]*|-" x)
26245 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
26246 lines))
26247 (progn
26248 (setq org-table-clean-did-remove-column nil)
26249 (delq nil
26250 (mapcar
26251 (lambda (x)
26252 (cond
26253 ((string-match "^[ \t]*| */ *|" x)
26254 (setq org-table-colgroup-info
26255 (mapcar (lambda (x)
26256 (cond ((member x '("<" "&lt;")) :start)
26257 ((member x '(">" "&gt;")) :end)
26258 ((member x '("<>" "&lt;&gt;")) :startend)
26259 (t nil)))
26260 (org-split-string x "[ \t]*|[ \t]*")))
26261 nil)
26262 (t x)))
26263 lines)))
26264 (setq org-table-clean-did-remove-column t)
26265 (delq nil
26266 (mapcar
26267 (lambda (x)
26268 (cond
26269 ((string-match "^[ \t]*| */ *|" x)
26270 (setq org-table-colgroup-info
26271 (mapcar (lambda (x)
26272 (cond ((member x '("<" "&lt;")) :start)
26273 ((member x '(">" "&gt;")) :end)
26274 ((member x '("<>" "&lt;&gt;")) :startend)
26275 (t nil)))
26276 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
26277 nil)
26278 ((string-match "^[ \t]*| *[!_^/] *|" x)
26279 nil) ; ignore this line
26280 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
26281 (string-match "^\\([ \t]*\\)|[^|]*|" x))
26282 ;; remove the first column
26283 (replace-match "\\1|" t nil x))))
26284 lines))))
26286 (defun org-format-table-table-html (lines)
26287 "Format a table generated by table.el into HTML.
26288 This conversion does *not* use `table-generate-source' from table.el.
26289 This has the advantage that Org-mode's HTML conversions can be used.
26290 But it has the disadvantage, that no cell- or row-spanning is allowed."
26291 (let (line field-buffer
26292 (head org-export-highlight-first-table-line)
26293 fields html empty)
26294 (setq html (concat html-table-tag "\n"))
26295 (while (setq line (pop lines))
26296 (setq empty "&nbsp;")
26297 (catch 'next-line
26298 (if (string-match "^[ \t]*\\+-" line)
26299 (progn
26300 (if field-buffer
26301 (progn
26302 (setq
26303 html
26304 (concat
26305 html
26306 "<tr>"
26307 (mapconcat
26308 (lambda (x)
26309 (if (equal x "") (setq x empty))
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 field-buffer "\n")
26316 "</tr>\n"))
26317 (setq head nil)
26318 (setq field-buffer nil)))
26319 ;; Ignore this line
26320 (throw 'next-line t)))
26321 ;; Break the line into fields and store the fields
26322 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26323 (if field-buffer
26324 (setq field-buffer (mapcar
26325 (lambda (x)
26326 (concat x "<br/>" (pop fields)))
26327 field-buffer))
26328 (setq field-buffer fields))))
26329 (setq html (concat html "</table>\n"))
26330 html))
26332 (defun org-format-table-table-html-using-table-generate-source (lines)
26333 "Format a table into html, using `table-generate-source' from table.el.
26334 This has the advantage that cell- or row-spanning is allowed.
26335 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
26336 (require 'table)
26337 (with-current-buffer (get-buffer-create " org-tmp1 ")
26338 (erase-buffer)
26339 (insert (mapconcat 'identity lines "\n"))
26340 (goto-char (point-min))
26341 (if (not (re-search-forward "|[^+]" nil t))
26342 (error "Error processing table"))
26343 (table-recognize-table)
26344 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
26345 (table-generate-source 'html " org-tmp2 ")
26346 (set-buffer " org-tmp2 ")
26347 (buffer-substring (point-min) (point-max))))
26349 (defun org-html-handle-time-stamps (s)
26350 "Format time stamps in string S, or remove them."
26351 (catch 'exit
26352 (let (r b)
26353 (while (string-match org-maybe-keyword-time-regexp s)
26354 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
26355 ;; never export CLOCK
26356 (throw 'exit ""))
26357 (or b (setq b (substring s 0 (match-beginning 0))))
26358 (if (not org-export-with-timestamps)
26359 (setq r (concat r (substring s 0 (match-beginning 0)))
26360 s (substring s (match-end 0)))
26361 (setq r (concat
26362 r (substring s 0 (match-beginning 0))
26363 (if (match-end 1)
26364 (format "@<span class=\"timestamp-kwd\">%s @</span>"
26365 (match-string 1 s)))
26366 (format " @<span class=\"timestamp\">%s@</span>"
26367 (substring
26368 (org-translate-time (match-string 3 s)) 1 -1)))
26369 s (substring s (match-end 0)))))
26370 ;; Line break if line started and ended with time stamp stuff
26371 (if (not r)
26373 (setq r (concat r s))
26374 (unless (string-match "\\S-" (concat b s))
26375 (setq r (concat r "@<br/>")))
26376 r))))
26378 (defun org-html-protect (s)
26379 ;; convert & to &amp;, < to &lt; and > to &gt;
26380 (let ((start 0))
26381 (while (string-match "&" s start)
26382 (setq s (replace-match "&amp;" t t s)
26383 start (1+ (match-beginning 0))))
26384 (while (string-match "<" s)
26385 (setq s (replace-match "&lt;" t t s)))
26386 (while (string-match ">" s)
26387 (setq s (replace-match "&gt;" t t s))))
26390 (defun org-export-cleanup-toc-line (s)
26391 "Remove tags and time staps from lines going into the toc."
26392 (when (memq org-export-with-tags '(not-in-toc nil))
26393 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
26394 (setq s (replace-match "" t t s))))
26395 (when org-export-remove-timestamps-from-toc
26396 (while (string-match org-maybe-keyword-time-regexp s)
26397 (setq s (replace-match "" t t s))))
26398 (while (string-match org-bracket-link-regexp s)
26399 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
26400 t t s)))
26403 (defun org-html-expand (string)
26404 "Prepare STRING for HTML export. Applies all active conversions.
26405 If there are links in the string, don't modify these."
26406 (let* ((re (concat org-bracket-link-regexp "\\|"
26407 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
26408 m s l res)
26409 (while (setq m (string-match re string))
26410 (setq s (substring string 0 m)
26411 l (match-string 0 string)
26412 string (substring string (match-end 0)))
26413 (push (org-html-do-expand s) res)
26414 (push l res))
26415 (push (org-html-do-expand string) res)
26416 (apply 'concat (nreverse res))))
26418 (defun org-html-do-expand (s)
26419 "Apply all active conversions to translate special ASCII to HTML."
26420 (setq s (org-html-protect s))
26421 (if org-export-html-expand
26422 (let ((start 0))
26423 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
26424 (setq s (replace-match "<\\1>" t nil s)))))
26425 (if org-export-with-emphasize
26426 (setq s (org-export-html-convert-emphasize s)))
26427 (if org-export-with-special-strings
26428 (setq s (org-export-html-convert-special-strings s)))
26429 (if org-export-with-sub-superscripts
26430 (setq s (org-export-html-convert-sub-super s)))
26431 (if org-export-with-TeX-macros
26432 (let ((start 0) wd ass)
26433 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26434 (if (get-text-property (match-beginning 0) 'org-protected s)
26435 (setq start (match-end 0))
26436 (setq wd (match-string 1 s))
26437 (if (setq ass (assoc wd org-html-entities))
26438 (setq s (replace-match (or (cdr ass)
26439 (concat "&" (car ass) ";"))
26440 t t s))
26441 (setq start (+ start (length wd))))))))
26444 (defun org-create-multibrace-regexp (left right n)
26445 "Create a regular expression which will match a balanced sexp.
26446 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26447 as single character strings.
26448 The regexp returned will match the entire expression including the
26449 delimiters. It will also define a single group which contains the
26450 match except for the outermost delimiters. The maximum depth of
26451 stacked delimiters is N. Escaping delimiters is not possible."
26452 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26453 (or "\\|")
26454 (re nothing)
26455 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26456 (while (> n 1)
26457 (setq n (1- n)
26458 re (concat re or next)
26459 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26460 (concat left "\\(" re "\\)" right)))
26462 (defvar org-match-substring-regexp
26463 (concat
26464 "\\([^\\]\\)\\([_^]\\)\\("
26465 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26466 "\\|"
26467 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26468 "\\|"
26469 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26470 "The regular expression matching a sub- or superscript.")
26472 (defvar org-match-substring-with-braces-regexp
26473 (concat
26474 "\\([^\\]\\)\\([_^]\\)\\("
26475 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26476 "\\)")
26477 "The regular expression matching a sub- or superscript, forcing braces.")
26479 (defconst org-export-html-special-string-regexps
26480 '(("\\\\-" . "&shy;")
26481 ("---\\([^-]\\)" . "&mdash;\\1")
26482 ("--\\([^-]\\)" . "&ndash;\\1")
26483 ("\\.\\.\\." . "&hellip;"))
26484 "Regular expressions for special string conversion.")
26486 (defun org-export-html-convert-special-strings (string)
26487 "Convert special characters in STRING to HTML."
26488 (let ((all org-export-html-special-string-regexps)
26489 e a re rpl start)
26490 (while (setq a (pop all))
26491 (setq re (car a) rpl (cdr a) start 0)
26492 (while (string-match re string start)
26493 (if (get-text-property (match-beginning 0) 'org-protected string)
26494 (setq start (match-end 0))
26495 (setq string (replace-match rpl t nil string)))))
26496 string))
26498 (defun org-export-html-convert-sub-super (string)
26499 "Convert sub- and superscripts in STRING to HTML."
26500 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26501 (while (string-match org-match-substring-regexp string s)
26502 (cond
26503 ((and requireb (match-end 8)) (setq s (match-end 2)))
26504 ((get-text-property (match-beginning 2) 'org-protected string)
26505 (setq s (match-end 2)))
26507 (setq s (match-end 1)
26508 key (if (string= (match-string 2 string) "_") "sub" "sup")
26509 c (or (match-string 8 string)
26510 (match-string 6 string)
26511 (match-string 5 string))
26512 string (replace-match
26513 (concat (match-string 1 string)
26514 "<" key ">" c "</" key ">")
26515 t t string)))))
26516 (while (string-match "\\\\\\([_^]\\)" string)
26517 (setq string (replace-match (match-string 1 string) t t string)))
26518 string))
26520 (defun org-export-html-convert-emphasize (string)
26521 "Apply emphasis."
26522 (let ((s 0) rpl)
26523 (while (string-match org-emph-re string s)
26524 (if (not (equal
26525 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26526 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26527 (setq s (match-beginning 0)
26529 (concat
26530 (match-string 1 string)
26531 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26532 (match-string 4 string)
26533 (nth 3 (assoc (match-string 3 string)
26534 org-emphasis-alist))
26535 (match-string 5 string))
26536 string (replace-match rpl t t string)
26537 s (+ s (- (length rpl) 2)))
26538 (setq s (1+ s))))
26539 string))
26541 (defvar org-par-open nil)
26542 (defun org-open-par ()
26543 "Insert <p>, but first close previous paragraph if any."
26544 (org-close-par-maybe)
26545 (insert "\n<p>")
26546 (setq org-par-open t))
26547 (defun org-close-par-maybe ()
26548 "Close paragraph if there is one open."
26549 (when org-par-open
26550 (insert "</p>")
26551 (setq org-par-open nil)))
26552 (defun org-close-li ()
26553 "Close <li> if necessary."
26554 (org-close-par-maybe)
26555 (insert "</li>\n"))
26557 (defvar body-only) ; dynamically scoped into this.
26558 (defun org-html-level-start (level title umax with-toc head-count)
26559 "Insert a new level in HTML export.
26560 When TITLE is nil, just close all open levels."
26561 (org-close-par-maybe)
26562 (let ((l org-level-max))
26563 (while (>= l level)
26564 (if (aref org-levels-open (1- l))
26565 (progn
26566 (org-html-level-close l umax)
26567 (aset org-levels-open (1- l) nil)))
26568 (setq l (1- l)))
26569 (when title
26570 ;; If title is nil, this means this function is called to close
26571 ;; all levels, so the rest is done only if title is given
26572 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26573 (setq title (replace-match
26574 (if org-export-with-tags
26575 (save-match-data
26576 (concat
26577 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26578 (mapconcat 'identity (org-split-string
26579 (match-string 1 title) ":")
26580 "&nbsp;")
26581 "</span>"))
26583 t t title)))
26584 (if (> level umax)
26585 (progn
26586 (if (aref org-levels-open (1- level))
26587 (progn
26588 (org-close-li)
26589 (insert "<li>" title "<br/>\n"))
26590 (aset org-levels-open (1- level) t)
26591 (org-close-par-maybe)
26592 (insert "<ul>\n<li>" title "<br/>\n")))
26593 (aset org-levels-open (1- level) t)
26594 (if (and org-export-with-section-numbers (not body-only))
26595 (setq title (concat (org-section-number level) " " title)))
26596 (setq level (+ level org-export-html-toplevel-hlevel -1))
26597 (if with-toc
26598 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26599 level level head-count title level))
26600 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26601 (org-open-par)))))
26603 (defun org-html-level-close (level max-outline-level)
26604 "Terminate one level in HTML export."
26605 (if (<= level max-outline-level)
26606 (insert "</div>\n")
26607 (org-close-li)
26608 (insert "</ul>\n")))
26610 ;;; iCalendar export
26612 ;;;###autoload
26613 (defun org-export-icalendar-this-file ()
26614 "Export current file as an iCalendar file.
26615 The iCalendar file will be located in the same directory as the Org-mode
26616 file, but with extension `.ics'."
26617 (interactive)
26618 (org-export-icalendar nil buffer-file-name))
26620 ;;;###autoload
26621 (defun org-export-icalendar-all-agenda-files ()
26622 "Export all files in `org-agenda-files' to iCalendar .ics files.
26623 Each iCalendar file will be located in the same directory as the Org-mode
26624 file, but with extension `.ics'."
26625 (interactive)
26626 (apply 'org-export-icalendar nil (org-agenda-files t)))
26628 ;;;###autoload
26629 (defun org-export-icalendar-combine-agenda-files ()
26630 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26631 The file is stored under the name `org-combined-agenda-icalendar-file'."
26632 (interactive)
26633 (apply 'org-export-icalendar t (org-agenda-files t)))
26635 (defun org-export-icalendar (combine &rest files)
26636 "Create iCalendar files for all elements of FILES.
26637 If COMBINE is non-nil, combine all calendar entries into a single large
26638 file and store it under the name `org-combined-agenda-icalendar-file'."
26639 (save-excursion
26640 (org-prepare-agenda-buffers files)
26641 (let* ((dir (org-export-directory
26642 :ical (list :publishing-directory
26643 org-export-publishing-directory)))
26644 file ical-file ical-buffer category started org-agenda-new-buffers)
26646 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26647 (when combine
26648 (setq ical-file
26649 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26650 org-combined-agenda-icalendar-file
26651 (expand-file-name org-combined-agenda-icalendar-file dir))
26652 ical-buffer (org-get-agenda-file-buffer ical-file))
26653 (set-buffer ical-buffer) (erase-buffer))
26654 (while (setq file (pop files))
26655 (catch 'nextfile
26656 (org-check-agenda-file file)
26657 (set-buffer (org-get-agenda-file-buffer file))
26658 (unless combine
26659 (setq ical-file (concat (file-name-as-directory dir)
26660 (file-name-sans-extension
26661 (file-name-nondirectory buffer-file-name))
26662 ".ics"))
26663 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26664 (with-current-buffer ical-buffer (erase-buffer)))
26665 (setq category (or org-category
26666 (file-name-sans-extension
26667 (file-name-nondirectory buffer-file-name))))
26668 (if (symbolp category) (setq category (symbol-name category)))
26669 (let ((standard-output ical-buffer))
26670 (if combine
26671 (and (not started) (setq started t)
26672 (org-start-icalendar-file org-icalendar-combined-name))
26673 (org-start-icalendar-file category))
26674 (org-print-icalendar-entries combine)
26675 (when (or (and combine (not files)) (not combine))
26676 (org-finish-icalendar-file)
26677 (set-buffer ical-buffer)
26678 (save-buffer)
26679 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26680 (org-release-buffers org-agenda-new-buffers))))
26682 (defvar org-after-save-iCalendar-file-hook nil
26683 "Hook run after an iCalendar file has been saved.
26684 The iCalendar buffer is still current when this hook is run.
26685 A good way to use this is to tell a desktop calenndar application to re-read
26686 the iCalendar file.")
26688 (defun org-print-icalendar-entries (&optional combine)
26689 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26690 When COMBINE is non nil, add the category to each line."
26691 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26692 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26693 (dts (org-ical-ts-to-string
26694 (format-time-string (cdr org-time-stamp-formats) (current-time))
26695 "DTSTART"))
26696 hd ts ts2 state status (inc t) pos b sexp rrule
26697 scheduledp deadlinep tmp pri category entry location summary desc
26698 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26699 (org-refresh-category-properties)
26700 (save-excursion
26701 (goto-char (point-min))
26702 (while (re-search-forward re1 nil t)
26703 (catch :skip
26704 (org-agenda-skip)
26705 (setq pos (match-beginning 0)
26706 ts (match-string 0)
26707 inc t
26708 hd (org-get-heading)
26709 summary (org-icalendar-cleanup-string
26710 (org-entry-get nil "SUMMARY"))
26711 desc (org-icalendar-cleanup-string
26712 (or (org-entry-get nil "DESCRIPTION")
26713 (and org-icalendar-include-body (org-get-entry)))
26714 t org-icalendar-include-body)
26715 location (org-icalendar-cleanup-string
26716 (org-entry-get nil "LOCATION"))
26717 category (org-get-category))
26718 (if (looking-at re2)
26719 (progn
26720 (goto-char (match-end 0))
26721 (setq ts2 (match-string 1) inc nil))
26722 (setq tmp (buffer-substring (max (point-min)
26723 (- pos org-ds-keyword-length))
26724 pos)
26725 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26726 (progn
26727 (setq inc nil)
26728 (replace-match "\\1" t nil ts))
26730 deadlinep (string-match org-deadline-regexp tmp)
26731 scheduledp (string-match org-scheduled-regexp tmp)
26732 ;; donep (org-entry-is-done-p)
26734 (if (or (string-match org-tr-regexp hd)
26735 (string-match org-ts-regexp hd))
26736 (setq hd (replace-match "" t t hd)))
26737 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26738 (setq rrule
26739 (concat "\nRRULE:FREQ="
26740 (cdr (assoc
26741 (match-string 2 ts)
26742 '(("d" . "DAILY")("w" . "WEEKLY")
26743 ("m" . "MONTHLY")("y" . "YEARLY"))))
26744 ";INTERVAL=" (match-string 1 ts)))
26745 (setq rrule ""))
26746 (setq summary (or summary hd))
26747 (if (string-match org-bracket-link-regexp summary)
26748 (setq summary
26749 (replace-match (if (match-end 3)
26750 (match-string 3 summary)
26751 (match-string 1 summary))
26752 t t summary)))
26753 (if deadlinep (setq summary (concat "DL: " summary)))
26754 (if scheduledp (setq summary (concat "S: " summary)))
26755 (if (string-match "\\`<%%" ts)
26756 (with-current-buffer sexp-buffer
26757 (insert (substring ts 1 -1) " " summary "\n"))
26758 (princ (format "BEGIN:VEVENT
26760 %s%s
26761 SUMMARY:%s%s%s
26762 CATEGORIES:%s
26763 END:VEVENT\n"
26764 (org-ical-ts-to-string ts "DTSTART")
26765 (org-ical-ts-to-string ts2 "DTEND" inc)
26766 rrule summary
26767 (if (and desc (string-match "\\S-" desc))
26768 (concat "\nDESCRIPTION: " desc) "")
26769 (if (and location (string-match "\\S-" location))
26770 (concat "\nLOCATION: " location) "")
26771 category)))))
26773 (when (and org-icalendar-include-sexps
26774 (condition-case nil (require 'icalendar) (error nil))
26775 (fboundp 'icalendar-export-region))
26776 ;; Get all the literal sexps
26777 (goto-char (point-min))
26778 (while (re-search-forward "^&?%%(" nil t)
26779 (catch :skip
26780 (org-agenda-skip)
26781 (setq b (match-beginning 0))
26782 (goto-char (1- (match-end 0)))
26783 (forward-sexp 1)
26784 (end-of-line 1)
26785 (setq sexp (buffer-substring b (point)))
26786 (with-current-buffer sexp-buffer
26787 (insert sexp "\n"))
26788 (princ (org-diary-to-ical-string sexp-buffer)))))
26790 (when org-icalendar-include-todo
26791 (goto-char (point-min))
26792 (while (re-search-forward org-todo-line-regexp nil t)
26793 (catch :skip
26794 (org-agenda-skip)
26795 (setq state (match-string 2))
26796 (setq status (if (member state org-done-keywords)
26797 "COMPLETED" "NEEDS-ACTION"))
26798 (when (and state
26799 (or (not (member state org-done-keywords))
26800 (eq org-icalendar-include-todo 'all))
26801 (not (member org-archive-tag (org-get-tags-at)))
26803 (setq hd (match-string 3)
26804 summary (org-icalendar-cleanup-string
26805 (org-entry-get nil "SUMMARY"))
26806 desc (org-icalendar-cleanup-string
26807 (or (org-entry-get nil "DESCRIPTION")
26808 (and org-icalendar-include-body (org-get-entry)))
26809 t org-icalendar-include-body)
26810 location (org-icalendar-cleanup-string
26811 (org-entry-get nil "LOCATION")))
26812 (if (string-match org-bracket-link-regexp hd)
26813 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26814 (match-string 1 hd))
26815 t t hd)))
26816 (if (string-match org-priority-regexp hd)
26817 (setq pri (string-to-char (match-string 2 hd))
26818 hd (concat (substring hd 0 (match-beginning 1))
26819 (substring hd (match-end 1))))
26820 (setq pri org-default-priority))
26821 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26822 (- org-lowest-priority org-highest-priority))))))
26824 (princ (format "BEGIN:VTODO
26826 SUMMARY:%s%s%s
26827 CATEGORIES:%s
26828 SEQUENCE:1
26829 PRIORITY:%d
26830 STATUS:%s
26831 END:VTODO\n"
26833 (or summary hd)
26834 (if (and location (string-match "\\S-" location))
26835 (concat "\nLOCATION: " location) "")
26836 (if (and desc (string-match "\\S-" desc))
26837 (concat "\nDESCRIPTION: " desc) "")
26838 category pri status)))))))))
26840 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26841 "Take out stuff and quote what needs to be quoted.
26842 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26843 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26844 characters."
26845 (if (not s)
26847 (when is-body
26848 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26849 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26850 (while (string-match re s) (setq s (replace-match "" t t s)))
26851 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26852 (let ((start 0))
26853 (while (string-match "\\([,;\\]\\)" s start)
26854 (setq start (+ (match-beginning 0) 2)
26855 s (replace-match "\\\\\\1" nil nil s))))
26856 (when is-body
26857 (while (string-match "[ \t]*\n[ \t]*" s)
26858 (setq s (replace-match "\\n" t t s))))
26859 (setq s (org-trim s))
26860 (if is-body
26861 (if maxlength
26862 (if (and (numberp maxlength)
26863 (> (length s) maxlength))
26864 (setq s (substring s 0 maxlength)))))
26867 (defun org-get-entry ()
26868 "Clean-up description string."
26869 (save-excursion
26870 (org-back-to-heading t)
26871 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26873 (defun org-start-icalendar-file (name)
26874 "Start an iCalendar file by inserting the header."
26875 (let ((user user-full-name)
26876 (name (or name "unknown"))
26877 (timezone (cadr (current-time-zone))))
26878 (princ
26879 (format "BEGIN:VCALENDAR
26880 VERSION:2.0
26881 X-WR-CALNAME:%s
26882 PRODID:-//%s//Emacs with Org-mode//EN
26883 X-WR-TIMEZONE:%s
26884 CALSCALE:GREGORIAN\n" name user timezone))))
26886 (defun org-finish-icalendar-file ()
26887 "Finish an iCalendar file by inserting the END statement."
26888 (princ "END:VCALENDAR\n"))
26890 (defun org-ical-ts-to-string (s keyword &optional inc)
26891 "Take a time string S and convert it to iCalendar format.
26892 KEYWORD is added in front, to make a complete line like DTSTART....
26893 When INC is non-nil, increase the hour by two (if time string contains
26894 a time), or the day by one (if it does not contain a time)."
26895 (let ((t1 (org-parse-time-string s 'nodefault))
26896 t2 fmt have-time time)
26897 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26898 (setq t2 t1 have-time t)
26899 (setq t2 (org-parse-time-string s)))
26900 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26901 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26902 (when inc
26903 (if have-time
26904 (if org-agenda-default-appointment-duration
26905 (setq mi (+ org-agenda-default-appointment-duration mi))
26906 (setq h (+ 2 h)))
26907 (setq d (1+ d))))
26908 (setq time (encode-time s mi h d m y)))
26909 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26910 (concat keyword (format-time-string fmt time))))
26912 ;;; XOXO export
26914 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26915 (with-current-buffer buffer
26916 (apply 'insert output)))
26917 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26919 (defun org-export-as-xoxo (&optional buffer)
26920 "Export the org buffer as XOXO.
26921 The XOXO buffer is named *xoxo-<source buffer name>*"
26922 (interactive (list (current-buffer)))
26923 ;; A quickie abstraction
26925 ;; Output everything as XOXO
26926 (with-current-buffer (get-buffer buffer)
26927 (let* ((pos (point))
26928 (opt-plist (org-combine-plists (org-default-export-plist)
26929 (org-infile-export-plist)))
26930 (filename (concat (file-name-as-directory
26931 (org-export-directory :xoxo opt-plist))
26932 (file-name-sans-extension
26933 (file-name-nondirectory buffer-file-name))
26934 ".html"))
26935 (out (find-file-noselect filename))
26936 (last-level 1)
26937 (hanging-li nil))
26938 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26939 ;; Check the output buffer is empty.
26940 (with-current-buffer out (erase-buffer))
26941 ;; Kick off the output
26942 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26943 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26944 (let* ((hd (match-string-no-properties 1))
26945 (level (length hd))
26946 (text (concat
26947 (match-string-no-properties 2)
26948 (save-excursion
26949 (goto-char (match-end 0))
26950 (let ((str ""))
26951 (catch 'loop
26952 (while 't
26953 (forward-line)
26954 (if (looking-at "^[ \t]\\(.*\\)")
26955 (setq str (concat str (match-string-no-properties 1)))
26956 (throw 'loop str)))))))))
26958 ;; Handle level rendering
26959 (cond
26960 ((> level last-level)
26961 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26963 ((< level last-level)
26964 (dotimes (- (- last-level level) 1)
26965 (if hanging-li
26966 (org-export-as-xoxo-insert-into out "</li>\n"))
26967 (org-export-as-xoxo-insert-into out "</ol>\n"))
26968 (when hanging-li
26969 (org-export-as-xoxo-insert-into out "</li>\n")
26970 (setq hanging-li nil)))
26972 ((equal level last-level)
26973 (if hanging-li
26974 (org-export-as-xoxo-insert-into out "</li>\n")))
26977 (setq last-level level)
26979 ;; And output the new li
26980 (setq hanging-li 't)
26981 (if (equal ?+ (elt text 0))
26982 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26983 (org-export-as-xoxo-insert-into out "<li>" text))))
26985 ;; Finally finish off the ol
26986 (dotimes (- last-level 1)
26987 (if hanging-li
26988 (org-export-as-xoxo-insert-into out "</li>\n"))
26989 (org-export-as-xoxo-insert-into out "</ol>\n"))
26991 (goto-char pos)
26992 ;; Finish the buffer off and clean it up.
26993 (switch-to-buffer-other-window out)
26994 (indent-region (point-min) (point-max) nil)
26995 (save-buffer)
26996 (goto-char (point-min))
27000 ;;;; Key bindings
27002 ;; Make `C-c C-x' a prefix key
27003 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
27005 ;; TAB key with modifiers
27006 (org-defkey org-mode-map "\C-i" 'org-cycle)
27007 (org-defkey org-mode-map [(tab)] 'org-cycle)
27008 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
27009 (org-defkey org-mode-map [(meta tab)] 'org-complete)
27010 (org-defkey org-mode-map "\M-\t" 'org-complete)
27011 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
27012 ;; The following line is necessary under Suse GNU/Linux
27013 (unless (featurep 'xemacs)
27014 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
27015 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
27016 (define-key org-mode-map [backtab] 'org-shifttab)
27018 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
27019 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
27020 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
27022 ;; Cursor keys with modifiers
27023 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
27024 (org-defkey org-mode-map [(meta right)] 'org-metaright)
27025 (org-defkey org-mode-map [(meta up)] 'org-metaup)
27026 (org-defkey org-mode-map [(meta down)] 'org-metadown)
27028 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
27029 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
27030 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
27031 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
27033 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
27034 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
27035 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
27036 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
27038 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
27039 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
27041 ;;; Extra keys for tty access.
27042 ;; We only set them when really needed because otherwise the
27043 ;; menus don't show the simple keys
27045 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
27046 (not window-system))
27047 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
27048 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
27049 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
27050 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
27051 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
27052 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
27053 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
27054 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
27055 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
27056 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
27057 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
27058 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
27059 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
27060 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
27061 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
27062 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
27063 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
27064 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
27065 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
27066 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
27067 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
27068 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
27070 ;; All the other keys
27072 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
27073 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
27074 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
27075 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
27076 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
27077 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
27078 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
27079 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
27080 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
27081 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
27082 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
27083 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
27084 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
27085 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
27086 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
27087 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
27088 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
27089 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
27090 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
27091 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
27092 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
27093 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
27094 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
27095 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
27096 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
27097 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
27098 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
27099 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
27100 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
27101 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
27102 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
27103 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
27104 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
27105 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
27106 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
27107 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
27108 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
27109 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
27110 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
27111 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
27112 (org-defkey org-mode-map "\C-c^" 'org-sort)
27113 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
27114 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
27115 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
27116 (org-defkey org-mode-map "\C-m" 'org-return)
27117 (org-defkey org-mode-map "\C-j" 'org-return-indent)
27118 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
27119 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
27120 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
27121 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
27122 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
27123 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
27124 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
27125 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
27126 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
27127 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
27128 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
27129 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
27130 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
27131 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
27132 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
27134 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
27135 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
27136 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
27137 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
27139 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
27140 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
27141 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
27142 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
27143 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
27144 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
27145 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
27146 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
27147 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
27148 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
27149 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
27150 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
27152 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
27154 (when (featurep 'xemacs)
27155 (org-defkey org-mode-map 'button3 'popup-mode-menu))
27157 (defsubst org-table-p () (org-at-table-p))
27159 (defun org-self-insert-command (N)
27160 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
27161 If the cursor is in a table looking at whitespace, the whitespace is
27162 overwritten, and the table is not marked as requiring realignment."
27163 (interactive "p")
27164 (if (and (org-table-p)
27165 (progn
27166 ;; check if we blank the field, and if that triggers align
27167 (and org-table-auto-blank-field
27168 (member last-command
27169 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
27170 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
27171 ;; got extra space, this field does not determine column width
27172 (let (org-table-may-need-update) (org-table-blank-field))
27173 ;; no extra space, this field may determine column width
27174 (org-table-blank-field)))
27176 (eq N 1)
27177 (looking-at "[^|\n]* |"))
27178 (let (org-table-may-need-update)
27179 (goto-char (1- (match-end 0)))
27180 (delete-backward-char 1)
27181 (goto-char (match-beginning 0))
27182 (self-insert-command N))
27183 (setq org-table-may-need-update t)
27184 (self-insert-command N)
27185 (org-fix-tags-on-the-fly)))
27187 (defun org-fix-tags-on-the-fly ()
27188 (when (and (equal (char-after (point-at-bol)) ?*)
27189 (org-on-heading-p))
27190 (org-align-tags-here org-tags-column)))
27192 (defun org-delete-backward-char (N)
27193 "Like `delete-backward-char', insert whitespace at field end in tables.
27194 When deleting backwards, in tables this function will insert whitespace in
27195 front of the next \"|\" separator, to keep the table aligned. The table will
27196 still be marked for re-alignment if the field did fill the entire column,
27197 because, in this case the deletion might narrow the column."
27198 (interactive "p")
27199 (if (and (org-table-p)
27200 (eq N 1)
27201 (string-match "|" (buffer-substring (point-at-bol) (point)))
27202 (looking-at ".*?|"))
27203 (let ((pos (point))
27204 (noalign (looking-at "[^|\n\r]* |"))
27205 (c org-table-may-need-update))
27206 (backward-delete-char N)
27207 (skip-chars-forward "^|")
27208 (insert " ")
27209 (goto-char (1- pos))
27210 ;; noalign: if there were two spaces at the end, this field
27211 ;; does not determine the width of the column.
27212 (if noalign (setq org-table-may-need-update c)))
27213 (backward-delete-char N)
27214 (org-fix-tags-on-the-fly)))
27216 (defun org-delete-char (N)
27217 "Like `delete-char', but insert whitespace at field end in tables.
27218 When deleting characters, in tables this function will insert whitespace in
27219 front of the next \"|\" separator, to keep the table aligned. The table will
27220 still be marked for re-alignment if the field did fill the entire column,
27221 because, in this case the deletion might narrow the column."
27222 (interactive "p")
27223 (if (and (org-table-p)
27224 (not (bolp))
27225 (not (= (char-after) ?|))
27226 (eq N 1))
27227 (if (looking-at ".*?|")
27228 (let ((pos (point))
27229 (noalign (looking-at "[^|\n\r]* |"))
27230 (c org-table-may-need-update))
27231 (replace-match (concat
27232 (substring (match-string 0) 1 -1)
27233 " |"))
27234 (goto-char pos)
27235 ;; noalign: if there were two spaces at the end, this field
27236 ;; does not determine the width of the column.
27237 (if noalign (setq org-table-may-need-update c)))
27238 (delete-char N))
27239 (delete-char N)
27240 (org-fix-tags-on-the-fly)))
27242 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
27243 (put 'org-self-insert-command 'delete-selection t)
27244 (put 'orgtbl-self-insert-command 'delete-selection t)
27245 (put 'org-delete-char 'delete-selection 'supersede)
27246 (put 'org-delete-backward-char 'delete-selection 'supersede)
27248 ;; Make `flyspell-mode' delay after some commands
27249 (put 'org-self-insert-command 'flyspell-delayed t)
27250 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
27251 (put 'org-delete-char 'flyspell-delayed t)
27252 (put 'org-delete-backward-char 'flyspell-delayed t)
27254 ;; Make pabbrev-mode expand after org-mode commands
27255 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
27256 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
27258 ;; How to do this: Measure non-white length of current string
27259 ;; If equal to column width, we should realign.
27261 (defun org-remap (map &rest commands)
27262 "In MAP, remap the functions given in COMMANDS.
27263 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
27264 (let (new old)
27265 (while commands
27266 (setq old (pop commands) new (pop commands))
27267 (if (fboundp 'command-remapping)
27268 (org-defkey map (vector 'remap old) new)
27269 (substitute-key-definition old new map global-map)))))
27271 (when (eq org-enable-table-editor 'optimized)
27272 ;; If the user wants maximum table support, we need to hijack
27273 ;; some standard editing functions
27274 (org-remap org-mode-map
27275 'self-insert-command 'org-self-insert-command
27276 'delete-char 'org-delete-char
27277 'delete-backward-char 'org-delete-backward-char)
27278 (org-defkey org-mode-map "|" 'org-force-self-insert))
27280 (defun org-shiftcursor-error ()
27281 "Throw an error because Shift-Cursor command was applied in wrong context."
27282 (error "This command is active in special context like tables, headlines or timestamps"))
27284 (defun org-shifttab (&optional arg)
27285 "Global visibility cycling or move to previous table field.
27286 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
27287 on context.
27288 See the individual commands for more information."
27289 (interactive "P")
27290 (cond
27291 ((org-at-table-p) (call-interactively 'org-table-previous-field))
27292 (arg (message "Content view to level: ")
27293 (org-content (prefix-numeric-value arg))
27294 (setq org-cycle-global-status 'overview))
27295 (t (call-interactively 'org-global-cycle))))
27297 (defun org-shiftmetaleft ()
27298 "Promote subtree or delete table column.
27299 Calls `org-promote-subtree', `org-outdent-item',
27300 or `org-table-delete-column', depending on context.
27301 See the individual commands for more information."
27302 (interactive)
27303 (cond
27304 ((org-at-table-p) (call-interactively 'org-table-delete-column))
27305 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
27306 ((org-at-item-p) (call-interactively 'org-outdent-item))
27307 (t (org-shiftcursor-error))))
27309 (defun org-shiftmetaright ()
27310 "Demote subtree or insert table column.
27311 Calls `org-demote-subtree', `org-indent-item',
27312 or `org-table-insert-column', depending on context.
27313 See the individual commands for more information."
27314 (interactive)
27315 (cond
27316 ((org-at-table-p) (call-interactively 'org-table-insert-column))
27317 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
27318 ((org-at-item-p) (call-interactively 'org-indent-item))
27319 (t (org-shiftcursor-error))))
27321 (defun org-shiftmetaup (&optional arg)
27322 "Move subtree up or kill table row.
27323 Calls `org-move-subtree-up' or `org-table-kill-row' or
27324 `org-move-item-up' depending on context. See the individual commands
27325 for more information."
27326 (interactive "P")
27327 (cond
27328 ((org-at-table-p) (call-interactively 'org-table-kill-row))
27329 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27330 ((org-at-item-p) (call-interactively 'org-move-item-up))
27331 (t (org-shiftcursor-error))))
27332 (defun org-shiftmetadown (&optional arg)
27333 "Move subtree down or insert table row.
27334 Calls `org-move-subtree-down' or `org-table-insert-row' or
27335 `org-move-item-down', depending on context. See the individual
27336 commands for more information."
27337 (interactive "P")
27338 (cond
27339 ((org-at-table-p) (call-interactively 'org-table-insert-row))
27340 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27341 ((org-at-item-p) (call-interactively 'org-move-item-down))
27342 (t (org-shiftcursor-error))))
27344 (defun org-metaleft (&optional arg)
27345 "Promote heading or move table column to left.
27346 Calls `org-do-promote' or `org-table-move-column', depending on context.
27347 With no specific context, calls the Emacs default `backward-word'.
27348 See the individual commands for more information."
27349 (interactive "P")
27350 (cond
27351 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
27352 ((or (org-on-heading-p) (org-region-active-p))
27353 (call-interactively 'org-do-promote))
27354 ((org-at-item-p) (call-interactively 'org-outdent-item))
27355 (t (call-interactively 'backward-word))))
27357 (defun org-metaright (&optional arg)
27358 "Demote subtree or move table column to right.
27359 Calls `org-do-demote' or `org-table-move-column', depending on context.
27360 With no specific context, calls the Emacs default `forward-word'.
27361 See the individual commands for more information."
27362 (interactive "P")
27363 (cond
27364 ((org-at-table-p) (call-interactively 'org-table-move-column))
27365 ((or (org-on-heading-p) (org-region-active-p))
27366 (call-interactively 'org-do-demote))
27367 ((org-at-item-p) (call-interactively 'org-indent-item))
27368 (t (call-interactively 'forward-word))))
27370 (defun org-metaup (&optional arg)
27371 "Move subtree up or move table row up.
27372 Calls `org-move-subtree-up' or `org-table-move-row' or
27373 `org-move-item-up', depending on context. See the individual commands
27374 for more information."
27375 (interactive "P")
27376 (cond
27377 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
27378 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27379 ((org-at-item-p) (call-interactively 'org-move-item-up))
27380 (t (transpose-lines 1) (beginning-of-line -1))))
27382 (defun org-metadown (&optional arg)
27383 "Move subtree down or move table row down.
27384 Calls `org-move-subtree-down' or `org-table-move-row' or
27385 `org-move-item-down', depending on context. See the individual
27386 commands for more information."
27387 (interactive "P")
27388 (cond
27389 ((org-at-table-p) (call-interactively 'org-table-move-row))
27390 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27391 ((org-at-item-p) (call-interactively 'org-move-item-down))
27392 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
27394 (defun org-shiftup (&optional arg)
27395 "Increase item in timestamp or increase priority of current headline.
27396 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
27397 depending on context. See the individual commands for more information."
27398 (interactive "P")
27399 (cond
27400 ((org-at-timestamp-p t)
27401 (call-interactively (if org-edit-timestamp-down-means-later
27402 'org-timestamp-down 'org-timestamp-up)))
27403 ((org-on-heading-p) (call-interactively 'org-priority-up))
27404 ((org-at-item-p) (call-interactively 'org-previous-item))
27405 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
27407 (defun org-shiftdown (&optional arg)
27408 "Decrease item in timestamp or decrease priority of current headline.
27409 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
27410 depending on context. See the individual commands for more information."
27411 (interactive "P")
27412 (cond
27413 ((org-at-timestamp-p t)
27414 (call-interactively (if org-edit-timestamp-down-means-later
27415 'org-timestamp-up 'org-timestamp-down)))
27416 ((org-on-heading-p) (call-interactively 'org-priority-down))
27417 (t (call-interactively 'org-next-item))))
27419 (defun org-shiftright ()
27420 "Next TODO keyword or timestamp one day later, depending on context."
27421 (interactive)
27422 (cond
27423 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
27424 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
27425 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
27426 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
27427 (t (org-shiftcursor-error))))
27429 (defun org-shiftleft ()
27430 "Previous TODO keyword or timestamp one day earlier, depending on context."
27431 (interactive)
27432 (cond
27433 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27434 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27435 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27436 ((org-at-property-p)
27437 (call-interactively 'org-property-previous-allowed-value))
27438 (t (org-shiftcursor-error))))
27440 (defun org-shiftcontrolright ()
27441 "Switch to next TODO set."
27442 (interactive)
27443 (cond
27444 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27445 (t (org-shiftcursor-error))))
27447 (defun org-shiftcontrolleft ()
27448 "Switch to previous TODO set."
27449 (interactive)
27450 (cond
27451 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27452 (t (org-shiftcursor-error))))
27454 (defun org-ctrl-c-ret ()
27455 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27456 (interactive)
27457 (cond
27458 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27459 (t (call-interactively 'org-insert-heading))))
27461 (defun org-copy-special ()
27462 "Copy region in table or copy current subtree.
27463 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27464 See the individual commands for more information."
27465 (interactive)
27466 (call-interactively
27467 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27469 (defun org-cut-special ()
27470 "Cut region in table or cut current subtree.
27471 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27472 See the individual commands for more information."
27473 (interactive)
27474 (call-interactively
27475 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27477 (defun org-paste-special (arg)
27478 "Paste rectangular region into table, or past subtree relative to level.
27479 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27480 See the individual commands for more information."
27481 (interactive "P")
27482 (if (org-at-table-p)
27483 (org-table-paste-rectangle)
27484 (org-paste-subtree arg)))
27486 (defun org-ctrl-c-ctrl-c (&optional arg)
27487 "Set tags in headline, or update according to changed information at point.
27489 This command does many different things, depending on context:
27491 - If the cursor is in a headline, prompt for tags and insert them
27492 into the current line, aligned to `org-tags-column'. When called
27493 with prefix arg, realign all tags in the current buffer.
27495 - If the cursor is in one of the special #+KEYWORD lines, this
27496 triggers scanning the buffer for these lines and updating the
27497 information.
27499 - If the cursor is inside a table, realign the table. This command
27500 works even if the automatic table editor has been turned off.
27502 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27503 the entire table.
27505 - If the cursor is a the beginning of a dynamic block, update it.
27507 - If the cursor is inside a table created by the table.el package,
27508 activate that table.
27510 - If the current buffer is a remember buffer, close note and file it.
27511 with a prefix argument, file it without further interaction to the default
27512 location.
27514 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27515 links in this buffer.
27517 - If the cursor is on a numbered item in a plain list, renumber the
27518 ordered list.
27520 - If the cursor is on a checkbox, toggle it."
27521 (interactive "P")
27522 (let ((org-enable-table-editor t))
27523 (cond
27524 ((or org-clock-overlays
27525 org-occur-highlights
27526 org-latex-fragment-image-overlays)
27527 (org-remove-clock-overlays)
27528 (org-remove-occur-highlights)
27529 (org-remove-latex-fragment-image-overlays)
27530 (message "Temporary highlights/overlays removed from current buffer"))
27531 ((and (local-variable-p 'org-finish-function (current-buffer))
27532 (fboundp org-finish-function))
27533 (funcall org-finish-function))
27534 ((org-at-property-p)
27535 (call-interactively 'org-property-action))
27536 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27537 ((org-on-heading-p) (call-interactively 'org-set-tags))
27538 ((org-at-table.el-p)
27539 (require 'table)
27540 (beginning-of-line 1)
27541 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27542 (call-interactively 'table-recognize-table))
27543 ((org-at-table-p)
27544 (org-table-maybe-eval-formula)
27545 (if arg
27546 (call-interactively 'org-table-recalculate)
27547 (org-table-maybe-recalculate-line))
27548 (call-interactively 'org-table-align))
27549 ((org-at-item-checkbox-p)
27550 (call-interactively 'org-toggle-checkbox))
27551 ((org-at-item-p)
27552 (call-interactively 'org-maybe-renumber-ordered-list))
27553 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27554 ;; Dynamic block
27555 (beginning-of-line 1)
27556 (org-update-dblock))
27557 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27558 (cond
27559 ((equal (match-string 1) "TBLFM")
27560 ;; Recalculate the table before this line
27561 (save-excursion
27562 (beginning-of-line 1)
27563 (skip-chars-backward " \r\n\t")
27564 (if (org-at-table-p)
27565 (org-call-with-arg 'org-table-recalculate t))))
27567 (call-interactively 'org-mode-restart))))
27568 (t (error "C-c C-c can do nothing useful at this location.")))))
27570 (defun org-mode-restart ()
27571 "Restart Org-mode, to scan again for special lines.
27572 Also updates the keyword regular expressions."
27573 (interactive)
27574 (let ((org-inhibit-startup t)) (org-mode))
27575 (message "Org-mode restarted to refresh keyword and special line setup"))
27577 (defun org-kill-note-or-show-branches ()
27578 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27579 (interactive)
27580 (if (not org-finish-function)
27581 (call-interactively 'show-branches)
27582 (let ((org-note-abort t))
27583 (funcall org-finish-function))))
27585 (defun org-return (&optional indent)
27586 "Goto next table row or insert a newline.
27587 Calls `org-table-next-row' or `newline', depending on context.
27588 See the individual commands for more information."
27589 (interactive)
27590 (cond
27591 ((bobp) (if indent (newline-and-indent) (newline)))
27592 ((and (org-at-heading-p)
27593 (looking-at
27594 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27595 (org-show-entry)
27596 (end-of-line 1)
27597 (newline))
27598 ((org-at-table-p)
27599 (org-table-justify-field-maybe)
27600 (call-interactively 'org-table-next-row))
27601 (t (if indent (newline-and-indent) (newline)))))
27603 (defun org-return-indent ()
27604 "Goto next table row or insert a newline and indent.
27605 Calls `org-table-next-row' or `newline-and-indent', depending on
27606 context. See the individual commands for more information."
27607 (interactive)
27608 (org-return t))
27610 (defun org-ctrl-c-star ()
27611 "Compute table, or change heading status of lines.
27612 Calls `org-table-recalculate' or `org-toggle-region-headlines',
27613 depending on context. This will also turn a plain list item or a normal
27614 line into a subheading."
27615 (interactive)
27616 (cond
27617 ((org-at-table-p)
27618 (call-interactively 'org-table-recalculate))
27619 ((org-region-active-p)
27620 ;; Convert all lines in region to list items
27621 (call-interactively 'org-toggle-region-headings))
27622 ((org-on-heading-p)
27623 (org-toggle-region-headings (point-at-bol)
27624 (min (1+ (point-at-eol)) (point-max))))
27625 ((org-at-item-p)
27626 ;; Convert to heading
27627 ;; FIXME: not yet implemented
27629 (t (org-toggle-region-headings (point-at-bol)
27630 (min (1+ (point-at-eol)) (point-max))))))
27632 (defun org-ctrl-c-minus ()
27633 "Insert separator line in table or modify bullet status of line.
27634 Also turns a plain line or a region of lines into list items.
27635 Calls `org-table-insert-hline', `org-toggle-region-items', or
27636 `org-cycle-list-bullet', depending on context."
27637 (interactive)
27638 (cond
27639 ((org-at-table-p)
27640 (call-interactively 'org-table-insert-hline))
27641 ((org-on-heading-p)
27642 ;; Convert to item
27643 (save-excursion
27644 (beginning-of-line 1)
27645 (if (looking-at "\\*+ ")
27646 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
27647 ((org-region-active-p)
27648 ;; Convert all lines in region to list items
27649 (call-interactively 'org-toggle-region-items))
27650 ((org-in-item-p)
27651 (call-interactively 'org-cycle-list-bullet))
27652 (t (org-toggle-region-items (point-at-bol)
27653 (min (1+ (point-at-eol)) (point-max))))))
27655 (defun org-toggle-region-items (beg end)
27656 "Convert all lines in region to list items.
27657 If the first line is already an item, convert all list items in the region
27658 to normal lines."
27659 (interactive "r")
27660 (let (l2 l)
27661 (save-excursion
27662 (goto-char end)
27663 (setq l2 (org-current-line))
27664 (goto-char beg)
27665 (beginning-of-line 1)
27666 (setq l (1- (org-current-line)))
27667 (if (org-at-item-p)
27668 ;; We already have items, de-itemize
27669 (while (< (setq l (1+ l)) l2)
27670 (when (org-at-item-p)
27671 (goto-char (match-beginning 2))
27672 (delete-region (match-beginning 2) (match-end 2))
27673 (and (looking-at "[ \t]+") (replace-match "")))
27674 (beginning-of-line 2))
27675 (while (< (setq l (1+ l)) l2)
27676 (unless (org-at-item-p)
27677 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27678 (replace-match "\\1- \\2")))
27679 (beginning-of-line 2))))))
27681 (defun org-toggle-region-headings (beg end)
27682 "Convert all lines in region to list items.
27683 If the first line is already an item, convert all list items in the region
27684 to normal lines."
27685 (interactive "r")
27686 (let (l2 l)
27687 (save-excursion
27688 (goto-char end)
27689 (setq l2 (org-current-line))
27690 (goto-char beg)
27691 (beginning-of-line 1)
27692 (setq l (1- (org-current-line)))
27693 (if (org-on-heading-p)
27694 ;; We already have headlines, de-star them
27695 (while (< (setq l (1+ l)) l2)
27696 (when (org-on-heading-p t)
27697 (and (looking-at outline-regexp) (replace-match "")))
27698 (beginning-of-line 2))
27699 (let* ((stars (save-excursion
27700 (re-search-backward org-complex-heading-regexp nil t)
27701 (or (match-string 1) "*")))
27702 (add-stars (if org-odd-levels-only "**" "*"))
27703 (rpl (concat stars add-stars " \\2")))
27704 (while (< (setq l (1+ l)) l2)
27705 (unless (org-on-heading-p)
27706 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27707 (replace-match rpl)))
27708 (beginning-of-line 2)))))))
27710 (defun org-meta-return (&optional arg)
27711 "Insert a new heading or wrap a region in a table.
27712 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27713 See the individual commands for more information."
27714 (interactive "P")
27715 (cond
27716 ((org-at-table-p)
27717 (call-interactively 'org-table-wrap-region))
27718 (t (call-interactively 'org-insert-heading))))
27720 ;;; Menu entries
27722 ;; Define the Org-mode menus
27723 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27724 '("Tbl"
27725 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27726 ["Next Field" org-cycle (org-at-table-p)]
27727 ["Previous Field" org-shifttab (org-at-table-p)]
27728 ["Next Row" org-return (org-at-table-p)]
27729 "--"
27730 ["Blank Field" org-table-blank-field (org-at-table-p)]
27731 ["Edit Field" org-table-edit-field (org-at-table-p)]
27732 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27733 "--"
27734 ("Column"
27735 ["Move Column Left" org-metaleft (org-at-table-p)]
27736 ["Move Column Right" org-metaright (org-at-table-p)]
27737 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27738 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27739 ("Row"
27740 ["Move Row Up" org-metaup (org-at-table-p)]
27741 ["Move Row Down" org-metadown (org-at-table-p)]
27742 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27743 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27744 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27745 "--"
27746 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27747 ("Rectangle"
27748 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27749 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27750 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27751 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27752 "--"
27753 ("Calculate"
27754 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27755 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27756 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27757 "--"
27758 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27759 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27760 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27761 "--"
27762 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27763 "--"
27764 ["Sum Column/Rectangle" org-table-sum
27765 (or (org-at-table-p) (org-region-active-p))]
27766 ["Which Column?" org-table-current-column (org-at-table-p)])
27767 ["Debug Formulas"
27768 org-table-toggle-formula-debugger
27769 :style toggle :selected org-table-formula-debug]
27770 ["Show Col/Row Numbers"
27771 org-table-toggle-coordinate-overlays
27772 :style toggle :selected org-table-overlay-coordinates]
27773 "--"
27774 ["Create" org-table-create (and (not (org-at-table-p))
27775 org-enable-table-editor)]
27776 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27777 ["Import from File" org-table-import (not (org-at-table-p))]
27778 ["Export to File" org-table-export (org-at-table-p)]
27779 "--"
27780 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27782 (easy-menu-define org-org-menu org-mode-map "Org menu"
27783 '("Org"
27784 ("Show/Hide"
27785 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27786 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27787 ["Sparse Tree" org-occur t]
27788 ["Reveal Context" org-reveal t]
27789 ["Show All" show-all t]
27790 "--"
27791 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27792 "--"
27793 ["New Heading" org-insert-heading t]
27794 ("Navigate Headings"
27795 ["Up" outline-up-heading t]
27796 ["Next" outline-next-visible-heading t]
27797 ["Previous" outline-previous-visible-heading t]
27798 ["Next Same Level" outline-forward-same-level t]
27799 ["Previous Same Level" outline-backward-same-level t]
27800 "--"
27801 ["Jump" org-goto t])
27802 ("Edit Structure"
27803 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27804 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27805 "--"
27806 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27807 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27808 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27809 "--"
27810 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27811 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27812 ["Demote Heading" org-metaright (not (org-at-table-p))]
27813 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27814 "--"
27815 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27816 "--"
27817 ["Convert to odd levels" org-convert-to-odd-levels t]
27818 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27819 ("Editing"
27820 ["Emphasis..." org-emphasize t])
27821 ("Archive"
27822 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27823 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27824 ; :active t :keys "C-u C-c C-x C-a"]
27825 ["Sparse trees open ARCHIVE trees"
27826 (setq org-sparse-tree-open-archived-trees
27827 (not org-sparse-tree-open-archived-trees))
27828 :style toggle :selected org-sparse-tree-open-archived-trees]
27829 ["Cycling opens ARCHIVE trees"
27830 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27831 :style toggle :selected org-cycle-open-archived-trees]
27832 ["Agenda includes ARCHIVE trees"
27833 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27834 :style toggle :selected (not org-agenda-skip-archived-trees)]
27835 "--"
27836 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27837 ; ["Check and Move Children" (org-archive-subtree '(4))
27838 ; :active t :keys "C-u C-c C-x C-s"]
27840 "--"
27841 ("TODO Lists"
27842 ["TODO/DONE/-" org-todo t]
27843 ("Select keyword"
27844 ["Next keyword" org-shiftright (org-on-heading-p)]
27845 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27846 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27847 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27848 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27849 ["Show TODO Tree" org-show-todo-tree t]
27850 ["Global TODO list" org-todo-list t]
27851 "--"
27852 ["Set Priority" org-priority t]
27853 ["Priority Up" org-shiftup t]
27854 ["Priority Down" org-shiftdown t])
27855 ("TAGS and Properties"
27856 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27857 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27858 "--"
27859 ["Set property" 'org-set-property t]
27860 ["Column view of properties" org-columns t]
27861 ["Insert Column View DBlock" org-insert-columns-dblock t])
27862 ("Dates and Scheduling"
27863 ["Timestamp" org-time-stamp t]
27864 ["Timestamp (inactive)" org-time-stamp-inactive t]
27865 ("Change Date"
27866 ["1 Day Later" org-shiftright t]
27867 ["1 Day Earlier" org-shiftleft t]
27868 ["1 ... Later" org-shiftup t]
27869 ["1 ... Earlier" org-shiftdown t])
27870 ["Compute Time Range" org-evaluate-time-range t]
27871 ["Schedule Item" org-schedule t]
27872 ["Deadline" org-deadline t]
27873 "--"
27874 ["Custom time format" org-toggle-time-stamp-overlays
27875 :style radio :selected org-display-custom-times]
27876 "--"
27877 ["Goto Calendar" org-goto-calendar t]
27878 ["Date from Calendar" org-date-from-calendar t])
27879 ("Logging work"
27880 ["Clock in" org-clock-in t]
27881 ["Clock out" org-clock-out t]
27882 ["Clock cancel" org-clock-cancel t]
27883 ["Goto running clock" org-clock-goto t]
27884 ["Display times" org-clock-display t]
27885 ["Create clock table" org-clock-report t]
27886 "--"
27887 ["Record DONE time"
27888 (progn (setq org-log-done (not org-log-done))
27889 (message "Switching to %s will %s record a timestamp"
27890 (car org-done-keywords)
27891 (if org-log-done "automatically" "not")))
27892 :style toggle :selected org-log-done])
27893 "--"
27894 ["Agenda Command..." org-agenda t]
27895 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27896 ("File List for Agenda")
27897 ("Special views current file"
27898 ["TODO Tree" org-show-todo-tree t]
27899 ["Check Deadlines" org-check-deadlines t]
27900 ["Timeline" org-timeline t]
27901 ["Tags Tree" org-tags-sparse-tree t])
27902 "--"
27903 ("Hyperlinks"
27904 ["Store Link (Global)" org-store-link t]
27905 ["Insert Link" org-insert-link t]
27906 ["Follow Link" org-open-at-point t]
27907 "--"
27908 ["Next link" org-next-link t]
27909 ["Previous link" org-previous-link t]
27910 "--"
27911 ["Descriptive Links"
27912 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27913 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27914 ["Literal Links"
27915 (progn
27916 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27917 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27918 "--"
27919 ["Export/Publish..." org-export t]
27920 ("LaTeX"
27921 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27922 :selected org-cdlatex-mode]
27923 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27924 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27925 ["Modify math symbol" org-cdlatex-math-modify
27926 (org-inside-LaTeX-fragment-p)]
27927 ["Export LaTeX fragments as images"
27928 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27929 :style toggle :selected org-export-with-LaTeX-fragments])
27930 "--"
27931 ("Documentation"
27932 ["Show Version" org-version t]
27933 ["Info Documentation" org-info t])
27934 ("Customize"
27935 ["Browse Org Group" org-customize t]
27936 "--"
27937 ["Expand This Menu" org-create-customize-menu
27938 (fboundp 'customize-menu-create)])
27939 "--"
27940 ["Refresh setup" org-mode-restart t]
27943 (defun org-info (&optional node)
27944 "Read documentation for Org-mode in the info system.
27945 With optional NODE, go directly to that node."
27946 (interactive)
27947 (info (format "(org)%s" (or node ""))))
27949 (defun org-install-agenda-files-menu ()
27950 (let ((bl (buffer-list)))
27951 (save-excursion
27952 (while bl
27953 (set-buffer (pop bl))
27954 (if (org-mode-p) (setq bl nil)))
27955 (when (org-mode-p)
27956 (easy-menu-change
27957 '("Org") "File List for Agenda"
27958 (append
27959 (list
27960 ["Edit File List" (org-edit-agenda-file-list) t]
27961 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27962 ["Remove Current File from List" org-remove-file t]
27963 ["Cycle through agenda files" org-cycle-agenda-files t]
27964 ["Occur in all agenda files" org-occur-in-agenda-files t]
27965 "--")
27966 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27968 ;;;; Documentation
27970 (defun org-customize ()
27971 "Call the customize function with org as argument."
27972 (interactive)
27973 (customize-browse 'org))
27975 (defun org-create-customize-menu ()
27976 "Create a full customization menu for Org-mode, insert it into the menu."
27977 (interactive)
27978 (if (fboundp 'customize-menu-create)
27979 (progn
27980 (easy-menu-change
27981 '("Org") "Customize"
27982 `(["Browse Org group" org-customize t]
27983 "--"
27984 ,(customize-menu-create 'org)
27985 ["Set" Custom-set t]
27986 ["Save" Custom-save t]
27987 ["Reset to Current" Custom-reset-current t]
27988 ["Reset to Saved" Custom-reset-saved t]
27989 ["Reset to Standard Settings" Custom-reset-standard t]))
27990 (message "\"Org\"-menu now contains full customization menu"))
27991 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27993 ;;;; Miscellaneous stuff
27996 ;;; Generally useful functions
27998 (defun org-context ()
27999 "Return a list of contexts of the current cursor position.
28000 If several contexts apply, all are returned.
28001 Each context entry is a list with a symbol naming the context, and
28002 two positions indicating start and end of the context. Possible
28003 contexts are:
28005 :headline anywhere in a headline
28006 :headline-stars on the leading stars in a headline
28007 :todo-keyword on a TODO keyword (including DONE) in a headline
28008 :tags on the TAGS in a headline
28009 :priority on the priority cookie in a headline
28010 :item on the first line of a plain list item
28011 :item-bullet on the bullet/number of a plain list item
28012 :checkbox on the checkbox in a plain list item
28013 :table in an org-mode table
28014 :table-special on a special filed in a table
28015 :table-table in a table.el table
28016 :link on a hyperlink
28017 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
28018 :target on a <<target>>
28019 :radio-target on a <<<radio-target>>>
28020 :latex-fragment on a LaTeX fragment
28021 :latex-preview on a LaTeX fragment with overlayed preview image
28023 This function expects the position to be visible because it uses font-lock
28024 faces as a help to recognize the following contexts: :table-special, :link,
28025 and :keyword."
28026 (let* ((f (get-text-property (point) 'face))
28027 (faces (if (listp f) f (list f)))
28028 (p (point)) clist o)
28029 ;; First the large context
28030 (cond
28031 ((org-on-heading-p t)
28032 (push (list :headline (point-at-bol) (point-at-eol)) clist)
28033 (when (progn
28034 (beginning-of-line 1)
28035 (looking-at org-todo-line-tags-regexp))
28036 (push (org-point-in-group p 1 :headline-stars) clist)
28037 (push (org-point-in-group p 2 :todo-keyword) clist)
28038 (push (org-point-in-group p 4 :tags) clist))
28039 (goto-char p)
28040 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
28041 (if (looking-at "\\[#[A-Z0-9]\\]")
28042 (push (org-point-in-group p 0 :priority) clist)))
28044 ((org-at-item-p)
28045 (push (org-point-in-group p 2 :item-bullet) clist)
28046 (push (list :item (point-at-bol)
28047 (save-excursion (org-end-of-item) (point)))
28048 clist)
28049 (and (org-at-item-checkbox-p)
28050 (push (org-point-in-group p 0 :checkbox) clist)))
28052 ((org-at-table-p)
28053 (push (list :table (org-table-begin) (org-table-end)) clist)
28054 (if (memq 'org-formula faces)
28055 (push (list :table-special
28056 (previous-single-property-change p 'face)
28057 (next-single-property-change p 'face)) clist)))
28058 ((org-at-table-p 'any)
28059 (push (list :table-table) clist)))
28060 (goto-char p)
28062 ;; Now the small context
28063 (cond
28064 ((org-at-timestamp-p)
28065 (push (org-point-in-group p 0 :timestamp) clist))
28066 ((memq 'org-link faces)
28067 (push (list :link
28068 (previous-single-property-change p 'face)
28069 (next-single-property-change p 'face)) clist))
28070 ((memq 'org-special-keyword faces)
28071 (push (list :keyword
28072 (previous-single-property-change p 'face)
28073 (next-single-property-change p 'face)) clist))
28074 ((org-on-target-p)
28075 (push (org-point-in-group p 0 :target) clist)
28076 (goto-char (1- (match-beginning 0)))
28077 (if (looking-at org-radio-target-regexp)
28078 (push (org-point-in-group p 0 :radio-target) clist))
28079 (goto-char p))
28080 ((setq o (car (delq nil
28081 (mapcar
28082 (lambda (x)
28083 (if (memq x org-latex-fragment-image-overlays) x))
28084 (org-overlays-at (point))))))
28085 (push (list :latex-fragment
28086 (org-overlay-start o) (org-overlay-end o)) clist)
28087 (push (list :latex-preview
28088 (org-overlay-start o) (org-overlay-end o)) clist))
28089 ((org-inside-LaTeX-fragment-p)
28090 ;; FIXME: positions wrong.
28091 (push (list :latex-fragment (point) (point)) clist)))
28093 (setq clist (nreverse (delq nil clist)))
28094 clist))
28096 ;; FIXME: Compare with at-regexp-p Do we need both?
28097 (defun org-in-regexp (re &optional nlines visually)
28098 "Check if point is inside a match of regexp.
28099 Normally only the current line is checked, but you can include NLINES extra
28100 lines both before and after point into the search.
28101 If VISUALLY is set, require that the cursor is not after the match but
28102 really on, so that the block visually is on the match."
28103 (catch 'exit
28104 (let ((pos (point))
28105 (eol (point-at-eol (+ 1 (or nlines 0))))
28106 (inc (if visually 1 0)))
28107 (save-excursion
28108 (beginning-of-line (- 1 (or nlines 0)))
28109 (while (re-search-forward re eol t)
28110 (if (and (<= (match-beginning 0) pos)
28111 (>= (+ inc (match-end 0)) pos))
28112 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
28114 (defun org-at-regexp-p (regexp)
28115 "Is point inside a match of REGEXP in the current line?"
28116 (catch 'exit
28117 (save-excursion
28118 (let ((pos (point)) (end (point-at-eol)))
28119 (beginning-of-line 1)
28120 (while (re-search-forward regexp end t)
28121 (if (and (<= (match-beginning 0) pos)
28122 (>= (match-end 0) pos))
28123 (throw 'exit t)))
28124 nil))))
28126 (defun org-occur-in-agenda-files (regexp &optional nlines)
28127 "Call `multi-occur' with buffers for all agenda files."
28128 (interactive "sOrg-files matching: \np")
28129 (let* ((files (org-agenda-files))
28130 (tnames (mapcar 'file-truename files))
28131 (extra org-agenda-text-search-extra-files)
28133 (while (setq f (pop extra))
28134 (unless (member (file-truename f) tnames)
28135 (add-to-list 'files f 'append)
28136 (add-to-list 'tnames (file-truename f) 'append)))
28137 (multi-occur
28138 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
28139 regexp)))
28141 (if (boundp 'occur-mode-find-occurrence-hook)
28142 ;; Emacs 23
28143 (add-hook 'occur-mode-find-occurrence-hook
28144 (lambda ()
28145 (when (org-mode-p)
28146 (org-reveal))))
28147 ;; Emacs 22
28148 (defadvice occur-mode-goto-occurrence
28149 (after org-occur-reveal activate)
28150 (and (org-mode-p) (org-reveal)))
28151 (defadvice occur-mode-goto-occurrence-other-window
28152 (after org-occur-reveal activate)
28153 (and (org-mode-p) (org-reveal)))
28154 (defadvice occur-mode-display-occurrence
28155 (after org-occur-reveal activate)
28156 (when (org-mode-p)
28157 (let ((pos (occur-mode-find-occurrence)))
28158 (with-current-buffer (marker-buffer pos)
28159 (save-excursion
28160 (goto-char pos)
28161 (org-reveal)))))))
28163 (defun org-uniquify (list)
28164 "Remove duplicate elements from LIST."
28165 (let (res)
28166 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
28167 res))
28169 (defun org-delete-all (elts list)
28170 "Remove all elements in ELTS from LIST."
28171 (while elts
28172 (setq list (delete (pop elts) list)))
28173 list)
28175 (defun org-back-over-empty-lines ()
28176 "Move backwards over witespace, to the beginning of the first empty line.
28177 Returns the number o empty lines passed."
28178 (let ((pos (point)))
28179 (skip-chars-backward " \t\n\r")
28180 (beginning-of-line 2)
28181 (goto-char (min (point) pos))
28182 (count-lines (point) pos)))
28184 (defun org-skip-whitespace ()
28185 (skip-chars-forward " \t\n\r"))
28187 (defun org-point-in-group (point group &optional context)
28188 "Check if POINT is in match-group GROUP.
28189 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
28190 match. If the match group does ot exist or point is not inside it,
28191 return nil."
28192 (and (match-beginning group)
28193 (>= point (match-beginning group))
28194 (<= point (match-end group))
28195 (if context
28196 (list context (match-beginning group) (match-end group))
28197 t)))
28199 (defun org-switch-to-buffer-other-window (&rest args)
28200 "Switch to buffer in a second window on the current frame.
28201 In particular, do not allow pop-up frames."
28202 (let (pop-up-frames special-display-buffer-names special-display-regexps
28203 special-display-function)
28204 (apply 'switch-to-buffer-other-window args)))
28206 (defun org-combine-plists (&rest plists)
28207 "Create a single property list from all plists in PLISTS.
28208 The process starts by copying the first list, and then setting properties
28209 from the other lists. Settings in the last list are the most significant
28210 ones and overrule settings in the other lists."
28211 (let ((rtn (copy-sequence (pop plists)))
28212 p v ls)
28213 (while plists
28214 (setq ls (pop plists))
28215 (while ls
28216 (setq p (pop ls) v (pop ls))
28217 (setq rtn (plist-put rtn p v))))
28218 rtn))
28220 (defun org-move-line-down (arg)
28221 "Move the current line down. With prefix argument, move it past ARG lines."
28222 (interactive "p")
28223 (let ((col (current-column))
28224 beg end pos)
28225 (beginning-of-line 1) (setq beg (point))
28226 (beginning-of-line 2) (setq end (point))
28227 (beginning-of-line (+ 1 arg))
28228 (setq pos (move-marker (make-marker) (point)))
28229 (insert (delete-and-extract-region beg end))
28230 (goto-char pos)
28231 (move-to-column col)))
28233 (defun org-move-line-up (arg)
28234 "Move the current line up. With prefix argument, move it past ARG lines."
28235 (interactive "p")
28236 (let ((col (current-column))
28237 beg end pos)
28238 (beginning-of-line 1) (setq beg (point))
28239 (beginning-of-line 2) (setq end (point))
28240 (beginning-of-line (- arg))
28241 (setq pos (move-marker (make-marker) (point)))
28242 (insert (delete-and-extract-region beg end))
28243 (goto-char pos)
28244 (move-to-column col)))
28246 (defun org-replace-escapes (string table)
28247 "Replace %-escapes in STRING with values in TABLE.
28248 TABLE is an association list with keys like \"%a\" and string values.
28249 The sequences in STRING may contain normal field width and padding information,
28250 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
28251 so values can contain further %-escapes if they are define later in TABLE."
28252 (let ((case-fold-search nil)
28253 e re rpl)
28254 (while (setq e (pop table))
28255 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
28256 (while (string-match re string)
28257 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
28258 (cdr e)))
28259 (setq string (replace-match rpl t t string))))
28260 string))
28263 (defun org-sublist (list start end)
28264 "Return a section of LIST, from START to END.
28265 Counting starts at 1."
28266 (let (rtn (c start))
28267 (setq list (nthcdr (1- start) list))
28268 (while (and list (<= c end))
28269 (push (pop list) rtn)
28270 (setq c (1+ c)))
28271 (nreverse rtn)))
28273 (defun org-find-base-buffer-visiting (file)
28274 "Like `find-buffer-visiting' but alway return the base buffer and
28275 not an indirect buffer"
28276 (let ((buf (find-buffer-visiting file)))
28277 (if buf
28278 (or (buffer-base-buffer buf) buf)
28279 nil)))
28281 (defun org-image-file-name-regexp ()
28282 "Return regexp matching the file names of images."
28283 (if (fboundp 'image-file-name-regexp)
28284 (image-file-name-regexp)
28285 (let ((image-file-name-extensions
28286 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
28287 "xbm" "xpm" "pbm" "pgm" "ppm")))
28288 (concat "\\."
28289 (regexp-opt (nconc (mapcar 'upcase
28290 image-file-name-extensions)
28291 image-file-name-extensions)
28293 "\\'"))))
28295 (defun org-file-image-p (file)
28296 "Return non-nil if FILE is an image."
28297 (save-match-data
28298 (string-match (org-image-file-name-regexp) file)))
28300 ;;; Paragraph filling stuff.
28301 ;; We want this to be just right, so use the full arsenal.
28303 (defun org-indent-line-function ()
28304 "Indent line like previous, but further if previous was headline or item."
28305 (interactive)
28306 (let* ((pos (point))
28307 (itemp (org-at-item-p))
28308 column bpos bcol tpos tcol bullet btype bullet-type)
28309 ;; Find the previous relevant line
28310 (beginning-of-line 1)
28311 (cond
28312 ((looking-at "#") (setq column 0))
28313 ((looking-at "\\*+ ") (setq column 0))
28315 (beginning-of-line 0)
28316 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
28317 (beginning-of-line 0))
28318 (cond
28319 ((looking-at "\\*+[ \t]+")
28320 (goto-char (match-end 0))
28321 (setq column (current-column)))
28322 ((org-in-item-p)
28323 (org-beginning-of-item)
28324 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28325 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
28326 (setq bpos (match-beginning 1) tpos (match-end 0)
28327 bcol (progn (goto-char bpos) (current-column))
28328 tcol (progn (goto-char tpos) (current-column))
28329 bullet (match-string 1)
28330 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
28331 (if (not itemp)
28332 (setq column tcol)
28333 (goto-char pos)
28334 (beginning-of-line 1)
28335 (if (looking-at "\\S-")
28336 (progn
28337 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28338 (setq bullet (match-string 1)
28339 btype (if (string-match "[0-9]" bullet) "n" bullet))
28340 (setq column (if (equal btype bullet-type) bcol tcol)))
28341 (setq column (org-get-indentation)))))
28342 (t (setq column (org-get-indentation))))))
28343 (goto-char pos)
28344 (if (<= (current-column) (current-indentation))
28345 (indent-line-to column)
28346 (save-excursion (indent-line-to column)))
28347 (setq column (current-column))
28348 (beginning-of-line 1)
28349 (if (looking-at
28350 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
28351 (replace-match (concat "\\1" (format org-property-format
28352 (match-string 2) (match-string 3)))
28353 t nil))
28354 (move-to-column column)))
28356 (defun org-set-autofill-regexps ()
28357 (interactive)
28358 ;; In the paragraph separator we include headlines, because filling
28359 ;; text in a line directly attached to a headline would otherwise
28360 ;; fill the headline as well.
28361 (org-set-local 'comment-start-skip "^#+[ \t]*")
28362 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
28363 ;; The paragraph starter includes hand-formatted lists.
28364 (org-set-local 'paragraph-start
28365 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
28366 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
28367 ;; But only if the user has not turned off tables or fixed-width regions
28368 (org-set-local
28369 'auto-fill-inhibit-regexp
28370 (concat "\\*+ \\|#\\+"
28371 "\\|[ \t]*" org-keyword-time-regexp
28372 (if (or org-enable-table-editor org-enable-fixed-width-editor)
28373 (concat
28374 "\\|[ \t]*["
28375 (if org-enable-table-editor "|" "")
28376 (if org-enable-fixed-width-editor ":" "")
28377 "]"))))
28378 ;; We use our own fill-paragraph function, to make sure that tables
28379 ;; and fixed-width regions are not wrapped. That function will pass
28380 ;; through to `fill-paragraph' when appropriate.
28381 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
28382 ; Adaptive filling: To get full control, first make sure that
28383 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
28384 (org-set-local 'adaptive-fill-regexp "\000")
28385 (org-set-local 'adaptive-fill-function
28386 'org-adaptive-fill-function)
28387 (org-set-local
28388 'align-mode-rules-list
28389 '((org-in-buffer-settings
28390 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
28391 (modes . '(org-mode))))))
28393 (defun org-fill-paragraph (&optional justify)
28394 "Re-align a table, pass through to fill-paragraph if no table."
28395 (let ((table-p (org-at-table-p))
28396 (table.el-p (org-at-table.el-p)))
28397 (cond ((and (equal (char-after (point-at-bol)) ?*)
28398 (save-excursion (goto-char (point-at-bol))
28399 (looking-at outline-regexp)))
28400 t) ; skip headlines
28401 (table.el-p t) ; skip table.el tables
28402 (table-p (org-table-align) t) ; align org-mode tables
28403 (t nil)))) ; call paragraph-fill
28405 ;; For reference, this is the default value of adaptive-fill-regexp
28406 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
28408 (defun org-adaptive-fill-function ()
28409 "Return a fill prefix for org-mode files.
28410 In particular, this makes sure hanging paragraphs for hand-formatted lists
28411 work correctly."
28412 (cond ((looking-at "#[ \t]+")
28413 (match-string 0))
28414 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
28415 (save-excursion
28416 (goto-char (match-end 0))
28417 (make-string (current-column) ?\ )))
28418 (t nil)))
28420 ;;;; Functions extending outline functionality
28423 (defun org-beginning-of-line (&optional arg)
28424 "Go to the beginning of the current line. If that is invisible, continue
28425 to a visible line beginning. This makes the function of C-a more intuitive.
28426 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28427 first attempt, and only move to after the tags when the cursor is already
28428 beyond the end of the headline."
28429 (interactive "P")
28430 (let ((pos (point)))
28431 (beginning-of-line 1)
28432 (if (bobp)
28434 (backward-char 1)
28435 (if (org-invisible-p)
28436 (while (and (not (bobp)) (org-invisible-p))
28437 (backward-char 1)
28438 (beginning-of-line 1))
28439 (forward-char 1)))
28440 (when org-special-ctrl-a/e
28441 (cond
28442 ((and (looking-at org-todo-line-regexp)
28443 (= (char-after (match-end 1)) ?\ ))
28444 (goto-char
28445 (if (eq org-special-ctrl-a/e t)
28446 (cond ((> pos (match-beginning 3)) (match-beginning 3))
28447 ((= pos (point)) (match-beginning 3))
28448 (t (point)))
28449 (cond ((> pos (point)) (point))
28450 ((not (eq last-command this-command)) (point))
28451 (t (match-beginning 3))))))
28452 ((org-at-item-p)
28453 (goto-char
28454 (if (eq org-special-ctrl-a/e t)
28455 (cond ((> pos (match-end 4)) (match-end 4))
28456 ((= pos (point)) (match-end 4))
28457 (t (point)))
28458 (cond ((> pos (point)) (point))
28459 ((not (eq last-command this-command)) (point))
28460 (t (match-end 4))))))))))
28462 (defun org-end-of-line (&optional arg)
28463 "Go to the end of the line.
28464 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28465 first attempt, and only move to after the tags when the cursor is already
28466 beyond the end of the headline."
28467 (interactive "P")
28468 (if (or (not org-special-ctrl-a/e)
28469 (not (org-on-heading-p)))
28470 (end-of-line arg)
28471 (let ((pos (point)))
28472 (beginning-of-line 1)
28473 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
28474 (if (eq org-special-ctrl-a/e t)
28475 (if (or (< pos (match-beginning 1))
28476 (= pos (match-end 0)))
28477 (goto-char (match-beginning 1))
28478 (goto-char (match-end 0)))
28479 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
28480 (goto-char (match-end 0))
28481 (goto-char (match-beginning 1))))
28482 (end-of-line arg)))))
28484 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
28485 (define-key org-mode-map "\C-e" 'org-end-of-line)
28487 (defun org-kill-line (&optional arg)
28488 "Kill line, to tags or end of line."
28489 (interactive "P")
28490 (cond
28491 ((or (not org-special-ctrl-k)
28492 (bolp)
28493 (not (org-on-heading-p)))
28494 (call-interactively 'kill-line))
28495 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
28496 (kill-region (point) (match-beginning 1))
28497 (org-set-tags nil t))
28498 (t (kill-region (point) (point-at-eol)))))
28500 (define-key org-mode-map "\C-k" 'org-kill-line)
28502 (defun org-invisible-p ()
28503 "Check if point is at a character currently not visible."
28504 ;; Early versions of noutline don't have `outline-invisible-p'.
28505 (if (fboundp 'outline-invisible-p)
28506 (outline-invisible-p)
28507 (get-char-property (point) 'invisible)))
28509 (defun org-invisible-p2 ()
28510 "Check if point is at a character currently not visible."
28511 (save-excursion
28512 (if (and (eolp) (not (bobp))) (backward-char 1))
28513 ;; Early versions of noutline don't have `outline-invisible-p'.
28514 (if (fboundp 'outline-invisible-p)
28515 (outline-invisible-p)
28516 (get-char-property (point) 'invisible))))
28518 (defalias 'org-back-to-heading 'outline-back-to-heading)
28519 (defalias 'org-on-heading-p 'outline-on-heading-p)
28520 (defalias 'org-at-heading-p 'outline-on-heading-p)
28521 (defun org-at-heading-or-item-p ()
28522 (or (org-on-heading-p) (org-at-item-p)))
28524 (defun org-on-target-p ()
28525 (or (org-in-regexp org-radio-target-regexp)
28526 (org-in-regexp org-target-regexp)))
28528 (defun org-up-heading-all (arg)
28529 "Move to the heading line of which the present line is a subheading.
28530 This function considers both visible and invisible heading lines.
28531 With argument, move up ARG levels."
28532 (if (fboundp 'outline-up-heading-all)
28533 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28534 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28536 (defun org-up-heading-safe ()
28537 "Move to the heading line of which the present line is a subheading.
28538 This version will not throw an error. It will return the level of the
28539 headline found, or nil if no higher level is found."
28540 (let ((pos (point)) start-level level
28541 (re (concat "^" outline-regexp)))
28542 (catch 'exit
28543 (outline-back-to-heading t)
28544 (setq start-level (funcall outline-level))
28545 (if (equal start-level 1) (throw 'exit nil))
28546 (while (re-search-backward re nil t)
28547 (setq level (funcall outline-level))
28548 (if (< level start-level) (throw 'exit level)))
28549 nil)))
28551 (defun org-first-sibling-p ()
28552 "Is this heading the first child of its parents?"
28553 (interactive)
28554 (let ((re (concat "^" outline-regexp))
28555 level l)
28556 (unless (org-at-heading-p t)
28557 (error "Not at a heading"))
28558 (setq level (funcall outline-level))
28559 (save-excursion
28560 (if (not (re-search-backward re nil t))
28562 (setq l (funcall outline-level))
28563 (< l level)))))
28565 (defun org-goto-sibling (&optional previous)
28566 "Goto the next sibling, even if it is invisible.
28567 When PREVIOUS is set, go to the previous sibling instead. Returns t
28568 when a sibling was found. When none is found, return nil and don't
28569 move point."
28570 (let ((fun (if previous 're-search-backward 're-search-forward))
28571 (pos (point))
28572 (re (concat "^" outline-regexp))
28573 level l)
28574 (when (condition-case nil (org-back-to-heading t) (error nil))
28575 (setq level (funcall outline-level))
28576 (catch 'exit
28577 (or previous (forward-char 1))
28578 (while (funcall fun re nil t)
28579 (setq l (funcall outline-level))
28580 (when (< l level) (goto-char pos) (throw 'exit nil))
28581 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28582 (goto-char pos)
28583 nil))))
28585 (defun org-show-siblings ()
28586 "Show all siblings of the current headline."
28587 (save-excursion
28588 (while (org-goto-sibling) (org-flag-heading nil)))
28589 (save-excursion
28590 (while (org-goto-sibling 'previous)
28591 (org-flag-heading nil))))
28593 (defun org-show-hidden-entry ()
28594 "Show an entry where even the heading is hidden."
28595 (save-excursion
28596 (org-show-entry)))
28598 (defun org-flag-heading (flag &optional entry)
28599 "Flag the current heading. FLAG non-nil means make invisible.
28600 When ENTRY is non-nil, show the entire entry."
28601 (save-excursion
28602 (org-back-to-heading t)
28603 ;; Check if we should show the entire entry
28604 (if entry
28605 (progn
28606 (org-show-entry)
28607 (save-excursion
28608 (and (outline-next-heading)
28609 (org-flag-heading nil))))
28610 (outline-flag-region (max (point-min) (1- (point)))
28611 (save-excursion (outline-end-of-heading) (point))
28612 flag))))
28614 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28615 ;; This is an exact copy of the original function, but it uses
28616 ;; `org-back-to-heading', to make it work also in invisible
28617 ;; trees. And is uses an invisible-OK argument.
28618 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28619 (org-back-to-heading invisible-OK)
28620 (let ((first t)
28621 (level (funcall outline-level)))
28622 (while (and (not (eobp))
28623 (or first (> (funcall outline-level) level)))
28624 (setq first nil)
28625 (outline-next-heading))
28626 (unless to-heading
28627 (if (memq (preceding-char) '(?\n ?\^M))
28628 (progn
28629 ;; Go to end of line before heading
28630 (forward-char -1)
28631 (if (memq (preceding-char) '(?\n ?\^M))
28632 ;; leave blank line before heading
28633 (forward-char -1))))))
28634 (point))
28636 (defun org-show-subtree ()
28637 "Show everything after this heading at deeper levels."
28638 (outline-flag-region
28639 (point)
28640 (save-excursion
28641 (outline-end-of-subtree) (outline-next-heading) (point))
28642 nil))
28644 (defun org-show-entry ()
28645 "Show the body directly following this heading.
28646 Show the heading too, if it is currently invisible."
28647 (interactive)
28648 (save-excursion
28649 (condition-case nil
28650 (progn
28651 (org-back-to-heading t)
28652 (outline-flag-region
28653 (max (point-min) (1- (point)))
28654 (save-excursion
28655 (re-search-forward
28656 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28657 (or (match-beginning 1) (point-max)))
28658 nil))
28659 (error nil))))
28661 (defun org-make-options-regexp (kwds)
28662 "Make a regular expression for keyword lines."
28663 (concat
28665 "#?[ \t]*\\+\\("
28666 (mapconcat 'regexp-quote kwds "\\|")
28667 "\\):[ \t]*"
28668 "\\(.+\\)"))
28670 ;; Make isearch reveal the necessary context
28671 (defun org-isearch-end ()
28672 "Reveal context after isearch exits."
28673 (when isearch-success ; only if search was successful
28674 (if (featurep 'xemacs)
28675 ;; Under XEmacs, the hook is run in the correct place,
28676 ;; we directly show the context.
28677 (org-show-context 'isearch)
28678 ;; In Emacs the hook runs *before* restoring the overlays.
28679 ;; So we have to use a one-time post-command-hook to do this.
28680 ;; (Emacs 22 has a special variable, see function `org-mode')
28681 (unless (and (boundp 'isearch-mode-end-hook-quit)
28682 isearch-mode-end-hook-quit)
28683 ;; Only when the isearch was not quitted.
28684 (org-add-hook 'post-command-hook 'org-isearch-post-command
28685 'append 'local)))))
28687 (defun org-isearch-post-command ()
28688 "Remove self from hook, and show context."
28689 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28690 (org-show-context 'isearch))
28693 ;;;; Integration with and fixes for other packages
28695 ;;; Imenu support
28697 (defvar org-imenu-markers nil
28698 "All markers currently used by Imenu.")
28699 (make-variable-buffer-local 'org-imenu-markers)
28701 (defun org-imenu-new-marker (&optional pos)
28702 "Return a new marker for use by Imenu, and remember the marker."
28703 (let ((m (make-marker)))
28704 (move-marker m (or pos (point)))
28705 (push m org-imenu-markers)
28708 (defun org-imenu-get-tree ()
28709 "Produce the index for Imenu."
28710 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28711 (setq org-imenu-markers nil)
28712 (let* ((n org-imenu-depth)
28713 (re (concat "^" outline-regexp))
28714 (subs (make-vector (1+ n) nil))
28715 (last-level 0)
28716 m tree level head)
28717 (save-excursion
28718 (save-restriction
28719 (widen)
28720 (goto-char (point-max))
28721 (while (re-search-backward re nil t)
28722 (setq level (org-reduced-level (funcall outline-level)))
28723 (when (<= level n)
28724 (looking-at org-complex-heading-regexp)
28725 (setq head (org-match-string-no-properties 4)
28726 m (org-imenu-new-marker))
28727 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28728 (if (>= level last-level)
28729 (push (cons head m) (aref subs level))
28730 (push (cons head (aref subs (1+ level))) (aref subs level))
28731 (loop for i from (1+ level) to n do (aset subs i nil)))
28732 (setq last-level level)))))
28733 (aref subs 1)))
28735 (eval-after-load "imenu"
28736 '(progn
28737 (add-hook 'imenu-after-jump-hook
28738 (lambda () (org-show-context 'org-goto)))))
28740 ;; Speedbar support
28742 (defun org-speedbar-set-agenda-restriction ()
28743 "Restrict future agenda commands to the location at point in speedbar.
28744 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28745 (interactive)
28746 (let (p m tp np dir txt w)
28747 (cond
28748 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28749 'org-imenu t))
28750 (setq m (get-text-property p 'org-imenu-marker))
28751 (save-excursion
28752 (save-restriction
28753 (set-buffer (marker-buffer m))
28754 (goto-char m)
28755 (org-agenda-set-restriction-lock 'subtree))))
28756 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28757 'speedbar-function 'speedbar-find-file))
28758 (setq tp (previous-single-property-change
28759 (1+ p) 'speedbar-function)
28760 np (next-single-property-change
28761 tp 'speedbar-function)
28762 dir (speedbar-line-directory)
28763 txt (buffer-substring-no-properties (or tp (point-min))
28764 (or np (point-max))))
28765 (save-excursion
28766 (save-restriction
28767 (set-buffer (find-file-noselect
28768 (let ((default-directory dir))
28769 (expand-file-name txt))))
28770 (unless (org-mode-p)
28771 (error "Cannot restrict to non-Org-mode file"))
28772 (org-agenda-set-restriction-lock 'file))))
28773 (t (error "Don't know how to restrict Org-mode's agenda")))
28774 (org-move-overlay org-speedbar-restriction-lock-overlay
28775 (point-at-bol) (point-at-eol))
28776 (setq current-prefix-arg nil)
28777 (org-agenda-maybe-redo)))
28779 (eval-after-load "speedbar"
28780 '(progn
28781 (speedbar-add-supported-extension ".org")
28782 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28783 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28784 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28785 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28786 (add-hook 'speedbar-visiting-tag-hook
28787 (lambda () (org-show-context 'org-goto)))))
28790 ;;; Fixes and Hacks
28792 ;; Make flyspell not check words in links, to not mess up our keymap
28793 (defun org-mode-flyspell-verify ()
28794 "Don't let flyspell put overlays at active buttons."
28795 (not (get-text-property (point) 'keymap)))
28797 ;; Make `bookmark-jump' show the jump location if it was hidden.
28798 (eval-after-load "bookmark"
28799 '(if (boundp 'bookmark-after-jump-hook)
28800 ;; We can use the hook
28801 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28802 ;; Hook not available, use advice
28803 (defadvice bookmark-jump (after org-make-visible activate)
28804 "Make the position visible."
28805 (org-bookmark-jump-unhide))))
28807 (defun org-bookmark-jump-unhide ()
28808 "Unhide the current position, to show the bookmark location."
28809 (and (org-mode-p)
28810 (or (org-invisible-p)
28811 (save-excursion (goto-char (max (point-min) (1- (point))))
28812 (org-invisible-p)))
28813 (org-show-context 'bookmark-jump)))
28815 ;; Make session.el ignore our circular variable
28816 (eval-after-load "session"
28817 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28819 ;;;; Experimental code
28821 (defun org-closed-in-range ()
28822 "Sparse tree of items closed in a certain time range.
28823 Still experimental, may disappear in the future."
28824 (interactive)
28825 ;; Get the time interval from the user.
28826 (let* ((time1 (time-to-seconds
28827 (org-read-date nil 'to-time nil "Starting date: ")))
28828 (time2 (time-to-seconds
28829 (org-read-date nil 'to-time nil "End date:")))
28830 ;; callback function
28831 (callback (lambda ()
28832 (let ((time
28833 (time-to-seconds
28834 (apply 'encode-time
28835 (org-parse-time-string
28836 (match-string 1))))))
28837 ;; check if time in interval
28838 (and (>= time time1) (<= time time2))))))
28839 ;; make tree, check each match with the callback
28840 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28842 ;;;; Finish up
28844 (provide 'org)
28846 (run-hooks 'org-load-hook)
28848 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28849 ;;; org.el ends here