Documentation of the new :link parameter in clock tables.
[org-mode.git] / org.el
blobc29fca1f8310dce0f90e0f97debd009d996686b6
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, valid 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-valid-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 (define-obsolete-function-alias 'org-get-legal-level
6561 'org-get-valid-level "23.1")
6563 (defun org-promote ()
6564 "Promote the current heading higher up the tree.
6565 If the region is active in `transient-mark-mode', promote all headings
6566 in the region."
6567 (org-back-to-heading t)
6568 (let* ((level (save-match-data (funcall outline-level)))
6569 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6570 (diff (abs (- level (length up-head) -1))))
6571 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6572 (replace-match up-head nil t)
6573 ;; Fixup tag positioning
6574 (and org-auto-align-tags (org-set-tags nil t))
6575 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6577 (defun org-demote ()
6578 "Demote the current heading lower down the tree.
6579 If the region is active in `transient-mark-mode', demote all headings
6580 in the region."
6581 (org-back-to-heading t)
6582 (let* ((level (save-match-data (funcall outline-level)))
6583 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6584 (diff (abs (- level (length down-head) -1))))
6585 (replace-match down-head nil t)
6586 ;; Fixup tag positioning
6587 (and org-auto-align-tags (org-set-tags nil t))
6588 (if org-adapt-indentation (org-fixup-indentation diff))))
6590 (defun org-map-tree (fun)
6591 "Call FUN for every heading underneath the current one."
6592 (org-back-to-heading)
6593 (let ((level (funcall outline-level)))
6594 (save-excursion
6595 (funcall fun)
6596 (while (and (progn
6597 (outline-next-heading)
6598 (> (funcall outline-level) level))
6599 (not (eobp)))
6600 (funcall fun)))))
6602 (defun org-map-region (fun beg end)
6603 "Call FUN for every heading between BEG and END."
6604 (let ((org-ignore-region t))
6605 (save-excursion
6606 (setq end (copy-marker end))
6607 (goto-char beg)
6608 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6609 (< (point) end))
6610 (funcall fun))
6611 (while (and (progn
6612 (outline-next-heading)
6613 (< (point) end))
6614 (not (eobp)))
6615 (funcall fun)))))
6617 (defun org-fixup-indentation (diff)
6618 "Change the indentation in the current entry by DIFF
6619 However, if any line in the current entry has no indentation, or if it
6620 would end up with no indentation after the change, nothing at all is done."
6621 (save-excursion
6622 (let ((end (save-excursion (outline-next-heading)
6623 (point-marker)))
6624 (prohibit (if (> diff 0)
6625 "^\\S-"
6626 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6627 col)
6628 (unless (save-excursion (end-of-line 1)
6629 (re-search-forward prohibit end t))
6630 (while (and (< (point) end)
6631 (re-search-forward "^[ \t]+" end t))
6632 (goto-char (match-end 0))
6633 (setq col (current-column))
6634 (if (< diff 0) (replace-match ""))
6635 (indent-to (+ diff col))))
6636 (move-marker end nil))))
6638 (defun org-convert-to-odd-levels ()
6639 "Convert an org-mode file with all levels allowed to one with odd levels.
6640 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6641 level 5 etc."
6642 (interactive)
6643 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6644 (let ((org-odd-levels-only nil) n)
6645 (save-excursion
6646 (goto-char (point-min))
6647 (while (re-search-forward "^\\*\\*+ " nil t)
6648 (setq n (- (length (match-string 0)) 2))
6649 (while (>= (setq n (1- n)) 0)
6650 (org-demote))
6651 (end-of-line 1))))))
6654 (defun org-convert-to-oddeven-levels ()
6655 "Convert an org-mode file with only odd levels to one with odd and even levels.
6656 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6657 section with an even level, conversion would destroy the structure of the file. An error
6658 is signaled in this case."
6659 (interactive)
6660 (goto-char (point-min))
6661 ;; First check if there are no even levels
6662 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6663 (org-show-context t)
6664 (error "Not all levels are odd in this file. Conversion not possible."))
6665 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6666 (let ((org-odd-levels-only nil) n)
6667 (save-excursion
6668 (goto-char (point-min))
6669 (while (re-search-forward "^\\*\\*+ " nil t)
6670 (setq n (/ (1- (length (match-string 0))) 2))
6671 (while (>= (setq n (1- n)) 0)
6672 (org-promote))
6673 (end-of-line 1))))))
6675 (defun org-tr-level (n)
6676 "Make N odd if required."
6677 (if org-odd-levels-only (1+ (/ n 2)) n))
6679 ;;; Vertical tree motion, cutting and pasting of subtrees
6681 (defun org-move-subtree-up (&optional arg)
6682 "Move the current subtree up past ARG headlines of the same level."
6683 (interactive "p")
6684 (org-move-subtree-down (- (prefix-numeric-value arg))))
6686 (defun org-move-subtree-down (&optional arg)
6687 "Move the current subtree down past ARG headlines of the same level."
6688 (interactive "p")
6689 (setq arg (prefix-numeric-value arg))
6690 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6691 'outline-get-last-sibling))
6692 (ins-point (make-marker))
6693 (cnt (abs arg))
6694 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6695 ;; Select the tree
6696 (org-back-to-heading)
6697 (setq beg0 (point))
6698 (save-excursion
6699 (setq ne-beg (org-back-over-empty-lines))
6700 (setq beg (point)))
6701 (save-match-data
6702 (save-excursion (outline-end-of-heading)
6703 (setq folded (org-invisible-p)))
6704 (outline-end-of-subtree))
6705 (outline-next-heading)
6706 (setq ne-end (org-back-over-empty-lines))
6707 (setq end (point))
6708 (goto-char beg0)
6709 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6710 ;; include less whitespace
6711 (save-excursion
6712 (goto-char beg)
6713 (forward-line (- ne-beg ne-end))
6714 (setq beg (point))))
6715 ;; Find insertion point, with error handling
6716 (while (> cnt 0)
6717 (or (and (funcall movfunc) (looking-at outline-regexp))
6718 (progn (goto-char beg0)
6719 (error "Cannot move past superior level or buffer limit")))
6720 (setq cnt (1- cnt)))
6721 (if (> arg 0)
6722 ;; Moving forward - still need to move over subtree
6723 (progn (org-end-of-subtree t t)
6724 (save-excursion
6725 (org-back-over-empty-lines)
6726 (or (bolp) (newline)))))
6727 (setq ne-ins (org-back-over-empty-lines))
6728 (move-marker ins-point (point))
6729 (setq txt (buffer-substring beg end))
6730 (delete-region beg end)
6731 (outline-flag-region (1- beg) beg nil)
6732 (outline-flag-region (1- (point)) (point) nil)
6733 (insert txt)
6734 (or (bolp) (insert "\n"))
6735 (setq ins-end (point))
6736 (goto-char ins-point)
6737 (org-skip-whitespace)
6738 (when (and (< arg 0)
6739 (org-first-sibling-p)
6740 (> ne-ins ne-beg))
6741 ;; Move whitespace back to beginning
6742 (save-excursion
6743 (goto-char ins-end)
6744 (let ((kill-whole-line t))
6745 (kill-line (- ne-ins ne-beg)) (point)))
6746 (insert (make-string (- ne-ins ne-beg) ?\n)))
6747 (move-marker ins-point nil)
6748 (org-compact-display-after-subtree-move)
6749 (unless folded
6750 (org-show-entry)
6751 (show-children)
6752 (org-cycle-hide-drawers 'children))))
6754 (defvar org-subtree-clip ""
6755 "Clipboard for cut and paste of subtrees.
6756 This is actually only a copy of the kill, because we use the normal kill
6757 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6759 (defvar org-subtree-clip-folded nil
6760 "Was the last copied subtree folded?
6761 This is used to fold the tree back after pasting.")
6763 (defun org-cut-subtree (&optional n)
6764 "Cut the current subtree into the clipboard.
6765 With prefix arg N, cut this many sequential subtrees.
6766 This is a short-hand for marking the subtree and then cutting it."
6767 (interactive "p")
6768 (org-copy-subtree n 'cut))
6770 (defun org-copy-subtree (&optional n cut)
6771 "Cut the current subtree into the clipboard.
6772 With prefix arg N, cut this many sequential subtrees.
6773 This is a short-hand for marking the subtree and then copying it.
6774 If CUT is non-nil, actually cut the subtree."
6775 (interactive "p")
6776 (let (beg end folded (beg0 (point)))
6777 (if (interactive-p)
6778 (org-back-to-heading nil) ; take what looks like a subtree
6779 (org-back-to-heading t)) ; take what is really there
6780 (org-back-over-empty-lines)
6781 (setq beg (point))
6782 (skip-chars-forward " \t\r\n")
6783 (save-match-data
6784 (save-excursion (outline-end-of-heading)
6785 (setq folded (org-invisible-p)))
6786 (condition-case nil
6787 (outline-forward-same-level (1- n))
6788 (error nil))
6789 (org-end-of-subtree t t))
6790 (org-back-over-empty-lines)
6791 (setq end (point))
6792 (goto-char beg0)
6793 (when (> end beg)
6794 (setq org-subtree-clip-folded folded)
6795 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6796 (setq org-subtree-clip (current-kill 0))
6797 (message "%s: Subtree(s) with %d characters"
6798 (if cut "Cut" "Copied")
6799 (length org-subtree-clip)))))
6801 (defun org-paste-subtree (&optional level tree)
6802 "Paste the clipboard as a subtree, with modification of headline level.
6803 The entire subtree is promoted or demoted in order to match a new headline
6804 level. By default, the new level is derived from the visible headings
6805 before and after the insertion point, and taken to be the inferior headline
6806 level of the two. So if the previous visible heading is level 3 and the
6807 next is level 4 (or vice versa), level 4 will be used for insertion.
6808 This makes sure that the subtree remains an independent subtree and does
6809 not swallow low level entries.
6811 You can also force a different level, either by using a numeric prefix
6812 argument, or by inserting the heading marker by hand. For example, if the
6813 cursor is after \"*****\", then the tree will be shifted to level 5.
6815 If you want to insert the tree as is, just use \\[yank].
6817 If optional TREE is given, use this text instead of the kill ring."
6818 (interactive "P")
6819 (unless (org-kill-is-subtree-p tree)
6820 (error "%s"
6821 (substitute-command-keys
6822 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6823 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6824 (^re (concat "^\\(" outline-regexp "\\)"))
6825 (re (concat "\\(" outline-regexp "\\)"))
6826 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6828 (old-level (if (string-match ^re txt)
6829 (- (match-end 0) (match-beginning 0) 1)
6830 -1))
6831 (force-level (cond (level (prefix-numeric-value level))
6832 ((string-match
6833 ^re_ (buffer-substring (point-at-bol) (point)))
6834 (- (match-end 1) (match-beginning 1)))
6835 (t nil)))
6836 (previous-level (save-excursion
6837 (condition-case nil
6838 (progn
6839 (outline-previous-visible-heading 1)
6840 (if (looking-at re)
6841 (- (match-end 0) (match-beginning 0) 1)
6843 (error 1))))
6844 (next-level (save-excursion
6845 (condition-case nil
6846 (progn
6847 (or (looking-at outline-regexp)
6848 (outline-next-visible-heading 1))
6849 (if (looking-at re)
6850 (- (match-end 0) (match-beginning 0) 1)
6852 (error 1))))
6853 (new-level (or force-level (max previous-level next-level)))
6854 (shift (if (or (= old-level -1)
6855 (= new-level -1)
6856 (= old-level new-level))
6858 (- new-level old-level)))
6859 (delta (if (> shift 0) -1 1))
6860 (func (if (> shift 0) 'org-demote 'org-promote))
6861 (org-odd-levels-only nil)
6862 beg end)
6863 ;; Remove the forced level indicator
6864 (if force-level
6865 (delete-region (point-at-bol) (point)))
6866 ;; Paste
6867 (beginning-of-line 1)
6868 (org-back-over-empty-lines) ;; FIXME: correct fix????
6869 (setq beg (point))
6870 (insert-before-markers txt) ;; FIXME: correct fix????
6871 (unless (string-match "\n\\'" txt) (insert "\n"))
6872 (setq end (point))
6873 (goto-char beg)
6874 (skip-chars-forward " \t\n\r")
6875 (setq beg (point))
6876 ;; Shift if necessary
6877 (unless (= shift 0)
6878 (save-restriction
6879 (narrow-to-region beg end)
6880 (while (not (= shift 0))
6881 (org-map-region func (point-min) (point-max))
6882 (setq shift (+ delta shift)))
6883 (goto-char (point-min))))
6884 (when (interactive-p)
6885 (message "Clipboard pasted as level %d subtree" new-level))
6886 (if (and kill-ring
6887 (eq org-subtree-clip (current-kill 0))
6888 org-subtree-clip-folded)
6889 ;; The tree was folded before it was killed/copied
6890 (hide-subtree))))
6892 (defun org-kill-is-subtree-p (&optional txt)
6893 "Check if the current kill is an outline subtree, or a set of trees.
6894 Returns nil if kill does not start with a headline, or if the first
6895 headline level is not the largest headline level in the tree.
6896 So this will actually accept several entries of equal levels as well,
6897 which is OK for `org-paste-subtree'.
6898 If optional TXT is given, check this string instead of the current kill."
6899 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6900 (start-level (and kill
6901 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6902 org-outline-regexp "\\)")
6903 kill)
6904 (- (match-end 2) (match-beginning 2) 1)))
6905 (re (concat "^" org-outline-regexp))
6906 (start (1+ (match-beginning 2))))
6907 (if (not start-level)
6908 (progn
6909 nil) ;; does not even start with a heading
6910 (catch 'exit
6911 (while (setq start (string-match re kill (1+ start)))
6912 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6913 (throw 'exit nil)))
6914 t))))
6916 (defun org-narrow-to-subtree ()
6917 "Narrow buffer to the current subtree."
6918 (interactive)
6919 (save-excursion
6920 (save-match-data
6921 (narrow-to-region
6922 (progn (org-back-to-heading) (point))
6923 (progn (org-end-of-subtree t t) (point))))))
6926 ;;; Outline Sorting
6928 (defun org-sort (with-case)
6929 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6930 Optional argument WITH-CASE means sort case-sensitively."
6931 (interactive "P")
6932 (if (org-at-table-p)
6933 (org-call-with-arg 'org-table-sort-lines with-case)
6934 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6936 (defvar org-priority-regexp) ; defined later in the file
6938 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6939 "Sort entries on a certain level of an outline tree.
6940 If there is an active region, the entries in the region are sorted.
6941 Else, if the cursor is before the first entry, sort the top-level items.
6942 Else, the children of the entry at point are sorted.
6944 Sorting can be alphabetically, numerically, and by date/time as given by
6945 the first time stamp in the entry. The command prompts for the sorting
6946 type unless it has been given to the function through the SORTING-TYPE
6947 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6948 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6949 called with point at the beginning of the record. It must return either
6950 a string or a number that should serve as the sorting key for that record.
6952 Comparing entries ignores case by default. However, with an optional argument
6953 WITH-CASE, the sorting considers case as well."
6954 (interactive "P")
6955 (let ((case-func (if with-case 'identity 'downcase))
6956 start beg end stars re re2
6957 txt what tmp plain-list-p)
6958 ;; Find beginning and end of region to sort
6959 (cond
6960 ((org-region-active-p)
6961 ;; we will sort the region
6962 (setq end (region-end)
6963 what "region")
6964 (goto-char (region-beginning))
6965 (if (not (org-on-heading-p)) (outline-next-heading))
6966 (setq start (point)))
6967 ((org-at-item-p)
6968 ;; we will sort this plain list
6969 (org-beginning-of-item-list) (setq start (point))
6970 (org-end-of-item-list) (setq end (point))
6971 (goto-char start)
6972 (setq plain-list-p t
6973 what "plain list"))
6974 ((or (org-on-heading-p)
6975 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6976 ;; we will sort the children of the current headline
6977 (org-back-to-heading)
6978 (setq start (point)
6979 end (progn (org-end-of-subtree t t)
6980 (org-back-over-empty-lines)
6981 (point))
6982 what "children")
6983 (goto-char start)
6984 (show-subtree)
6985 (outline-next-heading))
6987 ;; we will sort the top-level entries in this file
6988 (goto-char (point-min))
6989 (or (org-on-heading-p) (outline-next-heading))
6990 (setq start (point) end (point-max) what "top-level")
6991 (goto-char start)
6992 (show-all)))
6994 (setq beg (point))
6995 (if (>= beg end) (error "Nothing to sort"))
6997 (unless plain-list-p
6998 (looking-at "\\(\\*+\\)")
6999 (setq stars (match-string 1)
7000 re (concat "^" (regexp-quote stars) " +")
7001 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7002 txt (buffer-substring beg end))
7003 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7004 (if (and (not (equal stars "*")) (string-match re2 txt))
7005 (error "Region to sort contains a level above the first entry")))
7007 (unless sorting-type
7008 (message
7009 (if plain-list-p
7010 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7011 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
7012 what)
7013 (setq sorting-type (read-char-exclusive))
7015 (and (= (downcase sorting-type) ?f)
7016 (setq getkey-func
7017 (completing-read "Sort using function: "
7018 obarray 'fboundp t nil nil))
7019 (setq getkey-func (intern getkey-func)))
7021 (and (= (downcase sorting-type) ?r)
7022 (setq property
7023 (completing-read "Property: "
7024 (mapcar 'list (org-buffer-property-keys t))
7025 nil t))))
7027 (message "Sorting entries...")
7029 (save-restriction
7030 (narrow-to-region start end)
7032 (let ((dcst (downcase sorting-type))
7033 (now (current-time)))
7034 (sort-subr
7035 (/= dcst sorting-type)
7036 ;; This function moves to the beginning character of the "record" to
7037 ;; be sorted.
7038 (if plain-list-p
7039 (lambda nil
7040 (if (org-at-item-p) t (goto-char (point-max))))
7041 (lambda nil
7042 (if (re-search-forward re nil t)
7043 (goto-char (match-beginning 0))
7044 (goto-char (point-max)))))
7045 ;; This function moves to the last character of the "record" being
7046 ;; sorted.
7047 (if plain-list-p
7048 'org-end-of-item
7049 (lambda nil
7050 (save-match-data
7051 (condition-case nil
7052 (outline-forward-same-level 1)
7053 (error
7054 (goto-char (point-max)))))))
7056 ;; This function returns the value that gets sorted against.
7057 (if plain-list-p
7058 (lambda nil
7059 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7060 (cond
7061 ((= dcst ?n)
7062 (string-to-number (buffer-substring (match-end 0)
7063 (point-at-eol))))
7064 ((= dcst ?a)
7065 (buffer-substring (match-end 0) (point-at-eol)))
7066 ((= dcst ?t)
7067 (if (re-search-forward org-ts-regexp
7068 (point-at-eol) t)
7069 (org-time-string-to-time (match-string 0))
7070 now))
7071 ((= dcst ?f)
7072 (if getkey-func
7073 (progn
7074 (setq tmp (funcall getkey-func))
7075 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7076 tmp)
7077 (error "Invalid key function `%s'" getkey-func)))
7078 (t (error "Invalid sorting type `%c'" sorting-type)))))
7079 (lambda nil
7080 (cond
7081 ((= dcst ?n)
7082 (if (looking-at outline-regexp)
7083 (string-to-number (buffer-substring (match-end 0)
7084 (point-at-eol)))
7085 nil))
7086 ((= dcst ?a)
7087 (funcall case-func (buffer-substring (point-at-bol)
7088 (point-at-eol))))
7089 ((= dcst ?t)
7090 (if (re-search-forward org-ts-regexp
7091 (save-excursion
7092 (forward-line 2)
7093 (point)) t)
7094 (org-time-string-to-time (match-string 0))
7095 now))
7096 ((= dcst ?p)
7097 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7098 (string-to-char (match-string 2))
7099 org-default-priority))
7100 ((= dcst ?r)
7101 (or (org-entry-get nil property) ""))
7102 ((= dcst ?f)
7103 (if getkey-func
7104 (progn
7105 (setq tmp (funcall getkey-func))
7106 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7107 tmp)
7108 (error "Invalid key function `%s'" getkey-func)))
7109 (t (error "Invalid sorting type `%c'" sorting-type)))))
7111 (cond
7112 ((= dcst ?a) 'string<)
7113 ((= dcst ?t) 'time-less-p)
7114 (t nil)))))
7115 (message "Sorting entries...done")))
7117 (defun org-do-sort (table what &optional with-case sorting-type)
7118 "Sort TABLE of WHAT according to SORTING-TYPE.
7119 The user will be prompted for the SORTING-TYPE if the call to this
7120 function does not specify it. WHAT is only for the prompt, to indicate
7121 what is being sorted. The sorting key will be extracted from
7122 the car of the elements of the table.
7123 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7124 (unless sorting-type
7125 (message
7126 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7127 what)
7128 (setq sorting-type (read-char-exclusive)))
7129 (let ((dcst (downcase sorting-type))
7130 extractfun comparefun)
7131 ;; Define the appropriate functions
7132 (cond
7133 ((= dcst ?n)
7134 (setq extractfun 'string-to-number
7135 comparefun (if (= dcst sorting-type) '< '>)))
7136 ((= dcst ?a)
7137 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7138 (lambda(x) (downcase (org-sort-remove-invisible x))))
7139 comparefun (if (= dcst sorting-type)
7140 'string<
7141 (lambda (a b) (and (not (string< a b))
7142 (not (string= a b)))))))
7143 ((= dcst ?t)
7144 (setq extractfun
7145 (lambda (x)
7146 (if (string-match org-ts-regexp x)
7147 (time-to-seconds
7148 (org-time-string-to-time (match-string 0 x)))
7150 comparefun (if (= dcst sorting-type) '< '>)))
7151 (t (error "Invalid sorting type `%c'" sorting-type)))
7153 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7154 table)
7155 (lambda (a b) (funcall comparefun (car a) (car b))))))
7157 ;;;; Plain list items, including checkboxes
7159 ;;; Plain list items
7161 (defun org-at-item-p ()
7162 "Is point in a line starting a hand-formatted item?"
7163 (let ((llt org-plain-list-ordered-item-terminator))
7164 (save-excursion
7165 (goto-char (point-at-bol))
7166 (looking-at
7167 (cond
7168 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7169 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7170 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7171 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7173 (defun org-in-item-p ()
7174 "It the cursor inside a plain list item.
7175 Does not have to be the first line."
7176 (save-excursion
7177 (condition-case nil
7178 (progn
7179 (org-beginning-of-item)
7180 (org-at-item-p)
7182 (error nil))))
7184 (defun org-insert-item (&optional checkbox)
7185 "Insert a new item at the current level.
7186 Return t when things worked, nil when we are not in an item."
7187 (when (save-excursion
7188 (condition-case nil
7189 (progn
7190 (org-beginning-of-item)
7191 (org-at-item-p)
7192 (if (org-invisible-p) (error "Invisible item"))
7194 (error nil)))
7195 (let* ((bul (match-string 0))
7196 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7197 (match-end 0)))
7198 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7199 pos)
7200 (cond
7201 ((and (org-at-item-p) (<= (point) eow))
7202 ;; before the bullet
7203 (beginning-of-line 1)
7204 (open-line (if blank 2 1)))
7205 ((<= (point) eow)
7206 (beginning-of-line 1))
7208 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7209 (end-of-line 1)
7210 (delete-horizontal-space))
7211 (newline (if blank 2 1))))
7212 (insert bul (if checkbox "[ ]" ""))
7213 (just-one-space)
7214 (setq pos (point))
7215 (end-of-line 1)
7216 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7217 (org-maybe-renumber-ordered-list)
7218 (and checkbox (org-update-checkbox-count-maybe))
7221 ;;; Checkboxes
7223 (defun org-at-item-checkbox-p ()
7224 "Is point at a line starting a plain-list item with a checklet?"
7225 (and (org-at-item-p)
7226 (save-excursion
7227 (goto-char (match-end 0))
7228 (skip-chars-forward " \t")
7229 (looking-at "\\[[- X]\\]"))))
7231 (defun org-toggle-checkbox (&optional arg)
7232 "Toggle the checkbox in the current line."
7233 (interactive "P")
7234 (catch 'exit
7235 (let (beg end status (firstnew 'unknown))
7236 (cond
7237 ((org-region-active-p)
7238 (setq beg (region-beginning) end (region-end)))
7239 ((org-on-heading-p)
7240 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7241 ((org-at-item-checkbox-p)
7242 (let ((pos (point)))
7243 (replace-match
7244 (cond (arg "[-]")
7245 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7246 (t "[ ]"))
7247 t t)
7248 (goto-char pos))
7249 (throw 'exit t))
7250 (t (error "Not at a checkbox or heading, and no active region")))
7251 (save-excursion
7252 (goto-char beg)
7253 (while (< (point) end)
7254 (when (org-at-item-checkbox-p)
7255 (setq status (equal (match-string 0) "[X]"))
7256 (when (eq firstnew 'unknown)
7257 (setq firstnew (not status)))
7258 (replace-match
7259 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7260 (beginning-of-line 2)))))
7261 (org-update-checkbox-count-maybe))
7263 (defun org-update-checkbox-count-maybe ()
7264 "Update checkbox statistics unless turned off by user."
7265 (when org-provide-checkbox-statistics
7266 (org-update-checkbox-count)))
7268 (defun org-update-checkbox-count (&optional all)
7269 "Update the checkbox statistics in the current section.
7270 This will find all statistic cookies like [57%] and [6/12] and update them
7271 with the current numbers. With optional prefix argument ALL, do this for
7272 the whole buffer."
7273 (interactive "P")
7274 (save-excursion
7275 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7276 (beg (condition-case nil
7277 (progn (outline-back-to-heading) (point))
7278 (error (point-min))))
7279 (end (move-marker (make-marker)
7280 (progn (outline-next-heading) (point))))
7281 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7282 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7283 (re-find (concat re "\\|" re-box))
7284 beg-cookie end-cookie is-percent c-on c-off lim
7285 eline curr-ind next-ind continue-from startsearch
7286 (cstat 0)
7288 (when all
7289 (goto-char (point-min))
7290 (outline-next-heading)
7291 (setq beg (point) end (point-max)))
7292 (goto-char end)
7293 ;; find each statistic cookie
7294 (while (re-search-backward re-find beg t)
7295 (setq beg-cookie (match-beginning 1)
7296 end-cookie (match-end 1)
7297 cstat (+ cstat (if end-cookie 1 0))
7298 startsearch (point-at-eol)
7299 continue-from (point-at-bol)
7300 is-percent (match-beginning 2)
7301 lim (cond
7302 ((org-on-heading-p) (outline-next-heading) (point))
7303 ((org-at-item-p) (org-end-of-item) (point))
7304 (t nil))
7305 c-on 0
7306 c-off 0)
7307 (when lim
7308 ;; find first checkbox for this cookie and gather
7309 ;; statistics from all that are at this indentation level
7310 (goto-char startsearch)
7311 (if (re-search-forward re-box lim t)
7312 (progn
7313 (org-beginning-of-item)
7314 (setq curr-ind (org-get-indentation))
7315 (setq next-ind curr-ind)
7316 (while (= curr-ind next-ind)
7317 (save-excursion (end-of-line) (setq eline (point)))
7318 (if (re-search-forward re-box eline t)
7319 (if (member (match-string 2) '("[ ]" "[-]"))
7320 (setq c-off (1+ c-off))
7321 (setq c-on (1+ c-on))
7324 (org-end-of-item)
7325 (setq next-ind (org-get-indentation))
7327 (goto-char continue-from)
7328 ;; update cookie
7329 (when end-cookie
7330 (delete-region beg-cookie end-cookie)
7331 (goto-char beg-cookie)
7332 (insert
7333 (if is-percent
7334 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7335 (format "[%d/%d]" c-on (+ c-on c-off)))))
7336 ;; update items checkbox if it has one
7337 (when (org-at-item-p)
7338 (org-beginning-of-item)
7339 (when (and (> (+ c-on c-off) 0)
7340 (re-search-forward re-box (point-at-eol) t))
7341 (setq beg-cookie (match-beginning 2)
7342 end-cookie (match-end 2))
7343 (delete-region beg-cookie end-cookie)
7344 (goto-char beg-cookie)
7345 (cond ((= c-off 0) (insert "[X]"))
7346 ((= c-on 0) (insert "[ ]"))
7347 (t (insert "[-]")))
7349 (goto-char continue-from))
7350 (when (interactive-p)
7351 (message "Checkbox satistics updated %s (%d places)"
7352 (if all "in entire file" "in current outline entry") cstat)))))
7354 (defun org-get-checkbox-statistics-face ()
7355 "Select the face for checkbox statistics.
7356 The face will be `org-done' when all relevant boxes are checked. Otherwise
7357 it will be `org-todo'."
7358 (if (match-end 1)
7359 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7360 (if (and (> (match-end 2) (match-beginning 2))
7361 (equal (match-string 2) (match-string 3)))
7362 'org-done
7363 'org-todo)))
7365 (defun org-get-indentation (&optional line)
7366 "Get the indentation of the current line, interpreting tabs.
7367 When LINE is given, assume it represents a line and compute its indentation."
7368 (if line
7369 (if (string-match "^ *" (org-remove-tabs line))
7370 (match-end 0))
7371 (save-excursion
7372 (beginning-of-line 1)
7373 (skip-chars-forward " \t")
7374 (current-column))))
7376 (defun org-remove-tabs (s &optional width)
7377 "Replace tabulators in S with spaces.
7378 Assumes that s is a single line, starting in column 0."
7379 (setq width (or width tab-width))
7380 (while (string-match "\t" s)
7381 (setq s (replace-match
7382 (make-string
7383 (- (* width (/ (+ (match-beginning 0) width) width))
7384 (match-beginning 0)) ?\ )
7385 t t s)))
7388 (defun org-fix-indentation (line ind)
7389 "Fix indentation in LINE.
7390 IND is a cons cell with target and minimum indentation.
7391 If the current indenation in LINE is smaller than the minimum,
7392 leave it alone. If it is larger than ind, set it to the target."
7393 (let* ((l (org-remove-tabs line))
7394 (i (org-get-indentation l))
7395 (i1 (car ind)) (i2 (cdr ind)))
7396 (if (>= i i2) (setq l (substring line i2)))
7397 (if (> i1 0)
7398 (concat (make-string i1 ?\ ) l)
7399 l)))
7401 (defcustom org-empty-line-terminates-plain-lists nil
7402 "Non-nil means, an empty line ends all plain list levels.
7403 When nil, empty lines are part of the preceeding item."
7404 :group 'org-plain-lists
7405 :type 'boolean)
7407 (defun org-beginning-of-item ()
7408 "Go to the beginning of the current hand-formatted item.
7409 If the cursor is not in an item, throw an error."
7410 (interactive)
7411 (let ((pos (point))
7412 (limit (save-excursion
7413 (condition-case nil
7414 (progn
7415 (org-back-to-heading)
7416 (beginning-of-line 2) (point))
7417 (error (point-min)))))
7418 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7419 ind ind1)
7420 (if (org-at-item-p)
7421 (beginning-of-line 1)
7422 (beginning-of-line 1)
7423 (skip-chars-forward " \t")
7424 (setq ind (current-column))
7425 (if (catch 'exit
7426 (while t
7427 (beginning-of-line 0)
7428 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7430 (if (looking-at "[ \t]*$")
7431 (setq ind1 ind-empty)
7432 (skip-chars-forward " \t")
7433 (setq ind1 (current-column)))
7434 (if (< ind1 ind)
7435 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7437 (goto-char pos)
7438 (error "Not in an item")))))
7440 (defun org-end-of-item ()
7441 "Go to the end of the current hand-formatted item.
7442 If the cursor is not in an item, throw an error."
7443 (interactive)
7444 (let* ((pos (point))
7445 ind1
7446 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7447 (limit (save-excursion (outline-next-heading) (point)))
7448 (ind (save-excursion
7449 (org-beginning-of-item)
7450 (skip-chars-forward " \t")
7451 (current-column)))
7452 (end (catch 'exit
7453 (while t
7454 (beginning-of-line 2)
7455 (if (eobp) (throw 'exit (point)))
7456 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7457 (if (looking-at "[ \t]*$")
7458 (setq ind1 ind-empty)
7459 (skip-chars-forward " \t")
7460 (setq ind1 (current-column)))
7461 (if (<= ind1 ind)
7462 (throw 'exit (point-at-bol)))))))
7463 (if end
7464 (goto-char end)
7465 (goto-char pos)
7466 (error "Not in an item"))))
7468 (defun org-next-item ()
7469 "Move to the beginning of the next item in the current plain list.
7470 Error if not at a plain list, or if this is the last item in the list."
7471 (interactive)
7472 (let (ind ind1 (pos (point)))
7473 (org-beginning-of-item)
7474 (setq ind (org-get-indentation))
7475 (org-end-of-item)
7476 (setq ind1 (org-get-indentation))
7477 (unless (and (org-at-item-p) (= ind ind1))
7478 (goto-char pos)
7479 (error "On last item"))))
7481 (defun org-previous-item ()
7482 "Move to the beginning of the previous item in the current plain list.
7483 Error if not at a plain list, or if this is the first item in the list."
7484 (interactive)
7485 (let (beg ind ind1 (pos (point)))
7486 (org-beginning-of-item)
7487 (setq beg (point))
7488 (setq ind (org-get-indentation))
7489 (goto-char beg)
7490 (catch 'exit
7491 (while t
7492 (beginning-of-line 0)
7493 (if (looking-at "[ \t]*$")
7495 (if (<= (setq ind1 (org-get-indentation)) ind)
7496 (throw 'exit t)))))
7497 (condition-case nil
7498 (if (or (not (org-at-item-p))
7499 (< ind1 (1- ind)))
7500 (error "")
7501 (org-beginning-of-item))
7502 (error (goto-char pos)
7503 (error "On first item")))))
7505 (defun org-first-list-item-p ()
7506 "Is this heading the item in a plain list?"
7507 (unless (org-at-item-p)
7508 (error "Not at a plain list item"))
7509 (org-beginning-of-item)
7510 (= (point) (save-excursion (org-beginning-of-item-list))))
7512 (defun org-move-item-down ()
7513 "Move the plain list item at point down, i.e. swap with following item.
7514 Subitems (items with larger indentation) are considered part of the item,
7515 so this really moves item trees."
7516 (interactive)
7517 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7518 (org-beginning-of-item)
7519 (setq beg0 (point))
7520 (save-excursion
7521 (setq ne-beg (org-back-over-empty-lines))
7522 (setq beg (point)))
7523 (goto-char beg0)
7524 (setq ind (org-get-indentation))
7525 (org-end-of-item)
7526 (setq end0 (point))
7527 (setq ind1 (org-get-indentation))
7528 (setq ne-end (org-back-over-empty-lines))
7529 (setq end (point))
7530 (goto-char beg0)
7531 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7532 ;; include less whitespace
7533 (save-excursion
7534 (goto-char beg)
7535 (forward-line (- ne-beg ne-end))
7536 (setq beg (point))))
7537 (goto-char end0)
7538 (if (and (org-at-item-p) (= ind ind1))
7539 (progn
7540 (org-end-of-item)
7541 (org-back-over-empty-lines)
7542 (setq txt (buffer-substring beg end))
7543 (save-excursion
7544 (delete-region beg end))
7545 (setq pos (point))
7546 (insert txt)
7547 (goto-char pos) (org-skip-whitespace)
7548 (org-maybe-renumber-ordered-list))
7549 (goto-char pos)
7550 (error "Cannot move this item further down"))))
7552 (defun org-move-item-up (arg)
7553 "Move the plain list item at point up, i.e. swap with previous item.
7554 Subitems (items with larger indentation) are considered part of the item,
7555 so this really moves item trees."
7556 (interactive "p")
7557 (let (beg beg0 end ind ind1 (pos (point)) txt
7558 ne-beg ne-ins ins-end)
7559 (org-beginning-of-item)
7560 (setq beg0 (point))
7561 (setq ind (org-get-indentation))
7562 (save-excursion
7563 (setq ne-beg (org-back-over-empty-lines))
7564 (setq beg (point)))
7565 (goto-char beg0)
7566 (org-end-of-item)
7567 (setq end (point))
7568 (goto-char beg0)
7569 (catch 'exit
7570 (while t
7571 (beginning-of-line 0)
7572 (if (looking-at "[ \t]*$")
7573 (if org-empty-line-terminates-plain-lists
7574 (progn
7575 (goto-char pos)
7576 (error "Cannot move this item further up"))
7577 nil)
7578 (if (<= (setq ind1 (org-get-indentation)) ind)
7579 (throw 'exit t)))))
7580 (condition-case nil
7581 (org-beginning-of-item)
7582 (error (goto-char beg)
7583 (error "Cannot move this item further up")))
7584 (setq ind1 (org-get-indentation))
7585 (if (and (org-at-item-p) (= ind ind1))
7586 (progn
7587 (setq ne-ins (org-back-over-empty-lines))
7588 (setq txt (buffer-substring beg end))
7589 (save-excursion
7590 (delete-region beg end))
7591 (setq pos (point))
7592 (insert txt)
7593 (setq ins-end (point))
7594 (goto-char pos) (org-skip-whitespace)
7596 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7597 ;; Move whitespace back to beginning
7598 (save-excursion
7599 (goto-char ins-end)
7600 (let ((kill-whole-line t))
7601 (kill-line (- ne-ins ne-beg)) (point)))
7602 (insert (make-string (- ne-ins ne-beg) ?\n)))
7604 (org-maybe-renumber-ordered-list))
7605 (goto-char pos)
7606 (error "Cannot move this item further up"))))
7608 (defun org-maybe-renumber-ordered-list ()
7609 "Renumber the ordered list at point if setup allows it.
7610 This tests the user option `org-auto-renumber-ordered-lists' before
7611 doing the renumbering."
7612 (interactive)
7613 (when (and org-auto-renumber-ordered-lists
7614 (org-at-item-p))
7615 (if (match-beginning 3)
7616 (org-renumber-ordered-list 1)
7617 (org-fix-bullet-type))))
7619 (defun org-maybe-renumber-ordered-list-safe ()
7620 (condition-case nil
7621 (save-excursion
7622 (org-maybe-renumber-ordered-list))
7623 (error nil)))
7625 (defun org-cycle-list-bullet (&optional which)
7626 "Cycle through the different itemize/enumerate bullets.
7627 This cycle the entire list level through the sequence:
7629 `-' -> `+' -> `*' -> `1.' -> `1)'
7631 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7632 0 meand `-', 1 means `+' etc."
7633 (interactive "P")
7634 (org-preserve-lc
7635 (org-beginning-of-item-list)
7636 (org-at-item-p)
7637 (beginning-of-line 1)
7638 (let ((current (match-string 0))
7639 (prevp (eq which 'previous))
7640 new)
7641 (setq new (cond
7642 ((and (numberp which)
7643 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7644 ((string-match "-" current) (if prevp "1)" "+"))
7645 ((string-match "\\+" current)
7646 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7647 ((string-match "\\*" current) (if prevp "+" "1."))
7648 ((string-match "\\." current) (if prevp "*" "1)"))
7649 ((string-match ")" current) (if prevp "1." "-"))
7650 (t (error "This should not happen"))))
7651 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7652 (org-fix-bullet-type)
7653 (org-maybe-renumber-ordered-list))))
7655 (defun org-get-string-indentation (s)
7656 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7657 (let ((n -1) (i 0) (w tab-width) c)
7658 (catch 'exit
7659 (while (< (setq n (1+ n)) (length s))
7660 (setq c (aref s n))
7661 (cond ((= c ?\ ) (setq i (1+ i)))
7662 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7663 (t (throw 'exit t)))))
7666 (defun org-renumber-ordered-list (arg)
7667 "Renumber an ordered plain list.
7668 Cursor needs to be in the first line of an item, the line that starts
7669 with something like \"1.\" or \"2)\"."
7670 (interactive "p")
7671 (unless (and (org-at-item-p)
7672 (match-beginning 3))
7673 (error "This is not an ordered list"))
7674 (let ((line (org-current-line))
7675 (col (current-column))
7676 (ind (org-get-string-indentation
7677 (buffer-substring (point-at-bol) (match-beginning 3))))
7678 ;; (term (substring (match-string 3) -1))
7679 ind1 (n (1- arg))
7680 fmt)
7681 ;; find where this list begins
7682 (org-beginning-of-item-list)
7683 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7684 (setq fmt (concat "%d" (match-string 1)))
7685 (beginning-of-line 0)
7686 ;; walk forward and replace these numbers
7687 (catch 'exit
7688 (while t
7689 (catch 'next
7690 (beginning-of-line 2)
7691 (if (eobp) (throw 'exit nil))
7692 (if (looking-at "[ \t]*$") (throw 'next nil))
7693 (skip-chars-forward " \t") (setq ind1 (current-column))
7694 (if (> ind1 ind) (throw 'next t))
7695 (if (< ind1 ind) (throw 'exit t))
7696 (if (not (org-at-item-p)) (throw 'exit nil))
7697 (delete-region (match-beginning 2) (match-end 2))
7698 (goto-char (match-beginning 2))
7699 (insert (format fmt (setq n (1+ n)))))))
7700 (goto-line line)
7701 (move-to-column col)))
7703 (defun org-fix-bullet-type ()
7704 "Make sure all items in this list have the same bullet as the firsst item."
7705 (interactive)
7706 (unless (org-at-item-p) (error "This is not a list"))
7707 (let ((line (org-current-line))
7708 (col (current-column))
7709 (ind (current-indentation))
7710 ind1 bullet)
7711 ;; find where this list begins
7712 (org-beginning-of-item-list)
7713 (beginning-of-line 1)
7714 ;; find out what the bullet type is
7715 (looking-at "[ \t]*\\(\\S-+\\)")
7716 (setq bullet (match-string 1))
7717 ;; walk forward and replace these numbers
7718 (beginning-of-line 0)
7719 (catch 'exit
7720 (while t
7721 (catch 'next
7722 (beginning-of-line 2)
7723 (if (eobp) (throw 'exit nil))
7724 (if (looking-at "[ \t]*$") (throw 'next nil))
7725 (skip-chars-forward " \t") (setq ind1 (current-column))
7726 (if (> ind1 ind) (throw 'next t))
7727 (if (< ind1 ind) (throw 'exit t))
7728 (if (not (org-at-item-p)) (throw 'exit nil))
7729 (skip-chars-forward " \t")
7730 (looking-at "\\S-+")
7731 (replace-match bullet))))
7732 (goto-line line)
7733 (move-to-column col)
7734 (if (string-match "[0-9]" bullet)
7735 (org-renumber-ordered-list 1))))
7737 (defun org-beginning-of-item-list ()
7738 "Go to the beginning of the current item list.
7739 I.e. to the first item in this list."
7740 (interactive)
7741 (org-beginning-of-item)
7742 (let ((pos (point-at-bol))
7743 (ind (org-get-indentation))
7744 ind1)
7745 ;; find where this list begins
7746 (catch 'exit
7747 (while t
7748 (catch 'next
7749 (beginning-of-line 0)
7750 (if (looking-at "[ \t]*$")
7751 (throw (if (bobp) 'exit 'next) t))
7752 (skip-chars-forward " \t") (setq ind1 (current-column))
7753 (if (or (< ind1 ind)
7754 (and (= ind1 ind)
7755 (not (org-at-item-p)))
7756 (bobp))
7757 (throw 'exit t)
7758 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7759 (goto-char pos)))
7762 (defun org-end-of-item-list ()
7763 "Go to the end of the current item list.
7764 I.e. to the text after the last item."
7765 (interactive)
7766 (org-beginning-of-item)
7767 (let ((pos (point-at-bol))
7768 (ind (org-get-indentation))
7769 ind1)
7770 ;; find where this list begins
7771 (catch 'exit
7772 (while t
7773 (catch 'next
7774 (beginning-of-line 2)
7775 (if (looking-at "[ \t]*$")
7776 (throw (if (eobp) 'exit 'next) t))
7777 (skip-chars-forward " \t") (setq ind1 (current-column))
7778 (if (or (< ind1 ind)
7779 (and (= ind1 ind)
7780 (not (org-at-item-p)))
7781 (eobp))
7782 (progn
7783 (setq pos (point-at-bol))
7784 (throw 'exit t))))))
7785 (goto-char pos)))
7788 (defvar org-last-indent-begin-marker (make-marker))
7789 (defvar org-last-indent-end-marker (make-marker))
7791 (defun org-outdent-item (arg)
7792 "Outdent a local list item."
7793 (interactive "p")
7794 (org-indent-item (- arg)))
7796 (defun org-indent-item (arg)
7797 "Indent a local list item."
7798 (interactive "p")
7799 (unless (org-at-item-p)
7800 (error "Not on an item"))
7801 (save-excursion
7802 (let (beg end ind ind1 tmp delta ind-down ind-up)
7803 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7804 (setq beg org-last-indent-begin-marker
7805 end org-last-indent-end-marker)
7806 (org-beginning-of-item)
7807 (setq beg (move-marker org-last-indent-begin-marker (point)))
7808 (org-end-of-item)
7809 (setq end (move-marker org-last-indent-end-marker (point))))
7810 (goto-char beg)
7811 (setq tmp (org-item-indent-positions)
7812 ind (car tmp)
7813 ind-down (nth 2 tmp)
7814 ind-up (nth 1 tmp)
7815 delta (if (> arg 0)
7816 (if ind-down (- ind-down ind) 2)
7817 (if ind-up (- ind-up ind) -2)))
7818 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7819 (while (< (point) end)
7820 (beginning-of-line 1)
7821 (skip-chars-forward " \t") (setq ind1 (current-column))
7822 (delete-region (point-at-bol) (point))
7823 (or (eolp) (indent-to-column (+ ind1 delta)))
7824 (beginning-of-line 2))))
7825 (org-fix-bullet-type)
7826 (org-maybe-renumber-ordered-list-safe)
7827 (save-excursion
7828 (beginning-of-line 0)
7829 (condition-case nil (org-beginning-of-item) (error nil))
7830 (org-maybe-renumber-ordered-list-safe)))
7832 (defun org-item-indent-positions ()
7833 "Return indentation for plain list items.
7834 This returns a list with three values: The current indentation, the
7835 parent indentation and the indentation a child should habe.
7836 Assumes cursor in item line."
7837 (let* ((bolpos (point-at-bol))
7838 (ind (org-get-indentation))
7839 ind-down ind-up pos)
7840 (save-excursion
7841 (org-beginning-of-item-list)
7842 (skip-chars-backward "\n\r \t")
7843 (when (org-in-item-p)
7844 (org-beginning-of-item)
7845 (setq ind-up (org-get-indentation))))
7846 (setq pos (point))
7847 (save-excursion
7848 (cond
7849 ((and (condition-case nil (progn (org-previous-item) t)
7850 (error nil))
7851 (or (forward-char 1) t)
7852 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7853 (setq ind-down (org-get-indentation)))
7854 ((and (goto-char pos)
7855 (org-at-item-p))
7856 (goto-char (match-end 0))
7857 (skip-chars-forward " \t")
7858 (setq ind-down (current-column)))))
7859 (list ind ind-up ind-down)))
7861 ;;; The orgstruct minor mode
7863 ;; Define a minor mode which can be used in other modes in order to
7864 ;; integrate the org-mode structure editing commands.
7866 ;; This is really a hack, because the org-mode structure commands use
7867 ;; keys which normally belong to the major mode. Here is how it
7868 ;; works: The minor mode defines all the keys necessary to operate the
7869 ;; structure commands, but wraps the commands into a function which
7870 ;; tests if the cursor is currently at a headline or a plain list
7871 ;; item. If that is the case, the structure command is used,
7872 ;; temporarily setting many Org-mode variables like regular
7873 ;; expressions for filling etc. However, when any of those keys is
7874 ;; used at a different location, function uses `key-binding' to look
7875 ;; up if the key has an associated command in another currently active
7876 ;; keymap (minor modes, major mode, global), and executes that
7877 ;; command. There might be problems if any of the keys is otherwise
7878 ;; used as a prefix key.
7880 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7881 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7882 ;; addresses this by checking explicitly for both bindings.
7884 (defvar orgstruct-mode-map (make-sparse-keymap)
7885 "Keymap for the minor `orgstruct-mode'.")
7887 (defvar org-local-vars nil
7888 "List of local variables, for use by `orgstruct-mode'")
7890 ;;;###autoload
7891 (define-minor-mode orgstruct-mode
7892 "Toggle the minor more `orgstruct-mode'.
7893 This mode is for using Org-mode structure commands in other modes.
7894 The following key behave as if Org-mode was active, if the cursor
7895 is on a headline, or on a plain list item (both in the definition
7896 of Org-mode).
7898 M-up Move entry/item up
7899 M-down Move entry/item down
7900 M-left Promote
7901 M-right Demote
7902 M-S-up Move entry/item up
7903 M-S-down Move entry/item down
7904 M-S-left Promote subtree
7905 M-S-right Demote subtree
7906 M-q Fill paragraph and items like in Org-mode
7907 C-c ^ Sort entries
7908 C-c - Cycle list bullet
7909 TAB Cycle item visibility
7910 M-RET Insert new heading/item
7911 S-M-RET Insert new TODO heading / Chekbox item
7912 C-c C-c Set tags / toggle checkbox"
7913 nil " OrgStruct" nil
7914 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7916 ;;;###autoload
7917 (defun turn-on-orgstruct ()
7918 "Unconditionally turn on `orgstruct-mode'."
7919 (orgstruct-mode 1))
7921 ;;;###autoload
7922 (defun turn-on-orgstruct++ ()
7923 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7924 In addition to setting orgstruct-mode, this also exports all indentation and
7925 autofilling variables from org-mode into the buffer. Note that turning
7926 off orgstruct-mode will *not* remove these additional settings."
7927 (orgstruct-mode 1)
7928 (let (var val)
7929 (mapc
7930 (lambda (x)
7931 (when (string-match
7932 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7933 (symbol-name (car x)))
7934 (setq var (car x) val (nth 1 x))
7935 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7936 org-local-vars)))
7938 (defun orgstruct-error ()
7939 "Error when there is no default binding for a structure key."
7940 (interactive)
7941 (error "This key has no function outside structure elements"))
7943 (defun orgstruct-setup ()
7944 "Setup orgstruct keymaps."
7945 (let ((nfunc 0)
7946 (bindings
7947 (list
7948 '([(meta up)] org-metaup)
7949 '([(meta down)] org-metadown)
7950 '([(meta left)] org-metaleft)
7951 '([(meta right)] org-metaright)
7952 '([(meta shift up)] org-shiftmetaup)
7953 '([(meta shift down)] org-shiftmetadown)
7954 '([(meta shift left)] org-shiftmetaleft)
7955 '([(meta shift right)] org-shiftmetaright)
7956 '([(shift up)] org-shiftup)
7957 '([(shift down)] org-shiftdown)
7958 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7959 '("\M-q" fill-paragraph)
7960 '("\C-c^" org-sort)
7961 '("\C-c-" org-cycle-list-bullet)))
7962 elt key fun cmd)
7963 (while (setq elt (pop bindings))
7964 (setq nfunc (1+ nfunc))
7965 (setq key (org-key (car elt))
7966 fun (nth 1 elt)
7967 cmd (orgstruct-make-binding fun nfunc key))
7968 (org-defkey orgstruct-mode-map key cmd))
7970 ;; Special treatment needed for TAB and RET
7971 (org-defkey orgstruct-mode-map [(tab)]
7972 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7973 (org-defkey orgstruct-mode-map "\C-i"
7974 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7976 (org-defkey orgstruct-mode-map "\M-\C-m"
7977 (orgstruct-make-binding 'org-insert-heading 105
7978 "\M-\C-m" [(meta return)]))
7979 (org-defkey orgstruct-mode-map [(meta return)]
7980 (orgstruct-make-binding 'org-insert-heading 106
7981 [(meta return)] "\M-\C-m"))
7983 (org-defkey orgstruct-mode-map [(shift meta return)]
7984 (orgstruct-make-binding 'org-insert-todo-heading 107
7985 [(meta return)] "\M-\C-m"))
7987 (unless org-local-vars
7988 (setq org-local-vars (org-get-local-variables)))
7992 (defun orgstruct-make-binding (fun n &rest keys)
7993 "Create a function for binding in the structure minor mode.
7994 FUN is the command to call inside a table. N is used to create a unique
7995 command name. KEYS are keys that should be checked in for a command
7996 to execute outside of tables."
7997 (eval
7998 (list 'defun
7999 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8000 '(arg)
8001 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8002 "Outside of structure, run the binding of `"
8003 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8004 "'.")
8005 '(interactive "p")
8006 (list 'if
8007 '(org-context-p 'headline 'item)
8008 (list 'org-run-like-in-org-mode (list 'quote fun))
8009 (list 'let '(orgstruct-mode)
8010 (list 'call-interactively
8011 (append '(or)
8012 (mapcar (lambda (k)
8013 (list 'key-binding k))
8014 keys)
8015 '('orgstruct-error))))))))
8017 (defun org-context-p (&rest contexts)
8018 "Check if local context is and of CONTEXTS.
8019 Possible values in the list of contexts are `table', `headline', and `item'."
8020 (let ((pos (point)))
8021 (goto-char (point-at-bol))
8022 (prog1 (or (and (memq 'table contexts)
8023 (looking-at "[ \t]*|"))
8024 (and (memq 'headline contexts)
8025 (looking-at "\\*+"))
8026 (and (memq 'item contexts)
8027 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
8028 (goto-char pos))))
8030 (defun org-get-local-variables ()
8031 "Return a list of all local variables in an org-mode buffer."
8032 (let (varlist)
8033 (with-current-buffer (get-buffer-create "*Org tmp*")
8034 (erase-buffer)
8035 (org-mode)
8036 (setq varlist (buffer-local-variables)))
8037 (kill-buffer "*Org tmp*")
8038 (delq nil
8039 (mapcar
8040 (lambda (x)
8041 (setq x
8042 (if (symbolp x)
8043 (list x)
8044 (list (car x) (list 'quote (cdr x)))))
8045 (if (string-match
8046 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8047 (symbol-name (car x)))
8048 x nil))
8049 varlist))))
8051 ;;;###autoload
8052 (defun org-run-like-in-org-mode (cmd)
8053 (unless org-local-vars
8054 (setq org-local-vars (org-get-local-variables)))
8055 (eval (list 'let org-local-vars
8056 (list 'call-interactively (list 'quote cmd)))))
8058 ;;;; Archiving
8060 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
8062 (defun org-archive-subtree (&optional find-done)
8063 "Move the current subtree to the archive.
8064 The archive can be a certain top-level heading in the current file, or in
8065 a different file. The tree will be moved to that location, the subtree
8066 heading be marked DONE, and the current time will be added.
8068 When called with prefix argument FIND-DONE, find whole trees without any
8069 open TODO items and archive them (after getting confirmation from the user).
8070 If the cursor is not at a headline when this comand is called, try all level
8071 1 trees. If the cursor is on a headline, only try the direct children of
8072 this heading."
8073 (interactive "P")
8074 (if find-done
8075 (org-archive-all-done)
8076 ;; Save all relevant TODO keyword-relatex variables
8078 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
8079 (tr-org-todo-keywords-1 org-todo-keywords-1)
8080 (tr-org-todo-kwd-alist org-todo-kwd-alist)
8081 (tr-org-done-keywords org-done-keywords)
8082 (tr-org-todo-regexp org-todo-regexp)
8083 (tr-org-todo-line-regexp org-todo-line-regexp)
8084 (tr-org-odd-levels-only org-odd-levels-only)
8085 (this-buffer (current-buffer))
8086 (org-archive-location org-archive-location)
8087 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
8088 ;; start of variables that will be used for saving context
8089 ;; The compiler complains about them - keep them anyway!
8090 (file (abbreviate-file-name (buffer-file-name)))
8091 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
8092 (time (format-time-string
8093 (substring (cdr org-time-stamp-formats) 1 -1)
8094 (current-time)))
8095 afile heading buffer level newfile-p
8096 category todo priority
8097 ;; start of variables that will be used for savind context
8098 ltags itags prop)
8100 ;; Try to find a local archive location
8101 (save-excursion
8102 (save-restriction
8103 (widen)
8104 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
8105 (if (and prop (string-match "\\S-" prop))
8106 (setq org-archive-location prop)
8107 (if (or (re-search-backward re nil t)
8108 (re-search-forward re nil t))
8109 (setq org-archive-location (match-string 1))))))
8111 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
8112 (progn
8113 (setq afile (format (match-string 1 org-archive-location)
8114 (file-name-nondirectory buffer-file-name))
8115 heading (match-string 2 org-archive-location)))
8116 (error "Invalid `org-archive-location'"))
8117 (if (> (length afile) 0)
8118 (setq newfile-p (not (file-exists-p afile))
8119 buffer (find-file-noselect afile))
8120 (setq buffer (current-buffer)))
8121 (unless buffer
8122 (error "Cannot access file \"%s\"" afile))
8123 (if (and (> (length heading) 0)
8124 (string-match "^\\*+" heading))
8125 (setq level (match-end 0))
8126 (setq heading nil level 0))
8127 (save-excursion
8128 (org-back-to-heading t)
8129 ;; Get context information that will be lost by moving the tree
8130 (org-refresh-category-properties)
8131 (setq category (org-get-category)
8132 todo (and (looking-at org-todo-line-regexp)
8133 (match-string 2))
8134 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
8135 ltags (org-get-tags)
8136 itags (org-delete-all ltags (org-get-tags-at)))
8137 (setq ltags (mapconcat 'identity ltags " ")
8138 itags (mapconcat 'identity itags " "))
8139 ;; We first only copy, in case something goes wrong
8140 ;; we need to protect this-command, to avoid kill-region sets it,
8141 ;; which would lead to duplication of subtrees
8142 (let (this-command) (org-copy-subtree))
8143 (set-buffer buffer)
8144 ;; Enforce org-mode for the archive buffer
8145 (if (not (org-mode-p))
8146 ;; Force the mode for future visits.
8147 (let ((org-insert-mode-line-in-empty-file t)
8148 (org-inhibit-startup t))
8149 (call-interactively 'org-mode)))
8150 (when newfile-p
8151 (goto-char (point-max))
8152 (insert (format "\nArchived entries from file %s\n\n"
8153 (buffer-file-name this-buffer))))
8154 ;; Force the TODO keywords of the original buffer
8155 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
8156 (org-todo-keywords-1 tr-org-todo-keywords-1)
8157 (org-todo-kwd-alist tr-org-todo-kwd-alist)
8158 (org-done-keywords tr-org-done-keywords)
8159 (org-todo-regexp tr-org-todo-regexp)
8160 (org-todo-line-regexp tr-org-todo-line-regexp)
8161 (org-odd-levels-only
8162 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8163 org-odd-levels-only
8164 tr-org-odd-levels-only)))
8165 (goto-char (point-min))
8166 (show-all)
8167 (if heading
8168 (progn
8169 (if (re-search-forward
8170 (concat "^" (regexp-quote heading)
8171 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8172 nil t)
8173 (goto-char (match-end 0))
8174 ;; Heading not found, just insert it at the end
8175 (goto-char (point-max))
8176 (or (bolp) (insert "\n"))
8177 (insert "\n" heading "\n")
8178 (end-of-line 0))
8179 ;; Make the subtree visible
8180 (show-subtree)
8181 (org-end-of-subtree t)
8182 (skip-chars-backward " \t\r\n")
8183 (and (looking-at "[ \t\r\n]*")
8184 (replace-match "\n\n")))
8185 ;; No specific heading, just go to end of file.
8186 (goto-char (point-max)) (insert "\n"))
8187 ;; Paste
8188 (org-paste-subtree (org-get-valid-level level 1))
8190 ;; Mark the entry as done
8191 (when (and org-archive-mark-done
8192 (looking-at org-todo-line-regexp)
8193 (or (not (match-end 2))
8194 (not (member (match-string 2) org-done-keywords))))
8195 (let (org-log-done org-todo-log-states)
8196 (org-todo
8197 (car (or (member org-archive-mark-done org-done-keywords)
8198 org-done-keywords)))))
8200 ;; Add the context info
8201 (when org-archive-save-context-info
8202 (let ((l org-archive-save-context-info) e n v)
8203 (while (setq e (pop l))
8204 (when (and (setq v (symbol-value e))
8205 (stringp v) (string-match "\\S-" v))
8206 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8207 (org-entry-put (point) n v)))))
8209 ;; Save and kill the buffer, if it is not the same buffer.
8210 (if (not (eq this-buffer buffer))
8211 (progn (save-buffer) (kill-buffer buffer)))))
8212 ;; Here we are back in the original buffer. Everything seems to have
8213 ;; worked. So now cut the tree and finish up.
8214 (let (this-command) (org-cut-subtree))
8215 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8216 (message "Subtree archived %s"
8217 (if (eq this-buffer buffer)
8218 (concat "under heading: " heading)
8219 (concat "in file: " (abbreviate-file-name afile)))))))
8221 (defun org-refresh-category-properties ()
8222 "Refresh category text properties in teh buffer."
8223 (let ((def-cat (cond
8224 ((null org-category)
8225 (if buffer-file-name
8226 (file-name-sans-extension
8227 (file-name-nondirectory buffer-file-name))
8228 "???"))
8229 ((symbolp org-category) (symbol-name org-category))
8230 (t org-category)))
8231 beg end cat pos optionp)
8232 (org-unmodified
8233 (save-excursion
8234 (save-restriction
8235 (widen)
8236 (goto-char (point-min))
8237 (put-text-property (point) (point-max) 'org-category def-cat)
8238 (while (re-search-forward
8239 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8240 (setq pos (match-end 0)
8241 optionp (equal (char-after (match-beginning 0)) ?#)
8242 cat (org-trim (match-string 2)))
8243 (if optionp
8244 (setq beg (point-at-bol) end (point-max))
8245 (org-back-to-heading t)
8246 (setq beg (point) end (org-end-of-subtree t t)))
8247 (put-text-property beg end 'org-category cat)
8248 (goto-char pos)))))))
8250 (defun org-archive-all-done (&optional tag)
8251 "Archive sublevels of the current tree without open TODO items.
8252 If the cursor is not on a headline, try all level 1 trees. If
8253 it is on a headline, try all direct children.
8254 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8255 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8256 (rea (concat ".*:" org-archive-tag ":"))
8257 (begm (make-marker))
8258 (endm (make-marker))
8259 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8260 "Move subtree to archive (no open TODO items)? "))
8261 beg end (cntarch 0))
8262 (if (org-on-heading-p)
8263 (progn
8264 (setq re1 (concat "^" (regexp-quote
8265 (make-string
8266 (1+ (- (match-end 0) (match-beginning 0) 1))
8267 ?*))
8268 " "))
8269 (move-marker begm (point))
8270 (move-marker endm (org-end-of-subtree t)))
8271 (setq re1 "^* ")
8272 (move-marker begm (point-min))
8273 (move-marker endm (point-max)))
8274 (save-excursion
8275 (goto-char begm)
8276 (while (re-search-forward re1 endm t)
8277 (setq beg (match-beginning 0)
8278 end (save-excursion (org-end-of-subtree t) (point)))
8279 (goto-char beg)
8280 (if (re-search-forward re end t)
8281 (goto-char end)
8282 (goto-char beg)
8283 (if (and (or (not tag) (not (looking-at rea)))
8284 (y-or-n-p question))
8285 (progn
8286 (if tag
8287 (org-toggle-tag org-archive-tag 'on)
8288 (org-archive-subtree))
8289 (setq cntarch (1+ cntarch)))
8290 (goto-char end)))))
8291 (message "%d trees archived" cntarch)))
8293 (defun org-cycle-hide-drawers (state)
8294 "Re-hide all drawers after a visibility state change."
8295 (when (and (org-mode-p)
8296 (not (memq state '(overview folded))))
8297 (save-excursion
8298 (let* ((globalp (memq state '(contents all)))
8299 (beg (if globalp (point-min) (point)))
8300 (end (if globalp (point-max) (org-end-of-subtree t))))
8301 (goto-char beg)
8302 (while (re-search-forward org-drawer-regexp end t)
8303 (org-flag-drawer t))))))
8305 (defun org-flag-drawer (flag)
8306 (save-excursion
8307 (beginning-of-line 1)
8308 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8309 (let ((b (match-end 0))
8310 (outline-regexp org-outline-regexp))
8311 (if (re-search-forward
8312 "^[ \t]*:END:"
8313 (save-excursion (outline-next-heading) (point)) t)
8314 (outline-flag-region b (point-at-eol) flag)
8315 (error ":END: line missing"))))))
8317 (defun org-cycle-hide-archived-subtrees (state)
8318 "Re-hide all archived subtrees after a visibility state change."
8319 (when (and (not org-cycle-open-archived-trees)
8320 (not (memq state '(overview folded))))
8321 (save-excursion
8322 (let* ((globalp (memq state '(contents all)))
8323 (beg (if globalp (point-min) (point)))
8324 (end (if globalp (point-max) (org-end-of-subtree t))))
8325 (org-hide-archived-subtrees beg end)
8326 (goto-char beg)
8327 (if (looking-at (concat ".*:" org-archive-tag ":"))
8328 (message "%s" (substitute-command-keys
8329 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8331 (defun org-force-cycle-archived ()
8332 "Cycle subtree even if it is archived."
8333 (interactive)
8334 (setq this-command 'org-cycle)
8335 (let ((org-cycle-open-archived-trees t))
8336 (call-interactively 'org-cycle)))
8338 (defun org-hide-archived-subtrees (beg end)
8339 "Re-hide all archived subtrees after a visibility state change."
8340 (save-excursion
8341 (let* ((re (concat ":" org-archive-tag ":")))
8342 (goto-char beg)
8343 (while (re-search-forward re end t)
8344 (and (org-on-heading-p) (hide-subtree))
8345 (org-end-of-subtree t)))))
8347 (defun org-toggle-tag (tag &optional onoff)
8348 "Toggle the tag TAG for the current line.
8349 If ONOFF is `on' or `off', don't toggle but set to this state."
8350 (unless (org-on-heading-p t) (error "Not on headling"))
8351 (let (res current)
8352 (save-excursion
8353 (beginning-of-line)
8354 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8355 (point-at-eol) t)
8356 (progn
8357 (setq current (match-string 1))
8358 (replace-match ""))
8359 (setq current ""))
8360 (setq current (nreverse (org-split-string current ":")))
8361 (cond
8362 ((eq onoff 'on)
8363 (setq res t)
8364 (or (member tag current) (push tag current)))
8365 ((eq onoff 'off)
8366 (or (not (member tag current)) (setq current (delete tag current))))
8367 (t (if (member tag current)
8368 (setq current (delete tag current))
8369 (setq res t)
8370 (push tag current))))
8371 (end-of-line 1)
8372 (if current
8373 (progn
8374 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8375 (org-set-tags nil t))
8376 (delete-horizontal-space))
8377 (run-hooks 'org-after-tags-change-hook))
8378 res))
8380 (defun org-toggle-archive-tag (&optional arg)
8381 "Toggle the archive tag for the current headline.
8382 With prefix ARG, check all children of current headline and offer tagging
8383 the children that do not contain any open TODO items."
8384 (interactive "P")
8385 (if arg
8386 (org-archive-all-done 'tag)
8387 (let (set)
8388 (save-excursion
8389 (org-back-to-heading t)
8390 (setq set (org-toggle-tag org-archive-tag))
8391 (when set (hide-subtree)))
8392 (and set (beginning-of-line 1))
8393 (message "Subtree %s" (if set "archived" "unarchived")))))
8396 ;;;; Tables
8398 ;;; The table editor
8400 ;; Watch out: Here we are talking about two different kind of tables.
8401 ;; Most of the code is for the tables created with the Org-mode table editor.
8402 ;; Sometimes, we talk about tables created and edited with the table.el
8403 ;; Emacs package. We call the former org-type tables, and the latter
8404 ;; table.el-type tables.
8406 (defun org-before-change-function (beg end)
8407 "Every change indicates that a table might need an update."
8408 (setq org-table-may-need-update t))
8410 (defconst org-table-line-regexp "^[ \t]*|"
8411 "Detects an org-type table line.")
8412 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8413 "Detects an org-type table line.")
8414 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8415 "Detects a table line marked for automatic recalculation.")
8416 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8417 "Detects a table line marked for automatic recalculation.")
8418 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8419 "Detects a table line marked for automatic recalculation.")
8420 (defconst org-table-hline-regexp "^[ \t]*|-"
8421 "Detects an org-type table hline.")
8422 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8423 "Detects a table-type table hline.")
8424 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8425 "Detects an org-type or table-type table.")
8426 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8427 "Searching from within a table (any type) this finds the first line
8428 outside the table.")
8429 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8430 "Searching from within a table (any type) this finds the first line
8431 outside the table.")
8433 (defvar org-table-last-highlighted-reference nil)
8434 (defvar org-table-formula-history nil)
8436 (defvar org-table-column-names nil
8437 "Alist with column names, derived from the `!' line.")
8438 (defvar org-table-column-name-regexp nil
8439 "Regular expression matching the current column names.")
8440 (defvar org-table-local-parameters nil
8441 "Alist with parameter names, derived from the `$' line.")
8442 (defvar org-table-named-field-locations nil
8443 "Alist with locations of named fields.")
8445 (defvar org-table-current-line-types nil
8446 "Table row types, non-nil only for the duration of a comand.")
8447 (defvar org-table-current-begin-line nil
8448 "Table begin line, non-nil only for the duration of a comand.")
8449 (defvar org-table-current-begin-pos nil
8450 "Table begin position, non-nil only for the duration of a comand.")
8451 (defvar org-table-dlines nil
8452 "Vector of data line line numbers in the current table.")
8453 (defvar org-table-hlines nil
8454 "Vector of hline line numbers in the current table.")
8456 (defconst org-table-range-regexp
8457 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8458 ;; 1 2 3 4 5
8459 "Regular expression for matching ranges in formulas.")
8461 (defconst org-table-range-regexp2
8462 (concat
8463 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8464 "\\.\\."
8465 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8466 "Match a range for reference display.")
8468 (defconst org-table-translate-regexp
8469 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8470 "Match a reference that needs translation, for reference display.")
8472 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8474 (defun org-table-create-with-table.el ()
8475 "Use the table.el package to insert a new table.
8476 If there is already a table at point, convert between Org-mode tables
8477 and table.el tables."
8478 (interactive)
8479 (require 'table)
8480 (cond
8481 ((org-at-table.el-p)
8482 (if (y-or-n-p "Convert table to Org-mode table? ")
8483 (org-table-convert)))
8484 ((org-at-table-p)
8485 (if (y-or-n-p "Convert table to table.el table? ")
8486 (org-table-convert)))
8487 (t (call-interactively 'table-insert))))
8489 (defun org-table-create-or-convert-from-region (arg)
8490 "Convert region to table, or create an empty table.
8491 If there is an active region, convert it to a table, using the function
8492 `org-table-convert-region'. See the documentation of that function
8493 to learn how the prefix argument is interpreted to determine the field
8494 separator.
8495 If there is no such region, create an empty table with `org-table-create'."
8496 (interactive "P")
8497 (if (org-region-active-p)
8498 (org-table-convert-region (region-beginning) (region-end) arg)
8499 (org-table-create arg)))
8501 (defun org-table-create (&optional size)
8502 "Query for a size and insert a table skeleton.
8503 SIZE is a string Columns x Rows like for example \"3x2\"."
8504 (interactive "P")
8505 (unless size
8506 (setq size (read-string
8507 (concat "Table size Columns x Rows [e.g. "
8508 org-table-default-size "]: ")
8509 "" nil org-table-default-size)))
8511 (let* ((pos (point))
8512 (indent (make-string (current-column) ?\ ))
8513 (split (org-split-string size " *x *"))
8514 (rows (string-to-number (nth 1 split)))
8515 (columns (string-to-number (car split)))
8516 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8517 "\n")))
8518 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8519 (point-at-bol) (point)))
8520 (beginning-of-line 1)
8521 (newline))
8522 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8523 (dotimes (i rows) (insert line))
8524 (goto-char pos)
8525 (if (> rows 1)
8526 ;; Insert a hline after the first row.
8527 (progn
8528 (end-of-line 1)
8529 (insert "\n|-")
8530 (goto-char pos)))
8531 (org-table-align)))
8533 (defun org-table-convert-region (beg0 end0 &optional separator)
8534 "Convert region to a table.
8535 The region goes from BEG0 to END0, but these borders will be moved
8536 slightly, to make sure a beginning of line in the first line is included.
8538 SEPARATOR specifies the field separator in the lines. It can have the
8539 following values:
8541 '(4) Use the comma as a field separator
8542 '(16) Use a TAB as field separator
8543 integer When a number, use that many spaces as field separator
8544 nil When nil, the command tries to be smart and figure out the
8545 separator in the following way:
8546 - when each line contains a TAB, assume TAB-separated material
8547 - when each line contains a comme, assume CSV material
8548 - else, assume one or more SPACE charcters as separator."
8549 (interactive "rP")
8550 (let* ((beg (min beg0 end0))
8551 (end (max beg0 end0))
8553 (goto-char beg)
8554 (beginning-of-line 1)
8555 (setq beg (move-marker (make-marker) (point)))
8556 (goto-char end)
8557 (if (bolp) (backward-char 1) (end-of-line 1))
8558 (setq end (move-marker (make-marker) (point)))
8559 ;; Get the right field separator
8560 (unless separator
8561 (goto-char beg)
8562 (setq separator
8563 (cond
8564 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8565 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8566 (t 1))))
8567 (setq re (cond
8568 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8569 ((equal separator '(16)) "^\\|\t")
8570 ((integerp separator)
8571 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8572 (t (error "This should not happen"))))
8573 (goto-char beg)
8574 (while (re-search-forward re end t)
8575 (replace-match "| " t t))
8576 (goto-char beg)
8577 (insert " ")
8578 (org-table-align)))
8580 (defun org-table-import (file arg)
8581 "Import FILE as a table.
8582 The file is assumed to be tab-separated. Such files can be produced by most
8583 spreadsheet and database applications. If no tabs (at least one per line)
8584 are found, lines will be split on whitespace into fields."
8585 (interactive "f\nP")
8586 (or (bolp) (newline))
8587 (let ((beg (point))
8588 (pm (point-max)))
8589 (insert-file-contents file)
8590 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8592 (defun org-table-export ()
8593 "Export table as a tab-separated file.
8594 Such a file can be imported into a spreadsheet program like Excel."
8595 (interactive)
8596 (let* ((beg (org-table-begin))
8597 (end (org-table-end))
8598 (table (buffer-substring beg end))
8599 (file (read-file-name "Export table to: "))
8600 buf)
8601 (unless (or (not (file-exists-p file))
8602 (y-or-n-p (format "Overwrite file %s? " file)))
8603 (error "Abort"))
8604 (with-current-buffer (find-file-noselect file)
8605 (setq buf (current-buffer))
8606 (erase-buffer)
8607 (fundamental-mode)
8608 (insert table)
8609 (goto-char (point-min))
8610 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8611 (replace-match "" t t)
8612 (end-of-line 1))
8613 (goto-char (point-min))
8614 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8615 (replace-match "" t t)
8616 (goto-char (min (1+ (point)) (point-max))))
8617 (goto-char (point-min))
8618 (while (re-search-forward "^-[-+]*$" nil t)
8619 (replace-match "")
8620 (if (looking-at "\n")
8621 (delete-char 1)))
8622 (goto-char (point-min))
8623 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8624 (replace-match "\t" t t))
8625 (save-buffer))
8626 (kill-buffer buf)))
8628 (defvar org-table-aligned-begin-marker (make-marker)
8629 "Marker at the beginning of the table last aligned.
8630 Used to check if cursor still is in that table, to minimize realignment.")
8631 (defvar org-table-aligned-end-marker (make-marker)
8632 "Marker at the end of the table last aligned.
8633 Used to check if cursor still is in that table, to minimize realignment.")
8634 (defvar org-table-last-alignment nil
8635 "List of flags for flushright alignment, from the last re-alignment.
8636 This is being used to correctly align a single field after TAB or RET.")
8637 (defvar org-table-last-column-widths nil
8638 "List of max width of fields in each column.
8639 This is being used to correctly align a single field after TAB or RET.")
8640 (defvar org-table-overlay-coordinates nil
8641 "Overlay coordinates after each align of a table.")
8642 (make-variable-buffer-local 'org-table-overlay-coordinates)
8644 (defvar org-last-recalc-line nil)
8645 (defconst org-narrow-column-arrow "=>"
8646 "Used as display property in narrowed table columns.")
8648 (defun org-table-align ()
8649 "Align the table at point by aligning all vertical bars."
8650 (interactive)
8651 (let* (
8652 ;; Limits of table
8653 (beg (org-table-begin))
8654 (end (org-table-end))
8655 ;; Current cursor position
8656 (linepos (org-current-line))
8657 (colpos (org-table-current-column))
8658 (winstart (window-start))
8659 (winstartline (org-current-line (min winstart (1- (point-max)))))
8660 lines (new "") lengths l typenums ty fields maxfields i
8661 column
8662 (indent "") cnt frac
8663 rfmt hfmt
8664 (spaces '(1 . 1))
8665 (sp1 (car spaces))
8666 (sp2 (cdr spaces))
8667 (rfmt1 (concat
8668 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8669 (hfmt1 (concat
8670 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8671 emptystrings links dates emph narrow fmax f1 len c e)
8672 (untabify beg end)
8673 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8674 ;; Check if we have links or dates
8675 (goto-char beg)
8676 (setq links (re-search-forward org-bracket-link-regexp end t))
8677 (goto-char beg)
8678 (setq emph (and org-hide-emphasis-markers
8679 (re-search-forward org-emph-re end t)))
8680 (goto-char beg)
8681 (setq dates (and org-display-custom-times
8682 (re-search-forward org-ts-regexp-both end t)))
8683 ;; Make sure the link properties are right
8684 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8685 ;; Make sure the date properties are right
8686 (when dates (goto-char beg) (while (org-activate-dates end)))
8687 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8689 ;; Check if we are narrowing any columns
8690 (goto-char beg)
8691 (setq narrow (and org-format-transports-properties-p
8692 (re-search-forward "<[0-9]+>" end t)))
8693 ;; Get the rows
8694 (setq lines (org-split-string
8695 (buffer-substring beg end) "\n"))
8696 ;; Store the indentation of the first line
8697 (if (string-match "^ *" (car lines))
8698 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8699 ;; Mark the hlines by setting the corresponding element to nil
8700 ;; At the same time, we remove trailing space.
8701 (setq lines (mapcar (lambda (l)
8702 (if (string-match "^ *|-" l)
8704 (if (string-match "[ \t]+$" l)
8705 (substring l 0 (match-beginning 0))
8706 l)))
8707 lines))
8708 ;; Get the data fields by splitting the lines.
8709 (setq fields (mapcar
8710 (lambda (l)
8711 (org-split-string l " *| *"))
8712 (delq nil (copy-sequence lines))))
8713 ;; How many fields in the longest line?
8714 (condition-case nil
8715 (setq maxfields (apply 'max (mapcar 'length fields)))
8716 (error
8717 (kill-region beg end)
8718 (org-table-create org-table-default-size)
8719 (error "Empty table - created default table")))
8720 ;; A list of empty strings to fill any short rows on output
8721 (setq emptystrings (make-list maxfields ""))
8722 ;; Check for special formatting.
8723 (setq i -1)
8724 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8725 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8726 ;; Check if there is an explicit width specified
8727 (when narrow
8728 (setq c column fmax nil)
8729 (while c
8730 (setq e (pop c))
8731 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8732 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8733 ;; Find fields that are wider than fmax, and shorten them
8734 (when fmax
8735 (loop for xx in column do
8736 (when (and (stringp xx)
8737 (> (org-string-width xx) fmax))
8738 (org-add-props xx nil
8739 'help-echo
8740 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8741 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8742 (unless (> f1 1)
8743 (error "Cannot narrow field starting with wide link \"%s\""
8744 (match-string 0 xx)))
8745 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8746 (add-text-properties (- f1 2) f1
8747 (list 'display org-narrow-column-arrow)
8748 xx)))))
8749 ;; Get the maximum width for each column
8750 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8751 ;; Get the fraction of numbers, to decide about alignment of the column
8752 (setq cnt 0 frac 0.0)
8753 (loop for x in column do
8754 (if (equal x "")
8756 (setq frac ( / (+ (* frac cnt)
8757 (if (string-match org-table-number-regexp x) 1 0))
8758 (setq cnt (1+ cnt))))))
8759 (push (>= frac org-table-number-fraction) typenums))
8760 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8762 ;; Store the alignment of this table, for later editing of single fields
8763 (setq org-table-last-alignment typenums
8764 org-table-last-column-widths lengths)
8766 ;; With invisible characters, `format' does not get the field width right
8767 ;; So we need to make these fields wide by hand.
8768 (when (or links emph)
8769 (loop for i from 0 upto (1- maxfields) do
8770 (setq len (nth i lengths))
8771 (loop for j from 0 upto (1- (length fields)) do
8772 (setq c (nthcdr i (car (nthcdr j fields))))
8773 (if (and (stringp (car c))
8774 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8775 ; (string-match org-bracket-link-regexp (car c))
8776 (< (org-string-width (car c)) len))
8777 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8779 ;; Compute the formats needed for output of the table
8780 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8781 (while (setq l (pop lengths))
8782 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8783 (setq rfmt (concat rfmt (format rfmt1 ty l))
8784 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8785 (setq rfmt (concat rfmt "\n")
8786 hfmt (concat (substring hfmt 0 -1) "|\n"))
8788 (setq new (mapconcat
8789 (lambda (l)
8790 (if l (apply 'format rfmt
8791 (append (pop fields) emptystrings))
8792 hfmt))
8793 lines ""))
8794 ;; Replace the old one
8795 (delete-region beg end)
8796 (move-marker end nil)
8797 (move-marker org-table-aligned-begin-marker (point))
8798 (insert new)
8799 (move-marker org-table-aligned-end-marker (point))
8800 (when (and orgtbl-mode (not (org-mode-p)))
8801 (goto-char org-table-aligned-begin-marker)
8802 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8803 ;; Try to move to the old location
8804 (goto-line winstartline)
8805 (setq winstart (point-at-bol))
8806 (goto-line linepos)
8807 (set-window-start (selected-window) winstart 'noforce)
8808 (org-table-goto-column colpos)
8809 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8810 (setq org-table-may-need-update nil)
8813 (defun org-string-width (s)
8814 "Compute width of string, ignoring invisible characters.
8815 This ignores character with invisibility property `org-link', and also
8816 characters with property `org-cwidth', because these will become invisible
8817 upon the next fontification round."
8818 (let (b l)
8819 (when (or (eq t buffer-invisibility-spec)
8820 (assq 'org-link buffer-invisibility-spec))
8821 (while (setq b (text-property-any 0 (length s)
8822 'invisible 'org-link s))
8823 (setq s (concat (substring s 0 b)
8824 (substring s (or (next-single-property-change
8825 b 'invisible s) (length s)))))))
8826 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8827 (setq s (concat (substring s 0 b)
8828 (substring s (or (next-single-property-change
8829 b 'org-cwidth s) (length s))))))
8830 (setq l (string-width s) b -1)
8831 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8832 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8835 (defun org-table-begin (&optional table-type)
8836 "Find the beginning of the table and return its position.
8837 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8838 (save-excursion
8839 (if (not (re-search-backward
8840 (if table-type org-table-any-border-regexp
8841 org-table-border-regexp)
8842 nil t))
8843 (progn (goto-char (point-min)) (point))
8844 (goto-char (match-beginning 0))
8845 (beginning-of-line 2)
8846 (point))))
8848 (defun org-table-end (&optional table-type)
8849 "Find the end of the table and return its position.
8850 With argument TABLE-TYPE, go to the end of a table.el-type table."
8851 (save-excursion
8852 (if (not (re-search-forward
8853 (if table-type org-table-any-border-regexp
8854 org-table-border-regexp)
8855 nil t))
8856 (goto-char (point-max))
8857 (goto-char (match-beginning 0)))
8858 (point-marker)))
8860 (defun org-table-justify-field-maybe (&optional new)
8861 "Justify the current field, text to left, number to right.
8862 Optional argument NEW may specify text to replace the current field content."
8863 (cond
8864 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8865 ((org-at-table-hline-p))
8866 ((and (not new)
8867 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8868 (current-buffer)))
8869 (< (point) org-table-aligned-begin-marker)
8870 (>= (point) org-table-aligned-end-marker)))
8871 ;; This is not the same table, force a full re-align
8872 (setq org-table-may-need-update t))
8873 (t ;; realign the current field, based on previous full realign
8874 (let* ((pos (point)) s
8875 (col (org-table-current-column))
8876 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8877 l f n o e)
8878 (when (> col 0)
8879 (skip-chars-backward "^|\n")
8880 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8881 (progn
8882 (setq s (match-string 1)
8883 o (match-string 0)
8884 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8885 e (not (= (match-beginning 2) (match-end 2))))
8886 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8887 l (if e "|" (setq org-table-may-need-update t) ""))
8888 n (format f s))
8889 (if new
8890 (if (<= (length new) l) ;; FIXME: length -> str-width?
8891 (setq n (format f new))
8892 (setq n (concat new "|") org-table-may-need-update t)))
8893 (or (equal n o)
8894 (let (org-table-may-need-update)
8895 (replace-match n t t))))
8896 (setq org-table-may-need-update t))
8897 (goto-char pos))))))
8899 (defun org-table-next-field ()
8900 "Go to the next field in the current table, creating new lines as needed.
8901 Before doing so, re-align the table if necessary."
8902 (interactive)
8903 (org-table-maybe-eval-formula)
8904 (org-table-maybe-recalculate-line)
8905 (if (and org-table-automatic-realign
8906 org-table-may-need-update)
8907 (org-table-align))
8908 (let ((end (org-table-end)))
8909 (if (org-at-table-hline-p)
8910 (end-of-line 1))
8911 (condition-case nil
8912 (progn
8913 (re-search-forward "|" end)
8914 (if (looking-at "[ \t]*$")
8915 (re-search-forward "|" end))
8916 (if (and (looking-at "-")
8917 org-table-tab-jumps-over-hlines
8918 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8919 (goto-char (match-beginning 1)))
8920 (if (looking-at "-")
8921 (progn
8922 (beginning-of-line 0)
8923 (org-table-insert-row 'below))
8924 (if (looking-at " ") (forward-char 1))))
8925 (error
8926 (org-table-insert-row 'below)))))
8928 (defun org-table-previous-field ()
8929 "Go to the previous field in the table.
8930 Before doing so, re-align the table if necessary."
8931 (interactive)
8932 (org-table-justify-field-maybe)
8933 (org-table-maybe-recalculate-line)
8934 (if (and org-table-automatic-realign
8935 org-table-may-need-update)
8936 (org-table-align))
8937 (if (org-at-table-hline-p)
8938 (end-of-line 1))
8939 (re-search-backward "|" (org-table-begin))
8940 (re-search-backward "|" (org-table-begin))
8941 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8942 (re-search-backward "|" (org-table-begin)))
8943 (if (looking-at "| ?")
8944 (goto-char (match-end 0))))
8946 (defun org-table-next-row ()
8947 "Go to the next row (same column) in the current table.
8948 Before doing so, re-align the table if necessary."
8949 (interactive)
8950 (org-table-maybe-eval-formula)
8951 (org-table-maybe-recalculate-line)
8952 (if (or (looking-at "[ \t]*$")
8953 (save-excursion (skip-chars-backward " \t") (bolp)))
8954 (newline)
8955 (if (and org-table-automatic-realign
8956 org-table-may-need-update)
8957 (org-table-align))
8958 (let ((col (org-table-current-column)))
8959 (beginning-of-line 2)
8960 (if (or (not (org-at-table-p))
8961 (org-at-table-hline-p))
8962 (progn
8963 (beginning-of-line 0)
8964 (org-table-insert-row 'below)))
8965 (org-table-goto-column col)
8966 (skip-chars-backward "^|\n\r")
8967 (if (looking-at " ") (forward-char 1)))))
8969 (defun org-table-copy-down (n)
8970 "Copy a field down in the current column.
8971 If the field at the cursor is empty, copy into it the content of the nearest
8972 non-empty field above. With argument N, use the Nth non-empty field.
8973 If the current field is not empty, it is copied down to the next row, and
8974 the cursor is moved with it. Therefore, repeating this command causes the
8975 column to be filled row-by-row.
8976 If the variable `org-table-copy-increment' is non-nil and the field is an
8977 integer or a timestamp, it will be incremented while copying. In the case of
8978 a timestamp, if the cursor is on the year, change the year. If it is on the
8979 month or the day, change that. Point will stay on the current date field
8980 in order to easily repeat the interval."
8981 (interactive "p")
8982 (let* ((colpos (org-table-current-column))
8983 (col (current-column))
8984 (field (org-table-get-field))
8985 (non-empty (string-match "[^ \t]" field))
8986 (beg (org-table-begin))
8987 txt)
8988 (org-table-check-inside-data-field)
8989 (if non-empty
8990 (progn
8991 (setq txt (org-trim field))
8992 (org-table-next-row)
8993 (org-table-blank-field))
8994 (save-excursion
8995 (setq txt
8996 (catch 'exit
8997 (while (progn (beginning-of-line 1)
8998 (re-search-backward org-table-dataline-regexp
8999 beg t))
9000 (org-table-goto-column colpos t)
9001 (if (and (looking-at
9002 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
9003 (= (setq n (1- n)) 0))
9004 (throw 'exit (match-string 1))))))))
9005 (if txt
9006 (progn
9007 (if (and org-table-copy-increment
9008 (string-match "^[0-9]+$" txt))
9009 (setq txt (format "%d" (+ (string-to-number txt) 1))))
9010 (insert txt)
9011 (move-to-column col)
9012 (if (and org-table-copy-increment (org-at-timestamp-p t))
9013 (org-timestamp-up 1)
9014 (org-table-maybe-recalculate-line))
9015 (org-table-align)
9016 (move-to-column col))
9017 (error "No non-empty field found"))))
9019 (defun org-table-check-inside-data-field ()
9020 "Is point inside a table data field?
9021 I.e. not on a hline or before the first or after the last column?
9022 This actually throws an error, so it aborts the current command."
9023 (if (or (not (org-at-table-p))
9024 (= (org-table-current-column) 0)
9025 (org-at-table-hline-p)
9026 (looking-at "[ \t]*$"))
9027 (error "Not in table data field")))
9029 (defvar org-table-clip nil
9030 "Clipboard for table regions.")
9032 (defun org-table-blank-field ()
9033 "Blank the current table field or active region."
9034 (interactive)
9035 (org-table-check-inside-data-field)
9036 (if (and (interactive-p) (org-region-active-p))
9037 (let (org-table-clip)
9038 (org-table-cut-region (region-beginning) (region-end)))
9039 (skip-chars-backward "^|")
9040 (backward-char 1)
9041 (if (looking-at "|[^|\n]+")
9042 (let* ((pos (match-beginning 0))
9043 (match (match-string 0))
9044 (len (org-string-width match)))
9045 (replace-match (concat "|" (make-string (1- len) ?\ )))
9046 (goto-char (+ 2 pos))
9047 (substring match 1)))))
9049 (defun org-table-get-field (&optional n replace)
9050 "Return the value of the field in column N of current row.
9051 N defaults to current field.
9052 If REPLACE is a string, replace field with this value. The return value
9053 is always the old value."
9054 (and n (org-table-goto-column n))
9055 (skip-chars-backward "^|\n")
9056 (backward-char 1)
9057 (if (looking-at "|[^|\r\n]*")
9058 (let* ((pos (match-beginning 0))
9059 (val (buffer-substring (1+ pos) (match-end 0))))
9060 (if replace
9061 (replace-match (concat "|" replace) t t))
9062 (goto-char (min (point-at-eol) (+ 2 pos)))
9063 val)
9064 (forward-char 1) ""))
9066 (defun org-table-field-info (arg)
9067 "Show info about the current field, and highlight any reference at point."
9068 (interactive "P")
9069 (org-table-get-specials)
9070 (save-excursion
9071 (let* ((pos (point))
9072 (col (org-table-current-column))
9073 (cname (car (rassoc (int-to-string col) org-table-column-names)))
9074 (name (car (rassoc (list (org-current-line) col)
9075 org-table-named-field-locations)))
9076 (eql (org-table-get-stored-formulas))
9077 (dline (org-table-current-dline))
9078 (ref (format "@%d$%d" dline col))
9079 (ref1 (org-table-convert-refs-to-an ref))
9080 (fequation (or (assoc name eql) (assoc ref eql)))
9081 (cequation (assoc (int-to-string col) eql))
9082 (eqn (or fequation cequation)))
9083 (goto-char pos)
9084 (condition-case nil
9085 (org-table-show-reference 'local)
9086 (error nil))
9087 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
9088 dline col
9089 (if cname (concat " or $" cname) "")
9090 dline col ref1
9091 (if name (concat " or $" name) "")
9092 ;; FIXME: formula info not correct if special table line
9093 (if eqn
9094 (concat ", formula: "
9095 (org-table-formula-to-user
9096 (concat
9097 (if (string-match "^[$@]"(car eqn)) "" "$")
9098 (car eqn) "=" (cdr eqn))))
9099 "")))))
9101 (defun org-table-current-column ()
9102 "Find out which column we are in.
9103 When called interactively, column is also displayed in echo area."
9104 (interactive)
9105 (if (interactive-p) (org-table-check-inside-data-field))
9106 (save-excursion
9107 (let ((cnt 0) (pos (point)))
9108 (beginning-of-line 1)
9109 (while (search-forward "|" pos t)
9110 (setq cnt (1+ cnt)))
9111 (if (interactive-p) (message "This is table column %d" cnt))
9112 cnt)))
9114 (defun org-table-current-dline ()
9115 "Find out what table data line we are in.
9116 Only datalins count for this."
9117 (interactive)
9118 (if (interactive-p) (org-table-check-inside-data-field))
9119 (save-excursion
9120 (let ((cnt 0) (pos (point)))
9121 (goto-char (org-table-begin))
9122 (while (<= (point) pos)
9123 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
9124 (beginning-of-line 2))
9125 (if (interactive-p) (message "This is table line %d" cnt))
9126 cnt)))
9128 (defun org-table-goto-column (n &optional on-delim force)
9129 "Move the cursor to the Nth column in the current table line.
9130 With optional argument ON-DELIM, stop with point before the left delimiter
9131 of the field.
9132 If there are less than N fields, just go to after the last delimiter.
9133 However, when FORCE is non-nil, create new columns if necessary."
9134 (interactive "p")
9135 (let ((pos (point-at-eol)))
9136 (beginning-of-line 1)
9137 (when (> n 0)
9138 (while (and (> (setq n (1- n)) -1)
9139 (or (search-forward "|" pos t)
9140 (and force
9141 (progn (end-of-line 1)
9142 (skip-chars-backward "^|")
9143 (insert " | "))))))
9144 ; (backward-char 2) t)))))
9145 (when (and force (not (looking-at ".*|")))
9146 (save-excursion (end-of-line 1) (insert " | ")))
9147 (if on-delim
9148 (backward-char 1)
9149 (if (looking-at " ") (forward-char 1))))))
9151 (defun org-at-table-p (&optional table-type)
9152 "Return t if the cursor is inside an org-type table.
9153 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9154 (if org-enable-table-editor
9155 (save-excursion
9156 (beginning-of-line 1)
9157 (looking-at (if table-type org-table-any-line-regexp
9158 org-table-line-regexp)))
9159 nil))
9161 (defun org-at-table.el-p ()
9162 "Return t if and only if we are at a table.el table."
9163 (and (org-at-table-p 'any)
9164 (save-excursion
9165 (goto-char (org-table-begin 'any))
9166 (looking-at org-table1-hline-regexp))))
9168 (defun org-table-recognize-table.el ()
9169 "If there is a table.el table nearby, recognize it and move into it."
9170 (if org-table-tab-recognizes-table.el
9171 (if (org-at-table.el-p)
9172 (progn
9173 (beginning-of-line 1)
9174 (if (looking-at org-table-dataline-regexp)
9176 (if (looking-at org-table1-hline-regexp)
9177 (progn
9178 (beginning-of-line 2)
9179 (if (looking-at org-table-any-border-regexp)
9180 (beginning-of-line -1)))))
9181 (if (re-search-forward "|" (org-table-end t) t)
9182 (progn
9183 (require 'table)
9184 (if (table--at-cell-p (point))
9186 (message "recognizing table.el table...")
9187 (table-recognize-table)
9188 (message "recognizing table.el table...done")))
9189 (error "This should not happen..."))
9191 nil)
9192 nil))
9194 (defun org-at-table-hline-p ()
9195 "Return t if the cursor is inside a hline in a table."
9196 (if org-enable-table-editor
9197 (save-excursion
9198 (beginning-of-line 1)
9199 (looking-at org-table-hline-regexp))
9200 nil))
9202 (defun org-table-insert-column ()
9203 "Insert a new column into the table."
9204 (interactive)
9205 (if (not (org-at-table-p))
9206 (error "Not at a table"))
9207 (org-table-find-dataline)
9208 (let* ((col (max 1 (org-table-current-column)))
9209 (beg (org-table-begin))
9210 (end (org-table-end))
9211 ;; Current cursor position
9212 (linepos (org-current-line))
9213 (colpos col))
9214 (goto-char beg)
9215 (while (< (point) end)
9216 (if (org-at-table-hline-p)
9218 (org-table-goto-column col t)
9219 (insert "| "))
9220 (beginning-of-line 2))
9221 (move-marker end nil)
9222 (goto-line linepos)
9223 (org-table-goto-column colpos)
9224 (org-table-align)
9225 (org-table-fix-formulas "$" nil (1- col) 1)))
9227 (defun org-table-find-dataline ()
9228 "Find a dataline in the current table, which is needed for column commands."
9229 (if (and (org-at-table-p)
9230 (not (org-at-table-hline-p)))
9232 (let ((col (current-column))
9233 (end (org-table-end)))
9234 (move-to-column col)
9235 (while (and (< (point) end)
9236 (or (not (= (current-column) col))
9237 (org-at-table-hline-p)))
9238 (beginning-of-line 2)
9239 (move-to-column col))
9240 (if (and (org-at-table-p)
9241 (not (org-at-table-hline-p)))
9243 (error
9244 "Please position cursor in a data line for column operations")))))
9246 (defun org-table-delete-column ()
9247 "Delete a column from the table."
9248 (interactive)
9249 (if (not (org-at-table-p))
9250 (error "Not at a table"))
9251 (org-table-find-dataline)
9252 (org-table-check-inside-data-field)
9253 (let* ((col (org-table-current-column))
9254 (beg (org-table-begin))
9255 (end (org-table-end))
9256 ;; Current cursor position
9257 (linepos (org-current-line))
9258 (colpos col))
9259 (goto-char beg)
9260 (while (< (point) end)
9261 (if (org-at-table-hline-p)
9263 (org-table-goto-column col t)
9264 (and (looking-at "|[^|\n]+|")
9265 (replace-match "|")))
9266 (beginning-of-line 2))
9267 (move-marker end nil)
9268 (goto-line linepos)
9269 (org-table-goto-column colpos)
9270 (org-table-align)
9271 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9272 col -1 col)))
9274 (defun org-table-move-column-right ()
9275 "Move column to the right."
9276 (interactive)
9277 (org-table-move-column nil))
9278 (defun org-table-move-column-left ()
9279 "Move column to the left."
9280 (interactive)
9281 (org-table-move-column 'left))
9283 (defun org-table-move-column (&optional left)
9284 "Move the current column to the right. With arg LEFT, move to the left."
9285 (interactive "P")
9286 (if (not (org-at-table-p))
9287 (error "Not at a table"))
9288 (org-table-find-dataline)
9289 (org-table-check-inside-data-field)
9290 (let* ((col (org-table-current-column))
9291 (col1 (if left (1- col) col))
9292 (beg (org-table-begin))
9293 (end (org-table-end))
9294 ;; Current cursor position
9295 (linepos (org-current-line))
9296 (colpos (if left (1- col) (1+ col))))
9297 (if (and left (= col 1))
9298 (error "Cannot move column further left"))
9299 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9300 (error "Cannot move column further right"))
9301 (goto-char beg)
9302 (while (< (point) end)
9303 (if (org-at-table-hline-p)
9305 (org-table-goto-column col1 t)
9306 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9307 (replace-match "|\\2|\\1|")))
9308 (beginning-of-line 2))
9309 (move-marker end nil)
9310 (goto-line linepos)
9311 (org-table-goto-column colpos)
9312 (org-table-align)
9313 (org-table-fix-formulas
9314 "$" (list (cons (number-to-string col) (number-to-string colpos))
9315 (cons (number-to-string colpos) (number-to-string col))))))
9317 (defun org-table-move-row-down ()
9318 "Move table row down."
9319 (interactive)
9320 (org-table-move-row nil))
9321 (defun org-table-move-row-up ()
9322 "Move table row up."
9323 (interactive)
9324 (org-table-move-row 'up))
9326 (defun org-table-move-row (&optional up)
9327 "Move the current table line down. With arg UP, move it up."
9328 (interactive "P")
9329 (let* ((col (current-column))
9330 (pos (point))
9331 (hline1p (save-excursion (beginning-of-line 1)
9332 (looking-at org-table-hline-regexp)))
9333 (dline1 (org-table-current-dline))
9334 (dline2 (+ dline1 (if up -1 1)))
9335 (tonew (if up 0 2))
9336 txt hline2p)
9337 (beginning-of-line tonew)
9338 (unless (org-at-table-p)
9339 (goto-char pos)
9340 (error "Cannot move row further"))
9341 (setq hline2p (looking-at org-table-hline-regexp))
9342 (goto-char pos)
9343 (beginning-of-line 1)
9344 (setq pos (point))
9345 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9346 (delete-region (point) (1+ (point-at-eol)))
9347 (beginning-of-line tonew)
9348 (insert txt)
9349 (beginning-of-line 0)
9350 (move-to-column col)
9351 (unless (or hline1p hline2p)
9352 (org-table-fix-formulas
9353 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9354 (cons (number-to-string dline2) (number-to-string dline1)))))))
9356 (defun org-table-insert-row (&optional arg)
9357 "Insert a new row above the current line into the table.
9358 With prefix ARG, insert below the current line."
9359 (interactive "P")
9360 (if (not (org-at-table-p))
9361 (error "Not at a table"))
9362 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9363 (new (org-table-clean-line line)))
9364 ;; Fix the first field if necessary
9365 (if (string-match "^[ \t]*| *[#$] *|" line)
9366 (setq new (replace-match (match-string 0 line) t t new)))
9367 (beginning-of-line (if arg 2 1))
9368 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9369 (beginning-of-line 0)
9370 (re-search-forward "| ?" (point-at-eol) t)
9371 (and (or org-table-may-need-update org-table-overlay-coordinates)
9372 (org-table-align))
9373 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9375 (defun org-table-insert-hline (&optional above)
9376 "Insert a horizontal-line below the current line into the table.
9377 With prefix ABOVE, insert above the current line."
9378 (interactive "P")
9379 (if (not (org-at-table-p))
9380 (error "Not at a table"))
9381 (let ((line (org-table-clean-line
9382 (buffer-substring (point-at-bol) (point-at-eol))))
9383 (col (current-column)))
9384 (while (string-match "|\\( +\\)|" line)
9385 (setq line (replace-match
9386 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9387 ?-) "|") t t line)))
9388 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9389 (beginning-of-line (if above 1 2))
9390 (insert line "\n")
9391 (beginning-of-line (if above 1 -1))
9392 (move-to-column col)
9393 (and org-table-overlay-coordinates (org-table-align))))
9395 (defun org-table-hline-and-move (&optional same-column)
9396 "Insert a hline and move to the row below that line."
9397 (interactive "P")
9398 (let ((col (org-table-current-column)))
9399 (org-table-maybe-eval-formula)
9400 (org-table-maybe-recalculate-line)
9401 (org-table-insert-hline)
9402 (end-of-line 2)
9403 (if (looking-at "\n[ \t]*|-")
9404 (progn (insert "\n|") (org-table-align))
9405 (org-table-next-field))
9406 (if same-column (org-table-goto-column col))))
9408 (defun org-table-clean-line (s)
9409 "Convert a table line S into a string with only \"|\" and space.
9410 In particular, this does handle wide and invisible characters."
9411 (if (string-match "^[ \t]*|-" s)
9412 ;; It's a hline, just map the characters
9413 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9414 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9415 (setq s (replace-match
9416 (concat "|" (make-string (org-string-width (match-string 1 s))
9417 ?\ ) "|")
9418 t t s)))
9421 (defun org-table-kill-row ()
9422 "Delete the current row or horizontal line from the table."
9423 (interactive)
9424 (if (not (org-at-table-p))
9425 (error "Not at a table"))
9426 (let ((col (current-column))
9427 (dline (org-table-current-dline)))
9428 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9429 (if (not (org-at-table-p)) (beginning-of-line 0))
9430 (move-to-column col)
9431 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9432 dline -1 dline)))
9434 (defun org-table-sort-lines (with-case &optional sorting-type)
9435 "Sort table lines according to the column at point.
9437 The position of point indicates the column to be used for
9438 sorting, and the range of lines is the range between the nearest
9439 horizontal separator lines, or the entire table of no such lines
9440 exist. If point is before the first column, you will be prompted
9441 for the sorting column. If there is an active region, the mark
9442 specifies the first line and the sorting column, while point
9443 should be in the last line to be included into the sorting.
9445 The command then prompts for the sorting type which can be
9446 alphabetically, numerically, or by time (as given in a time stamp
9447 in the field). Sorting in reverse order is also possible.
9449 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9451 If SORTING-TYPE is specified when this function is called from a Lisp
9452 program, no prompting will take place. SORTING-TYPE must be a character,
9453 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9454 should be done in reverse order."
9455 (interactive "P")
9456 (let* ((thisline (org-current-line))
9457 (thiscol (org-table-current-column))
9458 beg end bcol ecol tend tbeg column lns pos)
9459 (when (equal thiscol 0)
9460 (if (interactive-p)
9461 (setq thiscol
9462 (string-to-number
9463 (read-string "Use column N for sorting: ")))
9464 (setq thiscol 1))
9465 (org-table-goto-column thiscol))
9466 (org-table-check-inside-data-field)
9467 (if (org-region-active-p)
9468 (progn
9469 (setq beg (region-beginning) end (region-end))
9470 (goto-char beg)
9471 (setq column (org-table-current-column)
9472 beg (point-at-bol))
9473 (goto-char end)
9474 (setq end (point-at-bol 2)))
9475 (setq column (org-table-current-column)
9476 pos (point)
9477 tbeg (org-table-begin)
9478 tend (org-table-end))
9479 (if (re-search-backward org-table-hline-regexp tbeg t)
9480 (setq beg (point-at-bol 2))
9481 (goto-char tbeg)
9482 (setq beg (point-at-bol 1)))
9483 (goto-char pos)
9484 (if (re-search-forward org-table-hline-regexp tend t)
9485 (setq end (point-at-bol 1))
9486 (goto-char tend)
9487 (setq end (point-at-bol))))
9488 (setq beg (move-marker (make-marker) beg)
9489 end (move-marker (make-marker) end))
9490 (untabify beg end)
9491 (goto-char beg)
9492 (org-table-goto-column column)
9493 (skip-chars-backward "^|")
9494 (setq bcol (current-column))
9495 (org-table-goto-column (1+ column))
9496 (skip-chars-backward "^|")
9497 (setq ecol (1- (current-column)))
9498 (org-table-goto-column column)
9499 (setq lns (mapcar (lambda(x) (cons
9500 (org-sort-remove-invisible
9501 (nth (1- column)
9502 (org-split-string x "[ \t]*|[ \t]*")))
9504 (org-split-string (buffer-substring beg end) "\n")))
9505 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9506 (delete-region beg end)
9507 (move-marker beg nil)
9508 (move-marker end nil)
9509 (insert (mapconcat 'cdr lns "\n") "\n")
9510 (goto-line thisline)
9511 (org-table-goto-column thiscol)
9512 (message "%d lines sorted, based on column %d" (length lns) column)))
9514 ;; FIXME: maybe we will not need this? Table sorting is broken....
9515 (defun org-sort-remove-invisible (s)
9516 (remove-text-properties 0 (length s) org-rm-props s)
9517 (while (string-match org-bracket-link-regexp s)
9518 (setq s (replace-match (if (match-end 2)
9519 (match-string 3 s)
9520 (match-string 1 s)) t t s)))
9523 (defun org-table-cut-region (beg end)
9524 "Copy region in table to the clipboard and blank all relevant fields."
9525 (interactive "r")
9526 (org-table-copy-region beg end 'cut))
9528 (defun org-table-copy-region (beg end &optional cut)
9529 "Copy rectangular region in table to clipboard.
9530 A special clipboard is used which can only be accessed
9531 with `org-table-paste-rectangle'."
9532 (interactive "rP")
9533 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9534 region cols
9535 (rpl (if cut " " nil)))
9536 (goto-char beg)
9537 (org-table-check-inside-data-field)
9538 (setq l01 (org-current-line)
9539 c01 (org-table-current-column))
9540 (goto-char end)
9541 (org-table-check-inside-data-field)
9542 (setq l02 (org-current-line)
9543 c02 (org-table-current-column))
9544 (setq l1 (min l01 l02) l2 (max l01 l02)
9545 c1 (min c01 c02) c2 (max c01 c02))
9546 (catch 'exit
9547 (while t
9548 (catch 'nextline
9549 (if (> l1 l2) (throw 'exit t))
9550 (goto-line l1)
9551 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9552 (setq cols nil ic1 c1 ic2 c2)
9553 (while (< ic1 (1+ ic2))
9554 (push (org-table-get-field ic1 rpl) cols)
9555 (setq ic1 (1+ ic1)))
9556 (push (nreverse cols) region)
9557 (setq l1 (1+ l1)))))
9558 (setq org-table-clip (nreverse region))
9559 (if cut (org-table-align))
9560 org-table-clip))
9562 (defun org-table-paste-rectangle ()
9563 "Paste a rectangular region into a table.
9564 The upper right corner ends up in the current field. All involved fields
9565 will be overwritten. If the rectangle does not fit into the present table,
9566 the table is enlarged as needed. The process ignores horizontal separator
9567 lines."
9568 (interactive)
9569 (unless (and org-table-clip (listp org-table-clip))
9570 (error "First cut/copy a region to paste!"))
9571 (org-table-check-inside-data-field)
9572 (let* ((clip org-table-clip)
9573 (line (org-current-line))
9574 (col (org-table-current-column))
9575 (org-enable-table-editor t)
9576 (org-table-automatic-realign nil)
9577 c cols field)
9578 (while (setq cols (pop clip))
9579 (while (org-at-table-hline-p) (beginning-of-line 2))
9580 (if (not (org-at-table-p))
9581 (progn (end-of-line 0) (org-table-next-field)))
9582 (setq c col)
9583 (while (setq field (pop cols))
9584 (org-table-goto-column c nil 'force)
9585 (org-table-get-field nil field)
9586 (setq c (1+ c)))
9587 (beginning-of-line 2))
9588 (goto-line line)
9589 (org-table-goto-column col)
9590 (org-table-align)))
9592 (defun org-table-convert ()
9593 "Convert from `org-mode' table to table.el and back.
9594 Obviously, this only works within limits. When an Org-mode table is
9595 converted to table.el, all horizontal separator lines get lost, because
9596 table.el uses these as cell boundaries and has no notion of horizontal lines.
9597 A table.el table can be converted to an Org-mode table only if it does not
9598 do row or column spanning. Multiline cells will become multiple cells.
9599 Beware, Org-mode does not test if the table can be successfully converted - it
9600 blindly applies a recipe that works for simple tables."
9601 (interactive)
9602 (require 'table)
9603 (if (org-at-table.el-p)
9604 ;; convert to Org-mode table
9605 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9606 (end (move-marker (make-marker) (org-table-end t))))
9607 (table-unrecognize-region beg end)
9608 (goto-char beg)
9609 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9610 (replace-match ""))
9611 (goto-char beg))
9612 (if (org-at-table-p)
9613 ;; convert to table.el table
9614 (let ((beg (move-marker (make-marker) (org-table-begin)))
9615 (end (move-marker (make-marker) (org-table-end))))
9616 ;; first, get rid of all horizontal lines
9617 (goto-char beg)
9618 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9619 (replace-match ""))
9620 ;; insert a hline before first
9621 (goto-char beg)
9622 (org-table-insert-hline 'above)
9623 (beginning-of-line -1)
9624 ;; insert a hline after each line
9625 (while (progn (beginning-of-line 3) (< (point) end))
9626 (org-table-insert-hline))
9627 (goto-char beg)
9628 (setq end (move-marker end (org-table-end)))
9629 ;; replace "+" at beginning and ending of hlines
9630 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9631 (replace-match "\\1+-"))
9632 (goto-char beg)
9633 (while (re-search-forward "-|[ \t]*$" end t)
9634 (replace-match "-+"))
9635 (goto-char beg)))))
9637 (defun org-table-wrap-region (arg)
9638 "Wrap several fields in a column like a paragraph.
9639 This is useful if you'd like to spread the contents of a field over several
9640 lines, in order to keep the table compact.
9642 If there is an active region, and both point and mark are in the same column,
9643 the text in the column is wrapped to minimum width for the given number of
9644 lines. Generally, this makes the table more compact. A prefix ARG may be
9645 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9646 formats the selected text to two lines. If the region was longer than two
9647 lines, the remaining lines remain empty. A negative prefix argument reduces
9648 the current number of lines by that amount. The wrapped text is pasted back
9649 into the table. If you formatted it to more lines than it was before, fields
9650 further down in the table get overwritten - so you might need to make space in
9651 the table first.
9653 If there is no region, the current field is split at the cursor position and
9654 the text fragment to the right of the cursor is prepended to the field one
9655 line down.
9657 If there is no region, but you specify a prefix ARG, the current field gets
9658 blank, and the content is appended to the field above."
9659 (interactive "P")
9660 (org-table-check-inside-data-field)
9661 (if (org-region-active-p)
9662 ;; There is a region: fill as a paragraph
9663 (let* ((beg (region-beginning))
9664 (cline (save-excursion (goto-char beg) (org-current-line)))
9665 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9666 nlines)
9667 (org-table-cut-region (region-beginning) (region-end))
9668 (if (> (length (car org-table-clip)) 1)
9669 (error "Region must be limited to single column"))
9670 (setq nlines (if arg
9671 (if (< arg 1)
9672 (+ (length org-table-clip) arg)
9673 arg)
9674 (length org-table-clip)))
9675 (setq org-table-clip
9676 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9677 nil nlines)))
9678 (goto-line cline)
9679 (org-table-goto-column ccol)
9680 (org-table-paste-rectangle))
9681 ;; No region, split the current field at point
9682 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9683 (skip-chars-forward "^\r\n|"))
9684 (if arg
9685 ;; combine with field above
9686 (let ((s (org-table-blank-field))
9687 (col (org-table-current-column)))
9688 (beginning-of-line 0)
9689 (while (org-at-table-hline-p) (beginning-of-line 0))
9690 (org-table-goto-column col)
9691 (skip-chars-forward "^|")
9692 (skip-chars-backward " ")
9693 (insert " " (org-trim s))
9694 (org-table-align))
9695 ;; split field
9696 (if (looking-at "\\([^|]+\\)+|")
9697 (let ((s (match-string 1)))
9698 (replace-match " |")
9699 (goto-char (match-beginning 0))
9700 (org-table-next-row)
9701 (insert (org-trim s) " ")
9702 (org-table-align))
9703 (org-table-next-row)))))
9705 (defvar org-field-marker nil)
9707 (defun org-table-edit-field (arg)
9708 "Edit table field in a different window.
9709 This is mainly useful for fields that contain hidden parts.
9710 When called with a \\[universal-argument] prefix, just make the full field visible so that
9711 it can be edited in place."
9712 (interactive "P")
9713 (if arg
9714 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9715 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9716 (remove-text-properties b e '(org-cwidth t invisible t
9717 display t intangible t))
9718 (if (and (boundp 'font-lock-mode) font-lock-mode)
9719 (font-lock-fontify-block)))
9720 (let ((pos (move-marker (make-marker) (point)))
9721 (field (org-table-get-field))
9722 (cw (current-window-configuration))
9724 (org-switch-to-buffer-other-window "*Org tmp*")
9725 (erase-buffer)
9726 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9727 (let ((org-inhibit-startup t)) (org-mode))
9728 (goto-char (setq p (point-max)))
9729 (insert (org-trim field))
9730 (remove-text-properties p (point-max)
9731 '(invisible t org-cwidth t display t
9732 intangible t))
9733 (goto-char p)
9734 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9735 (org-set-local 'org-window-configuration cw)
9736 (org-set-local 'org-field-marker pos)
9737 (message "Edit and finish with C-c C-c"))))
9739 (defun org-table-finish-edit-field ()
9740 "Finish editing a table data field.
9741 Remove all newline characters, insert the result into the table, realign
9742 the table and kill the editing buffer."
9743 (let ((pos org-field-marker)
9744 (cw org-window-configuration)
9745 (cb (current-buffer))
9746 text)
9747 (goto-char (point-min))
9748 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9749 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9750 (replace-match " "))
9751 (setq text (org-trim (buffer-string)))
9752 (set-window-configuration cw)
9753 (kill-buffer cb)
9754 (select-window (get-buffer-window (marker-buffer pos)))
9755 (goto-char pos)
9756 (move-marker pos nil)
9757 (org-table-check-inside-data-field)
9758 (org-table-get-field nil text)
9759 (org-table-align)
9760 (message "New field value inserted")))
9762 (defun org-trim (s)
9763 "Remove whitespace at beginning and end of string."
9764 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9765 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9768 (defun org-wrap (string &optional width lines)
9769 "Wrap string to either a number of lines, or a width in characters.
9770 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9771 that costs. If there is a word longer than WIDTH, the text is actually
9772 wrapped to the length of that word.
9773 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9774 many lines, whatever width that takes.
9775 The return value is a list of lines, without newlines at the end."
9776 (let* ((words (org-split-string string "[ \t\n]+"))
9777 (maxword (apply 'max (mapcar 'org-string-width words)))
9778 w ll)
9779 (cond (width
9780 (org-do-wrap words (max maxword width)))
9781 (lines
9782 (setq w maxword)
9783 (setq ll (org-do-wrap words maxword))
9784 (if (<= (length ll) lines)
9786 (setq ll words)
9787 (while (> (length ll) lines)
9788 (setq w (1+ w))
9789 (setq ll (org-do-wrap words w)))
9790 ll))
9791 (t (error "Cannot wrap this")))))
9794 (defun org-do-wrap (words width)
9795 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9796 (let (lines line)
9797 (while words
9798 (setq line (pop words))
9799 (while (and words (< (+ (length line) (length (car words))) width))
9800 (setq line (concat line " " (pop words))))
9801 (setq lines (push line lines)))
9802 (nreverse lines)))
9804 (defun org-split-string (string &optional separators)
9805 "Splits STRING into substrings at SEPARATORS.
9806 No empty strings are returned if there are matches at the beginning
9807 and end of string."
9808 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9809 (start 0)
9810 notfirst
9811 (list nil))
9812 (while (and (string-match rexp string
9813 (if (and notfirst
9814 (= start (match-beginning 0))
9815 (< start (length string)))
9816 (1+ start) start))
9817 (< (match-beginning 0) (length string)))
9818 (setq notfirst t)
9819 (or (eq (match-beginning 0) 0)
9820 (and (eq (match-beginning 0) (match-end 0))
9821 (eq (match-beginning 0) start))
9822 (setq list
9823 (cons (substring string start (match-beginning 0))
9824 list)))
9825 (setq start (match-end 0)))
9826 (or (eq start (length string))
9827 (setq list
9828 (cons (substring string start)
9829 list)))
9830 (nreverse list)))
9832 (defun org-table-map-tables (function)
9833 "Apply FUNCTION to the start of all tables in the buffer."
9834 (save-excursion
9835 (save-restriction
9836 (widen)
9837 (goto-char (point-min))
9838 (while (re-search-forward org-table-any-line-regexp nil t)
9839 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9840 (beginning-of-line 1)
9841 (if (looking-at org-table-line-regexp)
9842 (save-excursion (funcall function)))
9843 (re-search-forward org-table-any-border-regexp nil 1))))
9844 (message "Mapping tables: done"))
9846 (defvar org-timecnt) ; dynamically scoped parameter
9848 (defun org-table-sum (&optional beg end nlast)
9849 "Sum numbers in region of current table column.
9850 The result will be displayed in the echo area, and will be available
9851 as kill to be inserted with \\[yank].
9853 If there is an active region, it is interpreted as a rectangle and all
9854 numbers in that rectangle will be summed. If there is no active
9855 region and point is located in a table column, sum all numbers in that
9856 column.
9858 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9859 numbers are assumed to be times as well (in decimal hours) and the
9860 numbers are added as such.
9862 If NLAST is a number, only the NLAST fields will actually be summed."
9863 (interactive)
9864 (save-excursion
9865 (let (col (org-timecnt 0) diff h m s org-table-clip)
9866 (cond
9867 ((and beg end)) ; beg and end given explicitly
9868 ((org-region-active-p)
9869 (setq beg (region-beginning) end (region-end)))
9871 (setq col (org-table-current-column))
9872 (goto-char (org-table-begin))
9873 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9874 (error "No table data"))
9875 (org-table-goto-column col)
9876 (setq beg (point))
9877 (goto-char (org-table-end))
9878 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9879 (error "No table data"))
9880 (org-table-goto-column col)
9881 (setq end (point))))
9882 (let* ((items (apply 'append (org-table-copy-region beg end)))
9883 (items1 (cond ((not nlast) items)
9884 ((>= nlast (length items)) items)
9885 (t (setq items (reverse items))
9886 (setcdr (nthcdr (1- nlast) items) nil)
9887 (nreverse items))))
9888 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9889 items1)))
9890 (res (apply '+ numbers))
9891 (sres (if (= org-timecnt 0)
9892 (format "%g" res)
9893 (setq diff (* 3600 res)
9894 h (floor (/ diff 3600)) diff (mod diff 3600)
9895 m (floor (/ diff 60)) diff (mod diff 60)
9896 s diff)
9897 (format "%d:%02d:%02d" h m s))))
9898 (kill-new sres)
9899 (if (interactive-p)
9900 (message "%s"
9901 (substitute-command-keys
9902 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9903 (length numbers) sres))))
9904 sres))))
9906 (defun org-table-get-number-for-summing (s)
9907 (let (n)
9908 (if (string-match "^ *|? *" s)
9909 (setq s (replace-match "" nil nil s)))
9910 (if (string-match " *|? *$" s)
9911 (setq s (replace-match "" nil nil s)))
9912 (setq n (string-to-number s))
9913 (cond
9914 ((and (string-match "0" s)
9915 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9916 ((string-match "\\`[ \t]+\\'" s) nil)
9917 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9918 (let ((h (string-to-number (or (match-string 1 s) "0")))
9919 (m (string-to-number (or (match-string 2 s) "0")))
9920 (s (string-to-number (or (match-string 4 s) "0"))))
9921 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9922 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9923 ((equal n 0) nil)
9924 (t n))))
9926 (defun org-table-current-field-formula (&optional key noerror)
9927 "Return the formula active for the current field.
9928 Assumes that specials are in place.
9929 If KEY is given, return the key to this formula.
9930 Otherwise return the formula preceeded with \"=\" or \":=\"."
9931 (let* ((name (car (rassoc (list (org-current-line)
9932 (org-table-current-column))
9933 org-table-named-field-locations)))
9934 (col (org-table-current-column))
9935 (scol (int-to-string col))
9936 (ref (format "@%d$%d" (org-table-current-dline) col))
9937 (stored-list (org-table-get-stored-formulas noerror))
9938 (ass (or (assoc name stored-list)
9939 (assoc ref stored-list)
9940 (assoc scol stored-list))))
9941 (if key
9942 (car ass)
9943 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9944 (cdr ass))))))
9946 (defun org-table-get-formula (&optional equation named)
9947 "Read a formula from the minibuffer, offer stored formula as default.
9948 When NAMED is non-nil, look for a named equation."
9949 (let* ((stored-list (org-table-get-stored-formulas))
9950 (name (car (rassoc (list (org-current-line)
9951 (org-table-current-column))
9952 org-table-named-field-locations)))
9953 (ref (format "@%d$%d" (org-table-current-dline)
9954 (org-table-current-column)))
9955 (refass (assoc ref stored-list))
9956 (scol (if named
9957 (if name name ref)
9958 (int-to-string (org-table-current-column))))
9959 (dummy (and (or name refass) (not named)
9960 (not (y-or-n-p "Replace field formula with column formula? " ))
9961 (error "Abort")))
9962 (name (or name ref))
9963 (org-table-may-need-update nil)
9964 (stored (cdr (assoc scol stored-list)))
9965 (eq (cond
9966 ((and stored equation (string-match "^ *=? *$" equation))
9967 stored)
9968 ((stringp equation)
9969 equation)
9970 (t (org-table-formula-from-user
9971 (read-string
9972 (org-table-formula-to-user
9973 (format "%s formula %s%s="
9974 (if named "Field" "Column")
9975 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9976 scol))
9977 (if stored (org-table-formula-to-user stored) "")
9978 'org-table-formula-history
9979 )))))
9980 mustsave)
9981 (when (not (string-match "\\S-" eq))
9982 ;; remove formula
9983 (setq stored-list (delq (assoc scol stored-list) stored-list))
9984 (org-table-store-formulas stored-list)
9985 (error "Formula removed"))
9986 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9987 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9988 (if (and name (not named))
9989 ;; We set the column equation, delete the named one.
9990 (setq stored-list (delq (assoc name stored-list) stored-list)
9991 mustsave t))
9992 (if stored
9993 (setcdr (assoc scol stored-list) eq)
9994 (setq stored-list (cons (cons scol eq) stored-list)))
9995 (if (or mustsave (not (equal stored eq)))
9996 (org-table-store-formulas stored-list))
9997 eq))
9999 (defun org-table-store-formulas (alist)
10000 "Store the list of formulas below the current table."
10001 (setq alist (sort alist 'org-table-formula-less-p))
10002 (save-excursion
10003 (goto-char (org-table-end))
10004 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
10005 (progn
10006 ;; don't overwrite TBLFM, we might use text properties to store stuff
10007 (goto-char (match-beginning 2))
10008 (delete-region (match-beginning 2) (match-end 0)))
10009 (insert "#+TBLFM:"))
10010 (insert " "
10011 (mapconcat (lambda (x)
10012 (concat
10013 (if (equal (string-to-char (car x)) ?@) "" "$")
10014 (car x) "=" (cdr x)))
10015 alist "::")
10016 "\n")))
10018 (defsubst org-table-formula-make-cmp-string (a)
10019 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
10020 (concat
10021 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
10022 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
10023 (if (match-end 5) (concat "@@" (match-string 5 a))))))
10025 (defun org-table-formula-less-p (a b)
10026 "Compare two formulas for sorting."
10027 (let ((as (org-table-formula-make-cmp-string (car a)))
10028 (bs (org-table-formula-make-cmp-string (car b))))
10029 (and as bs (string< as bs))))
10031 (defun org-table-get-stored-formulas (&optional noerror)
10032 "Return an alist with the stored formulas directly after current table."
10033 (interactive)
10034 (let (scol eq eq-alist strings string seen)
10035 (save-excursion
10036 (goto-char (org-table-end))
10037 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
10038 (setq strings (org-split-string (match-string 2) " *:: *"))
10039 (while (setq string (pop strings))
10040 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
10041 (setq scol (if (match-end 2)
10042 (match-string 2 string)
10043 (match-string 1 string))
10044 eq (match-string 3 string)
10045 eq-alist (cons (cons scol eq) eq-alist))
10046 (if (member scol seen)
10047 (if noerror
10048 (progn
10049 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
10050 (ding)
10051 (sit-for 2))
10052 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
10053 (push scol seen))))))
10054 (nreverse eq-alist)))
10056 (defun org-table-fix-formulas (key replace &optional limit delta remove)
10057 "Modify the equations after the table structure has been edited.
10058 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
10059 For all numbers larger than LIMIT, shift them by DELTA."
10060 (save-excursion
10061 (goto-char (org-table-end))
10062 (when (looking-at "#\\+TBLFM:")
10063 (let ((re (concat key "\\([0-9]+\\)"))
10064 (re2
10065 (when remove
10066 (if (equal key "$")
10067 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
10068 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
10069 s n a)
10070 (when remove
10071 (while (re-search-forward re2 (point-at-eol) t)
10072 (replace-match "")))
10073 (while (re-search-forward re (point-at-eol) t)
10074 (setq s (match-string 1) n (string-to-number s))
10075 (cond
10076 ((setq a (assoc s replace))
10077 (replace-match (concat key (cdr a)) t t))
10078 ((and limit (> n limit))
10079 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
10081 (defun org-table-get-specials ()
10082 "Get the column names and local parameters for this table."
10083 (save-excursion
10084 (let ((beg (org-table-begin)) (end (org-table-end))
10085 names name fields fields1 field cnt
10086 c v l line col types dlines hlines)
10087 (setq org-table-column-names nil
10088 org-table-local-parameters nil
10089 org-table-named-field-locations nil
10090 org-table-current-begin-line nil
10091 org-table-current-begin-pos nil
10092 org-table-current-line-types nil)
10093 (goto-char beg)
10094 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10095 (setq names (org-split-string (match-string 1) " *| *")
10096 cnt 1)
10097 (while (setq name (pop names))
10098 (setq cnt (1+ cnt))
10099 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10100 (push (cons name (int-to-string cnt)) org-table-column-names))))
10101 (setq org-table-column-names (nreverse org-table-column-names))
10102 (setq org-table-column-name-regexp
10103 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10104 (goto-char beg)
10105 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10106 (setq fields (org-split-string (match-string 1) " *| *"))
10107 (while (setq field (pop fields))
10108 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10109 (push (cons (match-string 1 field) (match-string 2 field))
10110 org-table-local-parameters))))
10111 (goto-char beg)
10112 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10113 (setq c (match-string 1)
10114 fields (org-split-string (match-string 2) " *| *"))
10115 (save-excursion
10116 (beginning-of-line (if (equal c "_") 2 0))
10117 (setq line (org-current-line) col 1)
10118 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10119 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10120 (while (and fields1 (setq field (pop fields)))
10121 (setq v (pop fields1) col (1+ col))
10122 (when (and (stringp field) (stringp v)
10123 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10124 (push (cons field v) org-table-local-parameters)
10125 (push (list field line col) org-table-named-field-locations))))
10126 ;; Analyse the line types
10127 (goto-char beg)
10128 (setq org-table-current-begin-line (org-current-line)
10129 org-table-current-begin-pos (point)
10130 l org-table-current-begin-line)
10131 (while (looking-at "[ \t]*|\\(-\\)?")
10132 (push (if (match-end 1) 'hline 'dline) types)
10133 (if (match-end 1) (push l hlines) (push l dlines))
10134 (beginning-of-line 2)
10135 (setq l (1+ l)))
10136 (setq org-table-current-line-types (apply 'vector (nreverse types))
10137 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
10138 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
10140 (defun org-table-maybe-eval-formula ()
10141 "Check if the current field starts with \"=\" or \":=\".
10142 If yes, store the formula and apply it."
10143 ;; We already know we are in a table. Get field will only return a formula
10144 ;; when appropriate. It might return a separator line, but no problem.
10145 (when org-table-formula-evaluate-inline
10146 (let* ((field (org-trim (or (org-table-get-field) "")))
10147 named eq)
10148 (when (string-match "^:?=\\(.*\\)" field)
10149 (setq named (equal (string-to-char field) ?:)
10150 eq (match-string 1 field))
10151 (if (or (fboundp 'calc-eval)
10152 (equal (substring eq 0 (min 2 (length eq))) "'("))
10153 (org-table-eval-formula (if named '(4) nil)
10154 (org-table-formula-from-user eq))
10155 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10157 (defvar org-recalc-commands nil
10158 "List of commands triggering the recalculation of a line.
10159 Will be filled automatically during use.")
10161 (defvar org-recalc-marks
10162 '((" " . "Unmarked: no special line, no automatic recalculation")
10163 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10164 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10165 ("!" . "Column name definition line. Reference in formula as $name.")
10166 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10167 ("_" . "Names for values in row below this one.")
10168 ("^" . "Names for values in row above this one.")))
10170 (defun org-table-rotate-recalc-marks (&optional newchar)
10171 "Rotate the recalculation mark in the first column.
10172 If in any row, the first field is not consistent with a mark,
10173 insert a new column for the markers.
10174 When there is an active region, change all the lines in the region,
10175 after prompting for the marking character.
10176 After each change, a message will be displayed indicating the meaning
10177 of the new mark."
10178 (interactive)
10179 (unless (org-at-table-p) (error "Not at a table"))
10180 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10181 (beg (org-table-begin))
10182 (end (org-table-end))
10183 (l (org-current-line))
10184 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10185 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10186 (have-col
10187 (save-excursion
10188 (goto-char beg)
10189 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10190 (col (org-table-current-column))
10191 (forcenew (car (assoc newchar org-recalc-marks)))
10192 epos new)
10193 (when l1
10194 (message "Change region to what mark? Type # * ! $ or SPC: ")
10195 (setq newchar (char-to-string (read-char-exclusive))
10196 forcenew (car (assoc newchar org-recalc-marks))))
10197 (if (and newchar (not forcenew))
10198 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10199 newchar))
10200 (if l1 (goto-line l1))
10201 (save-excursion
10202 (beginning-of-line 1)
10203 (unless (looking-at org-table-dataline-regexp)
10204 (error "Not at a table data line")))
10205 (unless have-col
10206 (org-table-goto-column 1)
10207 (org-table-insert-column)
10208 (org-table-goto-column (1+ col)))
10209 (setq epos (point-at-eol))
10210 (save-excursion
10211 (beginning-of-line 1)
10212 (org-table-get-field
10213 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10214 (concat " "
10215 (setq new (or forcenew
10216 (cadr (member (match-string 1) marks))))
10217 " ")
10218 " # ")))
10219 (if (and l1 l2)
10220 (progn
10221 (goto-line l1)
10222 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10223 (and (looking-at org-table-dataline-regexp)
10224 (org-table-get-field 1 (concat " " new " "))))
10225 (goto-line l1)))
10226 (if (not (= epos (point-at-eol))) (org-table-align))
10227 (goto-line l)
10228 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10230 (defun org-table-maybe-recalculate-line ()
10231 "Recompute the current line if marked for it, and if we haven't just done it."
10232 (interactive)
10233 (and org-table-allow-automatic-line-recalculation
10234 (not (and (memq last-command org-recalc-commands)
10235 (equal org-last-recalc-line (org-current-line))))
10236 (save-excursion (beginning-of-line 1)
10237 (looking-at org-table-auto-recalculate-regexp))
10238 (org-table-recalculate) t))
10240 (defvar org-table-formula-debug nil
10241 "Non-nil means, debug table formulas.
10242 When nil, simply write \"#ERROR\" in corrupted fields.")
10243 (make-variable-buffer-local 'org-table-formula-debug)
10245 (defvar modes)
10246 (defsubst org-set-calc-mode (var &optional value)
10247 (if (stringp var)
10248 (setq var (assoc var '(("D" calc-angle-mode deg)
10249 ("R" calc-angle-mode rad)
10250 ("F" calc-prefer-frac t)
10251 ("S" calc-symbolic-mode t)))
10252 value (nth 2 var) var (nth 1 var)))
10253 (if (memq var modes)
10254 (setcar (cdr (memq var modes)) value)
10255 (cons var (cons value modes)))
10256 modes)
10258 (defun org-table-eval-formula (&optional arg equation
10259 suppress-align suppress-const
10260 suppress-store suppress-analysis)
10261 "Replace the table field value at the cursor by the result of a calculation.
10263 This function makes use of Dave Gillespie's Calc package, in my view the
10264 most exciting program ever written for GNU Emacs. So you need to have Calc
10265 installed in order to use this function.
10267 In a table, this command replaces the value in the current field with the
10268 result of a formula. It also installs the formula as the \"current\" column
10269 formula, by storing it in a special line below the table. When called
10270 with a `C-u' prefix, the current field must ba a named field, and the
10271 formula is installed as valid in only this specific field.
10273 When called with two `C-u' prefixes, insert the active equation
10274 for the field back into the current field, so that it can be
10275 edited there. This is useful in order to use \\[org-table-show-reference]
10276 to check the referenced fields.
10278 When called, the command first prompts for a formula, which is read in
10279 the minibuffer. Previously entered formulas are available through the
10280 history list, and the last used formula is offered as a default.
10281 These stored formulas are adapted correctly when moving, inserting, or
10282 deleting columns with the corresponding commands.
10284 The formula can be any algebraic expression understood by the Calc package.
10285 For details, see the Org-mode manual.
10287 This function can also be called from Lisp programs and offers
10288 additional arguments: EQUATION can be the formula to apply. If this
10289 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10290 used to speed-up recursive calls by by-passing unnecessary aligns.
10291 SUPPRESS-CONST suppresses the interpretation of constants in the
10292 formula, assuming that this has been done already outside the function.
10293 SUPPRESS-STORE means the formula should not be stored, either because
10294 it is already stored, or because it is a modified equation that should
10295 not overwrite the stored one."
10296 (interactive "P")
10297 (org-table-check-inside-data-field)
10298 (or suppress-analysis (org-table-get-specials))
10299 (if (equal arg '(16))
10300 (let ((eq (org-table-current-field-formula)))
10301 (or eq (error "No equation active for current field"))
10302 (org-table-get-field nil eq)
10303 (org-table-align)
10304 (setq org-table-may-need-update t))
10305 (let* (fields
10306 (ndown (if (integerp arg) arg 1))
10307 (org-table-automatic-realign nil)
10308 (case-fold-search nil)
10309 (down (> ndown 1))
10310 (formula (if (and equation suppress-store)
10311 equation
10312 (org-table-get-formula equation (equal arg '(4)))))
10313 (n0 (org-table-current-column))
10314 (modes (copy-sequence org-calc-default-modes))
10315 (numbers nil) ; was a variable, now fixed default
10316 (keep-empty nil)
10317 n form form0 bw fmt x ev orig c lispp literal)
10318 ;; Parse the format string. Since we have a lot of modes, this is
10319 ;; a lot of work. However, I think calc still uses most of the time.
10320 (if (string-match ";" formula)
10321 (let ((tmp (org-split-string formula ";")))
10322 (setq formula (car tmp)
10323 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10324 (nth 1 tmp)))
10325 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10326 (setq c (string-to-char (match-string 1 fmt))
10327 n (string-to-number (match-string 2 fmt)))
10328 (if (= c ?p)
10329 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10330 (setq modes (org-set-calc-mode
10331 'calc-float-format
10332 (list (cdr (assoc c '((?n . float) (?f . fix)
10333 (?s . sci) (?e . eng))))
10334 n))))
10335 (setq fmt (replace-match "" t t fmt)))
10336 (if (string-match "[NT]" fmt)
10337 (setq numbers (equal (match-string 0 fmt) "N")
10338 fmt (replace-match "" t t fmt)))
10339 (if (string-match "L" fmt)
10340 (setq literal t
10341 fmt (replace-match "" t t fmt)))
10342 (if (string-match "E" fmt)
10343 (setq keep-empty t
10344 fmt (replace-match "" t t fmt)))
10345 (while (string-match "[DRFS]" fmt)
10346 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10347 (setq fmt (replace-match "" t t fmt)))
10348 (unless (string-match "\\S-" fmt)
10349 (setq fmt nil))))
10350 (if (and (not suppress-const) org-table-formula-use-constants)
10351 (setq formula (org-table-formula-substitute-names formula)))
10352 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10353 (while (> ndown 0)
10354 (setq fields (org-split-string
10355 (org-no-properties
10356 (buffer-substring (point-at-bol) (point-at-eol)))
10357 " *| *"))
10358 (if (eq numbers t)
10359 (setq fields (mapcar
10360 (lambda (x) (number-to-string (string-to-number x)))
10361 fields)))
10362 (setq ndown (1- ndown))
10363 (setq form (copy-sequence formula)
10364 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10365 (if (and lispp literal) (setq lispp 'literal))
10366 ;; Check for old vertical references
10367 (setq form (org-rewrite-old-row-references form))
10368 ;; Insert complex ranges
10369 (while (string-match org-table-range-regexp form)
10370 (setq form
10371 (replace-match
10372 (save-match-data
10373 (org-table-make-reference
10374 (org-table-get-range (match-string 0 form) nil n0)
10375 keep-empty numbers lispp))
10376 t t form)))
10377 ;; Insert simple ranges
10378 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10379 (setq form
10380 (replace-match
10381 (save-match-data
10382 (org-table-make-reference
10383 (org-sublist
10384 fields (string-to-number (match-string 1 form))
10385 (string-to-number (match-string 2 form)))
10386 keep-empty numbers lispp))
10387 t t form)))
10388 (setq form0 form)
10389 ;; Insert the references to fields in same row
10390 (while (string-match "\\$\\([0-9]+\\)" form)
10391 (setq n (string-to-number (match-string 1 form))
10392 x (nth (1- (if (= n 0) n0 n)) fields))
10393 (unless x (error "Invalid field specifier \"%s\""
10394 (match-string 0 form)))
10395 (setq form (replace-match
10396 (save-match-data
10397 (org-table-make-reference x nil numbers lispp))
10398 t t form)))
10400 (if lispp
10401 (setq ev (condition-case nil
10402 (eval (eval (read form)))
10403 (error "#ERROR"))
10404 ev (if (numberp ev) (number-to-string ev) ev))
10405 (or (fboundp 'calc-eval)
10406 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10407 (setq ev (calc-eval (cons form modes)
10408 (if numbers 'num))))
10410 (when org-table-formula-debug
10411 (with-output-to-temp-buffer "*Substitution History*"
10412 (princ (format "Substitution history of formula
10413 Orig: %s
10414 $xyz-> %s
10415 @r$c-> %s
10416 $1-> %s\n" orig formula form0 form))
10417 (if (listp ev)
10418 (princ (format " %s^\nError: %s"
10419 (make-string (car ev) ?\-) (nth 1 ev)))
10420 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10421 ev (or fmt "NONE")
10422 (if fmt (format fmt (string-to-number ev)) ev)))))
10423 (setq bw (get-buffer-window "*Substitution History*"))
10424 (shrink-window-if-larger-than-buffer bw)
10425 (unless (and (interactive-p) (not ndown))
10426 (unless (let (inhibit-redisplay)
10427 (y-or-n-p "Debugging Formula. Continue to next? "))
10428 (org-table-align)
10429 (error "Abort"))
10430 (delete-window bw)
10431 (message "")))
10432 (if (listp ev) (setq fmt nil ev "#ERROR"))
10433 (org-table-justify-field-maybe
10434 (if fmt (format fmt (string-to-number ev)) ev))
10435 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10436 (call-interactively 'org-return)
10437 (setq ndown 0)))
10438 (and down (org-table-maybe-recalculate-line))
10439 (or suppress-align (and org-table-may-need-update
10440 (org-table-align))))))
10442 (defun org-table-put-field-property (prop value)
10443 (save-excursion
10444 (put-text-property (progn (skip-chars-backward "^|") (point))
10445 (progn (skip-chars-forward "^|") (point))
10446 prop value)))
10448 (defun org-table-get-range (desc &optional tbeg col highlight)
10449 "Get a calc vector from a column, accorting to descriptor DESC.
10450 Optional arguments TBEG and COL can give the beginning of the table and
10451 the current column, to avoid unnecessary parsing.
10452 HIGHLIGHT means, just highlight the range."
10453 (if (not (equal (string-to-char desc) ?@))
10454 (setq desc (concat "@" desc)))
10455 (save-excursion
10456 (or tbeg (setq tbeg (org-table-begin)))
10457 (or col (setq col (org-table-current-column)))
10458 (let ((thisline (org-current-line))
10459 beg end c1 c2 r1 r2 rangep tmp)
10460 (unless (string-match org-table-range-regexp desc)
10461 (error "Invalid table range specifier `%s'" desc))
10462 (setq rangep (match-end 3)
10463 r1 (and (match-end 1) (match-string 1 desc))
10464 r2 (and (match-end 4) (match-string 4 desc))
10465 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10466 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10468 (and c1 (setq c1 (+ (string-to-number c1)
10469 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10470 (and c2 (setq c2 (+ (string-to-number c2)
10471 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10472 (if (equal r1 "") (setq r1 nil))
10473 (if (equal r2 "") (setq r2 nil))
10474 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10475 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10476 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10477 (if (not r1) (setq r1 thisline))
10478 (if (not r2) (setq r2 thisline))
10479 (if (not c1) (setq c1 col))
10480 (if (not c2) (setq c2 col))
10481 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10482 ;; just one field
10483 (progn
10484 (goto-line r1)
10485 (while (not (looking-at org-table-dataline-regexp))
10486 (beginning-of-line 2))
10487 (prog1 (org-trim (org-table-get-field c1))
10488 (if highlight (org-table-highlight-rectangle (point) (point)))))
10489 ;; A range, return a vector
10490 ;; First sort the numbers to get a regular ractangle
10491 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10492 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10493 (goto-line r1)
10494 (while (not (looking-at org-table-dataline-regexp))
10495 (beginning-of-line 2))
10496 (org-table-goto-column c1)
10497 (setq beg (point))
10498 (goto-line r2)
10499 (while (not (looking-at org-table-dataline-regexp))
10500 (beginning-of-line 0))
10501 (org-table-goto-column c2)
10502 (setq end (point))
10503 (if highlight
10504 (org-table-highlight-rectangle
10505 beg (progn (skip-chars-forward "^|\n") (point))))
10506 ;; return string representation of calc vector
10507 (mapcar 'org-trim
10508 (apply 'append (org-table-copy-region beg end)))))))
10510 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10511 "Analyze descriptor DESC and retrieve the corresponding line number.
10512 The cursor is currently in line CLINE, the table begins in line BLINE,
10513 and TABLE is a vector with line types."
10514 (if (string-match "^[0-9]+$" desc)
10515 (aref org-table-dlines (string-to-number desc))
10516 (setq cline (or cline (org-current-line))
10517 bline (or bline org-table-current-begin-line)
10518 table (or table org-table-current-line-types))
10519 (if (or
10520 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10521 ;; 1 2 3 4 5 6
10522 (and (not (match-end 3)) (not (match-end 6)))
10523 (and (match-end 3) (match-end 6) (not (match-end 5))))
10524 (error "invalid row descriptor `%s'" desc))
10525 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10526 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10527 (odir (and (match-end 5) (match-string 5 desc)))
10528 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10529 (i (- cline bline))
10530 (rel (and (match-end 6)
10531 (or (and (match-end 1) (not (match-end 3)))
10532 (match-end 5)))))
10533 (if (and hn (not hdir))
10534 (progn
10535 (setq i 0 hdir "+")
10536 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10537 (if (and (not hn) on (not odir))
10538 (error "should never happen");;(aref org-table-dlines on)
10539 (if (and hn (> hn 0))
10540 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10541 (if on
10542 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10543 (+ bline i)))))
10545 (defun org-find-row-type (table i type backwards relative n)
10546 (let ((l (length table)))
10547 (while (> n 0)
10548 (while (and (setq i (+ i (if backwards -1 1)))
10549 (>= i 0) (< i l)
10550 (not (eq (aref table i) type))
10551 (if (and relative (eq (aref table i) 'hline))
10552 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10553 t)))
10554 (setq n (1- n)))
10555 (if (or (< i 0) (>= i l))
10556 (error "Row descriptior leads outside table")
10557 i)))
10559 (defun org-rewrite-old-row-references (s)
10560 (if (string-match "&[-+0-9I]" s)
10561 (error "Formula contains old &row reference, please rewrite using @-syntax")
10564 (defun org-table-make-reference (elements keep-empty numbers lispp)
10565 "Convert list ELEMENTS to something appropriate to insert into formula.
10566 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10567 NUMBERS indicates that everything should be converted to numbers.
10568 LISPP means to return something appropriate for a Lisp list."
10569 (if (stringp elements) ; just a single val
10570 (if lispp
10571 (if (eq lispp 'literal)
10572 elements
10573 (prin1-to-string (if numbers (string-to-number elements) elements)))
10574 (if (equal elements "") (setq elements "0"))
10575 (if numbers (number-to-string (string-to-number elements)) elements))
10576 (unless keep-empty
10577 (setq elements
10578 (delq nil
10579 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10580 elements))))
10581 (setq elements (or elements '("0")))
10582 (if lispp
10583 (mapconcat
10584 (lambda (x)
10585 (if (eq lispp 'literal)
10587 (prin1-to-string (if numbers (string-to-number x) x))))
10588 elements " ")
10589 (concat "[" (mapconcat
10590 (lambda (x)
10591 (if numbers (number-to-string (string-to-number x)) x))
10592 elements
10593 ",") "]"))))
10595 (defun org-table-recalculate (&optional all noalign)
10596 "Recalculate the current table line by applying all stored formulas.
10597 With prefix arg ALL, do this for all lines in the table."
10598 (interactive "P")
10599 (or (memq this-command org-recalc-commands)
10600 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10601 (unless (org-at-table-p) (error "Not at a table"))
10602 (if (equal all '(16))
10603 (org-table-iterate)
10604 (org-table-get-specials)
10605 (let* ((eqlist (sort (org-table-get-stored-formulas)
10606 (lambda (a b) (string< (car a) (car b)))))
10607 (inhibit-redisplay (not debug-on-error))
10608 (line-re org-table-dataline-regexp)
10609 (thisline (org-current-line))
10610 (thiscol (org-table-current-column))
10611 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10612 ;; Insert constants in all formulas
10613 (setq eqlist
10614 (mapcar (lambda (x)
10615 (setcdr x (org-table-formula-substitute-names (cdr x)))
10617 eqlist))
10618 ;; Split the equation list
10619 (while (setq eq (pop eqlist))
10620 (if (<= (string-to-char (car eq)) ?9)
10621 (push eq eqlnum)
10622 (push eq eqlname)))
10623 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10624 (if all
10625 (progn
10626 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10627 (goto-char (setq beg (org-table-begin)))
10628 (if (re-search-forward org-table-calculate-mark-regexp end t)
10629 ;; This is a table with marked lines, compute selected lines
10630 (setq line-re org-table-recalculate-regexp)
10631 ;; Move forward to the first non-header line
10632 (if (and (re-search-forward org-table-dataline-regexp end t)
10633 (re-search-forward org-table-hline-regexp end t)
10634 (re-search-forward org-table-dataline-regexp end t))
10635 (setq beg (match-beginning 0))
10636 nil))) ;; just leave beg where it is
10637 (setq beg (point-at-bol)
10638 end (move-marker (make-marker) (1+ (point-at-eol)))))
10639 (goto-char beg)
10640 (and all (message "Re-applying formulas to full table..."))
10642 ;; First find the named fields, and mark them untouchanble
10643 (remove-text-properties beg end '(org-untouchable t))
10644 (while (setq eq (pop eqlname))
10645 (setq name (car eq)
10646 a (assoc name org-table-named-field-locations))
10647 (and (not a)
10648 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10649 (setq a (list name
10650 (aref org-table-dlines
10651 (string-to-number (match-string 1 name)))
10652 (string-to-number (match-string 2 name)))))
10653 (when (and a (or all (equal (nth 1 a) thisline)))
10654 (message "Re-applying formula to field: %s" name)
10655 (goto-line (nth 1 a))
10656 (org-table-goto-column (nth 2 a))
10657 (push (append a (list (cdr eq))) eqlname1)
10658 (org-table-put-field-property :org-untouchable t)))
10660 ;; Now evauluate the column formulas, but skip fields covered by
10661 ;; field formulas
10662 (goto-char beg)
10663 (while (re-search-forward line-re end t)
10664 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10665 ;; Unprotected line, recalculate
10666 (and all (message "Re-applying formulas to full table...(line %d)"
10667 (setq cnt (1+ cnt))))
10668 (setq org-last-recalc-line (org-current-line))
10669 (setq eql eqlnum)
10670 (while (setq entry (pop eql))
10671 (goto-line org-last-recalc-line)
10672 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10673 (unless (get-text-property (point) :org-untouchable)
10674 (org-table-eval-formula nil (cdr entry)
10675 'noalign 'nocst 'nostore 'noanalysis)))))
10677 ;; Now evaluate the field formulas
10678 (while (setq eq (pop eqlname1))
10679 (message "Re-applying formula to field: %s" (car eq))
10680 (goto-line (nth 1 eq))
10681 (org-table-goto-column (nth 2 eq))
10682 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10683 'nostore 'noanalysis))
10685 (goto-line thisline)
10686 (org-table-goto-column thiscol)
10687 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10688 (or noalign (and org-table-may-need-update (org-table-align))
10689 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10691 ;; back to initial position
10692 (message "Re-applying formulas...done")
10693 (goto-line thisline)
10694 (org-table-goto-column thiscol)
10695 (or noalign (and org-table-may-need-update (org-table-align))
10696 (and all (message "Re-applying formulas...done"))))))
10698 (defun org-table-iterate (&optional arg)
10699 "Recalculate the table until it does not change anymore."
10700 (interactive "P")
10701 (let ((imax (if arg (prefix-numeric-value arg) 10))
10702 (i 0)
10703 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10704 thistbl)
10705 (catch 'exit
10706 (while (< i imax)
10707 (setq i (1+ i))
10708 (org-table-recalculate 'all)
10709 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10710 (if (not (string= lasttbl thistbl))
10711 (setq lasttbl thistbl)
10712 (if (> i 1)
10713 (message "Convergence after %d iterations" i)
10714 (message "Table was already stable"))
10715 (throw 'exit t)))
10716 (error "No convergence after %d iterations" i))))
10718 (defun org-table-formula-substitute-names (f)
10719 "Replace $const with values in string F."
10720 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10721 ;; First, check for column names
10722 (while (setq start (string-match org-table-column-name-regexp f start))
10723 (setq start (1+ start))
10724 (setq a (assoc (match-string 1 f) org-table-column-names))
10725 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10726 ;; Parameters and constants
10727 (setq start 0)
10728 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10729 (setq start (1+ start))
10730 (if (setq a (save-match-data
10731 (org-table-get-constant (match-string 1 f))))
10732 (setq f (replace-match
10733 (concat (if pp "(") a (if pp ")")) t t f))))
10734 (if org-table-formula-debug
10735 (put-text-property 0 (length f) :orig-formula f1 f))
10738 (defun org-table-get-constant (const)
10739 "Find the value for a parameter or constant in a formula.
10740 Parameters get priority."
10741 (or (cdr (assoc const org-table-local-parameters))
10742 (cdr (assoc const org-table-formula-constants-local))
10743 (cdr (assoc const org-table-formula-constants))
10744 (and (fboundp 'constants-get) (constants-get const))
10745 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10746 (org-entry-get nil (substring const 5) 'inherit))
10747 "#UNDEFINED_NAME"))
10749 (defvar org-table-fedit-map
10750 (let ((map (make-sparse-keymap)))
10751 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10752 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10753 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10754 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10755 (org-defkey map "\C-c?" 'org-table-show-reference)
10756 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10757 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10758 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10759 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10760 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10761 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10762 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10763 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10764 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10765 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10766 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10767 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10768 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10769 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10770 map))
10772 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10773 '("Edit-Formulas"
10774 ["Finish and Install" org-table-fedit-finish t]
10775 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10776 ["Abort" org-table-fedit-abort t]
10777 "--"
10778 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10779 ["Complete Lisp Symbol" lisp-complete-symbol t]
10780 "--"
10781 "Shift Reference at Point"
10782 ["Up" org-table-fedit-ref-up t]
10783 ["Down" org-table-fedit-ref-down t]
10784 ["Left" org-table-fedit-ref-left t]
10785 ["Right" org-table-fedit-ref-right t]
10787 "Change Test Row for Column Formulas"
10788 ["Up" org-table-fedit-line-up t]
10789 ["Down" org-table-fedit-line-down t]
10790 "--"
10791 ["Scroll Table Window" org-table-fedit-scroll t]
10792 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10793 ["Show Table Grid" org-table-fedit-toggle-coordinates
10794 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10795 org-table-overlay-coordinates)]
10796 "--"
10797 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10798 :style toggle :selected org-table-buffer-is-an]))
10800 (defvar org-pos)
10802 (defun org-table-edit-formulas ()
10803 "Edit the formulas of the current table in a separate buffer."
10804 (interactive)
10805 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10806 (beginning-of-line 0))
10807 (unless (org-at-table-p) (error "Not at a table"))
10808 (org-table-get-specials)
10809 (let ((key (org-table-current-field-formula 'key 'noerror))
10810 (eql (sort (org-table-get-stored-formulas 'noerror)
10811 'org-table-formula-less-p))
10812 (pos (move-marker (make-marker) (point)))
10813 (startline 1)
10814 (wc (current-window-configuration))
10815 (titles '((column . "# Column Formulas\n")
10816 (field . "# Field Formulas\n")
10817 (named . "# Named Field Formulas\n")))
10818 entry s type title)
10819 (org-switch-to-buffer-other-window "*Edit Formulas*")
10820 (erase-buffer)
10821 ;; Keep global-font-lock-mode from turning on font-lock-mode
10822 (let ((font-lock-global-modes '(not fundamental-mode)))
10823 (fundamental-mode))
10824 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10825 (org-set-local 'org-pos pos)
10826 (org-set-local 'org-window-configuration wc)
10827 (use-local-map org-table-fedit-map)
10828 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10829 (easy-menu-add org-table-fedit-menu)
10830 (setq startline (org-current-line))
10831 (while (setq entry (pop eql))
10832 (setq type (cond
10833 ((equal (string-to-char (car entry)) ?@) 'field)
10834 ((string-match "^[0-9]" (car entry)) 'column)
10835 (t 'named)))
10836 (when (setq title (assq type titles))
10837 (or (bobp) (insert "\n"))
10838 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10839 (setq titles (delq title titles)))
10840 (if (equal key (car entry)) (setq startline (org-current-line)))
10841 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10842 (car entry) " = " (cdr entry) "\n"))
10843 (remove-text-properties 0 (length s) '(face nil) s)
10844 (insert s))
10845 (if (eq org-table-use-standard-references t)
10846 (org-table-fedit-toggle-ref-type))
10847 (goto-line startline)
10848 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10850 (defun org-table-fedit-post-command ()
10851 (when (not (memq this-command '(lisp-complete-symbol)))
10852 (let ((win (selected-window)))
10853 (save-excursion
10854 (condition-case nil
10855 (org-table-show-reference)
10856 (error nil))
10857 (select-window win)))))
10859 (defun org-table-formula-to-user (s)
10860 "Convert a formula from internal to user representation."
10861 (if (eq org-table-use-standard-references t)
10862 (org-table-convert-refs-to-an s)
10865 (defun org-table-formula-from-user (s)
10866 "Convert a formula from user to internal representation."
10867 (if org-table-use-standard-references
10868 (org-table-convert-refs-to-rc s)
10871 (defun org-table-convert-refs-to-rc (s)
10872 "Convert spreadsheet references from AB7 to @7$28.
10873 Works for single references, but also for entire formulas and even the
10874 full TBLFM line."
10875 (let ((start 0))
10876 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10877 (cond
10878 ((match-end 3)
10879 ;; format match, just advance
10880 (setq start (match-end 0)))
10881 ((and (> (match-beginning 0) 0)
10882 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10883 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10884 ;; 3.e5 or something like this.
10885 (setq start (match-end 0)))
10887 (setq start (match-beginning 0)
10888 s (replace-match
10889 (if (equal (match-string 2 s) "&")
10890 (format "$%d" (org-letters-to-number (match-string 1 s)))
10891 (format "@%d$%d"
10892 (string-to-number (match-string 2 s))
10893 (org-letters-to-number (match-string 1 s))))
10894 t t s)))))
10897 (defun org-table-convert-refs-to-an (s)
10898 "Convert spreadsheet references from to @7$28 to AB7.
10899 Works for single references, but also for entire formulas and even the
10900 full TBLFM line."
10901 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10902 (setq s (replace-match
10903 (format "%s%d"
10904 (org-number-to-letters
10905 (string-to-number (match-string 2 s)))
10906 (string-to-number (match-string 1 s)))
10907 t t s)))
10908 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10909 (setq s (replace-match (concat "\\1"
10910 (org-number-to-letters
10911 (string-to-number (match-string 2 s))) "&")
10912 t nil s)))
10915 (defun org-letters-to-number (s)
10916 "Convert a base 26 number represented by letters into an integer.
10917 For example: AB -> 28."
10918 (let ((n 0))
10919 (setq s (upcase s))
10920 (while (> (length s) 0)
10921 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10922 s (substring s 1)))
10925 (defun org-number-to-letters (n)
10926 "Convert an integer into a base 26 number represented by letters.
10927 For example: 28 -> AB."
10928 (let ((s ""))
10929 (while (> n 0)
10930 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10931 n (/ (1- n) 26)))
10934 (defun org-table-fedit-convert-buffer (function)
10935 "Convert all references in this buffer, using FUNTION."
10936 (let ((line (org-current-line)))
10937 (goto-char (point-min))
10938 (while (not (eobp))
10939 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10940 (delete-region (point) (point-at-eol))
10941 (or (eobp) (forward-char 1)))
10942 (goto-line line)))
10944 (defun org-table-fedit-toggle-ref-type ()
10945 "Convert all references in the buffer from B3 to @3$2 and back."
10946 (interactive)
10947 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10948 (org-table-fedit-convert-buffer
10949 (if org-table-buffer-is-an
10950 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10951 (message "Reference type switched to %s"
10952 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10954 (defun org-table-fedit-ref-up ()
10955 "Shift the reference at point one row/hline up."
10956 (interactive)
10957 (org-table-fedit-shift-reference 'up))
10958 (defun org-table-fedit-ref-down ()
10959 "Shift the reference at point one row/hline down."
10960 (interactive)
10961 (org-table-fedit-shift-reference 'down))
10962 (defun org-table-fedit-ref-left ()
10963 "Shift the reference at point one field to the left."
10964 (interactive)
10965 (org-table-fedit-shift-reference 'left))
10966 (defun org-table-fedit-ref-right ()
10967 "Shift the reference at point one field to the right."
10968 (interactive)
10969 (org-table-fedit-shift-reference 'right))
10971 (defun org-table-fedit-shift-reference (dir)
10972 (cond
10973 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10974 (if (memq dir '(left right))
10975 (org-rematch-and-replace 1 (eq dir 'left))
10976 (error "Cannot shift reference in this direction")))
10977 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10978 ;; A B3-like reference
10979 (if (memq dir '(up down))
10980 (org-rematch-and-replace 2 (eq dir 'up))
10981 (org-rematch-and-replace 1 (eq dir 'left))))
10982 ((org-at-regexp-p
10983 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10984 ;; An internal reference
10985 (if (memq dir '(up down))
10986 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10987 (org-rematch-and-replace 5 (eq dir 'left))))))
10989 (defun org-rematch-and-replace (n &optional decr hline)
10990 "Re-match the group N, and replace it with the shifted refrence."
10991 (or (match-end n) (error "Cannot shift reference in this direction"))
10992 (goto-char (match-beginning n))
10993 (and (looking-at (regexp-quote (match-string n)))
10994 (replace-match (org-shift-refpart (match-string 0) decr hline)
10995 t t)))
10997 (defun org-shift-refpart (ref &optional decr hline)
10998 "Shift a refrence part REF.
10999 If DECR is set, decrease the references row/column, else increase.
11000 If HLINE is set, this may be a hline reference, it certainly is not
11001 a translation reference."
11002 (save-match-data
11003 (let* ((sign (string-match "^[-+]" ref)) n)
11005 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
11006 (cond
11007 ((and hline (string-match "^I+" ref))
11008 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
11009 (setq n (+ n (if decr -1 1)))
11010 (if (= n 0) (setq n (+ n (if decr -1 1))))
11011 (if sign
11012 (setq sign (if (< n 0) "-" "+") n (abs n))
11013 (setq n (max 1 n)))
11014 (concat sign (make-string n ?I)))
11016 ((string-match "^[0-9]+" ref)
11017 (setq n (string-to-number (concat sign ref)))
11018 (setq n (+ n (if decr -1 1)))
11019 (if sign
11020 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
11021 (number-to-string (max 1 n))))
11023 ((string-match "^[a-zA-Z]+" ref)
11024 (org-number-to-letters
11025 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
11027 (t (error "Cannot shift reference"))))))
11029 (defun org-table-fedit-toggle-coordinates ()
11030 "Toggle the display of coordinates in the refrenced table."
11031 (interactive)
11032 (let ((pos (marker-position org-pos)))
11033 (with-current-buffer (marker-buffer org-pos)
11034 (save-excursion
11035 (goto-char pos)
11036 (org-table-toggle-coordinate-overlays)))))
11038 (defun org-table-fedit-finish (&optional arg)
11039 "Parse the buffer for formula definitions and install them.
11040 With prefix ARG, apply the new formulas to the table."
11041 (interactive "P")
11042 (org-table-remove-rectangle-highlight)
11043 (if org-table-use-standard-references
11044 (progn
11045 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
11046 (setq org-table-buffer-is-an nil)))
11047 (let ((pos org-pos) eql var form)
11048 (goto-char (point-min))
11049 (while (re-search-forward
11050 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
11051 nil t)
11052 (setq var (if (match-end 2) (match-string 2) (match-string 1))
11053 form (match-string 3))
11054 (setq form (org-trim form))
11055 (when (not (equal form ""))
11056 (while (string-match "[ \t]*\n[ \t]*" form)
11057 (setq form (replace-match " " t t form)))
11058 (when (assoc var eql)
11059 (error "Double formulas for %s" var))
11060 (push (cons var form) eql)))
11061 (setq org-pos nil)
11062 (set-window-configuration org-window-configuration)
11063 (select-window (get-buffer-window (marker-buffer pos)))
11064 (goto-char pos)
11065 (unless (org-at-table-p)
11066 (error "Lost table position - cannot install formulae"))
11067 (org-table-store-formulas eql)
11068 (move-marker pos nil)
11069 (kill-buffer "*Edit Formulas*")
11070 (if arg
11071 (org-table-recalculate 'all)
11072 (message "New formulas installed - press C-u C-c C-c to apply."))))
11074 (defun org-table-fedit-abort ()
11075 "Abort editing formulas, without installing the changes."
11076 (interactive)
11077 (org-table-remove-rectangle-highlight)
11078 (let ((pos org-pos))
11079 (set-window-configuration org-window-configuration)
11080 (select-window (get-buffer-window (marker-buffer pos)))
11081 (goto-char pos)
11082 (move-marker pos nil)
11083 (message "Formula editing aborted without installing changes")))
11085 (defun org-table-fedit-lisp-indent ()
11086 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
11087 (interactive)
11088 (let ((pos (point)) beg end ind)
11089 (beginning-of-line 1)
11090 (cond
11091 ((looking-at "[ \t]")
11092 (goto-char pos)
11093 (call-interactively 'lisp-indent-line))
11094 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
11095 ((not (fboundp 'pp-buffer))
11096 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
11097 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
11098 (goto-char (- (match-end 0) 2))
11099 (setq beg (point))
11100 (setq ind (make-string (current-column) ?\ ))
11101 (condition-case nil (forward-sexp 1)
11102 (error
11103 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
11104 (setq end (point))
11105 (save-restriction
11106 (narrow-to-region beg end)
11107 (if (eq last-command this-command)
11108 (progn
11109 (goto-char (point-min))
11110 (setq this-command nil)
11111 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
11112 (replace-match " ")))
11113 (pp-buffer)
11114 (untabify (point-min) (point-max))
11115 (goto-char (1+ (point-min)))
11116 (while (re-search-forward "^." nil t)
11117 (beginning-of-line 1)
11118 (insert ind))
11119 (goto-char (point-max))
11120 (backward-delete-char 1)))
11121 (goto-char beg))
11122 (t nil))))
11124 (defvar org-show-positions nil)
11126 (defun org-table-show-reference (&optional local)
11127 "Show the location/value of the $ expression at point."
11128 (interactive)
11129 (org-table-remove-rectangle-highlight)
11130 (catch 'exit
11131 (let ((pos (if local (point) org-pos))
11132 (face2 'highlight)
11133 (org-inhibit-highlight-removal t)
11134 (win (selected-window))
11135 (org-show-positions nil)
11136 var name e what match dest)
11137 (if local (org-table-get-specials))
11138 (setq what (cond
11139 ((or (org-at-regexp-p org-table-range-regexp2)
11140 (org-at-regexp-p org-table-translate-regexp)
11141 (org-at-regexp-p org-table-range-regexp))
11142 (setq match
11143 (save-match-data
11144 (org-table-convert-refs-to-rc (match-string 0))))
11145 'range)
11146 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11147 ((org-at-regexp-p "\\$[0-9]+") 'column)
11148 ((not local) nil)
11149 (t (error "No reference at point")))
11150 match (and what (or match (match-string 0))))
11151 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11152 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11153 'secondary-selection))
11154 (org-add-hook 'before-change-functions
11155 'org-table-remove-rectangle-highlight)
11156 (if (eq what 'name) (setq var (substring match 1)))
11157 (when (eq what 'range)
11158 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11159 (setq match (org-table-formula-substitute-names match)))
11160 (unless local
11161 (save-excursion
11162 (end-of-line 1)
11163 (re-search-backward "^\\S-" nil t)
11164 (beginning-of-line 1)
11165 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11166 (setq dest
11167 (save-match-data
11168 (org-table-convert-refs-to-rc (match-string 1))))
11169 (org-table-add-rectangle-overlay
11170 (match-beginning 1) (match-end 1) face2))))
11171 (if (and (markerp pos) (marker-buffer pos))
11172 (if (get-buffer-window (marker-buffer pos))
11173 (select-window (get-buffer-window (marker-buffer pos)))
11174 (org-switch-to-buffer-other-window (get-buffer-window
11175 (marker-buffer pos)))))
11176 (goto-char pos)
11177 (org-table-force-dataline)
11178 (when dest
11179 (setq name (substring dest 1))
11180 (cond
11181 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11182 (setq e (assoc name org-table-named-field-locations))
11183 (goto-line (nth 1 e))
11184 (org-table-goto-column (nth 2 e)))
11185 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11186 (let ((l (string-to-number (match-string 1 dest)))
11187 (c (string-to-number (match-string 2 dest))))
11188 (goto-line (aref org-table-dlines l))
11189 (org-table-goto-column c)))
11190 (t (org-table-goto-column (string-to-number name))))
11191 (move-marker pos (point))
11192 (org-table-highlight-rectangle nil nil face2))
11193 (cond
11194 ((equal dest match))
11195 ((not match))
11196 ((eq what 'range)
11197 (condition-case nil
11198 (save-excursion
11199 (org-table-get-range match nil nil 'highlight))
11200 (error nil)))
11201 ((setq e (assoc var org-table-named-field-locations))
11202 (goto-line (nth 1 e))
11203 (org-table-goto-column (nth 2 e))
11204 (org-table-highlight-rectangle (point) (point))
11205 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11206 ((setq e (assoc var org-table-column-names))
11207 (org-table-goto-column (string-to-number (cdr e)))
11208 (org-table-highlight-rectangle (point) (point))
11209 (goto-char (org-table-begin))
11210 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11211 (org-table-end) t)
11212 (progn
11213 (goto-char (match-beginning 1))
11214 (org-table-highlight-rectangle)
11215 (message "Named column (column %s)" (cdr e)))
11216 (error "Column name not found")))
11217 ((eq what 'column)
11218 ;; column number
11219 (org-table-goto-column (string-to-number (substring match 1)))
11220 (org-table-highlight-rectangle (point) (point))
11221 (message "Column %s" (substring match 1)))
11222 ((setq e (assoc var org-table-local-parameters))
11223 (goto-char (org-table-begin))
11224 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11225 (progn
11226 (goto-char (match-beginning 1))
11227 (org-table-highlight-rectangle)
11228 (message "Local parameter."))
11229 (error "Parameter not found")))
11231 (cond
11232 ((not var) (error "No reference at point"))
11233 ((setq e (assoc var org-table-formula-constants-local))
11234 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11235 var (cdr e)))
11236 ((setq e (assoc var org-table-formula-constants))
11237 (message "Constant: $%s=%s in `org-table-formula-constants'."
11238 var (cdr e)))
11239 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11240 (message "Constant: $%s=%s, from `constants.el'%s."
11241 var e (format " (%s units)" constants-unit-system)))
11242 (t (error "Undefined name $%s" var)))))
11243 (goto-char pos)
11244 (when (and org-show-positions
11245 (not (memq this-command '(org-table-fedit-scroll
11246 org-table-fedit-scroll-down))))
11247 (push pos org-show-positions)
11248 (push org-table-current-begin-pos org-show-positions)
11249 (let ((min (apply 'min org-show-positions))
11250 (max (apply 'max org-show-positions)))
11251 (goto-char min) (recenter 0)
11252 (goto-char max)
11253 (or (pos-visible-in-window-p max) (recenter -1))))
11254 (select-window win))))
11256 (defun org-table-force-dataline ()
11257 "Make sure the cursor is in a dataline in a table."
11258 (unless (save-excursion
11259 (beginning-of-line 1)
11260 (looking-at org-table-dataline-regexp))
11261 (let* ((re org-table-dataline-regexp)
11262 (p1 (save-excursion (re-search-forward re nil 'move)))
11263 (p2 (save-excursion (re-search-backward re nil 'move))))
11264 (cond ((and p1 p2)
11265 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11266 p1 p2)))
11267 ((or p1 p2) (goto-char (or p1 p2)))
11268 (t (error "No table dataline around here"))))))
11270 (defun org-table-fedit-line-up ()
11271 "Move cursor one line up in the window showing the table."
11272 (interactive)
11273 (org-table-fedit-move 'previous-line))
11275 (defun org-table-fedit-line-down ()
11276 "Move cursor one line down in the window showing the table."
11277 (interactive)
11278 (org-table-fedit-move 'next-line))
11280 (defun org-table-fedit-move (command)
11281 "Move the cursor in the window shoinw the table.
11282 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11283 (let ((org-table-allow-automatic-line-recalculation nil)
11284 (pos org-pos) (win (selected-window)) p)
11285 (select-window (get-buffer-window (marker-buffer org-pos)))
11286 (setq p (point))
11287 (call-interactively command)
11288 (while (and (org-at-table-p)
11289 (org-at-table-hline-p))
11290 (call-interactively command))
11291 (or (org-at-table-p) (goto-char p))
11292 (move-marker pos (point))
11293 (select-window win)))
11295 (defun org-table-fedit-scroll (N)
11296 (interactive "p")
11297 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11298 (scroll-other-window N)))
11300 (defun org-table-fedit-scroll-down (N)
11301 (interactive "p")
11302 (org-table-fedit-scroll (- N)))
11304 (defvar org-table-rectangle-overlays nil)
11306 (defun org-table-add-rectangle-overlay (beg end &optional face)
11307 "Add a new overlay."
11308 (let ((ov (org-make-overlay beg end)))
11309 (org-overlay-put ov 'face (or face 'secondary-selection))
11310 (push ov org-table-rectangle-overlays)))
11312 (defun org-table-highlight-rectangle (&optional beg end face)
11313 "Highlight rectangular region in a table."
11314 (setq beg (or beg (point)) end (or end (point)))
11315 (let ((b (min beg end))
11316 (e (max beg end))
11317 l1 c1 l2 c2 tmp)
11318 (and (boundp 'org-show-positions)
11319 (setq org-show-positions (cons b (cons e org-show-positions))))
11320 (goto-char (min beg end))
11321 (setq l1 (org-current-line)
11322 c1 (org-table-current-column))
11323 (goto-char (max beg end))
11324 (setq l2 (org-current-line)
11325 c2 (org-table-current-column))
11326 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11327 (goto-line l1)
11328 (beginning-of-line 1)
11329 (loop for line from l1 to l2 do
11330 (when (looking-at org-table-dataline-regexp)
11331 (org-table-goto-column c1)
11332 (skip-chars-backward "^|\n") (setq beg (point))
11333 (org-table-goto-column c2)
11334 (skip-chars-forward "^|\n") (setq end (point))
11335 (org-table-add-rectangle-overlay beg end face))
11336 (beginning-of-line 2))
11337 (goto-char b))
11338 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11340 (defun org-table-remove-rectangle-highlight (&rest ignore)
11341 "Remove the rectangle overlays."
11342 (unless org-inhibit-highlight-removal
11343 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11344 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11345 (setq org-table-rectangle-overlays nil)))
11347 (defvar org-table-coordinate-overlays nil
11348 "Collects the cooordinate grid overlays, so that they can be removed.")
11349 (make-variable-buffer-local 'org-table-coordinate-overlays)
11351 (defun org-table-overlay-coordinates ()
11352 "Add overlays to the table at point, to show row/column coordinates."
11353 (interactive)
11354 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11355 (setq org-table-coordinate-overlays nil)
11356 (save-excursion
11357 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11358 (goto-char (org-table-begin))
11359 (while (org-at-table-p)
11360 (setq eol (point-at-eol))
11361 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11362 (push ov org-table-coordinate-overlays)
11363 (setq hline (looking-at org-table-hline-regexp))
11364 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11365 (format "%4d" (setq id (1+ id)))))
11366 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11367 (when hline
11368 (setq ic 0)
11369 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11370 (setq beg (1+ (match-beginning 0))
11371 ic (1+ ic)
11372 s1 (concat "$" (int-to-string ic))
11373 s2 (org-number-to-letters ic)
11374 str (if (eq org-table-use-standard-references t) s2 s1))
11375 (setq ov (org-make-overlay beg (+ beg (length str))))
11376 (push ov org-table-coordinate-overlays)
11377 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11378 (beginning-of-line 2)))))
11380 (defun org-table-toggle-coordinate-overlays ()
11381 "Toggle the display of Row/Column numbers in tables."
11382 (interactive)
11383 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11384 (message "Row/Column number display turned %s"
11385 (if org-table-overlay-coordinates "on" "off"))
11386 (if (and (org-at-table-p) org-table-overlay-coordinates)
11387 (org-table-align))
11388 (unless org-table-overlay-coordinates
11389 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11390 (setq org-table-coordinate-overlays nil)))
11392 (defun org-table-toggle-formula-debugger ()
11393 "Toggle the formula debugger in tables."
11394 (interactive)
11395 (setq org-table-formula-debug (not org-table-formula-debug))
11396 (message "Formula debugging has been turned %s"
11397 (if org-table-formula-debug "on" "off")))
11399 ;;; The orgtbl minor mode
11401 ;; Define a minor mode which can be used in other modes in order to
11402 ;; integrate the org-mode table editor.
11404 ;; This is really a hack, because the org-mode table editor uses several
11405 ;; keys which normally belong to the major mode, for example the TAB and
11406 ;; RET keys. Here is how it works: The minor mode defines all the keys
11407 ;; necessary to operate the table editor, but wraps the commands into a
11408 ;; function which tests if the cursor is currently inside a table. If that
11409 ;; is the case, the table editor command is executed. However, when any of
11410 ;; those keys is used outside a table, the function uses `key-binding' to
11411 ;; look up if the key has an associated command in another currently active
11412 ;; keymap (minor modes, major mode, global), and executes that command.
11413 ;; There might be problems if any of the keys used by the table editor is
11414 ;; otherwise used as a prefix key.
11416 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11417 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11418 ;; addresses this by checking explicitly for both bindings.
11420 ;; The optimized version (see variable `orgtbl-optimized') takes over
11421 ;; all keys which are bound to `self-insert-command' in the *global map*.
11422 ;; Some modes bind other commands to simple characters, for example
11423 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11424 ;; active, this binding is ignored inside tables and replaced with a
11425 ;; modified self-insert.
11427 (defvar orgtbl-mode nil
11428 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11429 table editor in arbitrary modes.")
11430 (make-variable-buffer-local 'orgtbl-mode)
11432 (defvar orgtbl-mode-map (make-keymap)
11433 "Keymap for `orgtbl-mode'.")
11435 ;;;###autoload
11436 (defun turn-on-orgtbl ()
11437 "Unconditionally turn on `orgtbl-mode'."
11438 (orgtbl-mode 1))
11440 (defvar org-old-auto-fill-inhibit-regexp nil
11441 "Local variable used by `orgtbl-mode'")
11443 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11444 "Matches a line belonging to an orgtbl.")
11446 (defconst orgtbl-extra-font-lock-keywords
11447 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11448 0 (quote 'org-table) 'prepend))
11449 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11451 ;;;###autoload
11452 (defun orgtbl-mode (&optional arg)
11453 "The `org-mode' table editor as a minor mode for use in other modes."
11454 (interactive)
11455 (if (org-mode-p)
11456 ;; Exit without error, in case some hook functions calls this
11457 ;; by accident in org-mode.
11458 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11459 (setq orgtbl-mode
11460 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11461 (if orgtbl-mode
11462 (progn
11463 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11464 ;; Make sure we are first in minor-mode-map-alist
11465 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11466 (and c (setq minor-mode-map-alist
11467 (cons c (delq c minor-mode-map-alist)))))
11468 (org-set-local (quote org-table-may-need-update) t)
11469 (org-add-hook 'before-change-functions 'org-before-change-function
11470 nil 'local)
11471 (org-set-local 'org-old-auto-fill-inhibit-regexp
11472 auto-fill-inhibit-regexp)
11473 (org-set-local 'auto-fill-inhibit-regexp
11474 (if auto-fill-inhibit-regexp
11475 (concat orgtbl-line-start-regexp "\\|"
11476 auto-fill-inhibit-regexp)
11477 orgtbl-line-start-regexp))
11478 (org-add-to-invisibility-spec '(org-cwidth))
11479 (when (fboundp 'font-lock-add-keywords)
11480 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11481 (org-restart-font-lock))
11482 (easy-menu-add orgtbl-mode-menu)
11483 (run-hooks 'orgtbl-mode-hook))
11484 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11485 (org-cleanup-narrow-column-properties)
11486 (org-remove-from-invisibility-spec '(org-cwidth))
11487 (remove-hook 'before-change-functions 'org-before-change-function t)
11488 (when (fboundp 'font-lock-remove-keywords)
11489 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11490 (org-restart-font-lock))
11491 (easy-menu-remove orgtbl-mode-menu)
11492 (force-mode-line-update 'all))))
11494 (defun org-cleanup-narrow-column-properties ()
11495 "Remove all properties related to narrow-column invisibility."
11496 (let ((s 1))
11497 (while (setq s (text-property-any s (point-max)
11498 'display org-narrow-column-arrow))
11499 (remove-text-properties s (1+ s) '(display t)))
11500 (setq s 1)
11501 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11502 (remove-text-properties s (1+ s) '(org-cwidth t)))
11503 (setq s 1)
11504 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11505 (remove-text-properties s (1+ s) '(invisible t)))))
11507 ;; Install it as a minor mode.
11508 (put 'orgtbl-mode :included t)
11509 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11510 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11512 (defun orgtbl-make-binding (fun n &rest keys)
11513 "Create a function for binding in the table minor mode.
11514 FUN is the command to call inside a table. N is used to create a unique
11515 command name. KEYS are keys that should be checked in for a command
11516 to execute outside of tables."
11517 (eval
11518 (list 'defun
11519 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11520 '(arg)
11521 (concat "In tables, run `" (symbol-name fun) "'.\n"
11522 "Outside of tables, run the binding of `"
11523 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11524 "'.")
11525 '(interactive "p")
11526 (list 'if
11527 '(org-at-table-p)
11528 (list 'call-interactively (list 'quote fun))
11529 (list 'let '(orgtbl-mode)
11530 (list 'call-interactively
11531 (append '(or)
11532 (mapcar (lambda (k)
11533 (list 'key-binding k))
11534 keys)
11535 '('orgtbl-error))))))))
11537 (defun orgtbl-error ()
11538 "Error when there is no default binding for a table key."
11539 (interactive)
11540 (error "This key has no function outside tables"))
11542 (defun orgtbl-setup ()
11543 "Setup orgtbl keymaps."
11544 (let ((nfunc 0)
11545 (bindings
11546 (list
11547 '([(meta shift left)] org-table-delete-column)
11548 '([(meta left)] org-table-move-column-left)
11549 '([(meta right)] org-table-move-column-right)
11550 '([(meta shift right)] org-table-insert-column)
11551 '([(meta shift up)] org-table-kill-row)
11552 '([(meta shift down)] org-table-insert-row)
11553 '([(meta up)] org-table-move-row-up)
11554 '([(meta down)] org-table-move-row-down)
11555 '("\C-c\C-w" org-table-cut-region)
11556 '("\C-c\M-w" org-table-copy-region)
11557 '("\C-c\C-y" org-table-paste-rectangle)
11558 '("\C-c-" org-table-insert-hline)
11559 '("\C-c}" org-table-toggle-coordinate-overlays)
11560 '("\C-c{" org-table-toggle-formula-debugger)
11561 '("\C-m" org-table-next-row)
11562 '([(shift return)] org-table-copy-down)
11563 '("\C-c\C-q" org-table-wrap-region)
11564 '("\C-c?" org-table-field-info)
11565 '("\C-c " org-table-blank-field)
11566 '("\C-c+" org-table-sum)
11567 '("\C-c=" org-table-eval-formula)
11568 '("\C-c'" org-table-edit-formulas)
11569 '("\C-c`" org-table-edit-field)
11570 '("\C-c*" org-table-recalculate)
11571 '("\C-c|" org-table-create-or-convert-from-region)
11572 '("\C-c^" org-table-sort-lines)
11573 '([(control ?#)] org-table-rotate-recalc-marks)))
11574 elt key fun cmd)
11575 (while (setq elt (pop bindings))
11576 (setq nfunc (1+ nfunc))
11577 (setq key (org-key (car elt))
11578 fun (nth 1 elt)
11579 cmd (orgtbl-make-binding fun nfunc key))
11580 (org-defkey orgtbl-mode-map key cmd))
11582 ;; Special treatment needed for TAB and RET
11583 (org-defkey orgtbl-mode-map [(return)]
11584 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11585 (org-defkey orgtbl-mode-map "\C-m"
11586 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11588 (org-defkey orgtbl-mode-map [(tab)]
11589 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11590 (org-defkey orgtbl-mode-map "\C-i"
11591 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11593 (org-defkey orgtbl-mode-map [(shift tab)]
11594 (orgtbl-make-binding 'org-table-previous-field 104
11595 [(shift tab)] [(tab)] "\C-i"))
11597 (org-defkey orgtbl-mode-map "\M-\C-m"
11598 (orgtbl-make-binding 'org-table-wrap-region 105
11599 "\M-\C-m" [(meta return)]))
11600 (org-defkey orgtbl-mode-map [(meta return)]
11601 (orgtbl-make-binding 'org-table-wrap-region 106
11602 [(meta return)] "\M-\C-m"))
11604 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11605 (when orgtbl-optimized
11606 ;; If the user wants maximum table support, we need to hijack
11607 ;; some standard editing functions
11608 (org-remap orgtbl-mode-map
11609 'self-insert-command 'orgtbl-self-insert-command
11610 'delete-char 'org-delete-char
11611 'delete-backward-char 'org-delete-backward-char)
11612 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11613 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11614 '("OrgTbl"
11615 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11616 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11617 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11618 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11619 "--"
11620 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11621 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11622 ["Copy Field from Above"
11623 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11624 "--"
11625 ("Column"
11626 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11627 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11628 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11629 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11630 ("Row"
11631 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11632 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11633 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11634 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11635 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
11636 "--"
11637 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11638 ("Rectangle"
11639 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11640 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11641 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11642 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11643 "--"
11644 ("Radio tables"
11645 ["Insert table template" orgtbl-insert-radio-table
11646 (assq major-mode orgtbl-radio-table-templates)]
11647 ["Comment/uncomment table" orgtbl-toggle-comment t])
11648 "--"
11649 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11650 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11651 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11652 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11653 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11654 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11655 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11656 ["Sum Column/Rectangle" org-table-sum
11657 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11658 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11659 ["Debug Formulas"
11660 org-table-toggle-formula-debugger :active (org-at-table-p)
11661 :keys "C-c {"
11662 :style toggle :selected org-table-formula-debug]
11663 ["Show Col/Row Numbers"
11664 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11665 :keys "C-c }"
11666 :style toggle :selected org-table-overlay-coordinates]
11670 (defun orgtbl-ctrl-c-ctrl-c (arg)
11671 "If the cursor is inside a table, realign the table.
11672 It it is a table to be sent away to a receiver, do it.
11673 With prefix arg, also recompute table."
11674 (interactive "P")
11675 (let ((pos (point)) action)
11676 (save-excursion
11677 (beginning-of-line 1)
11678 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11679 ((looking-at "[ \t]*|") pos)
11680 ((looking-at "#\\+TBLFM:") 'recalc))))
11681 (cond
11682 ((integerp action)
11683 (goto-char action)
11684 (org-table-maybe-eval-formula)
11685 (if arg
11686 (call-interactively 'org-table-recalculate)
11687 (org-table-maybe-recalculate-line))
11688 (call-interactively 'org-table-align)
11689 (orgtbl-send-table 'maybe))
11690 ((eq action 'recalc)
11691 (save-excursion
11692 (beginning-of-line 1)
11693 (skip-chars-backward " \r\n\t")
11694 (if (org-at-table-p)
11695 (org-call-with-arg 'org-table-recalculate t))))
11696 (t (let (orgtbl-mode)
11697 (call-interactively (key-binding "\C-c\C-c")))))))
11699 (defun orgtbl-tab (arg)
11700 "Justification and field motion for `orgtbl-mode'."
11701 (interactive "P")
11702 (if arg (org-table-edit-field t)
11703 (org-table-justify-field-maybe)
11704 (org-table-next-field)))
11706 (defun orgtbl-ret ()
11707 "Justification and field motion for `orgtbl-mode'."
11708 (interactive)
11709 (org-table-justify-field-maybe)
11710 (org-table-next-row))
11712 (defun orgtbl-self-insert-command (N)
11713 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11714 If the cursor is in a table looking at whitespace, the whitespace is
11715 overwritten, and the table is not marked as requiring realignment."
11716 (interactive "p")
11717 (if (and (org-at-table-p)
11719 (and org-table-auto-blank-field
11720 (member last-command
11721 '(orgtbl-hijacker-command-100
11722 orgtbl-hijacker-command-101
11723 orgtbl-hijacker-command-102
11724 orgtbl-hijacker-command-103
11725 orgtbl-hijacker-command-104
11726 orgtbl-hijacker-command-105))
11727 (org-table-blank-field))
11729 (eq N 1)
11730 (looking-at "[^|\n]* +|"))
11731 (let (org-table-may-need-update)
11732 (goto-char (1- (match-end 0)))
11733 (delete-backward-char 1)
11734 (goto-char (match-beginning 0))
11735 (self-insert-command N))
11736 (setq org-table-may-need-update t)
11737 (let (orgtbl-mode)
11738 (call-interactively (key-binding (vector last-input-event))))))
11740 (defun org-force-self-insert (N)
11741 "Needed to enforce self-insert under remapping."
11742 (interactive "p")
11743 (self-insert-command N))
11745 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11746 "Regula expression matching exponentials as produced by calc.")
11748 (defvar org-table-clean-did-remove-column nil)
11750 (defun orgtbl-export (table target)
11751 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11752 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11753 org-table-last-alignment org-table-last-column-widths
11754 maxcol column)
11755 (if (not (fboundp func))
11756 (error "Cannot export orgtbl table to %s" target))
11757 (setq lines (org-table-clean-before-export lines))
11758 (setq table
11759 (mapcar
11760 (lambda (x)
11761 (if (string-match org-table-hline-regexp x)
11762 'hline
11763 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11764 lines))
11765 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11766 table)))
11767 (loop for i from (1- maxcol) downto 0 do
11768 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11769 (setq column (delq nil column))
11770 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11771 (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))
11772 (funcall func table nil)))
11774 (defun orgtbl-send-table (&optional maybe)
11775 "Send a tranformed version of this table to the receiver position.
11776 With argument MAYBE, fail quietly if no transformation is defined for
11777 this table."
11778 (interactive)
11779 (catch 'exit
11780 (unless (org-at-table-p) (error "Not at a table"))
11781 ;; when non-interactive, we assume align has just happened.
11782 (when (interactive-p) (org-table-align))
11783 (save-excursion
11784 (goto-char (org-table-begin))
11785 (beginning-of-line 0)
11786 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11787 (if maybe
11788 (throw 'exit nil)
11789 (error "Don't know how to transform this table."))))
11790 (let* ((name (match-string 1))
11792 (transform (intern (match-string 2)))
11793 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11794 (skip (plist-get params :skip))
11795 (skipcols (plist-get params :skipcols))
11796 (txt (buffer-substring-no-properties
11797 (org-table-begin) (org-table-end)))
11798 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11799 (lines (org-table-clean-before-export lines))
11800 (i0 (if org-table-clean-did-remove-column 2 1))
11801 (table (mapcar
11802 (lambda (x)
11803 (if (string-match org-table-hline-regexp x)
11804 'hline
11805 (org-remove-by-index
11806 (org-split-string (org-trim x) "\\s-*|\\s-*")
11807 skipcols i0)))
11808 lines))
11809 (fun (if (= i0 2) 'cdr 'identity))
11810 (org-table-last-alignment
11811 (org-remove-by-index (funcall fun org-table-last-alignment)
11812 skipcols i0))
11813 (org-table-last-column-widths
11814 (org-remove-by-index (funcall fun org-table-last-column-widths)
11815 skipcols i0)))
11817 (unless (fboundp transform)
11818 (error "No such transformation function %s" transform))
11819 (setq txt (funcall transform table params))
11820 ;; Find the insertion place
11821 (save-excursion
11822 (goto-char (point-min))
11823 (unless (re-search-forward
11824 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11825 (error "Don't know where to insert translated table"))
11826 (goto-char (match-beginning 0))
11827 (beginning-of-line 2)
11828 (setq beg (point))
11829 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11830 (error "Cannot find end of insertion region"))
11831 (beginning-of-line 1)
11832 (delete-region beg (point))
11833 (goto-char beg)
11834 (insert txt "\n"))
11835 (message "Table converted and installed at receiver location"))))
11837 (defun org-remove-by-index (list indices &optional i0)
11838 "Remove the elements in LIST with indices in INDICES.
11839 First element has index 0, or I0 if given."
11840 (if (not indices)
11841 list
11842 (if (integerp indices) (setq indices (list indices)))
11843 (setq i0 (1- (or i0 0)))
11844 (delq :rm (mapcar (lambda (x)
11845 (setq i0 (1+ i0))
11846 (if (memq i0 indices) :rm x))
11847 list))))
11849 (defun orgtbl-toggle-comment ()
11850 "Comment or uncomment the orgtbl at point."
11851 (interactive)
11852 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11853 (re2 (concat "^" orgtbl-line-start-regexp))
11854 (commented (save-excursion (beginning-of-line 1)
11855 (cond ((looking-at re1) t)
11856 ((looking-at re2) nil)
11857 (t (error "Not at an org table")))))
11858 (re (if commented re1 re2))
11859 beg end)
11860 (save-excursion
11861 (beginning-of-line 1)
11862 (while (looking-at re) (beginning-of-line 0))
11863 (beginning-of-line 2)
11864 (setq beg (point))
11865 (while (looking-at re) (beginning-of-line 2))
11866 (setq end (point)))
11867 (comment-region beg end (if commented '(4) nil))))
11869 (defun orgtbl-insert-radio-table ()
11870 "Insert a radio table template appropriate for this major mode."
11871 (interactive)
11872 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11873 (txt (nth 1 e))
11874 name pos)
11875 (unless e (error "No radio table setup defined for %s" major-mode))
11876 (setq name (read-string "Table name: "))
11877 (while (string-match "%n" txt)
11878 (setq txt (replace-match name t t txt)))
11879 (or (bolp) (insert "\n"))
11880 (setq pos (point))
11881 (insert txt)
11882 (goto-char pos)))
11884 (defun org-get-param (params header i sym &optional hsym)
11885 "Get parameter value for symbol SYM.
11886 If this is a header line, actually get the value for the symbol with an
11887 additional \"h\" inserted after the colon.
11888 If the value is a protperty list, get the element for the current column.
11889 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11890 (let ((val (plist-get params sym)))
11891 (and hsym header (setq val (or (plist-get params hsym) val)))
11892 (if (consp val) (plist-get val i) val)))
11894 (defun orgtbl-to-generic (table params)
11895 "Convert the orgtbl-mode TABLE to some other format.
11896 This generic routine can be used for many standard cases.
11897 TABLE is a list, each entry either the symbol `hline' for a horizontal
11898 separator line, or a list of fields for that line.
11899 PARAMS is a property list of parameters that can influence the conversion.
11900 For the generic converter, some parameters are obligatory: You need to
11901 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11902 :splice, you must have :tstart and :tend.
11904 Valid parameters are
11906 :tstart String to start the table. Ignored when :splice is t.
11907 :tend String to end the table. Ignored when :splice is t.
11909 :splice When set to t, return only table body lines, don't wrap
11910 them into :tstart and :tend. Default is nil.
11912 :hline String to be inserted on horizontal separation lines.
11913 May be nil to ignore hlines.
11915 :lstart String to start a new table line.
11916 :lend String to end a table line
11917 :sep Separator between two fields
11918 :lfmt Format for entire line, with enough %s to capture all fields.
11919 If this is present, :lstart, :lend, and :sep are ignored.
11920 :fmt A format to be used to wrap the field, should contain
11921 %s for the original field value. For example, to wrap
11922 everything in dollars, you could use :fmt \"$%s$\".
11923 This may also be a property list with column numbers and
11924 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11926 :hlstart :hlend :hlsep :hlfmt :hfmt
11927 Same as above, specific for the header lines in the table.
11928 All lines before the first hline are treated as header.
11929 If any of these is not present, the data line value is used.
11931 :efmt Use this format to print numbers with exponentials.
11932 The format should have %s twice for inserting mantissa
11933 and exponent, for example \"%s\\\\times10^{%s}\". This
11934 may also be a property list with column numbers and
11935 formats. :fmt will still be applied after :efmt.
11937 In addition to this, the parameters :skip and :skipcols are always handled
11938 directly by `orgtbl-send-table'. See manual."
11939 (interactive)
11940 (let* ((p params)
11941 (splicep (plist-get p :splice))
11942 (hline (plist-get p :hline))
11943 rtn line i fm efm lfmt h)
11945 ;; Do we have a header?
11946 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11947 (setq h t))
11949 ;; Put header
11950 (unless splicep
11951 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11953 ;; Now loop over all lines
11954 (while (setq line (pop table))
11955 (if (eq line 'hline)
11956 ;; A horizontal separator line
11957 (progn (if hline (push hline rtn))
11958 (setq h nil)) ; no longer in header
11959 ;; A normal line. Convert the fields, push line onto the result list
11960 (setq i 0)
11961 (setq line
11962 (mapcar
11963 (lambda (f)
11964 (setq i (1+ i)
11965 fm (org-get-param p h i :fmt :hfmt)
11966 efm (org-get-param p h i :efmt))
11967 (if (and efm (string-match orgtbl-exp-regexp f))
11968 (setq f (format
11969 efm (match-string 1 f) (match-string 2 f))))
11970 (if fm (setq f (format fm f)))
11972 line))
11973 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11974 (push (apply 'format lfmt line) rtn)
11975 (push (concat
11976 (org-get-param p h i :lstart :hlstart)
11977 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11978 (org-get-param p h i :lend :hlend))
11979 rtn))))
11981 (unless splicep
11982 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11984 (mapconcat 'identity (nreverse rtn) "\n")))
11986 (defun orgtbl-to-latex (table params)
11987 "Convert the orgtbl-mode TABLE to LaTeX.
11988 TABLE is a list, each entry either the symbol `hline' for a horizontal
11989 separator line, or a list of fields for that line.
11990 PARAMS is a property list of parameters that can influence the conversion.
11991 Supports all parameters from `orgtbl-to-generic'. Most important for
11992 LaTeX are:
11994 :splice When set to t, return only table body lines, don't wrap
11995 them into a tabular environment. Default is nil.
11997 :fmt A format to be used to wrap the field, should contain %s for the
11998 original field value. For example, to wrap everything in dollars,
11999 use :fmt \"$%s$\". This may also be a property list with column
12000 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
12002 :efmt Format for transforming numbers with exponentials. The format
12003 should have %s twice for inserting mantissa and exponent, for
12004 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
12005 This may also be a property list with column numbers and formats.
12007 The general parameters :skip and :skipcols have already been applied when
12008 this function is called."
12009 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
12010 org-table-last-alignment ""))
12011 (params2
12012 (list
12013 :tstart (concat "\\begin{tabular}{" alignment "}")
12014 :tend "\\end{tabular}"
12015 :lstart "" :lend " \\\\" :sep " & "
12016 :efmt "%s\\,(%s)" :hline "\\hline")))
12017 (orgtbl-to-generic table (org-combine-plists params2 params))))
12019 (defun orgtbl-to-html (table params)
12020 "Convert the orgtbl-mode TABLE to LaTeX.
12021 TABLE is a list, each entry either the symbol `hline' for a horizontal
12022 separator line, or a list of fields for that line.
12023 PARAMS is a property list of parameters that can influence the conversion.
12024 Currently this function recognizes the following parameters:
12026 :splice When set to t, return only table body lines, don't wrap
12027 them into a <table> environment. Default is nil.
12029 The general parameters :skip and :skipcols have already been applied when
12030 this function is called. The function does *not* use `orgtbl-to-generic',
12031 so you cannot specify parameters for it."
12032 (let* ((splicep (plist-get params :splice))
12033 html)
12034 ;; Just call the formatter we already have
12035 ;; We need to make text lines for it, so put the fields back together.
12036 (setq html (org-format-org-table-html
12037 (mapcar
12038 (lambda (x)
12039 (if (eq x 'hline)
12040 "|----+----|"
12041 (concat "| " (mapconcat 'identity x " | ") " |")))
12042 table)
12043 splicep))
12044 (if (string-match "\n+\\'" html)
12045 (setq html (replace-match "" t t html)))
12046 html))
12048 (defun orgtbl-to-texinfo (table params)
12049 "Convert the orgtbl-mode TABLE to TeXInfo.
12050 TABLE is a list, each entry either the symbol `hline' for a horizontal
12051 separator line, or a list of fields for that line.
12052 PARAMS is a property list of parameters that can influence the conversion.
12053 Supports all parameters from `orgtbl-to-generic'. Most important for
12054 TeXInfo are:
12056 :splice nil/t When set to t, return only table body lines, don't wrap
12057 them into a multitable environment. Default is nil.
12059 :fmt fmt A format to be used to wrap the field, should contain
12060 %s for the original field value. For example, to wrap
12061 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
12062 This may also be a property list with column numbers and
12063 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
12065 :cf \"f1 f2..\" The column fractions for the table. By default these
12066 are computed automatically from the width of the columns
12067 under org-mode.
12069 The general parameters :skip and :skipcols have already been applied when
12070 this function is called."
12071 (let* ((total (float (apply '+ org-table-last-column-widths)))
12072 (colfrac (or (plist-get params :cf)
12073 (mapconcat
12074 (lambda (x) (format "%.3f" (/ (float x) total)))
12075 org-table-last-column-widths " ")))
12076 (params2
12077 (list
12078 :tstart (concat "@multitable @columnfractions " colfrac)
12079 :tend "@end multitable"
12080 :lstart "@item " :lend "" :sep " @tab "
12081 :hlstart "@headitem ")))
12082 (orgtbl-to-generic table (org-combine-plists params2 params))))
12084 ;;;; Link Stuff
12086 ;;; Link abbreviations
12088 (defun org-link-expand-abbrev (link)
12089 "Apply replacements as defined in `org-link-abbrev-alist."
12090 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
12091 (let* ((key (match-string 1 link))
12092 (as (or (assoc key org-link-abbrev-alist-local)
12093 (assoc key org-link-abbrev-alist)))
12094 (tag (and (match-end 2) (match-string 3 link)))
12095 rpl)
12096 (if (not as)
12097 link
12098 (setq rpl (cdr as))
12099 (cond
12100 ((symbolp rpl) (funcall rpl tag))
12101 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
12102 (t (concat rpl tag)))))
12103 link))
12105 ;;; Storing and inserting links
12107 (defvar org-insert-link-history nil
12108 "Minibuffer history for links inserted with `org-insert-link'.")
12110 (defvar org-stored-links nil
12111 "Contains the links stored with `org-store-link'.")
12113 (defvar org-store-link-plist nil
12114 "Plist with info about the most recently link created with `org-store-link'.")
12116 (defvar org-link-protocols nil
12117 "Link protocols added to Org-mode using `org-add-link-type'.")
12119 (defvar org-store-link-functions nil
12120 "List of functions that are called to create and store a link.
12121 Each function will be called in turn until one returns a non-nil
12122 value. Each function should check if it is responsible for creating
12123 this link (for example by looking at the major mode).
12124 If not, it must exit and return nil.
12125 If yes, it should return a non-nil value after a calling
12126 `org-store-link-props' with a list of properties and values.
12127 Special properties are:
12129 :type The link prefix. like \"http\". This must be given.
12130 :link The link, like \"http://www.astro.uva.nl/~dominik\".
12131 This is obligatory as well.
12132 :description Optional default description for the second pair
12133 of brackets in an Org-mode link. The user can still change
12134 this when inserting this link into an Org-mode buffer.
12136 In addition to these, any additional properties can be specified
12137 and then used in remember templates.")
12139 (defun org-add-link-type (type &optional follow publish)
12140 "Add TYPE to the list of `org-link-types'.
12141 Re-compute all regular expressions depending on `org-link-types'
12142 FOLLOW and PUBLISH are two functions. Both take the link path as
12143 an argument.
12144 FOLLOW should do whatever is necessary to follow the link, for example
12145 to find a file or display a mail message.
12147 PUBLISH takes the path and retuns the string that should be used when
12148 this document is published. FIMXE: This is actually not yet implemented."
12149 (add-to-list 'org-link-types type t)
12150 (org-make-link-regexps)
12151 (add-to-list 'org-link-protocols
12152 (list type follow publish)))
12154 (defun org-add-agenda-custom-command (entry)
12155 "Replace or add a command in `org-agenda-custom-commands'.
12156 This is mostly for hacking and trying a new command - once the command
12157 works you probably want to add it to `org-agenda-custom-commands' for good."
12158 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12159 (if ass
12160 (setcdr ass (cdr entry))
12161 (push entry org-agenda-custom-commands))))
12163 ;;;###autoload
12164 (defun org-store-link (arg)
12165 "\\<org-mode-map>Store an org-link to the current location.
12166 This link is added to `org-stored-links' and can later be inserted
12167 into an org-buffer with \\[org-insert-link].
12169 For some link types, a prefix arg is interpreted:
12170 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12171 For file links, arg negates `org-context-in-file-links'."
12172 (interactive "P")
12173 (setq org-store-link-plist nil) ; reset
12174 (let (link cpltxt desc description search txt)
12175 (cond
12177 ((run-hook-with-args-until-success 'org-store-link-functions)
12178 (setq link (plist-get org-store-link-plist :link)
12179 desc (or (plist-get org-store-link-plist :description) link)))
12181 ((eq major-mode 'bbdb-mode)
12182 (let ((name (bbdb-record-name (bbdb-current-record)))
12183 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
12184 (setq cpltxt (concat "bbdb:" (or name company))
12185 link (org-make-link cpltxt))
12186 (org-store-link-props :type "bbdb" :name name :company company)))
12188 ((eq major-mode 'Info-mode)
12189 (setq link (org-make-link "info:"
12190 (file-name-nondirectory Info-current-file)
12191 ":" Info-current-node))
12192 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
12193 ":" Info-current-node))
12194 (org-store-link-props :type "info" :file Info-current-file
12195 :node Info-current-node))
12197 ((eq major-mode 'calendar-mode)
12198 (let ((cd (calendar-cursor-to-date)))
12199 (setq link
12200 (format-time-string
12201 (car org-time-stamp-formats)
12202 (apply 'encode-time
12203 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12204 nil nil nil))))
12205 (org-store-link-props :type "calendar" :date cd)))
12207 ((or (eq major-mode 'vm-summary-mode)
12208 (eq major-mode 'vm-presentation-mode))
12209 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
12210 (vm-follow-summary-cursor)
12211 (save-excursion
12212 (vm-select-folder-buffer)
12213 (let* ((message (car vm-message-pointer))
12214 (folder buffer-file-name)
12215 (subject (vm-su-subject message))
12216 (to (vm-get-header-contents message "To"))
12217 (from (vm-get-header-contents message "From"))
12218 (message-id (vm-su-message-id message)))
12219 (org-store-link-props :type "vm" :from from :to to :subject subject
12220 :message-id message-id)
12221 (setq message-id (org-remove-angle-brackets message-id))
12222 (setq folder (abbreviate-file-name folder))
12223 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
12224 folder)
12225 (setq folder (replace-match "" t t folder)))
12226 (setq cpltxt (org-email-link-description))
12227 (setq link (org-make-link "vm:" folder "#" message-id)))))
12229 ((eq major-mode 'wl-summary-mode)
12230 (let* ((msgnum (wl-summary-message-number))
12231 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
12232 msgnum 'message-id))
12233 (wl-message-entity
12234 (if (fboundp 'elmo-message-entity)
12235 (elmo-message-entity
12236 wl-summary-buffer-elmo-folder msgnum)
12237 (elmo-msgdb-overview-get-entity
12238 msgnum (wl-summary-buffer-msgdb))))
12239 (from (wl-summary-line-from))
12240 (to (car (elmo-message-entity-field wl-message-entity 'to)))
12241 (subject (let (wl-thr-indent-string wl-parent-message-entity)
12242 (wl-summary-line-subject))))
12243 (org-store-link-props :type "wl" :from from :to to
12244 :subject subject :message-id message-id)
12245 (setq message-id (org-remove-angle-brackets message-id))
12246 (setq cpltxt (org-email-link-description))
12247 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
12248 "#" message-id))))
12250 ((or (equal major-mode 'mh-folder-mode)
12251 (equal major-mode 'mh-show-mode))
12252 (let ((from (org-mhe-get-header "From:"))
12253 (to (org-mhe-get-header "To:"))
12254 (message-id (org-mhe-get-header "Message-Id:"))
12255 (subject (org-mhe-get-header "Subject:")))
12256 (org-store-link-props :type "mh" :from from :to to
12257 :subject subject :message-id message-id)
12258 (setq cpltxt (org-email-link-description))
12259 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
12260 (org-remove-angle-brackets message-id)))))
12262 ((or (eq major-mode 'rmail-mode)
12263 (eq major-mode 'rmail-summary-mode))
12264 (save-window-excursion
12265 (save-restriction
12266 (when (eq major-mode 'rmail-summary-mode)
12267 (rmail-show-message rmail-current-message))
12268 (rmail-narrow-to-non-pruned-header)
12269 (let ((folder buffer-file-name)
12270 (message-id (mail-fetch-field "message-id"))
12271 (from (mail-fetch-field "from"))
12272 (to (mail-fetch-field "to"))
12273 (subject (mail-fetch-field "subject")))
12274 (org-store-link-props
12275 :type "rmail" :from from :to to
12276 :subject subject :message-id message-id)
12277 (setq message-id (org-remove-angle-brackets message-id))
12278 (setq cpltxt (org-email-link-description))
12279 (setq link (org-make-link "rmail:" folder "#" message-id)))
12280 (rmail-show-message rmail-current-message))))
12282 ((eq major-mode 'gnus-group-mode)
12283 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12284 (gnus-group-group-name)) ; version
12285 ((fboundp 'gnus-group-name)
12286 (gnus-group-name))
12287 (t "???"))))
12288 (unless group (error "Not on a group"))
12289 (org-store-link-props :type "gnus" :group group)
12290 (setq cpltxt (concat
12291 (if (org-xor arg org-usenet-links-prefer-google)
12292 "http://groups.google.com/groups?group="
12293 "gnus:")
12294 group)
12295 link (org-make-link cpltxt))))
12297 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12298 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12299 (let* ((group gnus-newsgroup-name)
12300 (article (gnus-summary-article-number))
12301 (header (gnus-summary-article-header article))
12302 (from (mail-header-from header))
12303 (message-id (mail-header-id header))
12304 (date (mail-header-date header))
12305 (subject (gnus-summary-subject-string)))
12306 (org-store-link-props :type "gnus" :from from :subject subject
12307 :message-id message-id :group group)
12308 (setq cpltxt (org-email-link-description))
12309 (if (org-xor arg org-usenet-links-prefer-google)
12310 (setq link
12311 (concat
12312 cpltxt "\n "
12313 (format "http://groups.google.com/groups?as_umsgid=%s"
12314 (org-fixup-message-id-for-http message-id))))
12315 (setq link (org-make-link "gnus:" group
12316 "#" (number-to-string article))))))
12318 ((eq major-mode 'w3-mode)
12319 (setq cpltxt (url-view-url t)
12320 link (org-make-link cpltxt))
12321 (org-store-link-props :type "w3" :url (url-view-url t)))
12323 ((eq major-mode 'w3m-mode)
12324 (setq cpltxt (or w3m-current-title w3m-current-url)
12325 link (org-make-link w3m-current-url))
12326 (org-store-link-props :type "w3m" :url (url-view-url t)))
12328 ((setq search (run-hook-with-args-until-success
12329 'org-create-file-search-functions))
12330 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12331 "::" search))
12332 (setq cpltxt (or description link)))
12334 ((eq major-mode 'image-mode)
12335 (setq cpltxt (concat "file:"
12336 (abbreviate-file-name buffer-file-name))
12337 link (org-make-link cpltxt))
12338 (org-store-link-props :type "image" :file buffer-file-name))
12340 ((eq major-mode 'dired-mode)
12341 ;; link to the file in the current line
12342 (setq cpltxt (concat "file:"
12343 (abbreviate-file-name
12344 (expand-file-name
12345 (dired-get-filename nil t))))
12346 link (org-make-link cpltxt)))
12348 ((and buffer-file-name (org-mode-p))
12349 ;; Just link to current headline
12350 (setq cpltxt (concat "file:"
12351 (abbreviate-file-name buffer-file-name)))
12352 ;; Add a context search string
12353 (when (org-xor org-context-in-file-links arg)
12354 ;; Check if we are on a target
12355 (if (org-in-regexp "<<\\(.*?\\)>>")
12356 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12357 (setq txt (cond
12358 ((org-on-heading-p) nil)
12359 ((org-region-active-p)
12360 (buffer-substring (region-beginning) (region-end)))
12361 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12362 (when (or (null txt) (string-match "\\S-" txt))
12363 (setq cpltxt
12364 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12365 desc "NONE"))))
12366 (if (string-match "::\\'" cpltxt)
12367 (setq cpltxt (substring cpltxt 0 -2)))
12368 (setq link (org-make-link cpltxt)))
12370 ((buffer-file-name (buffer-base-buffer))
12371 ;; Just link to this file here.
12372 (setq cpltxt (concat "file:"
12373 (abbreviate-file-name
12374 (buffer-file-name (buffer-base-buffer)))))
12375 ;; Add a context string
12376 (when (org-xor org-context-in-file-links arg)
12377 (setq txt (if (org-region-active-p)
12378 (buffer-substring (region-beginning) (region-end))
12379 (buffer-substring (point-at-bol) (point-at-eol))))
12380 ;; Only use search option if there is some text.
12381 (when (string-match "\\S-" txt)
12382 (setq cpltxt
12383 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12384 desc "NONE")))
12385 (setq link (org-make-link cpltxt)))
12387 ((interactive-p)
12388 (error "Cannot link to a buffer which is not visiting a file"))
12390 (t (setq link nil)))
12392 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12393 (setq link (or link cpltxt)
12394 desc (or desc cpltxt))
12395 (if (equal desc "NONE") (setq desc nil))
12397 (if (and (interactive-p) link)
12398 (progn
12399 (setq org-stored-links
12400 (cons (list link desc) org-stored-links))
12401 (message "Stored: %s" (or desc link)))
12402 (and link (org-make-link-string link desc)))))
12404 (defun org-store-link-props (&rest plist)
12405 "Store link properties, extract names and addresses."
12406 (let (x adr)
12407 (when (setq x (plist-get plist :from))
12408 (setq adr (mail-extract-address-components x))
12409 (plist-put plist :fromname (car adr))
12410 (plist-put plist :fromaddress (nth 1 adr)))
12411 (when (setq x (plist-get plist :to))
12412 (setq adr (mail-extract-address-components x))
12413 (plist-put plist :toname (car adr))
12414 (plist-put plist :toaddress (nth 1 adr))))
12415 (let ((from (plist-get plist :from))
12416 (to (plist-get plist :to)))
12417 (when (and from to org-from-is-user-regexp)
12418 (plist-put plist :fromto
12419 (if (string-match org-from-is-user-regexp from)
12420 (concat "to %t")
12421 (concat "from %f")))))
12422 (setq org-store-link-plist plist))
12424 (defun org-email-link-description (&optional fmt)
12425 "Return the description part of an email link.
12426 This takes information from `org-store-link-plist' and formats it
12427 according to FMT (default from `org-email-link-description-format')."
12428 (setq fmt (or fmt org-email-link-description-format))
12429 (let* ((p org-store-link-plist)
12430 (to (plist-get p :toaddress))
12431 (from (plist-get p :fromaddress))
12432 (table
12433 (list
12434 (cons "%c" (plist-get p :fromto))
12435 (cons "%F" (plist-get p :from))
12436 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12437 (cons "%T" (plist-get p :to))
12438 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12439 (cons "%s" (plist-get p :subject))
12440 (cons "%m" (plist-get p :message-id)))))
12441 (when (string-match "%c" fmt)
12442 ;; Check if the user wrote this message
12443 (if (and org-from-is-user-regexp from to
12444 (save-match-data (string-match org-from-is-user-regexp from)))
12445 (setq fmt (replace-match "to %t" t t fmt))
12446 (setq fmt (replace-match "from %f" t t fmt))))
12447 (org-replace-escapes fmt table)))
12449 (defun org-make-org-heading-search-string (&optional string heading)
12450 "Make search string for STRING or current headline."
12451 (interactive)
12452 (let ((s (or string (org-get-heading))))
12453 (unless (and string (not heading))
12454 ;; We are using a headline, clean up garbage in there.
12455 (if (string-match org-todo-regexp s)
12456 (setq s (replace-match "" t t s)))
12457 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12458 (setq s (replace-match "" t t s)))
12459 (setq s (org-trim s))
12460 (if (string-match (concat "^\\(" org-quote-string "\\|"
12461 org-comment-string "\\)") s)
12462 (setq s (replace-match "" t t s)))
12463 (while (string-match org-ts-regexp s)
12464 (setq s (replace-match "" t t s))))
12465 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12466 (setq s (replace-match " " t t s)))
12467 (or string (setq s (concat "*" s))) ; Add * for headlines
12468 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12470 (defun org-make-link (&rest strings)
12471 "Concatenate STRINGS."
12472 (apply 'concat strings))
12474 (defun org-make-link-string (link &optional description)
12475 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12476 (unless (string-match "\\S-" link)
12477 (error "Empty link"))
12478 (when (stringp description)
12479 ;; Remove brackets from the description, they are fatal.
12480 (while (string-match "\\[" description)
12481 (setq description (replace-match "{" t t description)))
12482 (while (string-match "\\]" description)
12483 (setq description (replace-match "}" t t description))))
12484 (when (equal (org-link-escape link) description)
12485 ;; No description needed, it is identical
12486 (setq description nil))
12487 (when (and (not description)
12488 (not (equal link (org-link-escape link))))
12489 (setq description link))
12490 (concat "[[" (org-link-escape link) "]"
12491 (if description (concat "[" description "]") "")
12492 "]"))
12494 (defconst org-link-escape-chars
12495 '((?\ . "%20")
12496 (?\[ . "%5B")
12497 (?\] . "%5D")
12498 (?\340 . "%E0") ; `a
12499 (?\342 . "%E2") ; ^a
12500 (?\347 . "%E7") ; ,c
12501 (?\350 . "%E8") ; `e
12502 (?\351 . "%E9") ; 'e
12503 (?\352 . "%EA") ; ^e
12504 (?\356 . "%EE") ; ^i
12505 (?\364 . "%F4") ; ^o
12506 (?\371 . "%F9") ; `u
12507 (?\373 . "%FB") ; ^u
12508 (?\; . "%3B")
12509 (?? . "%3F")
12510 (?= . "%3D")
12511 (?+ . "%2B")
12513 "Association list of escapes for some characters problematic in links.
12514 This is the list that is used for internal purposes.")
12516 (defconst org-link-escape-chars-browser
12517 '((?\ . "%20")) ; 32 for the SPC char
12518 "Association list of escapes for some characters problematic in links.
12519 This is the list that is used before handing over to the browser.")
12521 (defun org-link-escape (text &optional table)
12522 "Escape charaters in TEXT that are problematic for links."
12523 (setq table (or table org-link-escape-chars))
12524 (when text
12525 (let ((re (mapconcat (lambda (x) (regexp-quote
12526 (char-to-string (car x))))
12527 table "\\|")))
12528 (while (string-match re text)
12529 (setq text
12530 (replace-match
12531 (cdr (assoc (string-to-char (match-string 0 text))
12532 table))
12533 t t text)))
12534 text)))
12536 (defun org-link-unescape (text &optional table)
12537 "Reverse the action of `org-link-escape'."
12538 (setq table (or table org-link-escape-chars))
12539 (when text
12540 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12541 table "\\|")))
12542 (while (string-match re text)
12543 (setq text
12544 (replace-match
12545 (char-to-string (car (rassoc (match-string 0 text) table)))
12546 t t text)))
12547 text)))
12549 (defun org-xor (a b)
12550 "Exclusive or."
12551 (if a (not b) b))
12553 (defun org-get-header (header)
12554 "Find a header field in the current buffer."
12555 (save-excursion
12556 (goto-char (point-min))
12557 (let ((case-fold-search t) s)
12558 (cond
12559 ((eq header 'from)
12560 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12561 (setq s (match-string 1)))
12562 (while (string-match "\"" s)
12563 (setq s (replace-match "" t t s)))
12564 (if (string-match "[<(].*" s)
12565 (setq s (replace-match "" t t s))))
12566 ((eq header 'message-id)
12567 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12568 (setq s (match-string 1))))
12569 ((eq header 'subject)
12570 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12571 (setq s (match-string 1)))))
12572 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12573 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12574 s)))
12577 (defun org-fixup-message-id-for-http (s)
12578 "Replace special characters in a message id, so it can be used in an http query."
12579 (while (string-match "<" s)
12580 (setq s (replace-match "%3C" t t s)))
12581 (while (string-match ">" s)
12582 (setq s (replace-match "%3E" t t s)))
12583 (while (string-match "@" s)
12584 (setq s (replace-match "%40" t t s)))
12587 ;;;###autoload
12588 (defun org-insert-link-global ()
12589 "Insert a link like Org-mode does.
12590 This command can be called in any mode to insert a link in Org-mode syntax."
12591 (interactive)
12592 (org-run-like-in-org-mode 'org-insert-link))
12594 (defun org-insert-link (&optional complete-file)
12595 "Insert a link. At the prompt, enter the link.
12597 Completion can be used to select a link previously stored with
12598 `org-store-link'. When the empty string is entered (i.e. if you just
12599 press RET at the prompt), the link defaults to the most recently
12600 stored link. As SPC triggers completion in the minibuffer, you need to
12601 use M-SPC or C-q SPC to force the insertion of a space character.
12603 You will also be prompted for a description, and if one is given, it will
12604 be displayed in the buffer instead of the link.
12606 If there is already a link at point, this command will allow you to edit link
12607 and description parts.
12609 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12610 selected using completion. The path to the file will be relative to
12611 the current directory if the file is in the current directory or a
12612 subdirectory. Otherwise, the link will be the absolute path as
12613 completed in the minibuffer (i.e. normally ~/path/to/file).
12615 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12616 is in the current directory or below.
12617 With three \\[universal-argument] prefixes, negate the meaning of
12618 `org-keep-stored-link-after-insertion'."
12619 (interactive "P")
12620 (let* ((wcf (current-window-configuration))
12621 (region (if (org-region-active-p)
12622 (buffer-substring (region-beginning) (region-end))))
12623 (remove (and region (list (region-beginning) (region-end))))
12624 (desc region)
12625 tmphist ; byte-compile incorrectly complains about this
12626 link entry file)
12627 (cond
12628 ((org-in-regexp org-bracket-link-regexp 1)
12629 ;; We do have a link at point, and we are going to edit it.
12630 (setq remove (list (match-beginning 0) (match-end 0)))
12631 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12632 (setq link (read-string "Link: "
12633 (org-link-unescape
12634 (org-match-string-no-properties 1)))))
12635 ((or (org-in-regexp org-angle-link-re)
12636 (org-in-regexp org-plain-link-re))
12637 ;; Convert to bracket link
12638 (setq remove (list (match-beginning 0) (match-end 0))
12639 link (read-string "Link: "
12640 (org-remove-angle-brackets (match-string 0)))))
12641 ((equal complete-file '(4))
12642 ;; Completing read for file names.
12643 (setq file (read-file-name "File: "))
12644 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12645 (pwd1 (file-name-as-directory (abbreviate-file-name
12646 (expand-file-name ".")))))
12647 (cond
12648 ((equal complete-file '(16))
12649 (setq link (org-make-link
12650 "file:"
12651 (abbreviate-file-name (expand-file-name file)))))
12652 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12653 (setq link (org-make-link "file:" (match-string 1 file))))
12654 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12655 (expand-file-name file))
12656 (setq link (org-make-link
12657 "file:" (match-string 1 (expand-file-name file)))))
12658 (t (setq link (org-make-link "file:" file))))))
12660 ;; Read link, with completion for stored links.
12661 (with-output-to-temp-buffer "*Org Links*"
12662 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12663 (when org-stored-links
12664 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12665 (princ (mapconcat
12666 (lambda (x)
12667 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12668 (reverse org-stored-links) "\n"))))
12669 (let ((cw (selected-window)))
12670 (select-window (get-buffer-window "*Org Links*"))
12671 (shrink-window-if-larger-than-buffer)
12672 (setq truncate-lines t)
12673 (select-window cw))
12674 ;; Fake a link history, containing the stored links.
12675 (setq tmphist (append (mapcar 'car org-stored-links)
12676 org-insert-link-history))
12677 (unwind-protect
12678 (setq link (org-completing-read
12679 "Link: "
12680 (append
12681 (mapcar (lambda (x) (list (concat (car x) ":")))
12682 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12683 (mapcar (lambda (x) (list (concat x ":")))
12684 org-link-types))
12685 nil nil nil
12686 'tmphist
12687 (or (car (car org-stored-links)))))
12688 (set-window-configuration wcf)
12689 (kill-buffer "*Org Links*"))
12690 (setq entry (assoc link org-stored-links))
12691 (or entry (push link org-insert-link-history))
12692 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12693 (not org-keep-stored-link-after-insertion))
12694 (setq org-stored-links (delq (assoc link org-stored-links)
12695 org-stored-links)))
12696 (setq desc (or desc (nth 1 entry)))))
12698 (if (string-match org-plain-link-re link)
12699 ;; URL-like link, normalize the use of angular brackets.
12700 (setq link (org-make-link (org-remove-angle-brackets link))))
12702 ;; Check if we are linking to the current file with a search option
12703 ;; If yes, simplify the link by using only the search option.
12704 (when (and buffer-file-name
12705 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12706 (let* ((path (match-string 1 link))
12707 (case-fold-search nil)
12708 (search (match-string 2 link)))
12709 (save-match-data
12710 (if (equal (file-truename buffer-file-name) (file-truename path))
12711 ;; We are linking to this same file, with a search option
12712 (setq link search)))))
12714 ;; Check if we can/should use a relative path. If yes, simplify the link
12715 (when (string-match "\\<file:\\(.*\\)" link)
12716 (let* ((path (match-string 1 link))
12717 (origpath path)
12718 (case-fold-search nil))
12719 (cond
12720 ((eq org-link-file-path-type 'absolute)
12721 (setq path (abbreviate-file-name (expand-file-name path))))
12722 ((eq org-link-file-path-type 'noabbrev)
12723 (setq path (expand-file-name path)))
12724 ((eq org-link-file-path-type 'relative)
12725 (setq path (file-relative-name path)))
12727 (save-match-data
12728 (if (string-match (concat "^" (regexp-quote
12729 (file-name-as-directory
12730 (expand-file-name "."))))
12731 (expand-file-name path))
12732 ;; We are linking a file with relative path name.
12733 (setq path (substring (expand-file-name path)
12734 (match-end 0)))))))
12735 (setq link (concat "file:" path))
12736 (if (equal desc origpath)
12737 (setq desc path))))
12739 (setq desc (read-string "Description: " desc))
12740 (unless (string-match "\\S-" desc) (setq desc nil))
12741 (if remove (apply 'delete-region remove))
12742 (insert (org-make-link-string link desc))))
12744 (defun org-completing-read (&rest args)
12745 (let ((minibuffer-local-completion-map
12746 (copy-keymap minibuffer-local-completion-map)))
12747 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12748 (apply 'completing-read args)))
12750 ;;; Opening/following a link
12751 (defvar org-link-search-failed nil)
12753 (defun org-next-link ()
12754 "Move forward to the next link.
12755 If the link is in hidden text, expose it."
12756 (interactive)
12757 (when (and org-link-search-failed (eq this-command last-command))
12758 (goto-char (point-min))
12759 (message "Link search wrapped back to beginning of buffer"))
12760 (setq org-link-search-failed nil)
12761 (let* ((pos (point))
12762 (ct (org-context))
12763 (a (assoc :link ct)))
12764 (if a (goto-char (nth 2 a)))
12765 (if (re-search-forward org-any-link-re nil t)
12766 (progn
12767 (goto-char (match-beginning 0))
12768 (if (org-invisible-p) (org-show-context)))
12769 (goto-char pos)
12770 (setq org-link-search-failed t)
12771 (error "No further link found"))))
12773 (defun org-previous-link ()
12774 "Move backward to the previous link.
12775 If the link is in hidden text, expose it."
12776 (interactive)
12777 (when (and org-link-search-failed (eq this-command last-command))
12778 (goto-char (point-max))
12779 (message "Link search wrapped back to end of buffer"))
12780 (setq org-link-search-failed nil)
12781 (let* ((pos (point))
12782 (ct (org-context))
12783 (a (assoc :link ct)))
12784 (if a (goto-char (nth 1 a)))
12785 (if (re-search-backward org-any-link-re nil t)
12786 (progn
12787 (goto-char (match-beginning 0))
12788 (if (org-invisible-p) (org-show-context)))
12789 (goto-char pos)
12790 (setq org-link-search-failed t)
12791 (error "No further link found"))))
12793 (defun org-find-file-at-mouse (ev)
12794 "Open file link or URL at mouse."
12795 (interactive "e")
12796 (mouse-set-point ev)
12797 (org-open-at-point 'in-emacs))
12799 (defun org-open-at-mouse (ev)
12800 "Open file link or URL at mouse."
12801 (interactive "e")
12802 (mouse-set-point ev)
12803 (org-open-at-point))
12805 (defvar org-window-config-before-follow-link nil
12806 "The window configuration before following a link.
12807 This is saved in case the need arises to restore it.")
12809 (defvar org-open-link-marker (make-marker)
12810 "Marker pointing to the location where `org-open-at-point; was called.")
12812 ;;;###autoload
12813 (defun org-open-at-point-global ()
12814 "Follow a link like Org-mode does.
12815 This command can be called in any mode to follow a link that has
12816 Org-mode syntax."
12817 (interactive)
12818 (org-run-like-in-org-mode 'org-open-at-point))
12820 (defun org-open-at-point (&optional in-emacs)
12821 "Open link at or after point.
12822 If there is no link at point, this function will search forward up to
12823 the end of the current subtree.
12824 Normally, files will be opened by an appropriate application. If the
12825 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12826 (interactive "P")
12827 (move-marker org-open-link-marker (point))
12828 (setq org-window-config-before-follow-link (current-window-configuration))
12829 (org-remove-occur-highlights nil nil t)
12830 (if (org-at-timestamp-p t)
12831 (org-follow-timestamp-link)
12832 (let (type path link line search (pos (point)))
12833 (catch 'match
12834 (save-excursion
12835 (skip-chars-forward "^]\n\r")
12836 (when (org-in-regexp org-bracket-link-regexp)
12837 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12838 (while (string-match " *\n *" link)
12839 (setq link (replace-match " " t t link)))
12840 (setq link (org-link-expand-abbrev link))
12841 (if (string-match org-link-re-with-space2 link)
12842 (setq type (match-string 1 link) path (match-string 2 link))
12843 (setq type "thisfile" path link))
12844 (throw 'match t)))
12846 (when (get-text-property (point) 'org-linked-text)
12847 (setq type "thisfile"
12848 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12849 (1+ (point)) (point))
12850 path (buffer-substring
12851 (previous-single-property-change pos 'org-linked-text)
12852 (next-single-property-change pos 'org-linked-text)))
12853 (throw 'match t))
12855 (save-excursion
12856 (when (or (org-in-regexp org-angle-link-re)
12857 (org-in-regexp org-plain-link-re))
12858 (setq type (match-string 1) path (match-string 2))
12859 (throw 'match t)))
12860 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12861 (setq type "tree-match"
12862 path (match-string 1))
12863 (throw 'match t))
12864 (save-excursion
12865 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12866 (setq type "tags"
12867 path (match-string 1))
12868 (while (string-match ":" path)
12869 (setq path (replace-match "+" t t path)))
12870 (throw 'match t))))
12871 (unless path
12872 (error "No link found"))
12873 ;; Remove any trailing spaces in path
12874 (if (string-match " +\\'" path)
12875 (setq path (replace-match "" t t path)))
12877 (cond
12879 ((assoc type org-link-protocols)
12880 (funcall (nth 1 (assoc type org-link-protocols)) path))
12882 ((equal type "mailto")
12883 (let ((cmd (car org-link-mailto-program))
12884 (args (cdr org-link-mailto-program)) args1
12885 (address path) (subject "") a)
12886 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12887 (setq address (match-string 1 path)
12888 subject (org-link-escape (match-string 2 path))))
12889 (while args
12890 (cond
12891 ((not (stringp (car args))) (push (pop args) args1))
12892 (t (setq a (pop args))
12893 (if (string-match "%a" a)
12894 (setq a (replace-match address t t a)))
12895 (if (string-match "%s" a)
12896 (setq a (replace-match subject t t a)))
12897 (push a args1))))
12898 (apply cmd (nreverse args1))))
12900 ((member type '("http" "https" "ftp" "news"))
12901 (browse-url (concat type ":" (org-link-escape
12902 path org-link-escape-chars-browser))))
12904 ((member type '("message"))
12905 (browse-url (concat type ":" path)))
12907 ((string= type "tags")
12908 (org-tags-view in-emacs path))
12909 ((string= type "thisfile")
12910 (if in-emacs
12911 (switch-to-buffer-other-window
12912 (org-get-buffer-for-internal-link (current-buffer)))
12913 (org-mark-ring-push))
12914 (let ((cmd `(org-link-search
12915 ,path
12916 ,(cond ((equal in-emacs '(4)) 'occur)
12917 ((equal in-emacs '(16)) 'org-occur)
12918 (t nil))
12919 ,pos)))
12920 (condition-case nil (eval cmd)
12921 (error (progn (widen) (eval cmd))))))
12923 ((string= type "tree-match")
12924 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12926 ((string= type "file")
12927 (if (string-match "::\\([0-9]+\\)\\'" path)
12928 (setq line (string-to-number (match-string 1 path))
12929 path (substring path 0 (match-beginning 0)))
12930 (if (string-match "::\\(.+\\)\\'" path)
12931 (setq search (match-string 1 path)
12932 path (substring path 0 (match-beginning 0)))))
12933 (if (string-match "[*?{]" (file-name-nondirectory path))
12934 (dired path)
12935 (org-open-file path in-emacs line search)))
12937 ((string= type "news")
12938 (org-follow-gnus-link path))
12940 ((string= type "bbdb")
12941 (org-follow-bbdb-link path))
12943 ((string= type "info")
12944 (org-follow-info-link path))
12946 ((string= type "gnus")
12947 (let (group article)
12948 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12949 (error "Error in Gnus link"))
12950 (setq group (match-string 1 path)
12951 article (match-string 3 path))
12952 (org-follow-gnus-link group article)))
12954 ((string= type "vm")
12955 (let (folder article)
12956 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12957 (error "Error in VM link"))
12958 (setq folder (match-string 1 path)
12959 article (match-string 3 path))
12960 ;; in-emacs is the prefix arg, will be interpreted as read-only
12961 (org-follow-vm-link folder article in-emacs)))
12963 ((string= type "wl")
12964 (let (folder article)
12965 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12966 (error "Error in Wanderlust link"))
12967 (setq folder (match-string 1 path)
12968 article (match-string 3 path))
12969 (org-follow-wl-link folder article)))
12971 ((string= type "mhe")
12972 (let (folder article)
12973 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12974 (error "Error in MHE link"))
12975 (setq folder (match-string 1 path)
12976 article (match-string 3 path))
12977 (org-follow-mhe-link folder article)))
12979 ((string= type "rmail")
12980 (let (folder article)
12981 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12982 (error "Error in RMAIL link"))
12983 (setq folder (match-string 1 path)
12984 article (match-string 3 path))
12985 (org-follow-rmail-link folder article)))
12987 ((string= type "shell")
12988 (let ((cmd path))
12989 (if (or (not org-confirm-shell-link-function)
12990 (funcall org-confirm-shell-link-function
12991 (format "Execute \"%s\" in shell? "
12992 (org-add-props cmd nil
12993 'face 'org-warning))))
12994 (progn
12995 (message "Executing %s" cmd)
12996 (shell-command cmd))
12997 (error "Abort"))))
12999 ((string= type "elisp")
13000 (let ((cmd path))
13001 (if (or (not org-confirm-elisp-link-function)
13002 (funcall org-confirm-elisp-link-function
13003 (format "Execute \"%s\" as elisp? "
13004 (org-add-props cmd nil
13005 'face 'org-warning))))
13006 (message "%s => %s" cmd (eval (read cmd)))
13007 (error "Abort"))))
13010 (browse-url-at-point)))))
13011 (move-marker org-open-link-marker nil)
13012 (run-hook-with-args 'org-follow-link-hook))
13014 ;;; File search
13016 (defvar org-create-file-search-functions nil
13017 "List of functions to construct the right search string for a file link.
13018 These functions are called in turn with point at the location to
13019 which the link should point.
13021 A function in the hook should first test if it would like to
13022 handle this file type, for example by checking the major-mode or
13023 the file extension. If it decides not to handle this file, it
13024 should just return nil to give other functions a chance. If it
13025 does handle the file, it must return the search string to be used
13026 when following the link. The search string will be part of the
13027 file link, given after a double colon, and `org-open-at-point'
13028 will automatically search for it. If special measures must be
13029 taken to make the search successful, another function should be
13030 added to the companion hook `org-execute-file-search-functions',
13031 which see.
13033 A function in this hook may also use `setq' to set the variable
13034 `description' to provide a suggestion for the descriptive text to
13035 be used for this link when it gets inserted into an Org-mode
13036 buffer with \\[org-insert-link].")
13038 (defvar org-execute-file-search-functions nil
13039 "List of functions to execute a file search triggered by a link.
13041 Functions added to this hook must accept a single argument, the
13042 search string that was part of the file link, the part after the
13043 double colon. The function must first check if it would like to
13044 handle this search, for example by checking the major-mode or the
13045 file extension. If it decides not to handle this search, it
13046 should just return nil to give other functions a chance. If it
13047 does handle the search, it must return a non-nil value to keep
13048 other functions from trying.
13050 Each function can access the current prefix argument through the
13051 variable `current-prefix-argument'. Note that a single prefix is
13052 used to force opening a link in Emacs, so it may be good to only
13053 use a numeric or double prefix to guide the search function.
13055 In case this is needed, a function in this hook can also restore
13056 the window configuration before `org-open-at-point' was called using:
13058 (set-window-configuration org-window-config-before-follow-link)")
13060 (defun org-link-search (s &optional type avoid-pos)
13061 "Search for a link search option.
13062 If S is surrounded by forward slashes, it is interpreted as a
13063 regular expression. In org-mode files, this will create an `org-occur'
13064 sparse tree. In ordinary files, `occur' will be used to list matches.
13065 If the current buffer is in `dired-mode', grep will be used to search
13066 in all files. If AVOID-POS is given, ignore matches near that position."
13067 (let ((case-fold-search t)
13068 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
13069 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
13070 (append '(("") (" ") ("\t") ("\n"))
13071 org-emphasis-alist)
13072 "\\|") "\\)"))
13073 (pos (point))
13074 (pre "") (post "")
13075 words re0 re1 re2 re3 re4 re5 re2a reall)
13076 (cond
13077 ;; First check if there are any special
13078 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
13079 ;; Now try the builtin stuff
13080 ((save-excursion
13081 (goto-char (point-min))
13082 (and
13083 (re-search-forward
13084 (concat "<<" (regexp-quote s0) ">>") nil t)
13085 (setq pos (match-beginning 0))))
13086 ;; There is an exact target for this
13087 (goto-char pos))
13088 ((string-match "^/\\(.*\\)/$" s)
13089 ;; A regular expression
13090 (cond
13091 ((org-mode-p)
13092 (org-occur (match-string 1 s)))
13093 ;;((eq major-mode 'dired-mode)
13094 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
13095 (t (org-do-occur (match-string 1 s)))))
13097 ;; A normal search strings
13098 (when (equal (string-to-char s) ?*)
13099 ;; Anchor on headlines, post may include tags.
13100 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
13101 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
13102 s (substring s 1)))
13103 (remove-text-properties
13104 0 (length s)
13105 '(face nil mouse-face nil keymap nil fontified nil) s)
13106 ;; Make a series of regular expressions to find a match
13107 (setq words (org-split-string s "[ \n\r\t]+")
13108 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
13109 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
13110 "\\)" markers)
13111 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
13112 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
13113 re1 (concat pre re2 post)
13114 re3 (concat pre re4 post)
13115 re5 (concat pre ".*" re4)
13116 re2 (concat pre re2)
13117 re2a (concat pre re2a)
13118 re4 (concat pre re4)
13119 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
13120 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
13121 re5 "\\)"
13123 (cond
13124 ((eq type 'org-occur) (org-occur reall))
13125 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
13126 (t (goto-char (point-min))
13127 (if (or (org-search-not-self 1 re0 nil t)
13128 (org-search-not-self 1 re1 nil t)
13129 (org-search-not-self 1 re2 nil t)
13130 (org-search-not-self 1 re2a nil t)
13131 (org-search-not-self 1 re3 nil t)
13132 (org-search-not-self 1 re4 nil t)
13133 (org-search-not-self 1 re5 nil t)
13135 (goto-char (match-beginning 1))
13136 (goto-char pos)
13137 (error "No match")))))
13139 ;; Normal string-search
13140 (goto-char (point-min))
13141 (if (search-forward s nil t)
13142 (goto-char (match-beginning 0))
13143 (error "No match"))))
13144 (and (org-mode-p) (org-show-context 'link-search))))
13146 (defun org-search-not-self (group &rest args)
13147 "Execute `re-search-forward', but only accept matches that do not
13148 enclose the position of `org-open-link-marker'."
13149 (let ((m org-open-link-marker))
13150 (catch 'exit
13151 (while (apply 're-search-forward args)
13152 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
13153 (goto-char (match-end group))
13154 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
13155 (> (match-beginning 0) (marker-position m))
13156 (< (match-end 0) (marker-position m)))
13157 (save-match-data
13158 (or (not (org-in-regexp
13159 org-bracket-link-analytic-regexp 1))
13160 (not (match-end 4)) ; no description
13161 (and (<= (match-beginning 4) (point))
13162 (>= (match-end 4) (point))))))
13163 (throw 'exit (point))))))))
13165 (defun org-get-buffer-for-internal-link (buffer)
13166 "Return a buffer to be used for displaying the link target of internal links."
13167 (cond
13168 ((not org-display-internal-link-with-indirect-buffer)
13169 buffer)
13170 ((string-match "(Clone)$" (buffer-name buffer))
13171 (message "Buffer is already a clone, not making another one")
13172 ;; we also do not modify visibility in this case
13173 buffer)
13174 (t ; make a new indirect buffer for displaying the link
13175 (let* ((bn (buffer-name buffer))
13176 (ibn (concat bn "(Clone)"))
13177 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13178 (with-current-buffer ib (org-overview))
13179 ib))))
13181 (defun org-do-occur (regexp &optional cleanup)
13182 "Call the Emacs command `occur'.
13183 If CLEANUP is non-nil, remove the printout of the regular expression
13184 in the *Occur* buffer. This is useful if the regex is long and not useful
13185 to read."
13186 (occur regexp)
13187 (when cleanup
13188 (let ((cwin (selected-window)) win beg end)
13189 (when (setq win (get-buffer-window "*Occur*"))
13190 (select-window win))
13191 (goto-char (point-min))
13192 (when (re-search-forward "match[a-z]+" nil t)
13193 (setq beg (match-end 0))
13194 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13195 (setq end (1- (match-beginning 0)))))
13196 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13197 (goto-char (point-min))
13198 (select-window cwin))))
13200 ;;; The mark ring for links jumps
13202 (defvar org-mark-ring nil
13203 "Mark ring for positions before jumps in Org-mode.")
13204 (defvar org-mark-ring-last-goto nil
13205 "Last position in the mark ring used to go back.")
13206 ;; Fill and close the ring
13207 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13208 (loop for i from 1 to org-mark-ring-length do
13209 (push (make-marker) org-mark-ring))
13210 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13211 org-mark-ring)
13213 (defun org-mark-ring-push (&optional pos buffer)
13214 "Put the current position or POS into the mark ring and rotate it."
13215 (interactive)
13216 (setq pos (or pos (point)))
13217 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13218 (move-marker (car org-mark-ring)
13219 (or pos (point))
13220 (or buffer (current-buffer)))
13221 (message "%s"
13222 (substitute-command-keys
13223 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13225 (defun org-mark-ring-goto (&optional n)
13226 "Jump to the previous position in the mark ring.
13227 With prefix arg N, jump back that many stored positions. When
13228 called several times in succession, walk through the entire ring.
13229 Org-mode commands jumping to a different position in the current file,
13230 or to another Org-mode file, automatically push the old position
13231 onto the ring."
13232 (interactive "p")
13233 (let (p m)
13234 (if (eq last-command this-command)
13235 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13236 (setq p org-mark-ring))
13237 (setq org-mark-ring-last-goto p)
13238 (setq m (car p))
13239 (switch-to-buffer (marker-buffer m))
13240 (goto-char m)
13241 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13243 (defun org-remove-angle-brackets (s)
13244 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13245 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13247 (defun org-add-angle-brackets (s)
13248 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13249 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13252 ;;; Following specific links
13254 (defun org-follow-timestamp-link ()
13255 (cond
13256 ((org-at-date-range-p t)
13257 (let ((org-agenda-start-on-weekday)
13258 (t1 (match-string 1))
13259 (t2 (match-string 2)))
13260 (setq t1 (time-to-days (org-time-string-to-time t1))
13261 t2 (time-to-days (org-time-string-to-time t2)))
13262 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13263 ((org-at-timestamp-p t)
13264 (org-agenda-list nil (time-to-days (org-time-string-to-time
13265 (substring (match-string 1) 0 10)))
13267 (t (error "This should not happen"))))
13270 (defun org-follow-bbdb-link (name)
13271 "Follow a BBDB link to NAME."
13272 (require 'bbdb)
13273 (let ((inhibit-redisplay (not debug-on-error))
13274 (bbdb-electric-p nil))
13275 (catch 'exit
13276 ;; Exact match on name
13277 (bbdb-name (concat "\\`" name "\\'") nil)
13278 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13279 ;; Exact match on name
13280 (bbdb-company (concat "\\`" name "\\'") nil)
13281 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13282 ;; Partial match on name
13283 (bbdb-name name nil)
13284 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13285 ;; Partial match on company
13286 (bbdb-company name nil)
13287 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13288 ;; General match including network address and notes
13289 (bbdb name nil)
13290 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13291 (delete-window (get-buffer-window "*BBDB*"))
13292 (error "No matching BBDB record")))))
13294 (defun org-follow-info-link (name)
13295 "Follow an info file & node link to NAME."
13296 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13297 (string-match "\\(.*\\)" name))
13298 (progn
13299 (require 'info)
13300 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13301 (Info-find-node (match-string 1 name) (match-string 2 name))
13302 (Info-find-node (match-string 1 name) "Top")))
13303 (message "Could not open: %s" name)))
13305 (defun org-follow-gnus-link (&optional group article)
13306 "Follow a Gnus link to GROUP and ARTICLE."
13307 (require 'gnus)
13308 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13309 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13310 (cond ((and group article)
13311 (gnus-group-read-group 1 nil group)
13312 (gnus-summary-goto-article (string-to-number article) nil t))
13313 (group (gnus-group-jump-to-group group))))
13315 (defun org-follow-vm-link (&optional folder article readonly)
13316 "Follow a VM link to FOLDER and ARTICLE."
13317 (require 'vm)
13318 (setq article (org-add-angle-brackets article))
13319 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13320 ;; ange-ftp or efs or tramp access
13321 (let ((user (or (match-string 1 folder) (user-login-name)))
13322 (host (match-string 2 folder))
13323 (file (match-string 3 folder)))
13324 (cond
13325 ((featurep 'tramp)
13326 ;; use tramp to access the file
13327 (if (featurep 'xemacs)
13328 (setq folder (format "[%s@%s]%s" user host file))
13329 (setq folder (format "/%s@%s:%s" user host file))))
13331 ;; use ange-ftp or efs
13332 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13333 (setq folder (format "/%s@%s:%s" user host file))))))
13334 (when folder
13335 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13336 (sit-for 0.1)
13337 (when article
13338 (vm-select-folder-buffer)
13339 (widen)
13340 (let ((case-fold-search t))
13341 (goto-char (point-min))
13342 (if (not (re-search-forward
13343 (concat "^" "message-id: *" (regexp-quote article))))
13344 (error "Could not find the specified message in this folder"))
13345 (vm-isearch-update)
13346 (vm-isearch-narrow)
13347 (vm-beginning-of-message)
13348 (vm-summarize)))))
13350 (defun org-follow-wl-link (folder article)
13351 "Follow a Wanderlust link to FOLDER and ARTICLE."
13352 (if (and (string= folder "%")
13353 article
13354 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13355 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13356 ;; Thus, we recompose folder and article ids.
13357 (setq folder (format "%s#%s" folder (match-string 1 article))
13358 article (match-string 3 article)))
13359 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13360 (error "No such folder: %s" folder))
13361 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13362 (and article
13363 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13364 (wl-summary-redisplay)))
13366 (defun org-follow-rmail-link (folder article)
13367 "Follow an RMAIL link to FOLDER and ARTICLE."
13368 (setq article (org-add-angle-brackets article))
13369 (let (message-number)
13370 (save-excursion
13371 (save-window-excursion
13372 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13373 (setq message-number
13374 (save-restriction
13375 (widen)
13376 (goto-char (point-max))
13377 (if (re-search-backward
13378 (concat "^Message-ID:\\s-+" (regexp-quote
13379 (or article "")))
13380 nil t)
13381 (rmail-what-message))))))
13382 (if message-number
13383 (progn
13384 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13385 (rmail-show-message message-number)
13386 message-number)
13387 (error "Message not found"))))
13389 ;;; mh-e integration based on planner-mode
13390 (defun org-mhe-get-message-real-folder ()
13391 "Return the name of the current message real folder, so if you use
13392 sequences, it will now work."
13393 (save-excursion
13394 (let* ((folder
13395 (if (equal major-mode 'mh-folder-mode)
13396 mh-current-folder
13397 ;; Refer to the show buffer
13398 mh-show-folder-buffer))
13399 (end-index
13400 (if (boundp 'mh-index-folder)
13401 (min (length mh-index-folder) (length folder))))
13403 ;; a simple test on mh-index-data does not work, because
13404 ;; mh-index-data is always nil in a show buffer.
13405 (if (and (boundp 'mh-index-folder)
13406 (string= mh-index-folder (substring folder 0 end-index)))
13407 (if (equal major-mode 'mh-show-mode)
13408 (save-window-excursion
13409 (let (pop-up-frames)
13410 (when (buffer-live-p (get-buffer folder))
13411 (progn
13412 (pop-to-buffer folder)
13413 (org-mhe-get-message-folder-from-index)
13416 (org-mhe-get-message-folder-from-index)
13418 folder
13422 (defun org-mhe-get-message-folder-from-index ()
13423 "Returns the name of the message folder in a index folder buffer."
13424 (save-excursion
13425 (mh-index-previous-folder)
13426 (re-search-forward "^\\(+.*\\)$" nil t)
13427 (message "%s" (match-string 1))))
13429 (defun org-mhe-get-message-folder ()
13430 "Return the name of the current message folder. Be careful if you
13431 use sequences."
13432 (save-excursion
13433 (if (equal major-mode 'mh-folder-mode)
13434 mh-current-folder
13435 ;; Refer to the show buffer
13436 mh-show-folder-buffer)))
13438 (defun org-mhe-get-message-num ()
13439 "Return the number of the current message. Be careful if you
13440 use sequences."
13441 (save-excursion
13442 (if (equal major-mode 'mh-folder-mode)
13443 (mh-get-msg-num nil)
13444 ;; Refer to the show buffer
13445 (mh-show-buffer-message-number))))
13447 (defun org-mhe-get-header (header)
13448 "Return a header of the message in folder mode. This will create a
13449 show buffer for the corresponding message. If you have a more clever
13450 idea..."
13451 (let* ((folder (org-mhe-get-message-folder))
13452 (num (org-mhe-get-message-num))
13453 (buffer (get-buffer-create (concat "show-" folder)))
13454 (header-field))
13455 (with-current-buffer buffer
13456 (mh-display-msg num folder)
13457 (if (equal major-mode 'mh-folder-mode)
13458 (mh-header-display)
13459 (mh-show-header-display))
13460 (set-buffer buffer)
13461 (setq header-field (mh-get-header-field header))
13462 (if (equal major-mode 'mh-folder-mode)
13463 (mh-show)
13464 (mh-show-show))
13465 header-field)))
13467 (defun org-follow-mhe-link (folder article)
13468 "Follow an MHE link to FOLDER and ARTICLE.
13469 If ARTICLE is nil FOLDER is shown. If the configuration variable
13470 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13471 ARTICLE is searched in all folders. Indexed searches (swish++,
13472 namazu, and others supported by MH-E) will always search in all
13473 folders."
13474 (require 'mh-e)
13475 (require 'mh-search)
13476 (require 'mh-utils)
13477 (mh-find-path)
13478 (if (not article)
13479 (mh-visit-folder (mh-normalize-folder-name folder))
13480 (setq article (org-add-angle-brackets article))
13481 (mh-search-choose)
13482 (if (equal mh-searcher 'pick)
13483 (progn
13484 (mh-search folder (list "--message-id" article))
13485 (when (and org-mhe-search-all-folders
13486 (not (org-mhe-get-message-real-folder)))
13487 (kill-this-buffer)
13488 (mh-search "+" (list "--message-id" article))))
13489 (mh-search "+" article))
13490 (if (org-mhe-get-message-real-folder)
13491 (mh-show-msg 1)
13492 (kill-this-buffer)
13493 (error "Message not found"))))
13495 ;;; BibTeX links
13497 ;; Use the custom search meachnism to construct and use search strings for
13498 ;; file links to BibTeX database entries.
13500 (defun org-create-file-search-in-bibtex ()
13501 "Create the search string and description for a BibTeX database entry."
13502 (when (eq major-mode 'bibtex-mode)
13503 ;; yes, we want to construct this search string.
13504 ;; Make a good description for this entry, using names, year and the title
13505 ;; Put it into the `description' variable which is dynamically scoped.
13506 (let ((bibtex-autokey-names 1)
13507 (bibtex-autokey-names-stretch 1)
13508 (bibtex-autokey-name-case-convert-function 'identity)
13509 (bibtex-autokey-name-separator " & ")
13510 (bibtex-autokey-additional-names " et al.")
13511 (bibtex-autokey-year-length 4)
13512 (bibtex-autokey-name-year-separator " ")
13513 (bibtex-autokey-titlewords 3)
13514 (bibtex-autokey-titleword-separator " ")
13515 (bibtex-autokey-titleword-case-convert-function 'identity)
13516 (bibtex-autokey-titleword-length 'infty)
13517 (bibtex-autokey-year-title-separator ": "))
13518 (setq description (bibtex-generate-autokey)))
13519 ;; Now parse the entry, get the key and return it.
13520 (save-excursion
13521 (bibtex-beginning-of-entry)
13522 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13524 (defun org-execute-file-search-in-bibtex (s)
13525 "Find the link search string S as a key for a database entry."
13526 (when (eq major-mode 'bibtex-mode)
13527 ;; Yes, we want to do the search in this file.
13528 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13529 (goto-char (point-min))
13530 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13531 (regexp-quote s) "[ \t\n]*,") nil t)
13532 (goto-char (match-beginning 0)))
13533 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13534 ;; Use double prefix to indicate that any web link should be browsed
13535 (let ((b (current-buffer)) (p (point)))
13536 ;; Restore the window configuration because we just use the web link
13537 (set-window-configuration org-window-config-before-follow-link)
13538 (save-excursion (set-buffer b) (goto-char p)
13539 (bibtex-url)))
13540 (recenter 0)) ; Move entry start to beginning of window
13541 ;; return t to indicate that the search is done.
13544 ;; Finally add the functions to the right hooks.
13545 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13546 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13548 ;; end of Bibtex link setup
13550 ;;; Following file links
13552 (defun org-open-file (path &optional in-emacs line search)
13553 "Open the file at PATH.
13554 First, this expands any special file name abbreviations. Then the
13555 configuration variable `org-file-apps' is checked if it contains an
13556 entry for this file type, and if yes, the corresponding command is launched.
13557 If no application is found, Emacs simply visits the file.
13558 With optional argument IN-EMACS, Emacs will visit the file.
13559 Optional LINE specifies a line to go to, optional SEARCH a string to
13560 search for. If LINE or SEARCH is given, the file will always be
13561 opened in Emacs.
13562 If the file does not exist, an error is thrown."
13563 (setq in-emacs (or in-emacs line search))
13564 (let* ((file (if (equal path "")
13565 buffer-file-name
13566 (substitute-in-file-name (expand-file-name path))))
13567 (apps (append org-file-apps (org-default-apps)))
13568 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13569 (dirp (if remp nil (file-directory-p file)))
13570 (dfile (downcase file))
13571 (old-buffer (current-buffer))
13572 (old-pos (point))
13573 (old-mode major-mode)
13574 ext cmd)
13575 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13576 (setq ext (match-string 1 dfile))
13577 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13578 (setq ext (match-string 1 dfile))))
13579 (if in-emacs
13580 (setq cmd 'emacs)
13581 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13582 (and dirp (cdr (assoc 'directory apps)))
13583 (cdr (assoc ext apps))
13584 (cdr (assoc t apps)))))
13585 (when (eq cmd 'mailcap)
13586 (require 'mailcap)
13587 (mailcap-parse-mailcaps)
13588 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13589 (command (mailcap-mime-info mime-type)))
13590 (if (stringp command)
13591 (setq cmd command)
13592 (setq cmd 'emacs))))
13593 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13594 (not (file-exists-p file))
13595 (not org-open-non-existing-files))
13596 (error "No such file: %s" file))
13597 (cond
13598 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13599 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13600 (while (string-match "['\"]%s['\"]" cmd)
13601 (setq cmd (replace-match "%s" t t cmd)))
13602 (while (string-match "%s" cmd)
13603 (setq cmd (replace-match
13604 (save-match-data (shell-quote-argument file))
13605 t t cmd)))
13606 (save-window-excursion
13607 (start-process-shell-command cmd nil cmd)))
13608 ((or (stringp cmd)
13609 (eq cmd 'emacs))
13610 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13611 (widen)
13612 (if line (goto-line line)
13613 (if search (org-link-search search))))
13614 ((consp cmd)
13615 (eval cmd))
13616 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13617 (and (org-mode-p) (eq old-mode 'org-mode)
13618 (or (not (equal old-buffer (current-buffer)))
13619 (not (equal old-pos (point))))
13620 (org-mark-ring-push old-pos old-buffer))))
13622 (defun org-default-apps ()
13623 "Return the default applications for this operating system."
13624 (cond
13625 ((eq system-type 'darwin)
13626 org-file-apps-defaults-macosx)
13627 ((eq system-type 'windows-nt)
13628 org-file-apps-defaults-windowsnt)
13629 (t org-file-apps-defaults-gnu)))
13631 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13632 (defun org-file-remote-p (file)
13633 "Test whether FILE specifies a location on a remote system.
13634 Return non-nil if the location is indeed remote.
13636 For example, the filename \"/user@host:/foo\" specifies a location
13637 on the system \"/user@host:\"."
13638 (cond ((fboundp 'file-remote-p)
13639 (file-remote-p file))
13640 ((fboundp 'tramp-handle-file-remote-p)
13641 (tramp-handle-file-remote-p file))
13642 ((and (boundp 'ange-ftp-name-format)
13643 (string-match (car ange-ftp-name-format) file))
13645 (t nil)))
13648 ;;;; Hooks for remember.el, and refiling
13650 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13651 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13653 ;;;###autoload
13654 (defun org-remember-insinuate ()
13655 "Setup remember.el for use wiht Org-mode."
13656 (require 'remember)
13657 (setq remember-annotation-functions '(org-remember-annotation))
13658 (setq remember-handler-functions '(org-remember-handler))
13659 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13661 ;;;###autoload
13662 (defun org-remember-annotation ()
13663 "Return a link to the current location as an annotation for remember.el.
13664 If you are using Org-mode files as target for data storage with
13665 remember.el, then the annotations should include a link compatible with the
13666 conventions in Org-mode. This function returns such a link."
13667 (org-store-link nil))
13669 (defconst org-remember-help
13670 "Select a destination location for the note.
13671 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13672 RET on headline -> Store as sublevel entry to current headline
13673 RET at beg-of-buf -> Append to file as level 2 headline
13674 <left>/<right> -> before/after current headline, same headings level")
13676 (defvar org-remember-previous-location nil)
13677 (defvar org-force-remember-template-char) ;; dynamically scoped
13679 ;; Save the major mode of the buffer we called remember from
13680 (defvar org-select-template-temp-major-mode nil)
13682 ;; Temporary store the buffer where remember was called from
13683 (defvar org-select-template-original-buffer nil)
13685 (defun org-select-remember-template (&optional use-char)
13686 (when org-remember-templates
13687 (let* ((pre-selected-templates
13688 (mapcar
13689 (lambda (tpl)
13690 (let ((ctxt (nth 5 tpl))
13691 (mode org-select-template-temp-major-mode)
13692 (buf org-select-template-original-buffer))
13693 (if (or (and (functionp ctxt)
13694 (save-excursion
13695 (set-buffer buf)
13696 ;; Protect the user-defined function from error
13697 (condition-case nil (funcall ctxt) (error nil))))
13698 (and ctxt (listp ctxt)
13699 (delq nil (mapcar (lambda(x) (eq mode x)) ctxt))))
13700 tpl)))
13701 org-remember-templates))
13702 ;; If no template at this point, add the default templates:
13703 (pre-selected-templates1
13704 (if (not (delq nil pre-selected-templates))
13705 (mapcar (lambda(x) (if (not (nth 5 x)) x))
13706 org-remember-templates)
13707 pre-selected-templates))
13708 ;; Then unconditionnally add template for any contexts
13709 (pre-selected-templates2
13710 (append (mapcar (lambda(x) (if (eq (nth 5 x) t) x))
13711 org-remember-templates)
13712 (delq nil pre-selected-templates1)))
13713 (templates (mapcar (lambda (x)
13714 (if (stringp (car x))
13715 (append (list (nth 1 x) (car x)) (cddr x))
13716 (append (list (car x) "") (cdr x))))
13717 (delq nil pre-selected-templates2)))
13718 (char (or use-char
13719 (cond
13720 ((= (length templates) 1)
13721 (caar templates))
13722 ((and (boundp 'org-force-remember-template-char)
13723 org-force-remember-template-char)
13724 (if (stringp org-force-remember-template-char)
13725 (string-to-char org-force-remember-template-char)
13726 org-force-remember-template-char))
13728 (message "Select template: %s"
13729 (mapconcat
13730 (lambda (x)
13731 (cond
13732 ((not (string-match "\\S-" (nth 1 x)))
13733 (format "[%c]" (car x)))
13734 ((equal (downcase (car x))
13735 (downcase (aref (nth 1 x) 0)))
13736 (format "[%c]%s" (car x)
13737 (substring (nth 1 x) 1)))
13738 (t (format "[%c]%s" (car x) (nth 1 x)))))
13739 templates " "))
13740 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13741 (when (equal char0 ?\C-g)
13742 (jump-to-register remember-register)
13743 (kill-buffer remember-buffer))
13744 char0))))))
13745 (cddr (assoc char templates)))))
13747 (defvar x-last-selected-text)
13748 (defvar x-last-selected-text-primary)
13750 ;;;###autoload
13751 (defun org-remember-apply-template (&optional use-char skip-interactive)
13752 "Initialize *remember* buffer with template, invoke `org-mode'.
13753 This function should be placed into `remember-mode-hook' and in fact requires
13754 to be run from that hook to function properly."
13755 (if org-remember-templates
13756 (let* ((entry (org-select-remember-template use-char))
13757 (tpl (car entry))
13758 (plist-p (if org-store-link-plist t nil))
13759 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13760 (string-match "\\S-" (nth 1 entry)))
13761 (nth 1 entry)
13762 org-default-notes-file))
13763 (headline (nth 2 entry))
13764 (v-c (or (and (eq window-system 'x)
13765 (fboundp 'x-cut-buffer-or-selection-value)
13766 (x-cut-buffer-or-selection-value))
13767 (org-bound-and-true-p x-last-selected-text)
13768 (org-bound-and-true-p x-last-selected-text-primary)
13769 (and (> (length kill-ring) 0) (current-kill 0))))
13770 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13771 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13772 (v-u (concat "[" (substring v-t 1 -1) "]"))
13773 (v-U (concat "[" (substring v-T 1 -1) "]"))
13774 ;; `initial' and `annotation' are bound in `remember'
13775 (v-i (if (boundp 'initial) initial))
13776 (v-a (if (and (boundp 'annotation) annotation)
13777 (if (equal annotation "[[]]") "" annotation)
13778 ""))
13779 (v-A (if (and v-a
13780 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13781 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13782 v-a))
13783 (v-n user-full-name)
13784 (org-startup-folded nil)
13785 org-time-was-given org-end-time-was-given x
13786 prompt completions char time pos default histvar)
13787 (setq org-store-link-plist
13788 (append (list :annotation v-a :initial v-i)
13789 org-store-link-plist))
13790 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13791 (erase-buffer)
13792 (insert (substitute-command-keys
13793 (format
13794 "## Filing location: Select interactively, default, or last used:
13795 ## %s to select file and header location interactively.
13796 ## %s \"%s\" -> \"* %s\"
13797 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13798 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13799 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13800 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13801 (abbreviate-file-name (or file org-default-notes-file))
13802 (or headline "")
13803 (or (car org-remember-previous-location) "???")
13804 (or (cdr org-remember-previous-location) "???"))))
13805 (insert tpl) (goto-char (point-min))
13806 ;; Simple %-escapes
13807 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13808 (when (and initial (equal (match-string 0) "%i"))
13809 (save-match-data
13810 (let* ((lead (buffer-substring
13811 (point-at-bol) (match-beginning 0))))
13812 (setq v-i (mapconcat 'identity
13813 (org-split-string initial "\n")
13814 (concat "\n" lead))))))
13815 (replace-match
13816 (or (eval (intern (concat "v-" (match-string 1)))) "")
13817 t t))
13819 ;; %[] Insert contents of a file.
13820 (goto-char (point-min))
13821 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13822 (let ((start (match-beginning 0))
13823 (end (match-end 0))
13824 (filename (expand-file-name (match-string 1))))
13825 (goto-char start)
13826 (delete-region start end)
13827 (condition-case error
13828 (insert-file-contents filename)
13829 (error (insert (format "%%![Couldn't insert %s: %s]"
13830 filename error))))))
13831 ;; %() embedded elisp
13832 (goto-char (point-min))
13833 (while (re-search-forward "%\\((.+)\\)" nil t)
13834 (goto-char (match-beginning 0))
13835 (let ((template-start (point)))
13836 (forward-char 1)
13837 (let ((result
13838 (condition-case error
13839 (eval (read (current-buffer)))
13840 (error (format "%%![Error: %s]" error)))))
13841 (delete-region template-start (point))
13842 (insert result))))
13844 ;; From the property list
13845 (when plist-p
13846 (goto-char (point-min))
13847 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13848 (and (setq x (or (plist-get org-store-link-plist
13849 (intern (match-string 1))) ""))
13850 (replace-match x t t))))
13852 ;; Turn on org-mode in the remember buffer, set local variables
13853 (org-mode)
13854 (org-set-local 'org-finish-function 'org-remember-finalize)
13855 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13856 (org-set-local 'org-default-notes-file file))
13857 (if (and headline (stringp headline) (string-match "\\S-" headline))
13858 (org-set-local 'org-remember-default-headline headline))
13859 ;; Interactive template entries
13860 (goto-char (point-min))
13861 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13862 (setq char (if (match-end 3) (match-string 3))
13863 prompt (if (match-end 2) (match-string 2)))
13864 (goto-char (match-beginning 0))
13865 (replace-match "")
13866 (setq completions nil default nil)
13867 (when prompt
13868 (setq completions (org-split-string prompt "|")
13869 prompt (pop completions)
13870 default (car completions)
13871 histvar (intern (concat
13872 "org-remember-template-prompt-history::"
13873 (or prompt "")))
13874 completions (mapcar 'list completions)))
13875 (cond
13876 ((member char '("G" "g"))
13877 (let* ((org-last-tags-completion-table
13878 (org-global-tags-completion-table
13879 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13880 (org-add-colon-after-tag-completion t)
13881 (ins (completing-read
13882 (if prompt (concat prompt ": ") "Tags: ")
13883 'org-tags-completion-function nil nil nil
13884 'org-tags-history)))
13885 (setq ins (mapconcat 'identity
13886 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13887 ":"))
13888 (when (string-match "\\S-" ins)
13889 (or (equal (char-before) ?:) (insert ":"))
13890 (insert ins)
13891 (or (equal (char-after) ?:) (insert ":")))))
13892 (char
13893 (setq org-time-was-given (equal (upcase char) char))
13894 (setq time (org-read-date (equal (upcase char) "U") t nil
13895 prompt))
13896 (org-insert-time-stamp time org-time-was-given
13897 (member char '("u" "U"))
13898 nil nil (list org-end-time-was-given)))
13900 (insert (org-completing-read
13901 (concat (if prompt prompt "Enter string")
13902 (if default (concat " [" default "]"))
13903 ": ")
13904 completions nil nil nil histvar default)))))
13905 (goto-char (point-min))
13906 (if (re-search-forward "%\\?" nil t)
13907 (replace-match "")
13908 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13909 (org-mode)
13910 (org-set-local 'org-finish-function 'org-remember-finalize))
13911 (when (save-excursion
13912 (goto-char (point-min))
13913 (re-search-forward "%!" nil t))
13914 (replace-match "")
13915 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13917 (defun org-remember-finish-immediately ()
13918 "File remember note immediately.
13919 This should be run in `post-command-hook' and will remove itself
13920 from that hook."
13921 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13922 (when org-finish-function
13923 (funcall org-finish-function)))
13925 (defvar org-clock-marker) ; Defined below
13926 (defun org-remember-finalize ()
13927 "Finalize the remember process."
13928 (unless (fboundp 'remember-finalize)
13929 (defalias 'remember-finalize 'remember-buffer))
13930 (when (and org-clock-marker
13931 (equal (marker-buffer org-clock-marker) (current-buffer)))
13932 ;; FIXME: test this, this is w/o notetaking!
13933 (let (org-log-note-clock-out) (org-clock-out)))
13934 (when buffer-file-name
13935 (save-buffer)
13936 (setq buffer-file-name nil))
13937 (remember-finalize))
13939 ;;;###autoload
13940 (defun org-remember (&optional goto org-force-remember-template-char)
13941 "Call `remember'. If this is already a remember buffer, re-apply template.
13942 If there is an active region, make sure remember uses it as initial content
13943 of the remember buffer.
13945 When called interactively with a `C-u' prefix argument GOTO, don't remember
13946 anything, just go to the file/headline where the selected template usually
13947 stores its notes. With a double prefix arg `C-u C-u', go to the last
13948 note stored by remember.
13950 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13951 associated with a template in `org-remember-templates'."
13952 (interactive "P")
13953 (cond
13954 ((equal goto '(4)) (org-go-to-remember-target))
13955 ((equal goto '(16)) (org-remember-goto-last-stored))
13957 ;; set temporary variables that will be needed in
13958 ;; `org-select-remember-template'
13959 (setq org-select-template-temp-major-mode major-mode)
13960 (setq org-select-template-original-buffer (current-buffer))
13961 (if (memq org-finish-function '(remember-buffer remember-finalize))
13962 (progn
13963 (when (< (length org-remember-templates) 2)
13964 (error "No other template available"))
13965 (erase-buffer)
13966 (let ((annotation (plist-get org-store-link-plist :annotation))
13967 (initial (plist-get org-store-link-plist :initial)))
13968 (org-remember-apply-template))
13969 (message "Press C-c C-c to remember data"))
13970 (if (org-region-active-p)
13971 (remember (buffer-substring (point) (mark)))
13972 (call-interactively 'remember))))))
13974 (defun org-remember-goto-last-stored ()
13975 "Go to the location where the last remember note was stored."
13976 (interactive)
13977 (bookmark-jump "org-remember-last-stored")
13978 (message "This is the last note stored by remember"))
13980 (defun org-go-to-remember-target (&optional template-key)
13981 "Go to the target location of a remember template.
13982 The user is queried for the template."
13983 (interactive)
13984 (let* (org-select-template-temp-major-mode
13985 (entry (org-select-remember-template template-key))
13986 (file (nth 1 entry))
13987 (heading (nth 2 entry))
13988 visiting)
13989 (unless (and file (stringp file) (string-match "\\S-" file))
13990 (setq file org-default-notes-file))
13991 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13992 (setq heading org-remember-default-headline))
13993 (setq visiting (org-find-base-buffer-visiting file))
13994 (if (not visiting) (find-file-noselect file))
13995 (switch-to-buffer (or visiting (get-file-buffer file)))
13996 (widen)
13997 (goto-char (point-min))
13998 (if (re-search-forward
13999 (concat "^\\*+[ \t]+" (regexp-quote heading)
14000 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
14001 nil t)
14002 (goto-char (match-beginning 0))
14003 (error "Target headline not found: %s" heading))))
14005 (defvar org-note-abort nil) ; dynamically scoped
14007 ;;;###autoload
14008 (defun org-remember-handler ()
14009 "Store stuff from remember.el into an org file.
14010 First prompts for an org file. If the user just presses return, the value
14011 of `org-default-notes-file' is used.
14012 Then the command offers the headings tree of the selected file in order to
14013 file the text at a specific location.
14014 You can either immediately press RET to get the note appended to the
14015 file, or you can use vertical cursor motion and visibility cycling (TAB) to
14016 find a better place. Then press RET or <left> or <right> in insert the note.
14018 Key Cursor position Note gets inserted
14019 -----------------------------------------------------------------------------
14020 RET buffer-start as level 1 heading at end of file
14021 RET on headline as sublevel of the heading at cursor
14022 RET no heading at cursor position, level taken from context.
14023 Or use prefix arg to specify level manually.
14024 <left> on headline as same level, before current heading
14025 <right> on headline as same level, after current heading
14027 So the fastest way to store the note is to press RET RET to append it to
14028 the default file. This way your current train of thought is not
14029 interrupted, in accordance with the principles of remember.el.
14030 You can also get the fast execution without prompting by using
14031 C-u C-c C-c to exit the remember buffer. See also the variable
14032 `org-remember-store-without-prompt'.
14034 Before being stored away, the function ensures that the text has a
14035 headline, i.e. a first line that starts with a \"*\". If not, a headline
14036 is constructed from the current date and some additional data.
14038 If the variable `org-adapt-indentation' is non-nil, the entire text is
14039 also indented so that it starts in the same column as the headline
14040 \(i.e. after the stars).
14042 See also the variable `org-reverse-note-order'."
14043 (goto-char (point-min))
14044 (while (looking-at "^[ \t]*\n\\|^##.*\n")
14045 (replace-match ""))
14046 (goto-char (point-max))
14047 (beginning-of-line 1)
14048 (while (looking-at "[ \t]*$\\|##.*")
14049 (delete-region (1- (point)) (point-max))
14050 (beginning-of-line 1))
14051 (catch 'quit
14052 (if org-note-abort (throw 'quit nil))
14053 (let* ((txt (buffer-substring (point-min) (point-max)))
14054 (fastp (org-xor (equal current-prefix-arg '(4))
14055 org-remember-store-without-prompt))
14056 (file (cond
14057 (fastp org-default-notes-file)
14058 ((and (eq org-remember-interactive-interface 'refile)
14059 org-refile-targets)
14060 org-default-notes-file)
14061 ((not (and (equal current-prefix-arg '(16))
14062 org-remember-previous-location))
14063 (org-get-org-file))))
14064 (heading org-remember-default-headline)
14065 (visiting (and file (org-find-base-buffer-visiting file)))
14066 (org-startup-folded nil)
14067 (org-startup-align-all-tables nil)
14068 (org-goto-start-pos 1)
14069 spos exitcmd level indent reversed)
14070 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
14071 (setq file (car org-remember-previous-location)
14072 heading (cdr org-remember-previous-location)
14073 fastp t))
14074 (setq current-prefix-arg nil)
14075 (if (string-match "[ \t\n]+\\'" txt)
14076 (setq txt (replace-match "" t t txt)))
14077 ;; Modify text so that it becomes a nice subtree which can be inserted
14078 ;; into an org tree.
14079 (let* ((lines (split-string txt "\n"))
14080 first)
14081 (setq first (car lines) lines (cdr lines))
14082 (if (string-match "^\\*+ " first)
14083 ;; Is already a headline
14084 (setq indent nil)
14085 ;; We need to add a headline: Use time and first buffer line
14086 (setq lines (cons first lines)
14087 first (concat "* " (current-time-string)
14088 " (" (remember-buffer-desc) ")")
14089 indent " "))
14090 (if (and org-adapt-indentation indent)
14091 (setq lines (mapcar
14092 (lambda (x)
14093 (if (string-match "\\S-" x)
14094 (concat indent x) x))
14095 lines)))
14096 (setq txt (concat first "\n"
14097 (mapconcat 'identity lines "\n"))))
14098 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
14099 (setq txt (replace-match "\n\n" t t txt))
14100 (if (string-match "[ \t\n]*\\'" txt)
14101 (setq txt (replace-match "\n" t t txt))))
14102 ;; Put the modified text back into the remember buffer, for refile.
14103 (erase-buffer)
14104 (insert txt)
14105 (goto-char (point-min))
14106 (when (and (eq org-remember-interactive-interface 'refile)
14107 (not fastp))
14108 (org-refile nil (or visiting (find-file-noselect file)))
14109 (throw 'quit t))
14110 ;; Find the file
14111 (if (not visiting) (find-file-noselect file))
14112 (with-current-buffer (or visiting (get-file-buffer file))
14113 (unless (org-mode-p)
14114 (error "Target files for remember notes must be in Org-mode"))
14115 (save-excursion
14116 (save-restriction
14117 (widen)
14118 (and (goto-char (point-min))
14119 (not (re-search-forward "^\\* " nil t))
14120 (insert "\n* " (or heading "Notes") "\n"))
14121 (setq reversed (org-notes-order-reversed-p))
14123 ;; Find the default location
14124 (when (and heading (stringp heading) (string-match "\\S-" heading))
14125 (goto-char (point-min))
14126 (if (re-search-forward
14127 (concat "^\\*+[ \t]+" (regexp-quote heading)
14128 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
14129 nil t)
14130 (setq org-goto-start-pos (match-beginning 0))
14131 (when fastp
14132 (goto-char (point-max))
14133 (unless (bolp) (newline))
14134 (insert "* " heading "\n")
14135 (setq org-goto-start-pos (point-at-bol 0)))))
14137 ;; Ask the User for a location, using the appropriate interface
14138 (cond
14139 (fastp (setq spos org-goto-start-pos
14140 exitcmd 'return))
14141 ((eq org-remember-interactive-interface 'outline)
14142 (setq spos (org-get-location (current-buffer)
14143 org-remember-help)
14144 exitcmd (cdr spos)
14145 spos (car spos)))
14146 ((eq org-remember-interactive-interface 'outline-path-completion)
14147 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
14148 (org-refile-use-outline-path t))
14149 (setq spos (org-refile-get-location "Heading: ")
14150 exitcmd 'return
14151 spos (nth 3 spos))))
14152 (t (error "this should not hapen")))
14153 (if (not spos) (throw 'quit nil)) ; return nil to show we did
14154 ; not handle this note
14155 (goto-char spos)
14156 (cond ((org-on-heading-p t)
14157 (org-back-to-heading t)
14158 (setq level (funcall outline-level))
14159 (cond
14160 ((eq exitcmd 'return)
14161 ;; sublevel of current
14162 (setq org-remember-previous-location
14163 (cons (abbreviate-file-name file)
14164 (org-get-heading 'notags)))
14165 (if reversed
14166 (outline-next-heading)
14167 (org-end-of-subtree t)
14168 (if (not (bolp))
14169 (if (looking-at "[ \t]*\n")
14170 (beginning-of-line 2)
14171 (end-of-line 1)
14172 (insert "\n"))))
14173 (bookmark-set "org-remember-last-stored")
14174 (org-paste-subtree (org-get-valid-level level 1) txt))
14175 ((eq exitcmd 'left)
14176 ;; before current
14177 (bookmark-set "org-remember-last-stored")
14178 (org-paste-subtree level txt))
14179 ((eq exitcmd 'right)
14180 ;; after current
14181 (org-end-of-subtree t)
14182 (bookmark-set "org-remember-last-stored")
14183 (org-paste-subtree level txt))
14184 (t (error "This should not happen"))))
14186 ((and (bobp) (not reversed))
14187 ;; Put it at the end, one level below level 1
14188 (save-restriction
14189 (widen)
14190 (goto-char (point-max))
14191 (if (not (bolp)) (newline))
14192 (bookmark-set "org-remember-last-stored")
14193 (org-paste-subtree (org-get-valid-level 1 1) txt)))
14195 ((and (bobp) reversed)
14196 ;; Put it at the start, as level 1
14197 (save-restriction
14198 (widen)
14199 (goto-char (point-min))
14200 (re-search-forward "^\\*+ " nil t)
14201 (beginning-of-line 1)
14202 (bookmark-set "org-remember-last-stored")
14203 (org-paste-subtree 1 txt)))
14205 ;; Put it right there, with automatic level determined by
14206 ;; org-paste-subtree or from prefix arg
14207 (bookmark-set "org-remember-last-stored")
14208 (org-paste-subtree
14209 (if (numberp current-prefix-arg) current-prefix-arg)
14210 txt)))
14211 (when remember-save-after-remembering
14212 (save-buffer)
14213 (if (not visiting) (kill-buffer (current-buffer)))))))))
14215 t) ;; return t to indicate that we took care of this note.
14217 (defun org-get-org-file ()
14218 "Read a filename, with default directory `org-directory'."
14219 (let ((default (or org-default-notes-file remember-data-file)))
14220 (read-file-name (format "File name [%s]: " default)
14221 (file-name-as-directory org-directory)
14222 default)))
14224 (defun org-notes-order-reversed-p ()
14225 "Check if the current file should receive notes in reversed order."
14226 (cond
14227 ((not org-reverse-note-order) nil)
14228 ((eq t org-reverse-note-order) t)
14229 ((not (listp org-reverse-note-order)) nil)
14230 (t (catch 'exit
14231 (let ((all org-reverse-note-order)
14232 entry)
14233 (while (setq entry (pop all))
14234 (if (string-match (car entry) buffer-file-name)
14235 (throw 'exit (cdr entry))))
14236 nil)))))
14238 ;;; Refiling
14240 (defvar org-refile-target-table nil
14241 "The list of refile targets, created by `org-refile'.")
14243 (defvar org-agenda-new-buffers nil
14244 "Buffers created to visit agenda files.")
14246 (defun org-get-refile-targets (&optional default-buffer)
14247 "Produce a table with refile targets."
14248 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
14249 targets txt re files f desc descre)
14250 (with-current-buffer (or default-buffer (current-buffer))
14251 (while (setq entry (pop entries))
14252 (setq files (car entry) desc (cdr entry))
14253 (cond
14254 ((null files) (setq files (list (current-buffer))))
14255 ((eq files 'org-agenda-files)
14256 (setq files (org-agenda-files 'unrestricted)))
14257 ((and (symbolp files) (fboundp files))
14258 (setq files (funcall files)))
14259 ((and (symbolp files) (boundp files))
14260 (setq files (symbol-value files))))
14261 (if (stringp files) (setq files (list files)))
14262 (cond
14263 ((eq (car desc) :tag)
14264 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
14265 ((eq (car desc) :todo)
14266 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
14267 ((eq (car desc) :regexp)
14268 (setq descre (cdr desc)))
14269 ((eq (car desc) :level)
14270 (setq descre (concat "^\\*\\{" (number-to-string
14271 (if org-odd-levels-only
14272 (1- (* 2 (cdr desc)))
14273 (cdr desc)))
14274 "\\}[ \t]")))
14275 ((eq (car desc) :maxlevel)
14276 (setq descre (concat "^\\*\\{1," (number-to-string
14277 (if org-odd-levels-only
14278 (1- (* 2 (cdr desc)))
14279 (cdr desc)))
14280 "\\}[ \t]")))
14281 (t (error "Bad refiling target description %s" desc)))
14282 (while (setq f (pop files))
14283 (save-excursion
14284 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
14285 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
14286 (save-excursion
14287 (save-restriction
14288 (widen)
14289 (goto-char (point-min))
14290 (while (re-search-forward descre nil t)
14291 (goto-char (point-at-bol))
14292 (when (looking-at org-complex-heading-regexp)
14293 (setq txt (match-string 4)
14294 re (concat "^" (regexp-quote
14295 (buffer-substring (match-beginning 1)
14296 (match-end 4)))))
14297 (if (match-end 5) (setq re (concat re "[ \t]+"
14298 (regexp-quote
14299 (match-string 5)))))
14300 (setq re (concat re "[ \t]*$"))
14301 (when org-refile-use-outline-path
14302 (setq txt (mapconcat 'identity
14303 (append
14304 (if (eq org-refile-use-outline-path 'file)
14305 (list (file-name-nondirectory
14306 (buffer-file-name (buffer-base-buffer))))
14307 (if (eq org-refile-use-outline-path 'full-file-path)
14308 (list (buffer-file-name (buffer-base-buffer)))))
14309 (org-get-outline-path)
14310 (list txt))
14311 "/")))
14312 (push (list txt f re (point)) targets))
14313 (goto-char (point-at-eol))))))))
14314 (nreverse targets))))
14316 (defun org-get-outline-path ()
14317 "Return the outline path to the current entry, as a list."
14318 (let (rtn)
14319 (save-excursion
14320 (while (org-up-heading-safe)
14321 (when (looking-at org-complex-heading-regexp)
14322 (push (org-match-string-no-properties 4) rtn)))
14323 rtn)))
14325 (defvar org-refile-history nil
14326 "History for refiling operations.")
14328 (defun org-refile (&optional goto default-buffer)
14329 "Move the entry at point to another heading.
14330 The list of target headings is compiled using the information in
14331 `org-refile-targets', which see. This list is created upon first use, and
14332 you can update it by calling this command with a double prefix (`C-u C-u').
14333 FIXME: Can we find a better way of updating?
14335 At the target location, the entry is filed as a subitem of the target heading.
14336 Depending on `org-reverse-note-order', the new subitem will either be the
14337 first of the last subitem.
14339 With prefix arg GOTO, the command will only visit the target location,
14340 not actually move anything.
14341 With a double prefix `C-c C-c', go to the location where the last refiling
14342 operation has put the subtree.
14344 With a double prefix argument, the command can be used to jump to any
14345 heading in the current buffer."
14346 (interactive "P")
14347 (let* ((cbuf (current-buffer))
14348 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14349 pos it nbuf file re level reversed)
14350 (if (equal goto '(16))
14351 (org-refile-goto-last-stored)
14352 (when (setq it (org-refile-get-location
14353 (if goto "Goto: " "Refile to: ") default-buffer))
14354 (setq file (nth 1 it)
14355 re (nth 2 it)
14356 pos (nth 3 it))
14357 (setq nbuf (or (find-buffer-visiting file)
14358 (find-file-noselect file)))
14359 (if goto
14360 (progn
14361 (switch-to-buffer nbuf)
14362 (goto-char pos)
14363 (org-show-context 'org-goto))
14364 (org-copy-special)
14365 (save-excursion
14366 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14367 (find-file-noselect file))))
14368 (setq reversed (org-notes-order-reversed-p))
14369 (save-excursion
14370 (save-restriction
14371 (widen)
14372 (goto-char pos)
14373 (looking-at outline-regexp)
14374 (setq level (org-get-valid-level (funcall outline-level) 1))
14375 (goto-char
14376 (if reversed
14377 (outline-next-heading)
14378 (or (save-excursion (outline-get-next-sibling))
14379 (org-end-of-subtree t t)
14380 (point-max))))
14381 (bookmark-set "org-refile-last-stored")
14382 (org-paste-subtree level))))
14383 (org-cut-special)
14384 (message "Entry refiled to \"%s\"" (car it)))))))
14386 (defun org-refile-goto-last-stored ()
14387 "Go to the location where the last refile was stored."
14388 (interactive)
14389 (bookmark-jump "org-refile-last-stored")
14390 (message "This is the location of the last refile"))
14392 (defun org-refile-get-location (&optional prompt default-buffer)
14393 "Prompt the user for a refile location, using PROMPT."
14394 (let ((org-refile-targets org-refile-targets)
14395 (org-refile-use-outline-path org-refile-use-outline-path))
14396 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14397 (unless org-refile-target-table
14398 (error "No refile targets"))
14399 (let* ((cbuf (current-buffer))
14400 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14401 (fname (and filename (file-truename filename)))
14402 (tbl (mapcar
14403 (lambda (x)
14404 (if (not (equal fname (file-truename (nth 1 x))))
14405 (cons (concat (car x) " (" (file-name-nondirectory
14406 (nth 1 x)) ")")
14407 (cdr x))
14409 org-refile-target-table))
14410 (completion-ignore-case t))
14411 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14412 tbl)))
14414 ;;;; Dynamic blocks
14416 (defun org-find-dblock (name)
14417 "Find the first dynamic block with name NAME in the buffer.
14418 If not found, stay at current position and return nil."
14419 (let (pos)
14420 (save-excursion
14421 (goto-char (point-min))
14422 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14423 nil t)
14424 (match-beginning 0))))
14425 (if pos (goto-char pos))
14426 pos))
14428 (defconst org-dblock-start-re
14429 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14430 "Matches the startline of a dynamic block, with parameters.")
14432 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14433 "Matches the end of a dyhamic block.")
14435 (defun org-create-dblock (plist)
14436 "Create a dynamic block section, with parameters taken from PLIST.
14437 PLIST must containe a :name entry which is used as name of the block."
14438 (unless (bolp) (newline))
14439 (let ((name (plist-get plist :name)))
14440 (insert "#+BEGIN: " name)
14441 (while plist
14442 (if (eq (car plist) :name)
14443 (setq plist (cddr plist))
14444 (insert " " (prin1-to-string (pop plist)))))
14445 (insert "\n\n#+END:\n")
14446 (beginning-of-line -2)))
14448 (defun org-prepare-dblock ()
14449 "Prepare dynamic block for refresh.
14450 This empties the block, puts the cursor at the insert position and returns
14451 the property list including an extra property :name with the block name."
14452 (unless (looking-at org-dblock-start-re)
14453 (error "Not at a dynamic block"))
14454 (let* ((begdel (1+ (match-end 0)))
14455 (name (org-no-properties (match-string 1)))
14456 (params (append (list :name name)
14457 (read (concat "(" (match-string 3) ")")))))
14458 (unless (re-search-forward org-dblock-end-re nil t)
14459 (error "Dynamic block not terminated"))
14460 (delete-region begdel (match-beginning 0))
14461 (goto-char begdel)
14462 (open-line 1)
14463 params))
14465 (defun org-map-dblocks (&optional command)
14466 "Apply COMMAND to all dynamic blocks in the current buffer.
14467 If COMMAND is not given, use `org-update-dblock'."
14468 (let ((cmd (or command 'org-update-dblock))
14469 pos)
14470 (save-excursion
14471 (goto-char (point-min))
14472 (while (re-search-forward org-dblock-start-re nil t)
14473 (goto-char (setq pos (match-beginning 0)))
14474 (condition-case nil
14475 (funcall cmd)
14476 (error (message "Error during update of dynamic block")))
14477 (goto-char pos)
14478 (unless (re-search-forward org-dblock-end-re nil t)
14479 (error "Dynamic block not terminated"))))))
14481 (defun org-dblock-update (&optional arg)
14482 "User command for updating dynamic blocks.
14483 Update the dynamic block at point. With prefix ARG, update all dynamic
14484 blocks in the buffer."
14485 (interactive "P")
14486 (if arg
14487 (org-update-all-dblocks)
14488 (or (looking-at org-dblock-start-re)
14489 (org-beginning-of-dblock))
14490 (org-update-dblock)))
14492 (defun org-update-dblock ()
14493 "Update the dynamic block at point
14494 This means to empty the block, parse for parameters and then call
14495 the correct writing function."
14496 (save-window-excursion
14497 (let* ((pos (point))
14498 (line (org-current-line))
14499 (params (org-prepare-dblock))
14500 (name (plist-get params :name))
14501 (cmd (intern (concat "org-dblock-write:" name))))
14502 (message "Updating dynamic block `%s' at line %d..." name line)
14503 (funcall cmd params)
14504 (message "Updating dynamic block `%s' at line %d...done" name line)
14505 (goto-char pos))))
14507 (defun org-beginning-of-dblock ()
14508 "Find the beginning of the dynamic block at point.
14509 Error if there is no scuh block at point."
14510 (let ((pos (point))
14511 beg)
14512 (end-of-line 1)
14513 (if (and (re-search-backward org-dblock-start-re nil t)
14514 (setq beg (match-beginning 0))
14515 (re-search-forward org-dblock-end-re nil t)
14516 (> (match-end 0) pos))
14517 (goto-char beg)
14518 (goto-char pos)
14519 (error "Not in a dynamic block"))))
14521 (defun org-update-all-dblocks ()
14522 "Update all dynamic blocks in the buffer.
14523 This function can be used in a hook."
14524 (when (org-mode-p)
14525 (org-map-dblocks 'org-update-dblock)))
14528 ;;;; Completion
14530 (defconst org-additional-option-like-keywords
14531 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14532 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14533 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14535 (defun org-complete (&optional arg)
14536 "Perform completion on word at point.
14537 At the beginning of a headline, this completes TODO keywords as given in
14538 `org-todo-keywords'.
14539 If the current word is preceded by a backslash, completes the TeX symbols
14540 that are supported for HTML support.
14541 If the current word is preceded by \"#+\", completes special words for
14542 setting file options.
14543 In the line after \"#+STARTUP:, complete valid keywords.\"
14544 At all other locations, this simply calls the value of
14545 `org-completion-fallback-command'."
14546 (interactive "P")
14547 (org-without-partial-completion
14548 (catch 'exit
14549 (let* ((end (point))
14550 (beg1 (save-excursion
14551 (skip-chars-backward (org-re "[:alnum:]_@"))
14552 (point)))
14553 (beg (save-excursion
14554 (skip-chars-backward "a-zA-Z0-9_:$")
14555 (point)))
14556 (confirm (lambda (x) (stringp (car x))))
14557 (searchhead (equal (char-before beg) ?*))
14558 (tag (and (equal (char-before beg1) ?:)
14559 (equal (char-after (point-at-bol)) ?*)))
14560 (prop (and (equal (char-before beg1) ?:)
14561 (not (equal (char-after (point-at-bol)) ?*))))
14562 (texp (equal (char-before beg) ?\\))
14563 (link (equal (char-before beg) ?\[))
14564 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14565 beg)
14566 "#+"))
14567 (startup (string-match "^#\\+STARTUP:.*"
14568 (buffer-substring (point-at-bol) (point))))
14569 (completion-ignore-case opt)
14570 (type nil)
14571 (tbl nil)
14572 (table (cond
14573 (opt
14574 (setq type :opt)
14575 (append
14576 (mapcar
14577 (lambda (x)
14578 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14579 (cons (match-string 2 x) (match-string 1 x)))
14580 (org-split-string (org-get-current-options) "\n"))
14581 (mapcar 'list org-additional-option-like-keywords)))
14582 (startup
14583 (setq type :startup)
14584 org-startup-options)
14585 (link (append org-link-abbrev-alist-local
14586 org-link-abbrev-alist))
14587 (texp
14588 (setq type :tex)
14589 org-html-entities)
14590 ((string-match "\\`\\*+[ \t]+\\'"
14591 (buffer-substring (point-at-bol) beg))
14592 (setq type :todo)
14593 (mapcar 'list org-todo-keywords-1))
14594 (searchhead
14595 (setq type :searchhead)
14596 (save-excursion
14597 (goto-char (point-min))
14598 (while (re-search-forward org-todo-line-regexp nil t)
14599 (push (list
14600 (org-make-org-heading-search-string
14601 (match-string 3) t))
14602 tbl)))
14603 tbl)
14604 (tag (setq type :tag beg beg1)
14605 (or org-tag-alist (org-get-buffer-tags)))
14606 (prop (setq type :prop beg beg1)
14607 (mapcar 'list (org-buffer-property-keys nil t t)))
14608 (t (progn
14609 (call-interactively org-completion-fallback-command)
14610 (throw 'exit nil)))))
14611 (pattern (buffer-substring-no-properties beg end))
14612 (completion (try-completion pattern table confirm)))
14613 (cond ((eq completion t)
14614 (if (not (assoc (upcase pattern) table))
14615 (message "Already complete")
14616 (if (equal type :opt)
14617 (insert (substring (cdr (assoc (upcase pattern) table))
14618 (length pattern)))
14619 (if (memq type '(:tag :prop)) (insert ":")))))
14620 ((null completion)
14621 (message "Can't find completion for \"%s\"" pattern)
14622 (ding))
14623 ((not (string= pattern completion))
14624 (delete-region beg end)
14625 (if (string-match " +$" completion)
14626 (setq completion (replace-match "" t t completion)))
14627 (insert completion)
14628 (if (get-buffer-window "*Completions*")
14629 (delete-window (get-buffer-window "*Completions*")))
14630 (if (assoc completion table)
14631 (if (eq type :todo) (insert " ")
14632 (if (memq type '(:tag :prop)) (insert ":"))))
14633 (if (and (equal type :opt) (assoc completion table))
14634 (message "%s" (substitute-command-keys
14635 "Press \\[org-complete] again to insert example settings"))))
14637 (message "Making completion list...")
14638 (let ((list (sort (all-completions pattern table confirm)
14639 'string<)))
14640 (with-output-to-temp-buffer "*Completions*"
14641 (condition-case nil
14642 ;; Protection needed for XEmacs and emacs 21
14643 (display-completion-list list pattern)
14644 (error (display-completion-list list)))))
14645 (message "Making completion list...%s" "done")))))))
14647 ;;;; TODO, DEADLINE, Comments
14649 (defun org-toggle-comment ()
14650 "Change the COMMENT state of an entry."
14651 (interactive)
14652 (save-excursion
14653 (org-back-to-heading)
14654 (let (case-fold-search)
14655 (if (looking-at (concat outline-regexp
14656 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14657 (replace-match "" t t nil 1)
14658 (if (looking-at outline-regexp)
14659 (progn
14660 (goto-char (match-end 0))
14661 (insert org-comment-string " ")))))))
14663 (defvar org-last-todo-state-is-todo nil
14664 "This is non-nil when the last TODO state change led to a TODO state.
14665 If the last change removed the TODO tag or switched to DONE, then
14666 this is nil.")
14668 (defvar org-setting-tags nil) ; dynamically skiped
14670 ;; FIXME: better place
14671 (defun org-property-or-variable-value (var &optional inherit)
14672 "Check if there is a property fixing the value of VAR.
14673 If yes, return this value. If not, return the current value of the variable."
14674 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14675 (if (and prop (stringp prop) (string-match "\\S-" prop))
14676 (read prop)
14677 (symbol-value var))))
14679 (defun org-parse-local-options (string var)
14680 "Parse STRING for startup setting relevant for variable VAR."
14681 (let ((rtn (symbol-value var))
14682 e opts)
14683 (save-match-data
14684 (if (or (not string) (not (string-match "\\S-" string)))
14686 (setq opts (delq nil (mapcar (lambda (x)
14687 (setq e (assoc x org-startup-options))
14688 (if (eq (nth 1 e) var) e nil))
14689 (org-split-string string "[ \t]+"))))
14690 (if (not opts)
14692 (setq rtn nil)
14693 (while (setq e (pop opts))
14694 (if (not (nth 3 e))
14695 (setq rtn (nth 2 e))
14696 (if (not (listp rtn)) (setq rtn nil))
14697 (push (nth 2 e) rtn)))
14698 rtn)))))
14700 (defvar org-blocker-hook nil
14701 "Hook for functions that are allowed to block a state change.
14703 Each function gets as its single argument a property list, see
14704 `org-trigger-hook' for more information about this list.
14706 If any of the functions in this hook returns nil, the state change
14707 is blocked.")
14709 (defvar org-trigger-hook nil
14710 "Hook for functions that are triggered by a state change.
14712 Each function gets as its single argument a property list with at least
14713 the following elements:
14715 (:type type-of-change :position pos-at-entry-start
14716 :from old-state :to new-state)
14718 Depending on the type, more properties may be present.
14720 This mechanism is currently implemented for:
14722 TODO state changes
14723 ------------------
14724 :type todo-state-change
14725 :from previous state (keyword as a string), or nil
14726 :to new state (keyword as a string), or nil")
14729 (defun org-todo (&optional arg)
14730 "Change the TODO state of an item.
14731 The state of an item is given by a keyword at the start of the heading,
14732 like
14733 *** TODO Write paper
14734 *** DONE Call mom
14736 The different keywords are specified in the variable `org-todo-keywords'.
14737 By default the available states are \"TODO\" and \"DONE\".
14738 So for this example: when the item starts with TODO, it is changed to DONE.
14739 When it starts with DONE, the DONE is removed. And when neither TODO nor
14740 DONE are present, add TODO at the beginning of the heading.
14742 With C-u prefix arg, use completion to determine the new state.
14743 With numeric prefix arg, switch to that state.
14745 For calling through lisp, arg is also interpreted in the following way:
14746 'none -> empty state
14747 \"\"(empty string) -> switch to empty state
14748 'done -> switch to DONE
14749 'nextset -> switch to the next set of keywords
14750 'previousset -> switch to the previous set of keywords
14751 \"WAITING\" -> switch to the specified keyword, but only if it
14752 really is a member of `org-todo-keywords'."
14753 (interactive "P")
14754 (save-excursion
14755 (catch 'exit
14756 (org-back-to-heading)
14757 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14758 (or (looking-at (concat " +" org-todo-regexp " *"))
14759 (looking-at " *"))
14760 (let* ((match-data (match-data))
14761 (startpos (point-at-bol))
14762 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14763 (org-log-done org-log-done)
14764 (org-log-repeat org-log-repeat)
14765 (org-todo-log-states org-todo-log-states)
14766 (this (match-string 1))
14767 (hl-pos (match-beginning 0))
14768 (head (org-get-todo-sequence-head this))
14769 (ass (assoc head org-todo-kwd-alist))
14770 (interpret (nth 1 ass))
14771 (done-word (nth 3 ass))
14772 (final-done-word (nth 4 ass))
14773 (last-state (or this ""))
14774 (completion-ignore-case t)
14775 (member (member this org-todo-keywords-1))
14776 (tail (cdr member))
14777 (state (cond
14778 ((and org-todo-key-trigger
14779 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14780 (and (not arg) org-use-fast-todo-selection
14781 (not (eq org-use-fast-todo-selection 'prefix)))))
14782 ;; Use fast selection
14783 (org-fast-todo-selection))
14784 ((and (equal arg '(4))
14785 (or (not org-use-fast-todo-selection)
14786 (not org-todo-key-trigger)))
14787 ;; Read a state with completion
14788 (completing-read "State: " (mapcar (lambda(x) (list x))
14789 org-todo-keywords-1)
14790 nil t))
14791 ((eq arg 'right)
14792 (if this
14793 (if tail (car tail) nil)
14794 (car org-todo-keywords-1)))
14795 ((eq arg 'left)
14796 (if (equal member org-todo-keywords-1)
14798 (if this
14799 (nth (- (length org-todo-keywords-1) (length tail) 2)
14800 org-todo-keywords-1)
14801 (org-last org-todo-keywords-1))))
14802 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14803 (setq arg nil))) ; hack to fall back to cycling
14804 (arg
14805 ;; user or caller requests a specific state
14806 (cond
14807 ((equal arg "") nil)
14808 ((eq arg 'none) nil)
14809 ((eq arg 'done) (or done-word (car org-done-keywords)))
14810 ((eq arg 'nextset)
14811 (or (car (cdr (member head org-todo-heads)))
14812 (car org-todo-heads)))
14813 ((eq arg 'previousset)
14814 (let ((org-todo-heads (reverse org-todo-heads)))
14815 (or (car (cdr (member head org-todo-heads)))
14816 (car org-todo-heads))))
14817 ((car (member arg org-todo-keywords-1)))
14818 ((nth (1- (prefix-numeric-value arg))
14819 org-todo-keywords-1))))
14820 ((null member) (or head (car org-todo-keywords-1)))
14821 ((equal this final-done-word) nil) ;; -> make empty
14822 ((null tail) nil) ;; -> first entry
14823 ((eq interpret 'sequence)
14824 (car tail))
14825 ((memq interpret '(type priority))
14826 (if (eq this-command last-command)
14827 (car tail)
14828 (if (> (length tail) 0)
14829 (or done-word (car org-done-keywords))
14830 nil)))
14831 (t nil)))
14832 (next (if state (concat " " state " ") " "))
14833 (change-plist (list :type 'todo-state-change :from this :to state
14834 :position startpos))
14835 dolog now-done-p)
14836 (when org-blocker-hook
14837 (unless (save-excursion
14838 (save-match-data
14839 (run-hook-with-args-until-failure
14840 'org-blocker-hook change-plist)))
14841 (if (interactive-p)
14842 (error "TODO state change from %s to %s blocked" this state)
14843 ;; fail silently
14844 (message "TODO state change from %s to %s blocked" this state)
14845 (throw 'exit nil))))
14846 (store-match-data match-data)
14847 (replace-match next t t)
14848 (unless (pos-visible-in-window-p hl-pos)
14849 (message "TODO state changed to %s" (org-trim next)))
14850 (unless head
14851 (setq head (org-get-todo-sequence-head state)
14852 ass (assoc head org-todo-kwd-alist)
14853 interpret (nth 1 ass)
14854 done-word (nth 3 ass)
14855 final-done-word (nth 4 ass)))
14856 (when (memq arg '(nextset previousset))
14857 (message "Keyword-Set %d/%d: %s"
14858 (- (length org-todo-sets) -1
14859 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14860 (length org-todo-sets)
14861 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14862 (setq org-last-todo-state-is-todo
14863 (not (member state org-done-keywords)))
14864 (setq now-done-p (and (member state org-done-keywords)
14865 (not (member this org-done-keywords))))
14866 (and logging (org-local-logging logging))
14867 (when (and (or org-todo-log-states org-log-done)
14868 (not (memq arg '(nextset previousset))))
14869 ;; we need to look at recording a time and note
14870 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14871 (nth 2 (assoc this org-todo-log-states))))
14872 (when (and state
14873 (member state org-not-done-keywords)
14874 (not (member this org-not-done-keywords)))
14875 ;; This is now a todo state and was not one before
14876 ;; If there was a CLOSED time stamp, get rid of it.
14877 (org-add-planning-info nil nil 'closed))
14878 (when (and now-done-p org-log-done)
14879 ;; It is now done, and it was not done before
14880 (org-add-planning-info 'closed (org-current-time))
14881 (if (and (not dolog) (eq 'note org-log-done))
14882 (org-add-log-maybe 'done state 'findpos 'note)))
14883 (when (and state dolog)
14884 ;; This is a non-nil state, and we need to log it
14885 (org-add-log-maybe 'state state 'findpos dolog)))
14886 ;; Fixup tag positioning
14887 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14888 (run-hooks 'org-after-todo-state-change-hook)
14889 (if (and arg (not (member state org-done-keywords)))
14890 (setq head (org-get-todo-sequence-head state)))
14891 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14892 ;; Do we need to trigger a repeat?
14893 (when now-done-p (org-auto-repeat-maybe state))
14894 ;; Fixup cursor location if close to the keyword
14895 (if (and (outline-on-heading-p)
14896 (not (bolp))
14897 (save-excursion (beginning-of-line 1)
14898 (looking-at org-todo-line-regexp))
14899 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14900 (progn
14901 (goto-char (or (match-end 2) (match-end 1)))
14902 (just-one-space)))
14903 (when org-trigger-hook
14904 (save-excursion
14905 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14907 (defun org-local-logging (value)
14908 "Get logging settings from a property VALUE."
14909 (let* (words w a)
14910 ;; directly set the variables, they are already local.
14911 (setq org-log-done nil
14912 org-log-repeat nil
14913 org-todo-log-states nil)
14914 (setq words (org-split-string value))
14915 (while (setq w (pop words))
14916 (cond
14917 ((setq a (assoc w org-startup-options))
14918 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14919 (set (nth 1 a) (nth 2 a))))
14920 ((setq a (org-extract-log-state-settings w))
14921 (and (member (car a) org-todo-keywords-1)
14922 (push a org-todo-log-states)))))))
14924 (defun org-get-todo-sequence-head (kwd)
14925 "Return the head of the TODO sequence to which KWD belongs.
14926 If KWD is not set, check if there is a text property remembering the
14927 right sequence."
14928 (let (p)
14929 (cond
14930 ((not kwd)
14931 (or (get-text-property (point-at-bol) 'org-todo-head)
14932 (progn
14933 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14934 nil (point-at-eol)))
14935 (get-text-property p 'org-todo-head))))
14936 ((not (member kwd org-todo-keywords-1))
14937 (car org-todo-keywords-1))
14938 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14940 (defun org-fast-todo-selection ()
14941 "Fast TODO keyword selection with single keys.
14942 Returns the new TODO keyword, or nil if no state change should occur."
14943 (let* ((fulltable org-todo-key-alist)
14944 (done-keywords org-done-keywords) ;; needed for the faces.
14945 (maxlen (apply 'max (mapcar
14946 (lambda (x)
14947 (if (stringp (car x)) (string-width (car x)) 0))
14948 fulltable)))
14949 (expert nil)
14950 (fwidth (+ maxlen 3 1 3))
14951 (ncol (/ (- (window-width) 4) fwidth))
14952 tg cnt e c tbl
14953 groups ingroup)
14954 (save-window-excursion
14955 (if expert
14956 (set-buffer (get-buffer-create " *Org todo*"))
14957 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14958 (erase-buffer)
14959 (org-set-local 'org-done-keywords done-keywords)
14960 (setq tbl fulltable cnt 0)
14961 (while (setq e (pop tbl))
14962 (cond
14963 ((equal e '(:startgroup))
14964 (push '() groups) (setq ingroup t)
14965 (when (not (= cnt 0))
14966 (setq cnt 0)
14967 (insert "\n"))
14968 (insert "{ "))
14969 ((equal e '(:endgroup))
14970 (setq ingroup nil cnt 0)
14971 (insert "}\n"))
14973 (setq tg (car e) c (cdr e))
14974 (if ingroup (push tg (car groups)))
14975 (setq tg (org-add-props tg nil 'face
14976 (org-get-todo-face tg)))
14977 (if (and (= cnt 0) (not ingroup)) (insert " "))
14978 (insert "[" c "] " tg (make-string
14979 (- fwidth 4 (length tg)) ?\ ))
14980 (when (= (setq cnt (1+ cnt)) ncol)
14981 (insert "\n")
14982 (if ingroup (insert " "))
14983 (setq cnt 0)))))
14984 (insert "\n")
14985 (goto-char (point-min))
14986 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14987 (fit-window-to-buffer))
14988 (message "[a-z..]:Set [SPC]:clear")
14989 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14990 (cond
14991 ((or (= c ?\C-g)
14992 (and (= c ?q) (not (rassoc c fulltable))))
14993 (setq quit-flag t))
14994 ((= c ?\ ) nil)
14995 ((setq e (rassoc c fulltable) tg (car e))
14997 (t (setq quit-flag t))))))
14999 (defun org-get-repeat ()
15000 "Check if tere is a deadline/schedule with repeater in this entry."
15001 (save-match-data
15002 (save-excursion
15003 (org-back-to-heading t)
15004 (if (re-search-forward
15005 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
15006 (match-string 1)))))
15008 (defvar org-last-changed-timestamp)
15009 (defvar org-log-post-message)
15010 (defvar org-log-note-purpose)
15011 (defun org-auto-repeat-maybe (done-word)
15012 "Check if the current headline contains a repeated deadline/schedule.
15013 If yes, set TODO state back to what it was and change the base date
15014 of repeating deadline/scheduled time stamps to new date.
15015 This function is run automatically after each state change to a DONE state."
15016 ;; last-state is dynamically scoped into this function
15017 (let* ((repeat (org-get-repeat))
15018 (aa (assoc last-state org-todo-kwd-alist))
15019 (interpret (nth 1 aa))
15020 (head (nth 2 aa))
15021 (whata '(("d" . day) ("m" . month) ("y" . year)))
15022 (msg "Entry repeats: ")
15023 (org-log-done nil)
15024 (org-todo-log-states nil)
15025 re type n what ts)
15026 (when repeat
15027 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
15028 (org-todo (if (eq interpret 'type) last-state head))
15029 (when (and org-log-repeat
15030 (or (not (memq 'org-add-log-note
15031 (default-value 'post-command-hook)))
15032 (eq org-log-note-purpose 'done)))
15033 ;; Make sure a note is taken;
15034 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
15035 'findpos org-log-repeat))
15036 (org-back-to-heading t)
15037 (org-add-planning-info nil nil 'closed)
15038 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
15039 org-deadline-time-regexp "\\)\\|\\("
15040 org-ts-regexp "\\)"))
15041 (while (re-search-forward
15042 re (save-excursion (outline-next-heading) (point)) t)
15043 (setq type (if (match-end 1) org-scheduled-string
15044 (if (match-end 3) org-deadline-string "Plain:"))
15045 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
15046 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
15047 (setq n (string-to-number (match-string 1 ts))
15048 what (match-string 2 ts))
15049 (if (equal what "w") (setq n (* n 7) what "d"))
15050 (org-timestamp-change n (cdr (assoc what whata)))
15051 (setq msg (concat msg type org-last-changed-timestamp " "))))
15052 (setq org-log-post-message msg)
15053 (message "%s" msg))))
15055 (defun org-show-todo-tree (arg)
15056 "Make a compact tree which shows all headlines marked with TODO.
15057 The tree will show the lines where the regexp matches, and all higher
15058 headlines above the match.
15059 With a \\[universal-argument] prefix, also show the DONE entries.
15060 With a numeric prefix N, construct a sparse tree for the Nth element
15061 of `org-todo-keywords-1'."
15062 (interactive "P")
15063 (let ((case-fold-search nil)
15064 (kwd-re
15065 (cond ((null arg) org-not-done-regexp)
15066 ((equal arg '(4))
15067 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
15068 (mapcar 'list org-todo-keywords-1))))
15069 (concat "\\("
15070 (mapconcat 'identity (org-split-string kwd "|") "\\|")
15071 "\\)\\>")))
15072 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
15073 (regexp-quote (nth (1- (prefix-numeric-value arg))
15074 org-todo-keywords-1)))
15075 (t (error "Invalid prefix argument: %s" arg)))))
15076 (message "%d TODO entries found"
15077 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
15079 (defun org-deadline (&optional remove)
15080 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
15081 With argument REMOVE, remove any deadline from the item."
15082 (interactive "P")
15083 (if remove
15084 (progn
15085 (org-remove-timestamp-with-keyword org-deadline-string)
15086 (message "Item no longer has a deadline."))
15087 (org-add-planning-info 'deadline nil 'closed)))
15089 (defun org-schedule (&optional remove)
15090 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
15091 With argument REMOVE, remove any scheduling date from the item."
15092 (interactive "P")
15093 (if remove
15094 (progn
15095 (org-remove-timestamp-with-keyword org-scheduled-string)
15096 (message "Item is no longer scheduled."))
15097 (org-add-planning-info 'scheduled nil 'closed)))
15099 (defun org-remove-timestamp-with-keyword (keyword)
15100 "Remove all time stamps with KEYWORD in the current entry."
15101 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
15102 beg)
15103 (save-excursion
15104 (org-back-to-heading t)
15105 (setq beg (point))
15106 (org-end-of-subtree t t)
15107 (while (re-search-backward re beg t)
15108 (replace-match "")
15109 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
15110 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
15112 (defun org-add-planning-info (what &optional time &rest remove)
15113 "Insert new timestamp with keyword in the line directly after the headline.
15114 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
15115 If non is given, the user is prompted for a date.
15116 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
15117 be removed."
15118 (interactive)
15119 (let (org-time-was-given org-end-time-was-given)
15120 (when what (setq time (or time (org-read-date nil 'to-time))))
15121 (when (and org-insert-labeled-timestamps-at-point
15122 (member what '(scheduled deadline)))
15123 (insert
15124 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
15125 (org-insert-time-stamp time org-time-was-given
15126 nil nil nil (list org-end-time-was-given))
15127 (setq what nil))
15128 (save-excursion
15129 (save-restriction
15130 (let (col list elt ts buffer-invisibility-spec)
15131 (org-back-to-heading t)
15132 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
15133 (goto-char (match-end 1))
15134 (setq col (current-column))
15135 (goto-char (match-end 0))
15136 (if (eobp) (insert "\n") (forward-char 1))
15137 (if (and (not (looking-at outline-regexp))
15138 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
15139 "[^\r\n]*"))
15140 (not (equal (match-string 1) org-clock-string)))
15141 (narrow-to-region (match-beginning 0) (match-end 0))
15142 (insert-before-markers "\n")
15143 (backward-char 1)
15144 (narrow-to-region (point) (point))
15145 (indent-to-column col))
15146 ;; Check if we have to remove something.
15147 (setq list (cons what remove))
15148 (while list
15149 (setq elt (pop list))
15150 (goto-char (point-min))
15151 (when (or (and (eq elt 'scheduled)
15152 (re-search-forward org-scheduled-time-regexp nil t))
15153 (and (eq elt 'deadline)
15154 (re-search-forward org-deadline-time-regexp nil t))
15155 (and (eq elt 'closed)
15156 (re-search-forward org-closed-time-regexp nil t)))
15157 (replace-match "")
15158 (if (looking-at "--+<[^>]+>") (replace-match ""))
15159 (if (looking-at " +") (replace-match ""))))
15160 (goto-char (point-max))
15161 (when what
15162 (insert
15163 (if (not (equal (char-before) ?\ )) " " "")
15164 (cond ((eq what 'scheduled) org-scheduled-string)
15165 ((eq what 'deadline) org-deadline-string)
15166 ((eq what 'closed) org-closed-string))
15167 " ")
15168 (setq ts (org-insert-time-stamp
15169 time
15170 (or org-time-was-given
15171 (and (eq what 'closed) org-log-done-with-time))
15172 (eq what 'closed)
15173 nil nil (list org-end-time-was-given)))
15174 (end-of-line 1))
15175 (goto-char (point-min))
15176 (widen)
15177 (if (looking-at "[ \t]+\r?\n")
15178 (replace-match ""))
15179 ts)))))
15181 (defvar org-log-note-marker (make-marker))
15182 (defvar org-log-note-purpose nil)
15183 (defvar org-log-note-state nil)
15184 (defvar org-log-note-how nil)
15185 (defvar org-log-note-window-configuration nil)
15186 (defvar org-log-note-return-to (make-marker))
15187 (defvar org-log-post-message nil
15188 "Message to be displayed after a log note has been stored.
15189 The auto-repeater uses this.")
15191 (defun org-add-log-maybe (&optional purpose state findpos how)
15192 "Set up the post command hook to take a note.
15193 If this is about to TODO state change, the new state is expected in STATE.
15194 When FINDPOS is non-nil, find the correct position for the note in
15195 the current entry. If not, assume that it can be inserted at point."
15196 (save-excursion
15197 (when findpos
15198 (org-back-to-heading t)
15199 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
15200 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
15201 "[^\r\n]*\\)?"))
15202 (goto-char (match-end 0))
15203 (unless org-log-states-order-reversed
15204 (and (= (char-after) ?\n) (forward-char 1))
15205 (org-skip-over-state-notes)
15206 (skip-chars-backward " \t\n\r")))
15207 (move-marker org-log-note-marker (point))
15208 (setq org-log-note-purpose purpose
15209 org-log-note-state state
15210 org-log-note-how how)
15211 (add-hook 'post-command-hook 'org-add-log-note 'append)))
15213 (defun org-skip-over-state-notes ()
15214 "Skip past the list of State notes in an entry."
15215 (if (looking-at "\n[ \t]*- State") (forward-char 1))
15216 (while (looking-at "[ \t]*- State")
15217 (condition-case nil
15218 (org-next-item)
15219 (error (org-end-of-item)))))
15221 (defun org-add-log-note (&optional purpose)
15222 "Pop up a window for taking a note, and add this note later at point."
15223 (remove-hook 'post-command-hook 'org-add-log-note)
15224 (setq org-log-note-window-configuration (current-window-configuration))
15225 (delete-other-windows)
15226 (move-marker org-log-note-return-to (point))
15227 (switch-to-buffer (marker-buffer org-log-note-marker))
15228 (goto-char org-log-note-marker)
15229 (org-switch-to-buffer-other-window "*Org Note*")
15230 (erase-buffer)
15231 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
15232 (org-store-log-note)
15233 (let ((org-inhibit-startup t)) (org-mode))
15234 (insert (format "# Insert note for %s.
15235 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
15236 (cond
15237 ((eq org-log-note-purpose 'clock-out) "stopped clock")
15238 ((eq org-log-note-purpose 'done) "closed todo item")
15239 ((eq org-log-note-purpose 'state)
15240 (format "state change to \"%s\"" org-log-note-state))
15241 (t (error "This should not happen")))))
15242 (org-set-local 'org-finish-function 'org-store-log-note)))
15244 (defun org-store-log-note ()
15245 "Finish taking a log note, and insert it to where it belongs."
15246 (let ((txt (buffer-string))
15247 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
15248 lines ind)
15249 (kill-buffer (current-buffer))
15250 (while (string-match "\\`#.*\n[ \t\n]*" txt)
15251 (setq txt (replace-match "" t t txt)))
15252 (if (string-match "\\s-+\\'" txt)
15253 (setq txt (replace-match "" t t txt)))
15254 (setq lines (org-split-string txt "\n"))
15255 (when (and note (string-match "\\S-" note))
15256 (setq note
15257 (org-replace-escapes
15258 note
15259 (list (cons "%u" (user-login-name))
15260 (cons "%U" user-full-name)
15261 (cons "%t" (format-time-string
15262 (org-time-stamp-format 'long 'inactive)
15263 (current-time)))
15264 (cons "%s" (if org-log-note-state
15265 (concat "\"" org-log-note-state "\"")
15266 "")))))
15267 (if lines (setq note (concat note " \\\\")))
15268 (push note lines))
15269 (when (or current-prefix-arg org-note-abort) (setq lines nil))
15270 (when lines
15271 (save-excursion
15272 (set-buffer (marker-buffer org-log-note-marker))
15273 (save-excursion
15274 (goto-char org-log-note-marker)
15275 (move-marker org-log-note-marker nil)
15276 (end-of-line 1)
15277 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
15278 (indent-relative nil)
15279 (insert "- " (pop lines))
15280 (org-indent-line-function)
15281 (beginning-of-line 1)
15282 (looking-at "[ \t]*")
15283 (setq ind (concat (match-string 0) " "))
15284 (end-of-line 1)
15285 (while lines (insert "\n" ind (pop lines)))))))
15286 (set-window-configuration org-log-note-window-configuration)
15287 (with-current-buffer (marker-buffer org-log-note-return-to)
15288 (goto-char org-log-note-return-to))
15289 (move-marker org-log-note-return-to nil)
15290 (and org-log-post-message (message "%s" org-log-post-message)))
15292 ;; FIXME: what else would be useful?
15293 ;; - priority
15294 ;; - date
15296 (defun org-sparse-tree (&optional arg)
15297 "Create a sparse tree, prompt for the details.
15298 This command can create sparse trees. You first need to select the type
15299 of match used to create the tree:
15301 t Show entries with a specific TODO keyword.
15302 T Show entries selected by a tags match.
15303 p Enter a property name and its value (both with completion on existing
15304 names/values) and show entries with that property.
15305 r Show entries matching a regular expression
15306 d Show deadlines due within `org-deadline-warning-days'."
15307 (interactive "P")
15308 (let (ans kwd value)
15309 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15310 (setq ans (read-char-exclusive))
15311 (cond
15312 ((equal ans ?d)
15313 (call-interactively 'org-check-deadlines))
15314 ((equal ans ?b)
15315 (call-interactively 'org-check-before-date))
15316 ((equal ans ?t)
15317 (org-show-todo-tree '(4)))
15318 ((equal ans ?T)
15319 (call-interactively 'org-tags-sparse-tree))
15320 ((member ans '(?p ?P))
15321 (setq kwd (completing-read "Property: "
15322 (mapcar 'list (org-buffer-property-keys))))
15323 (setq value (completing-read "Value: "
15324 (mapcar 'list (org-property-values kwd))))
15325 (unless (string-match "\\`{.*}\\'" value)
15326 (setq value (concat "\"" value "\"")))
15327 (org-tags-sparse-tree arg (concat kwd "=" value)))
15328 ((member ans '(?r ?R ?/))
15329 (call-interactively 'org-occur))
15330 (t (error "No such sparse tree command \"%c\"" ans)))))
15332 (defvar org-occur-highlights nil
15333 "List of overlays used for occur matches.")
15334 (make-variable-buffer-local 'org-occur-highlights)
15335 (defvar org-occur-parameters nil
15336 "Parameters of the active org-occur calls.
15337 This is a list, each call to org-occur pushes as cons cell,
15338 containing the regular expression and the callback, onto the list.
15339 The list can contain several entries if `org-occur' has been called
15340 several time with the KEEP-PREVIOUS argument. Otherwise, this list
15341 will only contain one set of parameters. When the highlights are
15342 removed (for example with `C-c C-c', or with the next edit (depending
15343 on `org-remove-highlights-with-change'), this variable is emptied
15344 as well.")
15345 (make-variable-buffer-local 'org-occur-parameters)
15347 (defun org-occur (regexp &optional keep-previous callback)
15348 "Make a compact tree which shows all matches of REGEXP.
15349 The tree will show the lines where the regexp matches, and all higher
15350 headlines above the match. It will also show the heading after the match,
15351 to make sure editing the matching entry is easy.
15352 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15353 call to `org-occur' will be kept, to allow stacking of calls to this
15354 command.
15355 If CALLBACK is non-nil, it is a function which is called to confirm
15356 that the match should indeed be shown."
15357 (interactive "sRegexp: \nP")
15358 (unless keep-previous
15359 (org-remove-occur-highlights nil nil t))
15360 (push (cons regexp callback) org-occur-parameters)
15361 (let ((cnt 0))
15362 (save-excursion
15363 (goto-char (point-min))
15364 (if (or (not keep-previous) ; do not want to keep
15365 (not org-occur-highlights)) ; no previous matches
15366 ;; hide everything
15367 (org-overview))
15368 (while (re-search-forward regexp nil t)
15369 (when (or (not callback)
15370 (save-match-data (funcall callback)))
15371 (setq cnt (1+ cnt))
15372 (when org-highlight-sparse-tree-matches
15373 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15374 (org-show-context 'occur-tree))))
15375 (when org-remove-highlights-with-change
15376 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15377 nil 'local))
15378 (unless org-sparse-tree-open-archived-trees
15379 (org-hide-archived-subtrees (point-min) (point-max)))
15380 (run-hooks 'org-occur-hook)
15381 (if (interactive-p)
15382 (message "%d match(es) for regexp %s" cnt regexp))
15383 cnt))
15385 (defun org-show-context (&optional key)
15386 "Make sure point and context and visible.
15387 How much context is shown depends upon the variables
15388 `org-show-hierarchy-above', `org-show-following-heading'. and
15389 `org-show-siblings'."
15390 (let ((heading-p (org-on-heading-p t))
15391 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15392 (following-p (org-get-alist-option org-show-following-heading key))
15393 (entry-p (org-get-alist-option org-show-entry-below key))
15394 (siblings-p (org-get-alist-option org-show-siblings key)))
15395 (catch 'exit
15396 ;; Show heading or entry text
15397 (if (and heading-p (not entry-p))
15398 (org-flag-heading nil) ; only show the heading
15399 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15400 (org-show-hidden-entry))) ; show entire entry
15401 (when following-p
15402 ;; Show next sibling, or heading below text
15403 (save-excursion
15404 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15405 (org-flag-heading nil))))
15406 (when siblings-p (org-show-siblings))
15407 (when hierarchy-p
15408 ;; show all higher headings, possibly with siblings
15409 (save-excursion
15410 (while (and (condition-case nil
15411 (progn (org-up-heading-all 1) t)
15412 (error nil))
15413 (not (bobp)))
15414 (org-flag-heading nil)
15415 (when siblings-p (org-show-siblings))))))))
15417 (defun org-reveal (&optional siblings)
15418 "Show current entry, hierarchy above it, and the following headline.
15419 This can be used to show a consistent set of context around locations
15420 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15421 not t for the search context.
15423 With optional argument SIBLINGS, on each level of the hierarchy all
15424 siblings are shown. This repairs the tree structure to what it would
15425 look like when opened with hierarchical calls to `org-cycle'."
15426 (interactive "P")
15427 (let ((org-show-hierarchy-above t)
15428 (org-show-following-heading t)
15429 (org-show-siblings (if siblings t org-show-siblings)))
15430 (org-show-context nil)))
15432 (defun org-highlight-new-match (beg end)
15433 "Highlight from BEG to END and mark the highlight is an occur headline."
15434 (let ((ov (org-make-overlay beg end)))
15435 (org-overlay-put ov 'face 'secondary-selection)
15436 (push ov org-occur-highlights)))
15438 (defun org-remove-occur-highlights (&optional beg end noremove)
15439 "Remove the occur highlights from the buffer.
15440 BEG and END are ignored. If NOREMOVE is nil, remove this function
15441 from the `before-change-functions' in the current buffer."
15442 (interactive)
15443 (unless org-inhibit-highlight-removal
15444 (mapc 'org-delete-overlay org-occur-highlights)
15445 (setq org-occur-highlights nil)
15446 (setq org-occur-parameters nil)
15447 (unless noremove
15448 (remove-hook 'before-change-functions
15449 'org-remove-occur-highlights 'local))))
15451 ;;;; Priorities
15453 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15454 "Regular expression matching the priority indicator.")
15456 (defvar org-remove-priority-next-time nil)
15458 (defun org-priority-up ()
15459 "Increase the priority of the current item."
15460 (interactive)
15461 (org-priority 'up))
15463 (defun org-priority-down ()
15464 "Decrease the priority of the current item."
15465 (interactive)
15466 (org-priority 'down))
15468 (defun org-priority (&optional action)
15469 "Change the priority of an item by ARG.
15470 ACTION can be `set', `up', `down', or a character."
15471 (interactive)
15472 (setq action (or action 'set))
15473 (let (current new news have remove)
15474 (save-excursion
15475 (org-back-to-heading)
15476 (if (looking-at org-priority-regexp)
15477 (setq current (string-to-char (match-string 2))
15478 have t)
15479 (setq current org-default-priority))
15480 (cond
15481 ((or (eq action 'set) (integerp action))
15482 (if (integerp action)
15483 (setq new action)
15484 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15485 (setq new (read-char-exclusive)))
15486 (if (and (= (upcase org-highest-priority) org-highest-priority)
15487 (= (upcase org-lowest-priority) org-lowest-priority))
15488 (setq new (upcase new)))
15489 (cond ((equal new ?\ ) (setq remove t))
15490 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15491 (error "Priority must be between `%c' and `%c'"
15492 org-highest-priority org-lowest-priority))))
15493 ((eq action 'up)
15494 (if (and (not have) (eq last-command this-command))
15495 (setq new org-lowest-priority)
15496 (setq new (if (and org-priority-start-cycle-with-default (not have))
15497 org-default-priority (1- current)))))
15498 ((eq action 'down)
15499 (if (and (not have) (eq last-command this-command))
15500 (setq new org-highest-priority)
15501 (setq new (if (and org-priority-start-cycle-with-default (not have))
15502 org-default-priority (1+ current)))))
15503 (t (error "Invalid action")))
15504 (if (or (< (upcase new) org-highest-priority)
15505 (> (upcase new) org-lowest-priority))
15506 (setq remove t))
15507 (setq news (format "%c" new))
15508 (if have
15509 (if remove
15510 (replace-match "" t t nil 1)
15511 (replace-match news t t nil 2))
15512 (if remove
15513 (error "No priority cookie found in line")
15514 (looking-at org-todo-line-regexp)
15515 (if (match-end 2)
15516 (progn
15517 (goto-char (match-end 2))
15518 (insert " [#" news "]"))
15519 (goto-char (match-beginning 3))
15520 (insert "[#" news "] ")))))
15521 (org-preserve-lc (org-set-tags nil 'align))
15522 (if remove
15523 (message "Priority removed")
15524 (message "Priority of current item set to %s" news))))
15527 (defun org-get-priority (s)
15528 "Find priority cookie and return priority."
15529 (save-match-data
15530 (if (not (string-match org-priority-regexp s))
15531 (* 1000 (- org-lowest-priority org-default-priority))
15532 (* 1000 (- org-lowest-priority
15533 (string-to-char (match-string 2 s)))))))
15535 ;;;; Tags
15537 (defun org-scan-tags (action matcher &optional todo-only)
15538 "Scan headline tags with inheritance and produce output ACTION.
15539 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15540 evaluated, testing if a given set of tags qualifies a headline for
15541 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15542 are included in the output."
15543 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15544 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15545 (org-re
15546 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15547 (props (list 'face nil
15548 'done-face 'org-done
15549 'undone-face nil
15550 'mouse-face 'highlight
15551 'org-not-done-regexp org-not-done-regexp
15552 'org-todo-regexp org-todo-regexp
15553 'keymap org-agenda-keymap
15554 'help-echo
15555 (format "mouse-2 or RET jump to org file %s"
15556 (abbreviate-file-name
15557 (or (buffer-file-name (buffer-base-buffer))
15558 (buffer-name (buffer-base-buffer)))))))
15559 (case-fold-search nil)
15560 lspos
15561 tags tags-list tags-alist (llast 0) rtn level category i txt
15562 todo marker entry priority)
15563 (save-excursion
15564 (goto-char (point-min))
15565 (when (eq action 'sparse-tree)
15566 (org-overview)
15567 (org-remove-occur-highlights))
15568 (while (re-search-forward re nil t)
15569 (catch :skip
15570 (setq todo (if (match-end 1) (match-string 2))
15571 tags (if (match-end 4) (match-string 4)))
15572 (goto-char (setq lspos (1+ (match-beginning 0))))
15573 (setq level (org-reduced-level (funcall outline-level))
15574 category (org-get-category))
15575 (setq i llast llast level)
15576 ;; remove tag lists from same and sublevels
15577 (while (>= i level)
15578 (when (setq entry (assoc i tags-alist))
15579 (setq tags-alist (delete entry tags-alist)))
15580 (setq i (1- i)))
15581 ;; add the nex tags
15582 (when tags
15583 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15584 tags-alist
15585 (cons (cons level tags) tags-alist)))
15586 ;; compile tags for current headline
15587 (setq tags-list
15588 (if org-use-tag-inheritance
15589 (apply 'append (mapcar 'cdr tags-alist))
15590 tags))
15591 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15592 (eval matcher)
15593 (or (not org-agenda-skip-archived-trees)
15594 (not (member org-archive-tag tags-list))))
15595 (and (eq action 'agenda) (org-agenda-skip))
15596 ;; list this headline
15598 (if (eq action 'sparse-tree)
15599 (progn
15600 (and org-highlight-sparse-tree-matches
15601 (org-get-heading) (match-end 0)
15602 (org-highlight-new-match
15603 (match-beginning 0) (match-beginning 1)))
15604 (org-show-context 'tags-tree))
15605 (setq txt (org-format-agenda-item
15607 (concat
15608 (if org-tags-match-list-sublevels
15609 (make-string (1- level) ?.) "")
15610 (org-get-heading))
15611 category tags-list)
15612 priority (org-get-priority txt))
15613 (goto-char lspos)
15614 (setq marker (org-agenda-new-marker))
15615 (org-add-props txt props
15616 'org-marker marker 'org-hd-marker marker 'org-category category
15617 'priority priority 'type "tagsmatch")
15618 (push txt rtn))
15619 ;; if we are to skip sublevels, jump to end of subtree
15620 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15621 (when (and (eq action 'sparse-tree)
15622 (not org-sparse-tree-open-archived-trees))
15623 (org-hide-archived-subtrees (point-min) (point-max)))
15624 (nreverse rtn)))
15626 (defvar todo-only) ;; dynamically scoped
15628 (defun org-tags-sparse-tree (&optional todo-only match)
15629 "Create a sparse tree according to tags string MATCH.
15630 MATCH can contain positive and negative selection of tags, like
15631 \"+WORK+URGENT-WITHBOSS\".
15632 If optional argument TODO_ONLY is non-nil, only select lines that are
15633 also TODO lines."
15634 (interactive "P")
15635 (org-prepare-agenda-buffers (list (current-buffer)))
15636 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15638 (defvar org-cached-props nil)
15639 (defun org-cached-entry-get (pom property)
15640 (if (or (eq t org-use-property-inheritance)
15641 (member property org-use-property-inheritance))
15642 ;; Caching is not possible, check it directly
15643 (org-entry-get pom property 'inherit)
15644 ;; Get all properties, so that we can do complicated checks easily
15645 (cdr (assoc property (or org-cached-props
15646 (setq org-cached-props
15647 (org-entry-properties pom)))))))
15649 (defun org-global-tags-completion-table (&optional files)
15650 "Return the list of all tags in all agenda buffer/files."
15651 (save-excursion
15652 (org-uniquify
15653 (delq nil
15654 (apply 'append
15655 (mapcar
15656 (lambda (file)
15657 (set-buffer (find-file-noselect file))
15658 (append (org-get-buffer-tags)
15659 (mapcar (lambda (x) (if (stringp (car-safe x))
15660 (list (car-safe x)) nil))
15661 org-tag-alist)))
15662 (if (and files (car files))
15663 files
15664 (org-agenda-files))))))))
15666 (defun org-make-tags-matcher (match)
15667 "Create the TAGS//TODO matcher form for the selection string MATCH."
15668 ;; todo-only is scoped dynamically into this function, and the function
15669 ;; may change it it the matcher asksk for it.
15670 (unless match
15671 ;; Get a new match request, with completion
15672 (let ((org-last-tags-completion-table
15673 (org-global-tags-completion-table)))
15674 (setq match (completing-read
15675 "Match: " 'org-tags-completion-function nil nil nil
15676 'org-tags-history))))
15678 ;; Parse the string and create a lisp form
15679 (let ((match0 match)
15680 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15681 minus tag mm
15682 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15683 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15684 (if (string-match "/+" match)
15685 ;; match contains also a todo-matching request
15686 (progn
15687 (setq tagsmatch (substring match 0 (match-beginning 0))
15688 todomatch (substring match (match-end 0)))
15689 (if (string-match "^!" todomatch)
15690 (setq todo-only t todomatch (substring todomatch 1)))
15691 (if (string-match "^\\s-*$" todomatch)
15692 (setq todomatch nil)))
15693 ;; only matching tags
15694 (setq tagsmatch match todomatch nil))
15696 ;; Make the tags matcher
15697 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15698 (setq tagsmatcher t)
15699 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15700 (while (setq term (pop orterms))
15701 (while (and (equal (substring term -1) "\\") orterms)
15702 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15703 (while (string-match re term)
15704 (setq minus (and (match-end 1)
15705 (equal (match-string 1 term) "-"))
15706 tag (match-string 2 term)
15707 re-p (equal (string-to-char tag) ?{)
15708 level-p (match-end 3)
15709 prop-p (match-end 4)
15710 mm (cond
15711 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15712 (level-p `(= level ,(string-to-number
15713 (match-string 3 term))))
15714 (prop-p
15715 (setq pn (match-string 4 term)
15716 pv (match-string 5 term)
15717 cat-p (equal pn "CATEGORY")
15718 re-p (equal (string-to-char pv) ?{)
15719 pv (substring pv 1 -1))
15720 (if (equal pn "CATEGORY")
15721 (setq gv '(get-text-property (point) 'org-category))
15722 (setq gv `(org-cached-entry-get nil ,pn)))
15723 (if re-p
15724 `(string-match ,pv (or ,gv ""))
15725 `(equal ,pv (or ,gv ""))))
15726 (t `(member ,(downcase tag) tags-list)))
15727 mm (if minus (list 'not mm) mm)
15728 term (substring term (match-end 0)))
15729 (push mm tagsmatcher))
15730 (push (if (> (length tagsmatcher) 1)
15731 (cons 'and tagsmatcher)
15732 (car tagsmatcher))
15733 orlist)
15734 (setq tagsmatcher nil))
15735 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15736 (setq tagsmatcher
15737 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15739 ;; Make the todo matcher
15740 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15741 (setq todomatcher t)
15742 (setq orterms (org-split-string todomatch "|") orlist nil)
15743 (while (setq term (pop orterms))
15744 (while (string-match re term)
15745 (setq minus (and (match-end 1)
15746 (equal (match-string 1 term) "-"))
15747 kwd (match-string 2 term)
15748 re-p (equal (string-to-char kwd) ?{)
15749 term (substring term (match-end 0))
15750 mm (if re-p
15751 `(string-match ,(substring kwd 1 -1) todo)
15752 (list 'equal 'todo kwd))
15753 mm (if minus (list 'not mm) mm))
15754 (push mm todomatcher))
15755 (push (if (> (length todomatcher) 1)
15756 (cons 'and todomatcher)
15757 (car todomatcher))
15758 orlist)
15759 (setq todomatcher nil))
15760 (setq todomatcher (if (> (length orlist) 1)
15761 (cons 'or orlist) (car orlist))))
15763 ;; Return the string and lisp forms of the matcher
15764 (setq matcher (if todomatcher
15765 (list 'and tagsmatcher todomatcher)
15766 tagsmatcher))
15767 (cons match0 matcher)))
15769 (defun org-match-any-p (re list)
15770 "Does re match any element of list?"
15771 (setq list (mapcar (lambda (x) (string-match re x)) list))
15772 (delq nil list))
15774 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15775 (defvar org-tags-overlay (org-make-overlay 1 1))
15776 (org-detach-overlay org-tags-overlay)
15778 (defun org-align-tags-here (to-col)
15779 ;; Assumes that this is a headline
15780 (let ((pos (point)) (col (current-column)) tags)
15781 (beginning-of-line 1)
15782 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15783 (< pos (match-beginning 2)))
15784 (progn
15785 (setq tags (match-string 2))
15786 (goto-char (match-beginning 1))
15787 (insert " ")
15788 (delete-region (point) (1+ (match-end 0)))
15789 (backward-char 1)
15790 (move-to-column
15791 (max (1+ (current-column))
15792 (1+ col)
15793 (if (> to-col 0)
15794 to-col
15795 (- (abs to-col) (length tags))))
15797 (insert tags)
15798 (move-to-column (min (current-column) col) t))
15799 (goto-char pos))))
15801 (defun org-set-tags (&optional arg just-align)
15802 "Set the tags for the current headline.
15803 With prefix ARG, realign all tags in headings in the current buffer."
15804 (interactive "P")
15805 (let* ((re (concat "^" outline-regexp))
15806 (current (org-get-tags-string))
15807 (col (current-column))
15808 (org-setting-tags t)
15809 table current-tags inherited-tags ; computed below when needed
15810 tags p0 c0 c1 rpl)
15811 (if arg
15812 (save-excursion
15813 (goto-char (point-min))
15814 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15815 (while (re-search-forward re nil t)
15816 (org-set-tags nil t)
15817 (end-of-line 1)))
15818 (message "All tags realigned to column %d" org-tags-column))
15819 (if just-align
15820 (setq tags current)
15821 ;; Get a new set of tags from the user
15822 (save-excursion
15823 (setq table (or org-tag-alist (org-get-buffer-tags))
15824 org-last-tags-completion-table table
15825 current-tags (org-split-string current ":")
15826 inherited-tags (nreverse
15827 (nthcdr (length current-tags)
15828 (nreverse (org-get-tags-at))))
15829 tags
15830 (if (or (eq t org-use-fast-tag-selection)
15831 (and org-use-fast-tag-selection
15832 (delq nil (mapcar 'cdr table))))
15833 (org-fast-tag-selection
15834 current-tags inherited-tags table
15835 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15836 (let ((org-add-colon-after-tag-completion t))
15837 (org-trim
15838 (org-without-partial-completion
15839 (completing-read "Tags: " 'org-tags-completion-function
15840 nil nil current 'org-tags-history)))))))
15841 (while (string-match "[-+&]+" tags)
15842 ;; No boolean logic, just a list
15843 (setq tags (replace-match ":" t t tags))))
15845 (if (string-match "\\`[\t ]*\\'" tags)
15846 (setq tags "")
15847 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15848 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15850 ;; Insert new tags at the correct column
15851 (beginning-of-line 1)
15852 (cond
15853 ((and (equal current "") (equal tags "")))
15854 ((re-search-forward
15855 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15856 (point-at-eol) t)
15857 (if (equal tags "")
15858 (setq rpl "")
15859 (goto-char (match-beginning 0))
15860 (setq c0 (current-column) p0 (point)
15861 c1 (max (1+ c0) (if (> org-tags-column 0)
15862 org-tags-column
15863 (- (- org-tags-column) (length tags))))
15864 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15865 (replace-match rpl t t)
15866 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15867 tags)
15868 (t (error "Tags alignment failed")))
15869 (move-to-column col)
15870 (unless just-align
15871 (run-hooks 'org-after-tags-change-hook)))))
15873 (defun org-change-tag-in-region (beg end tag off)
15874 "Add or remove TAG for each entry in the region.
15875 This works in the agenda, and also in an org-mode buffer."
15876 (interactive
15877 (list (region-beginning) (region-end)
15878 (let ((org-last-tags-completion-table
15879 (if (org-mode-p)
15880 (org-get-buffer-tags)
15881 (org-global-tags-completion-table))))
15882 (completing-read
15883 "Tag: " 'org-tags-completion-function nil nil nil
15884 'org-tags-history))
15885 (progn
15886 (message "[s]et or [r]emove? ")
15887 (equal (read-char-exclusive) ?r))))
15888 (if (fboundp 'deactivate-mark) (deactivate-mark))
15889 (let ((agendap (equal major-mode 'org-agenda-mode))
15890 l1 l2 m buf pos newhead (cnt 0))
15891 (goto-char end)
15892 (setq l2 (1- (org-current-line)))
15893 (goto-char beg)
15894 (setq l1 (org-current-line))
15895 (loop for l from l1 to l2 do
15896 (goto-line l)
15897 (setq m (get-text-property (point) 'org-hd-marker))
15898 (when (or (and (org-mode-p) (org-on-heading-p))
15899 (and agendap m))
15900 (setq buf (if agendap (marker-buffer m) (current-buffer))
15901 pos (if agendap m (point)))
15902 (with-current-buffer buf
15903 (save-excursion
15904 (save-restriction
15905 (goto-char pos)
15906 (setq cnt (1+ cnt))
15907 (org-toggle-tag tag (if off 'off 'on))
15908 (setq newhead (org-get-heading)))))
15909 (and agendap (org-agenda-change-all-lines newhead m))))
15910 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15912 (defun org-tags-completion-function (string predicate &optional flag)
15913 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15914 (confirm (lambda (x) (stringp (car x)))))
15915 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15916 (setq s1 (match-string 1 string)
15917 s2 (match-string 2 string))
15918 (setq s1 "" s2 string))
15919 (cond
15920 ((eq flag nil)
15921 ;; try completion
15922 (setq rtn (try-completion s2 ctable confirm))
15923 (if (stringp rtn)
15924 (setq rtn
15925 (concat s1 s2 (substring rtn (length s2))
15926 (if (and org-add-colon-after-tag-completion
15927 (assoc rtn ctable))
15928 ":" ""))))
15929 rtn)
15930 ((eq flag t)
15931 ;; all-completions
15932 (all-completions s2 ctable confirm)
15934 ((eq flag 'lambda)
15935 ;; exact match?
15936 (assoc s2 ctable)))
15939 (defun org-fast-tag-insert (kwd tags face &optional end)
15940 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15941 (insert (format "%-12s" (concat kwd ":"))
15942 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15943 (or end "")))
15945 (defun org-fast-tag-show-exit (flag)
15946 (save-excursion
15947 (goto-line 3)
15948 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15949 (replace-match ""))
15950 (when flag
15951 (end-of-line 1)
15952 (move-to-column (- (window-width) 19) t)
15953 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15955 (defun org-set-current-tags-overlay (current prefix)
15956 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15957 (if (featurep 'xemacs)
15958 (org-overlay-display org-tags-overlay (concat prefix s)
15959 'secondary-selection)
15960 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15961 (org-overlay-display org-tags-overlay (concat prefix s)))))
15963 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15964 "Fast tag selection with single keys.
15965 CURRENT is the current list of tags in the headline, INHERITED is the
15966 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15967 possibly with grouping information. TODO-TABLE is a similar table with
15968 TODO keywords, should these have keys assigned to them.
15969 If the keys are nil, a-z are automatically assigned.
15970 Returns the new tags string, or nil to not change the current settings."
15971 (let* ((fulltable (append table todo-table))
15972 (maxlen (apply 'max (mapcar
15973 (lambda (x)
15974 (if (stringp (car x)) (string-width (car x)) 0))
15975 fulltable)))
15976 (buf (current-buffer))
15977 (expert (eq org-fast-tag-selection-single-key 'expert))
15978 (buffer-tags nil)
15979 (fwidth (+ maxlen 3 1 3))
15980 (ncol (/ (- (window-width) 4) fwidth))
15981 (i-face 'org-done)
15982 (c-face 'org-todo)
15983 tg cnt e c char c1 c2 ntable tbl rtn
15984 ov-start ov-end ov-prefix
15985 (exit-after-next org-fast-tag-selection-single-key)
15986 (done-keywords org-done-keywords)
15987 groups ingroup)
15988 (save-excursion
15989 (beginning-of-line 1)
15990 (if (looking-at
15991 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15992 (setq ov-start (match-beginning 1)
15993 ov-end (match-end 1)
15994 ov-prefix "")
15995 (setq ov-start (1- (point-at-eol))
15996 ov-end (1+ ov-start))
15997 (skip-chars-forward "^\n\r")
15998 (setq ov-prefix
15999 (concat
16000 (buffer-substring (1- (point)) (point))
16001 (if (> (current-column) org-tags-column)
16003 (make-string (- org-tags-column (current-column)) ?\ ))))))
16004 (org-move-overlay org-tags-overlay ov-start ov-end)
16005 (save-window-excursion
16006 (if expert
16007 (set-buffer (get-buffer-create " *Org tags*"))
16008 (delete-other-windows)
16009 (split-window-vertically)
16010 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
16011 (erase-buffer)
16012 (org-set-local 'org-done-keywords done-keywords)
16013 (org-fast-tag-insert "Inherited" inherited i-face "\n")
16014 (org-fast-tag-insert "Current" current c-face "\n\n")
16015 (org-fast-tag-show-exit exit-after-next)
16016 (org-set-current-tags-overlay current ov-prefix)
16017 (setq tbl fulltable char ?a cnt 0)
16018 (while (setq e (pop tbl))
16019 (cond
16020 ((equal e '(:startgroup))
16021 (push '() groups) (setq ingroup t)
16022 (when (not (= cnt 0))
16023 (setq cnt 0)
16024 (insert "\n"))
16025 (insert "{ "))
16026 ((equal e '(:endgroup))
16027 (setq ingroup nil cnt 0)
16028 (insert "}\n"))
16030 (setq tg (car e) c2 nil)
16031 (if (cdr e)
16032 (setq c (cdr e))
16033 ;; automatically assign a character.
16034 (setq c1 (string-to-char
16035 (downcase (substring
16036 tg (if (= (string-to-char tg) ?@) 1 0)))))
16037 (if (or (rassoc c1 ntable) (rassoc c1 table))
16038 (while (or (rassoc char ntable) (rassoc char table))
16039 (setq char (1+ char)))
16040 (setq c2 c1))
16041 (setq c (or c2 char)))
16042 (if ingroup (push tg (car groups)))
16043 (setq tg (org-add-props tg nil 'face
16044 (cond
16045 ((not (assoc tg table))
16046 (org-get-todo-face tg))
16047 ((member tg current) c-face)
16048 ((member tg inherited) i-face)
16049 (t nil))))
16050 (if (and (= cnt 0) (not ingroup)) (insert " "))
16051 (insert "[" c "] " tg (make-string
16052 (- fwidth 4 (length tg)) ?\ ))
16053 (push (cons tg c) ntable)
16054 (when (= (setq cnt (1+ cnt)) ncol)
16055 (insert "\n")
16056 (if ingroup (insert " "))
16057 (setq cnt 0)))))
16058 (setq ntable (nreverse ntable))
16059 (insert "\n")
16060 (goto-char (point-min))
16061 (if (and (not expert) (fboundp 'fit-window-to-buffer))
16062 (fit-window-to-buffer))
16063 (setq rtn
16064 (catch 'exit
16065 (while t
16066 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
16067 (if groups " [!] no groups" " [!]groups")
16068 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
16069 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
16070 (cond
16071 ((= c ?\r) (throw 'exit t))
16072 ((= c ?!)
16073 (setq groups (not groups))
16074 (goto-char (point-min))
16075 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
16076 ((= c ?\C-c)
16077 (if (not expert)
16078 (org-fast-tag-show-exit
16079 (setq exit-after-next (not exit-after-next)))
16080 (setq expert nil)
16081 (delete-other-windows)
16082 (split-window-vertically)
16083 (org-switch-to-buffer-other-window " *Org tags*")
16084 (and (fboundp 'fit-window-to-buffer)
16085 (fit-window-to-buffer))))
16086 ((or (= c ?\C-g)
16087 (and (= c ?q) (not (rassoc c ntable))))
16088 (org-detach-overlay org-tags-overlay)
16089 (setq quit-flag t))
16090 ((= c ?\ )
16091 (setq current nil)
16092 (if exit-after-next (setq exit-after-next 'now)))
16093 ((= c ?\t)
16094 (condition-case nil
16095 (setq tg (completing-read
16096 "Tag: "
16097 (or buffer-tags
16098 (with-current-buffer buf
16099 (org-get-buffer-tags)))))
16100 (quit (setq tg "")))
16101 (when (string-match "\\S-" tg)
16102 (add-to-list 'buffer-tags (list tg))
16103 (if (member tg current)
16104 (setq current (delete tg current))
16105 (push tg current)))
16106 (if exit-after-next (setq exit-after-next 'now)))
16107 ((setq e (rassoc c todo-table) tg (car e))
16108 (with-current-buffer buf
16109 (save-excursion (org-todo tg)))
16110 (if exit-after-next (setq exit-after-next 'now)))
16111 ((setq e (rassoc c ntable) tg (car e))
16112 (if (member tg current)
16113 (setq current (delete tg current))
16114 (loop for g in groups do
16115 (if (member tg g)
16116 (mapc (lambda (x)
16117 (setq current (delete x current)))
16118 g)))
16119 (push tg current))
16120 (if exit-after-next (setq exit-after-next 'now))))
16122 ;; Create a sorted list
16123 (setq current
16124 (sort current
16125 (lambda (a b)
16126 (assoc b (cdr (memq (assoc a ntable) ntable))))))
16127 (if (eq exit-after-next 'now) (throw 'exit t))
16128 (goto-char (point-min))
16129 (beginning-of-line 2)
16130 (delete-region (point) (point-at-eol))
16131 (org-fast-tag-insert "Current" current c-face)
16132 (org-set-current-tags-overlay current ov-prefix)
16133 (while (re-search-forward
16134 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
16135 (setq tg (match-string 1))
16136 (add-text-properties
16137 (match-beginning 1) (match-end 1)
16138 (list 'face
16139 (cond
16140 ((member tg current) c-face)
16141 ((member tg inherited) i-face)
16142 (t (get-text-property (match-beginning 1) 'face))))))
16143 (goto-char (point-min)))))
16144 (org-detach-overlay org-tags-overlay)
16145 (if rtn
16146 (mapconcat 'identity current ":")
16147 nil))))
16149 (defun org-get-tags-string ()
16150 "Get the TAGS string in the current headline."
16151 (unless (org-on-heading-p t)
16152 (error "Not on a heading"))
16153 (save-excursion
16154 (beginning-of-line 1)
16155 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16156 (org-match-string-no-properties 1)
16157 "")))
16159 (defun org-get-tags ()
16160 "Get the list of tags specified in the current headline."
16161 (org-split-string (org-get-tags-string) ":"))
16163 (defun org-get-buffer-tags ()
16164 "Get a table of all tags used in the buffer, for completion."
16165 (let (tags)
16166 (save-excursion
16167 (goto-char (point-min))
16168 (while (re-search-forward
16169 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
16170 (when (equal (char-after (point-at-bol 0)) ?*)
16171 (mapc (lambda (x) (add-to-list 'tags x))
16172 (org-split-string (org-match-string-no-properties 1) ":")))))
16173 (mapcar 'list tags)))
16176 ;;;; Properties
16178 ;;; Setting and retrieving properties
16180 (defconst org-special-properties
16181 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
16182 "TIMESTAMP" "TIMESTAMP_IA")
16183 "The special properties valid in Org-mode.
16185 These are properties that are not defined in the property drawer,
16186 but in some other way.")
16188 (defconst org-default-properties
16189 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
16190 "LOCATION" "LOGGING" "COLUMNS")
16191 "Some properties that are used by Org-mode for various purposes.
16192 Being in this list makes sure that they are offered for completion.")
16194 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
16195 "Regular expression matching the first line of a property drawer.")
16197 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
16198 "Regular expression matching the first line of a property drawer.")
16200 (defun org-property-action ()
16201 "Do an action on properties."
16202 (interactive)
16203 (let (c)
16204 (org-at-property-p)
16205 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
16206 (setq c (read-char-exclusive))
16207 (cond
16208 ((equal c ?s)
16209 (call-interactively 'org-set-property))
16210 ((equal c ?d)
16211 (call-interactively 'org-delete-property))
16212 ((equal c ?D)
16213 (call-interactively 'org-delete-property-globally))
16214 ((equal c ?c)
16215 (call-interactively 'org-compute-property-at-point))
16216 (t (error "No such property action %c" c)))))
16218 (defun org-at-property-p ()
16219 "Is the cursor in a property line?"
16220 ;; FIXME: Does not check if we are actually in the drawer.
16221 ;; FIXME: also returns true on any drawers.....
16222 ;; This is used by C-c C-c for property action.
16223 (save-excursion
16224 (beginning-of-line 1)
16225 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
16227 (defmacro org-with-point-at (pom &rest body)
16228 "Move to buffer and point of point-or-marker POM for the duration of BODY."
16229 (declare (indent 1) (debug t))
16230 `(save-excursion
16231 (if (markerp pom) (set-buffer (marker-buffer pom)))
16232 (save-excursion
16233 (goto-char (or pom (point)))
16234 ,@body)))
16236 (defun org-get-property-block (&optional beg end force)
16237 "Return the (beg . end) range of the body of the property drawer.
16238 BEG and END can be beginning and end of subtree, if not given
16239 they will be found.
16240 If the drawer does not exist and FORCE is non-nil, create the drawer."
16241 (catch 'exit
16242 (save-excursion
16243 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
16244 (end (or end (progn (outline-next-heading) (point)))))
16245 (goto-char beg)
16246 (if (re-search-forward org-property-start-re end t)
16247 (setq beg (1+ (match-end 0)))
16248 (if force
16249 (save-excursion
16250 (org-insert-property-drawer)
16251 (setq end (progn (outline-next-heading) (point))))
16252 (throw 'exit nil))
16253 (goto-char beg)
16254 (if (re-search-forward org-property-start-re end t)
16255 (setq beg (1+ (match-end 0)))))
16256 (if (re-search-forward org-property-end-re end t)
16257 (setq end (match-beginning 0))
16258 (or force (throw 'exit nil))
16259 (goto-char beg)
16260 (setq end beg)
16261 (org-indent-line-function)
16262 (insert ":END:\n"))
16263 (cons beg end)))))
16265 (defun org-entry-properties (&optional pom which)
16266 "Get all properties of the entry at point-or-marker POM.
16267 This includes the TODO keyword, the tags, time strings for deadline,
16268 scheduled, and clocking, and any additional properties defined in the
16269 entry. The return value is an alist, keys may occur multiple times
16270 if the property key was used several times.
16271 POM may also be nil, in which case the current entry is used.
16272 If WHICH is nil or `all', get all properties. If WHICH is
16273 `special' or `standard', only get that subclass."
16274 (setq which (or which 'all))
16275 (org-with-point-at pom
16276 (let ((clockstr (substring org-clock-string 0 -1))
16277 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
16278 beg end range props sum-props key value string clocksum)
16279 (save-excursion
16280 (when (condition-case nil (org-back-to-heading t) (error nil))
16281 (setq beg (point))
16282 (setq sum-props (get-text-property (point) 'org-summaries))
16283 (setq clocksum (get-text-property (point) :org-clock-minutes))
16284 (outline-next-heading)
16285 (setq end (point))
16286 (when (memq which '(all special))
16287 ;; Get the special properties, like TODO and tags
16288 (goto-char beg)
16289 (when (and (looking-at org-todo-line-regexp) (match-end 2))
16290 (push (cons "TODO" (org-match-string-no-properties 2)) props))
16291 (when (looking-at org-priority-regexp)
16292 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16293 (when (and (setq value (org-get-tags-string))
16294 (string-match "\\S-" value))
16295 (push (cons "TAGS" value) props))
16296 (when (setq value (org-get-tags-at))
16297 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16298 props))
16299 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16300 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16301 string (if (equal key clockstr)
16302 (org-no-properties
16303 (org-trim
16304 (buffer-substring
16305 (match-beginning 3) (goto-char (point-at-eol)))))
16306 (substring (org-match-string-no-properties 3) 1 -1)))
16307 (unless key
16308 (if (= (char-after (match-beginning 3)) ?\[)
16309 (setq key "TIMESTAMP_IA")
16310 (setq key "TIMESTAMP")))
16311 (when (or (equal key clockstr) (not (assoc key props)))
16312 (push (cons key string) props)))
16316 (when (memq which '(all standard))
16317 ;; Get the standard properties, like :PORP: ...
16318 (setq range (org-get-property-block beg end))
16319 (when range
16320 (goto-char (car range))
16321 (while (re-search-forward
16322 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16323 (cdr range) t)
16324 (setq key (org-match-string-no-properties 1)
16325 value (org-trim (or (org-match-string-no-properties 2) "")))
16326 (unless (member key excluded)
16327 (push (cons key (or value "")) props)))))
16328 (if clocksum
16329 (push (cons "CLOCKSUM"
16330 (org-column-number-to-string (/ (float clocksum) 60.)
16331 'add_times))
16332 props))
16333 (append sum-props (nreverse props)))))))
16335 (defun org-entry-get (pom property &optional inherit)
16336 "Get value of PROPERTY for entry at point-or-marker POM.
16337 If INHERIT is non-nil and the entry does not have the property,
16338 then also check higher levels of the hierarchy.
16339 If the property is present but empty, the return value is the empty string.
16340 If the property is not present at all, nil is returned."
16341 (org-with-point-at pom
16342 (if inherit
16343 (org-entry-get-with-inheritance property)
16344 (if (member property org-special-properties)
16345 ;; We need a special property. Use brute force, get all properties.
16346 (cdr (assoc property (org-entry-properties nil 'special)))
16347 (let ((range (org-get-property-block)))
16348 (if (and range
16349 (goto-char (car range))
16350 (re-search-forward
16351 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16352 (cdr range) t))
16353 ;; Found the property, return it.
16354 (if (match-end 1)
16355 (org-match-string-no-properties 1)
16356 "")))))))
16358 (defun org-entry-delete (pom property)
16359 "Delete the property PROPERTY from entry at point-or-marker POM."
16360 (org-with-point-at pom
16361 (if (member property org-special-properties)
16362 nil ; cannot delete these properties.
16363 (let ((range (org-get-property-block)))
16364 (if (and range
16365 (goto-char (car range))
16366 (re-search-forward
16367 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16368 (cdr range) t))
16369 (progn
16370 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16372 nil)))))
16374 ;; Multi-values properties are properties that contain multiple values
16375 ;; These values are assumed to be single words, separated by whitespace.
16376 (defun org-entry-add-to-multivalued-property (pom property value)
16377 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16378 (let* ((old (org-entry-get pom property))
16379 (values (and old (org-split-string old "[ \t]"))))
16380 (unless (member value values)
16381 (setq values (cons value values))
16382 (org-entry-put pom property
16383 (mapconcat 'identity values " ")))))
16385 (defun org-entry-remove-from-multivalued-property (pom property value)
16386 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16387 (let* ((old (org-entry-get pom property))
16388 (values (and old (org-split-string old "[ \t]"))))
16389 (when (member value values)
16390 (setq values (delete value values))
16391 (org-entry-put pom property
16392 (mapconcat 'identity values " ")))))
16394 (defun org-entry-member-in-multivalued-property (pom property value)
16395 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16396 (let* ((old (org-entry-get pom property))
16397 (values (and old (org-split-string old "[ \t]"))))
16398 (member value values)))
16400 (defvar org-entry-property-inherited-from (make-marker))
16402 (defun org-entry-get-with-inheritance (property)
16403 "Get entry property, and search higher levels if not present."
16404 (let (tmp)
16405 (save-excursion
16406 (save-restriction
16407 (widen)
16408 (catch 'ex
16409 (while t
16410 (when (setq tmp (org-entry-get nil property))
16411 (org-back-to-heading t)
16412 (move-marker org-entry-property-inherited-from (point))
16413 (throw 'ex tmp))
16414 (or (org-up-heading-safe) (throw 'ex nil)))))
16415 (or tmp (cdr (assoc property org-local-properties))
16416 (cdr (assoc property org-global-properties))))))
16418 (defun org-entry-put (pom property value)
16419 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16420 (org-with-point-at pom
16421 (org-back-to-heading t)
16422 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16423 range)
16424 (cond
16425 ((equal property "TODO")
16426 (when (and (stringp value) (string-match "\\S-" value)
16427 (not (member value org-todo-keywords-1)))
16428 (error "\"%s\" is not a valid TODO state" value))
16429 (if (or (not value)
16430 (not (string-match "\\S-" value)))
16431 (setq value 'none))
16432 (org-todo value)
16433 (org-set-tags nil 'align))
16434 ((equal property "PRIORITY")
16435 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16436 (string-to-char value) ?\ ))
16437 (org-set-tags nil 'align))
16438 ((equal property "SCHEDULED")
16439 (if (re-search-forward org-scheduled-time-regexp end t)
16440 (cond
16441 ((eq value 'earlier) (org-timestamp-change -1 'day))
16442 ((eq value 'later) (org-timestamp-change 1 'day))
16443 (t (call-interactively 'org-schedule)))
16444 (call-interactively 'org-schedule)))
16445 ((equal property "DEADLINE")
16446 (if (re-search-forward org-deadline-time-regexp end t)
16447 (cond
16448 ((eq value 'earlier) (org-timestamp-change -1 'day))
16449 ((eq value 'later) (org-timestamp-change 1 'day))
16450 (t (call-interactively 'org-deadline)))
16451 (call-interactively 'org-deadline)))
16452 ((member property org-special-properties)
16453 (error "The %s property can not yet be set with `org-entry-put'"
16454 property))
16455 (t ; a non-special property
16456 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16457 (setq range (org-get-property-block beg end 'force))
16458 (goto-char (car range))
16459 (if (re-search-forward
16460 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16461 (progn
16462 (delete-region (match-beginning 1) (match-end 1))
16463 (goto-char (match-beginning 1)))
16464 (goto-char (cdr range))
16465 (insert "\n")
16466 (backward-char 1)
16467 (org-indent-line-function)
16468 (insert ":" property ":"))
16469 (and value (insert " " value))
16470 (org-indent-line-function)))))))
16472 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16473 "Get all property keys in the current buffer.
16474 With INCLUDE-SPECIALS, also list the special properties that relect things
16475 like tags and TODO state.
16476 With INCLUDE-DEFAULTS, also include properties that has special meaning
16477 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16478 With INCLUDE-COLUMNS, also include property names given in COLUMN
16479 formats in the current buffer."
16480 (let (rtn range cfmt cols s p)
16481 (save-excursion
16482 (save-restriction
16483 (widen)
16484 (goto-char (point-min))
16485 (while (re-search-forward org-property-start-re nil t)
16486 (setq range (org-get-property-block))
16487 (goto-char (car range))
16488 (while (re-search-forward
16489 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16490 (cdr range) t)
16491 (add-to-list 'rtn (org-match-string-no-properties 1)))
16492 (outline-next-heading))))
16494 (when include-specials
16495 (setq rtn (append org-special-properties rtn)))
16497 (when include-defaults
16498 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16500 (when include-columns
16501 (save-excursion
16502 (save-restriction
16503 (widen)
16504 (goto-char (point-min))
16505 (while (re-search-forward
16506 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16507 nil t)
16508 (setq cfmt (match-string 2) s 0)
16509 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16510 cfmt s)
16511 (setq s (match-end 0)
16512 p (match-string 1 cfmt))
16513 (unless (or (equal p "ITEM")
16514 (member p org-special-properties))
16515 (add-to-list 'rtn (match-string 1 cfmt))))))))
16517 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16519 (defun org-property-values (key)
16520 "Return a list of all values of property KEY."
16521 (save-excursion
16522 (save-restriction
16523 (widen)
16524 (goto-char (point-min))
16525 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16526 values)
16527 (while (re-search-forward re nil t)
16528 (add-to-list 'values (org-trim (match-string 1))))
16529 (delete "" values)))))
16531 (defun org-insert-property-drawer ()
16532 "Insert a property drawer into the current entry."
16533 (interactive)
16534 (org-back-to-heading t)
16535 (looking-at outline-regexp)
16536 (let ((indent (- (match-end 0)(match-beginning 0)))
16537 (beg (point))
16538 (re (concat "^[ \t]*" org-keyword-time-regexp))
16539 end hiddenp)
16540 (outline-next-heading)
16541 (setq end (point))
16542 (goto-char beg)
16543 (while (re-search-forward re end t))
16544 (setq hiddenp (org-invisible-p))
16545 (end-of-line 1)
16546 (and (equal (char-after) ?\n) (forward-char 1))
16547 (org-skip-over-state-notes)
16548 (skip-chars-backward " \t\n\r")
16549 (if (eq (char-before) ?*) (forward-char 1))
16550 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16551 (beginning-of-line 0)
16552 (indent-to-column indent)
16553 (beginning-of-line 2)
16554 (indent-to-column indent)
16555 (beginning-of-line 0)
16556 (if hiddenp
16557 (save-excursion
16558 (org-back-to-heading t)
16559 (hide-entry))
16560 (org-flag-drawer t))))
16562 (defun org-set-property (property value)
16563 "In the current entry, set PROPERTY to VALUE.
16564 When called interactively, this will prompt for a property name, offering
16565 completion on existing and default properties. And then it will prompt
16566 for a value, offering competion either on allowed values (via an inherited
16567 xxx_ALL property) or on existing values in other instances of this property
16568 in the current file."
16569 (interactive
16570 (let* ((prop (completing-read
16571 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16572 (cur (org-entry-get nil prop))
16573 (allowed (org-property-get-allowed-values nil prop 'table))
16574 (existing (mapcar 'list (org-property-values prop)))
16575 (val (if allowed
16576 (completing-read "Value: " allowed nil 'req-match)
16577 (completing-read
16578 (concat "Value" (if (and cur (string-match "\\S-" cur))
16579 (concat "[" cur "]") "")
16580 ": ")
16581 existing nil nil "" nil cur))))
16582 (list prop (if (equal val "") cur val))))
16583 (unless (equal (org-entry-get nil property) value)
16584 (org-entry-put nil property value)))
16586 (defun org-delete-property (property)
16587 "In the current entry, delete PROPERTY."
16588 (interactive
16589 (let* ((prop (completing-read
16590 "Property: " (org-entry-properties nil 'standard))))
16591 (list prop)))
16592 (message "Property %s %s" property
16593 (if (org-entry-delete nil property)
16594 "deleted"
16595 "was not present in the entry")))
16597 (defun org-delete-property-globally (property)
16598 "Remove PROPERTY globally, from all entries."
16599 (interactive
16600 (let* ((prop (completing-read
16601 "Globally remove property: "
16602 (mapcar 'list (org-buffer-property-keys)))))
16603 (list prop)))
16604 (save-excursion
16605 (save-restriction
16606 (widen)
16607 (goto-char (point-min))
16608 (let ((cnt 0))
16609 (while (re-search-forward
16610 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16611 nil t)
16612 (setq cnt (1+ cnt))
16613 (replace-match ""))
16614 (message "Property \"%s\" removed from %d entries" property cnt)))))
16616 (defvar org-columns-current-fmt-compiled) ; defined below
16618 (defun org-compute-property-at-point ()
16619 "Compute the property at point.
16620 This looks for an enclosing column format, extracts the operator and
16621 then applies it to the proerty in the column format's scope."
16622 (interactive)
16623 (unless (org-at-property-p)
16624 (error "Not at a property"))
16625 (let ((prop (org-match-string-no-properties 2)))
16626 (org-columns-get-format-and-top-level)
16627 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16628 (error "No operator defined for property %s" prop))
16629 (org-columns-compute prop)))
16631 (defun org-property-get-allowed-values (pom property &optional table)
16632 "Get allowed values for the property PROPERTY.
16633 When TABLE is non-nil, return an alist that can directly be used for
16634 completion."
16635 (let (vals)
16636 (cond
16637 ((equal property "TODO")
16638 (setq vals (org-with-point-at pom
16639 (append org-todo-keywords-1 '("")))))
16640 ((equal property "PRIORITY")
16641 (let ((n org-lowest-priority))
16642 (while (>= n org-highest-priority)
16643 (push (char-to-string n) vals)
16644 (setq n (1- n)))))
16645 ((member property org-special-properties))
16647 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16649 (when (and vals (string-match "\\S-" vals))
16650 (setq vals (car (read-from-string (concat "(" vals ")"))))
16651 (setq vals (mapcar (lambda (x)
16652 (cond ((stringp x) x)
16653 ((numberp x) (number-to-string x))
16654 ((symbolp x) (symbol-name x))
16655 (t "???")))
16656 vals)))))
16657 (if table (mapcar 'list vals) vals)))
16659 (defun org-property-previous-allowed-value (&optional previous)
16660 "Switch to the next allowed value for this property."
16661 (interactive)
16662 (org-property-next-allowed-value t))
16664 (defun org-property-next-allowed-value (&optional previous)
16665 "Switch to the next allowed value for this property."
16666 (interactive)
16667 (unless (org-at-property-p)
16668 (error "Not at a property"))
16669 (let* ((key (match-string 2))
16670 (value (match-string 3))
16671 (allowed (or (org-property-get-allowed-values (point) key)
16672 (and (member value '("[ ]" "[-]" "[X]"))
16673 '("[ ]" "[X]"))))
16674 nval)
16675 (unless allowed
16676 (error "Allowed values for this property have not been defined"))
16677 (if previous (setq allowed (reverse allowed)))
16678 (if (member value allowed)
16679 (setq nval (car (cdr (member value allowed)))))
16680 (setq nval (or nval (car allowed)))
16681 (if (equal nval value)
16682 (error "Only one allowed value for this property"))
16683 (org-at-property-p)
16684 (replace-match (concat " :" key ": " nval) t t)
16685 (org-indent-line-function)
16686 (beginning-of-line 1)
16687 (skip-chars-forward " \t")))
16689 (defun org-find-entry-with-id (ident)
16690 "Locate the entry that contains the ID property with exact value IDENT.
16691 IDENT can be a string, a symbol or a number, this function will search for
16692 the string representation of it.
16693 Return the position where this entry starts, or nil if there is no such entry."
16694 (let ((id (cond
16695 ((stringp ident) ident)
16696 ((symbol-name ident) (symbol-name ident))
16697 ((numberp ident) (number-to-string ident))
16698 (t (error "IDENT %s must be a string, symbol or number" ident))))
16699 (case-fold-search nil))
16700 (save-excursion
16701 (save-restriction
16702 (widen)
16703 (goto-char (point-min))
16704 (when (re-search-forward
16705 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16706 nil t)
16707 (org-back-to-heading)
16708 (point))))))
16710 ;;; Column View
16712 (defvar org-columns-overlays nil
16713 "Holds the list of current column overlays.")
16715 (defvar org-columns-current-fmt nil
16716 "Local variable, holds the currently active column format.")
16717 (defvar org-columns-current-fmt-compiled nil
16718 "Local variable, holds the currently active column format.
16719 This is the compiled version of the format.")
16720 (defvar org-columns-current-widths nil
16721 "Loval variable, holds the currently widths of fields.")
16722 (defvar org-columns-current-maxwidths nil
16723 "Loval variable, holds the currently active maximum column widths.")
16724 (defvar org-columns-begin-marker (make-marker)
16725 "Points to the position where last a column creation command was called.")
16726 (defvar org-columns-top-level-marker (make-marker)
16727 "Points to the position where current columns region starts.")
16729 (defvar org-columns-map (make-sparse-keymap)
16730 "The keymap valid in column display.")
16732 (defun org-columns-content ()
16733 "Switch to contents view while in columns view."
16734 (interactive)
16735 (org-overview)
16736 (org-content))
16738 (org-defkey org-columns-map "c" 'org-columns-content)
16739 (org-defkey org-columns-map "o" 'org-overview)
16740 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16741 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16742 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16743 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16744 (org-defkey org-columns-map "v" 'org-columns-show-value)
16745 (org-defkey org-columns-map "q" 'org-columns-quit)
16746 (org-defkey org-columns-map "r" 'org-columns-redo)
16747 (org-defkey org-columns-map "g" 'org-columns-redo)
16748 (org-defkey org-columns-map [left] 'backward-char)
16749 (org-defkey org-columns-map "\M-b" 'backward-char)
16750 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16751 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16752 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16753 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16754 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16755 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16756 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16757 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16758 (org-defkey org-columns-map "<" 'org-columns-narrow)
16759 (org-defkey org-columns-map ">" 'org-columns-widen)
16760 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16761 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16762 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16763 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16765 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16766 '("Column"
16767 ["Edit property" org-columns-edit-value t]
16768 ["Next allowed value" org-columns-next-allowed-value t]
16769 ["Previous allowed value" org-columns-previous-allowed-value t]
16770 ["Show full value" org-columns-show-value t]
16771 ["Edit allowed values" org-columns-edit-allowed t]
16772 "--"
16773 ["Edit column attributes" org-columns-edit-attributes t]
16774 ["Increase column width" org-columns-widen t]
16775 ["Decrease column width" org-columns-narrow t]
16776 "--"
16777 ["Move column right" org-columns-move-right t]
16778 ["Move column left" org-columns-move-left t]
16779 ["Add column" org-columns-new t]
16780 ["Delete column" org-columns-delete t]
16781 "--"
16782 ["CONTENTS" org-columns-content t]
16783 ["OVERVIEW" org-overview t]
16784 ["Refresh columns display" org-columns-redo t]
16785 "--"
16786 ["Open link" org-columns-open-link t]
16787 "--"
16788 ["Quit" org-columns-quit t]))
16790 (defun org-columns-new-overlay (beg end &optional string face)
16791 "Create a new column overlay and add it to the list."
16792 (let ((ov (org-make-overlay beg end)))
16793 (org-overlay-put ov 'face (or face 'secondary-selection))
16794 (org-overlay-display ov string face)
16795 (push ov org-columns-overlays)
16796 ov))
16798 (defun org-columns-display-here (&optional props)
16799 "Overlay the current line with column display."
16800 (interactive)
16801 (let* ((fmt org-columns-current-fmt-compiled)
16802 (beg (point-at-bol))
16803 (level-face (save-excursion
16804 (beginning-of-line 1)
16805 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16806 (org-get-level-face 2))))
16807 (color (list :foreground
16808 (face-attribute (or level-face 'default) :foreground)))
16809 props pom property ass width f string ov column val modval)
16810 ;; Check if the entry is in another buffer.
16811 (unless props
16812 (if (eq major-mode 'org-agenda-mode)
16813 (setq pom (or (get-text-property (point) 'org-hd-marker)
16814 (get-text-property (point) 'org-marker))
16815 props (if pom (org-entry-properties pom) nil))
16816 (setq props (org-entry-properties nil))))
16817 ;; Walk the format
16818 (while (setq column (pop fmt))
16819 (setq property (car column)
16820 ass (if (equal property "ITEM")
16821 (cons "ITEM"
16822 (save-match-data
16823 (org-no-properties
16824 (org-remove-tabs
16825 (buffer-substring-no-properties
16826 (point-at-bol) (point-at-eol))))))
16827 (assoc property props))
16828 width (or (cdr (assoc property org-columns-current-maxwidths))
16829 (nth 2 column)
16830 (length property))
16831 f (format "%%-%d.%ds | " width width)
16832 val (or (cdr ass) "")
16833 modval (if (equal property "ITEM")
16834 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16835 string (format f (or modval val)))
16836 ;; Create the overlay
16837 (org-unmodified
16838 (setq ov (org-columns-new-overlay
16839 beg (setq beg (1+ beg)) string
16840 (list color 'org-column)))
16841 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16842 (org-overlay-put ov 'keymap org-columns-map)
16843 (org-overlay-put ov 'org-columns-key property)
16844 (org-overlay-put ov 'org-columns-value (cdr ass))
16845 (org-overlay-put ov 'org-columns-value-modified modval)
16846 (org-overlay-put ov 'org-columns-pom pom)
16847 (org-overlay-put ov 'org-columns-format f))
16848 (if (or (not (char-after beg))
16849 (equal (char-after beg) ?\n))
16850 (let ((inhibit-read-only t))
16851 (save-excursion
16852 (goto-char beg)
16853 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16854 ;; Make the rest of the line disappear.
16855 (org-unmodified
16856 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16857 (org-overlay-put ov 'invisible t)
16858 (org-overlay-put ov 'keymap org-columns-map)
16859 (org-overlay-put ov 'intangible t)
16860 (push ov org-columns-overlays)
16861 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16862 (org-overlay-put ov 'keymap org-columns-map)
16863 (push ov org-columns-overlays)
16864 (let ((inhibit-read-only t))
16865 (put-text-property (max (point-min) (1- (point-at-bol)))
16866 (min (point-max) (1+ (point-at-eol)))
16867 'read-only "Type `e' to edit property")))))
16869 (defvar org-previous-header-line-format nil
16870 "The header line format before column view was turned on.")
16871 (defvar org-columns-inhibit-recalculation nil
16872 "Inhibit recomputing of columns on column view startup.")
16875 (defvar header-line-format)
16876 (defun org-columns-display-here-title ()
16877 "Overlay the newline before the current line with the table title."
16878 (interactive)
16879 (let ((fmt org-columns-current-fmt-compiled)
16880 string (title "")
16881 property width f column str widths)
16882 (while (setq column (pop fmt))
16883 (setq property (car column)
16884 str (or (nth 1 column) property)
16885 width (or (cdr (assoc property org-columns-current-maxwidths))
16886 (nth 2 column)
16887 (length str))
16888 widths (push width widths)
16889 f (format "%%-%d.%ds | " width width)
16890 string (format f str)
16891 title (concat title string)))
16892 (setq title (concat
16893 (org-add-props " " nil 'display '(space :align-to 0))
16894 (org-add-props title nil 'face '(:weight bold :underline t))))
16895 (org-set-local 'org-previous-header-line-format header-line-format)
16896 (org-set-local 'org-columns-current-widths (nreverse widths))
16897 (setq header-line-format title)))
16899 (defun org-columns-remove-overlays ()
16900 "Remove all currently active column overlays."
16901 (interactive)
16902 (when (marker-buffer org-columns-begin-marker)
16903 (with-current-buffer (marker-buffer org-columns-begin-marker)
16904 (when (local-variable-p 'org-previous-header-line-format)
16905 (setq header-line-format org-previous-header-line-format)
16906 (kill-local-variable 'org-previous-header-line-format))
16907 (move-marker org-columns-begin-marker nil)
16908 (move-marker org-columns-top-level-marker nil)
16909 (org-unmodified
16910 (mapc 'org-delete-overlay org-columns-overlays)
16911 (setq org-columns-overlays nil)
16912 (let ((inhibit-read-only t))
16913 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16915 (defun org-columns-cleanup-item (item fmt)
16916 "Remove from ITEM what is a column in the format FMT."
16917 (if (not org-complex-heading-regexp)
16918 item
16919 (when (string-match org-complex-heading-regexp item)
16920 (concat
16921 (org-add-props (concat (match-string 1 item) " ") nil
16922 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16923 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16924 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16925 " " (match-string 4 item)
16926 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16928 (defun org-columns-show-value ()
16929 "Show the full value of the property."
16930 (interactive)
16931 (let ((value (get-char-property (point) 'org-columns-value)))
16932 (message "Value is: %s" (or value ""))))
16934 (defun org-columns-quit ()
16935 "Remove the column overlays and in this way exit column editing."
16936 (interactive)
16937 (org-unmodified
16938 (org-columns-remove-overlays)
16939 (let ((inhibit-read-only t))
16940 (remove-text-properties (point-min) (point-max) '(read-only t))))
16941 (when (eq major-mode 'org-agenda-mode)
16942 (message
16943 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16945 (defun org-columns-check-computed ()
16946 "Check if this column value is computed.
16947 If yes, throw an error indicating that changing it does not make sense."
16948 (let ((val (get-char-property (point) 'org-columns-value)))
16949 (when (and (stringp val)
16950 (get-char-property 0 'org-computed val))
16951 (error "This value is computed from the entry's children"))))
16953 (defun org-columns-todo (&optional arg)
16954 "Change the TODO state during column view."
16955 (interactive "P")
16956 (org-columns-edit-value "TODO"))
16958 (defun org-columns-set-tags-or-toggle (&optional arg)
16959 "Toggle checkbox at point, or set tags for current headline."
16960 (interactive "P")
16961 (if (string-match "\\`\\[[ xX-]\\]\\'"
16962 (get-char-property (point) 'org-columns-value))
16963 (org-columns-next-allowed-value)
16964 (org-columns-edit-value "TAGS")))
16966 (defun org-columns-edit-value (&optional key)
16967 "Edit the value of the property at point in column view.
16968 Where possible, use the standard interface for changing this line."
16969 (interactive)
16970 (org-columns-check-computed)
16971 (let* ((external-key key)
16972 (col (current-column))
16973 (key (or key (get-char-property (point) 'org-columns-key)))
16974 (value (get-char-property (point) 'org-columns-value))
16975 (bol (point-at-bol)) (eol (point-at-eol))
16976 (pom (or (get-text-property bol 'org-hd-marker)
16977 (point))) ; keep despite of compiler waring
16978 (line-overlays
16979 (delq nil (mapcar (lambda (x)
16980 (and (eq (overlay-buffer x) (current-buffer))
16981 (>= (overlay-start x) bol)
16982 (<= (overlay-start x) eol)
16984 org-columns-overlays)))
16985 nval eval allowed)
16986 (cond
16987 ((equal key "CLOCKSUM")
16988 (error "This special column cannot be edited"))
16989 ((equal key "ITEM")
16990 (setq eval '(org-with-point-at pom
16991 (org-edit-headline))))
16992 ((equal key "TODO")
16993 (setq eval '(org-with-point-at pom
16994 (let ((current-prefix-arg
16995 (if external-key current-prefix-arg '(4))))
16996 (call-interactively 'org-todo)))))
16997 ((equal key "PRIORITY")
16998 (setq eval '(org-with-point-at pom
16999 (call-interactively 'org-priority))))
17000 ((equal key "TAGS")
17001 (setq eval '(org-with-point-at pom
17002 (let ((org-fast-tag-selection-single-key
17003 (if (eq org-fast-tag-selection-single-key 'expert)
17004 t org-fast-tag-selection-single-key)))
17005 (call-interactively 'org-set-tags)))))
17006 ((equal key "DEADLINE")
17007 (setq eval '(org-with-point-at pom
17008 (call-interactively 'org-deadline))))
17009 ((equal key "SCHEDULED")
17010 (setq eval '(org-with-point-at pom
17011 (call-interactively 'org-schedule))))
17013 (setq allowed (org-property-get-allowed-values pom key 'table))
17014 (if allowed
17015 (setq nval (completing-read "Value: " allowed nil t))
17016 (setq nval (read-string "Edit: " value)))
17017 (setq nval (org-trim nval))
17018 (when (not (equal nval value))
17019 (setq eval '(org-entry-put pom key nval)))))
17020 (when eval
17021 (let ((inhibit-read-only t))
17022 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
17023 (unwind-protect
17024 (progn
17025 (setq org-columns-overlays
17026 (org-delete-all line-overlays org-columns-overlays))
17027 (mapc 'org-delete-overlay line-overlays)
17028 (org-columns-eval eval))
17029 (org-columns-display-here))))
17030 (move-to-column col)
17031 (if (and (org-mode-p)
17032 (nth 3 (assoc key org-columns-current-fmt-compiled)))
17033 (org-columns-update key))))
17035 (defun org-edit-headline () ; FIXME: this is not columns specific
17036 "Edit the current headline, the part without TODO keyword, TAGS."
17037 (org-back-to-heading)
17038 (when (looking-at org-todo-line-regexp)
17039 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
17040 (txt (match-string 3))
17041 (post "")
17042 txt2)
17043 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
17044 (setq post (match-string 0 txt)
17045 txt (substring txt 0 (match-beginning 0))))
17046 (setq txt2 (read-string "Edit: " txt))
17047 (when (not (equal txt txt2))
17048 (beginning-of-line 1)
17049 (insert pre txt2 post)
17050 (delete-region (point) (point-at-eol))
17051 (org-set-tags nil t)))))
17053 (defun org-columns-edit-allowed ()
17054 "Edit the list of allowed values for the current property."
17055 (interactive)
17056 (let* ((key (get-char-property (point) 'org-columns-key))
17057 (key1 (concat key "_ALL"))
17058 (allowed (org-entry-get (point) key1 t))
17059 nval)
17060 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
17061 (setq nval (read-string "Allowed: " allowed))
17062 (org-entry-put
17063 (cond ((marker-position org-entry-property-inherited-from)
17064 org-entry-property-inherited-from)
17065 ((marker-position org-columns-top-level-marker)
17066 org-columns-top-level-marker))
17067 key1 nval)))
17069 (defmacro org-no-warnings (&rest body)
17070 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
17072 (defun org-columns-eval (form)
17073 (let (hidep)
17074 (save-excursion
17075 (beginning-of-line 1)
17076 ;; `next-line' is needed here, because it skips invisible line.
17077 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
17078 (setq hidep (org-on-heading-p 1)))
17079 (eval form)
17080 (and hidep (hide-entry))))
17082 (defun org-columns-previous-allowed-value ()
17083 "Switch to the previous allowed value for this column."
17084 (interactive)
17085 (org-columns-next-allowed-value t))
17087 (defun org-columns-next-allowed-value (&optional previous)
17088 "Switch to the next allowed value for this column."
17089 (interactive)
17090 (org-columns-check-computed)
17091 (let* ((col (current-column))
17092 (key (get-char-property (point) 'org-columns-key))
17093 (value (get-char-property (point) 'org-columns-value))
17094 (bol (point-at-bol)) (eol (point-at-eol))
17095 (pom (or (get-text-property bol 'org-hd-marker)
17096 (point))) ; keep despite of compiler waring
17097 (line-overlays
17098 (delq nil (mapcar (lambda (x)
17099 (and (eq (overlay-buffer x) (current-buffer))
17100 (>= (overlay-start x) bol)
17101 (<= (overlay-start x) eol)
17103 org-columns-overlays)))
17104 (allowed (or (org-property-get-allowed-values pom key)
17105 (and (memq
17106 (nth 4 (assoc key org-columns-current-fmt-compiled))
17107 '(checkbox checkbox-n-of-m checkbox-percent))
17108 '("[ ]" "[X]"))))
17109 nval)
17110 (when (equal key "ITEM")
17111 (error "Cannot edit item headline from here"))
17112 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
17113 (error "Allowed values for this property have not been defined"))
17114 (if (member key '("SCHEDULED" "DEADLINE"))
17115 (setq nval (if previous 'earlier 'later))
17116 (if previous (setq allowed (reverse allowed)))
17117 (if (member value allowed)
17118 (setq nval (car (cdr (member value allowed)))))
17119 (setq nval (or nval (car allowed)))
17120 (if (equal nval value)
17121 (error "Only one allowed value for this property")))
17122 (let ((inhibit-read-only t))
17123 (remove-text-properties (1- bol) eol '(read-only t))
17124 (unwind-protect
17125 (progn
17126 (setq org-columns-overlays
17127 (org-delete-all line-overlays org-columns-overlays))
17128 (mapc 'org-delete-overlay line-overlays)
17129 (org-columns-eval '(org-entry-put pom key nval)))
17130 (org-columns-display-here)))
17131 (move-to-column col)
17132 (if (and (org-mode-p)
17133 (nth 3 (assoc key org-columns-current-fmt-compiled)))
17134 (org-columns-update key))))
17136 (defun org-verify-version (task)
17137 (cond
17138 ((eq task 'columns)
17139 (if (or (featurep 'xemacs)
17140 (< emacs-major-version 22))
17141 (error "Emacs 22 is required for the columns feature")))))
17143 (defun org-columns-open-link (&optional arg)
17144 (interactive "P")
17145 (let ((value (get-char-property (point) 'org-columns-value)))
17146 (org-open-link-from-string value arg)))
17148 (defun org-open-link-from-string (s &optional arg)
17149 "Open a link in the string S, as if it was in Org-mode."
17150 (interactive)
17151 (with-temp-buffer
17152 (let ((org-inhibit-startup t))
17153 (org-mode)
17154 (insert s)
17155 (goto-char (point-min))
17156 (org-open-at-point arg))))
17158 (defun org-columns-get-format-and-top-level ()
17159 (let (fmt)
17160 (when (condition-case nil (org-back-to-heading) (error nil))
17161 (move-marker org-entry-property-inherited-from nil)
17162 (setq fmt (org-entry-get nil "COLUMNS" t)))
17163 (setq fmt (or fmt org-columns-default-format))
17164 (org-set-local 'org-columns-current-fmt fmt)
17165 (org-columns-compile-format fmt)
17166 (if (marker-position org-entry-property-inherited-from)
17167 (move-marker org-columns-top-level-marker
17168 org-entry-property-inherited-from)
17169 (move-marker org-columns-top-level-marker (point)))
17170 fmt))
17172 (defun org-columns ()
17173 "Turn on column view on an org-mode file."
17174 (interactive)
17175 (org-verify-version 'columns)
17176 (org-columns-remove-overlays)
17177 (move-marker org-columns-begin-marker (point))
17178 (let (beg end fmt cache maxwidths)
17179 (setq fmt (org-columns-get-format-and-top-level))
17180 (save-excursion
17181 (goto-char org-columns-top-level-marker)
17182 (setq beg (point))
17183 (unless org-columns-inhibit-recalculation
17184 (org-columns-compute-all))
17185 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
17186 (point-max)))
17187 ;; Get and cache the properties
17188 (goto-char beg)
17189 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
17190 (save-excursion
17191 (save-restriction
17192 (narrow-to-region beg end)
17193 (org-clock-sum))))
17194 (while (re-search-forward (concat "^" outline-regexp) end t)
17195 (push (cons (org-current-line) (org-entry-properties)) cache))
17196 (when cache
17197 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17198 (org-set-local 'org-columns-current-maxwidths maxwidths)
17199 (org-columns-display-here-title)
17200 (mapc (lambda (x)
17201 (goto-line (car x))
17202 (org-columns-display-here (cdr x)))
17203 cache)))))
17205 (defun org-columns-new (&optional prop title width op fmt &rest rest)
17206 "Insert a new column, to the leeft o the current column."
17207 (interactive)
17208 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
17209 cell)
17210 (setq prop (completing-read
17211 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
17212 nil nil prop))
17213 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
17214 (setq width (read-string "Column width: " (if width (number-to-string width))))
17215 (if (string-match "\\S-" width)
17216 (setq width (string-to-number width))
17217 (setq width nil))
17218 (setq fmt (completing-read "Summary [none]: "
17219 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
17220 nil t))
17221 (if (string-match "\\S-" fmt)
17222 (setq fmt (intern fmt))
17223 (setq fmt nil))
17224 (if (eq fmt 'none) (setq fmt nil))
17225 (if editp
17226 (progn
17227 (setcar editp prop)
17228 (setcdr editp (list title width nil fmt)))
17229 (setq cell (nthcdr (1- (current-column))
17230 org-columns-current-fmt-compiled))
17231 (setcdr cell (cons (list prop title width nil fmt)
17232 (cdr cell))))
17233 (org-columns-store-format)
17234 (org-columns-redo)))
17236 (defun org-columns-delete ()
17237 "Delete the column at point from columns view."
17238 (interactive)
17239 (let* ((n (current-column))
17240 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
17241 (when (y-or-n-p
17242 (format "Are you sure you want to remove column \"%s\"? " title))
17243 (setq org-columns-current-fmt-compiled
17244 (delq (nth n org-columns-current-fmt-compiled)
17245 org-columns-current-fmt-compiled))
17246 (org-columns-store-format)
17247 (org-columns-redo)
17248 (if (>= (current-column) (length org-columns-current-fmt-compiled))
17249 (backward-char 1)))))
17251 (defun org-columns-edit-attributes ()
17252 "Edit the attributes of the current column."
17253 (interactive)
17254 (let* ((n (current-column))
17255 (info (nth n org-columns-current-fmt-compiled)))
17256 (apply 'org-columns-new info)))
17258 (defun org-columns-widen (arg)
17259 "Make the column wider by ARG characters."
17260 (interactive "p")
17261 (let* ((n (current-column))
17262 (entry (nth n org-columns-current-fmt-compiled))
17263 (width (or (nth 2 entry)
17264 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
17265 (setq width (max 1 (+ width arg)))
17266 (setcar (nthcdr 2 entry) width)
17267 (org-columns-store-format)
17268 (org-columns-redo)))
17270 (defun org-columns-narrow (arg)
17271 "Make the column nrrower by ARG characters."
17272 (interactive "p")
17273 (org-columns-widen (- arg)))
17275 (defun org-columns-move-right ()
17276 "Swap this column with the one to the right."
17277 (interactive)
17278 (let* ((n (current-column))
17279 (cell (nthcdr n org-columns-current-fmt-compiled))
17281 (when (>= n (1- (length org-columns-current-fmt-compiled)))
17282 (error "Cannot shift this column further to the right"))
17283 (setq e (car cell))
17284 (setcar cell (car (cdr cell)))
17285 (setcdr cell (cons e (cdr (cdr cell))))
17286 (org-columns-store-format)
17287 (org-columns-redo)
17288 (forward-char 1)))
17290 (defun org-columns-move-left ()
17291 "Swap this column with the one to the left."
17292 (interactive)
17293 (let* ((n (current-column)))
17294 (when (= n 0)
17295 (error "Cannot shift this column further to the left"))
17296 (backward-char 1)
17297 (org-columns-move-right)
17298 (backward-char 1)))
17300 (defun org-columns-store-format ()
17301 "Store the text version of the current columns format in appropriate place.
17302 This is either in the COLUMNS property of the node starting the current column
17303 display, or in the #+COLUMNS line of the current buffer."
17304 (let (fmt (cnt 0))
17305 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17306 (org-set-local 'org-columns-current-fmt fmt)
17307 (if (marker-position org-columns-top-level-marker)
17308 (save-excursion
17309 (goto-char org-columns-top-level-marker)
17310 (if (and (org-at-heading-p)
17311 (org-entry-get nil "COLUMNS"))
17312 (org-entry-put nil "COLUMNS" fmt)
17313 (goto-char (point-min))
17314 ;; Overwrite all #+COLUMNS lines....
17315 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17316 (setq cnt (1+ cnt))
17317 (replace-match (concat "#+COLUMNS: " fmt) t t))
17318 (unless (> cnt 0)
17319 (goto-char (point-min))
17320 (or (org-on-heading-p t) (outline-next-heading))
17321 (let ((inhibit-read-only t))
17322 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17323 (org-set-local 'org-columns-default-format fmt))))))
17325 (defvar org-overriding-columns-format nil
17326 "When set, overrides any other definition.")
17327 (defvar org-agenda-view-columns-initially nil
17328 "When set, switch to columns view immediately after creating the agenda.")
17330 (defun org-agenda-columns ()
17331 "Turn on column view in the agenda."
17332 (interactive)
17333 (org-verify-version 'columns)
17334 (org-columns-remove-overlays)
17335 (move-marker org-columns-begin-marker (point))
17336 (let (fmt cache maxwidths m)
17337 (cond
17338 ((and (local-variable-p 'org-overriding-columns-format)
17339 org-overriding-columns-format)
17340 (setq fmt org-overriding-columns-format))
17341 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17342 (setq fmt (org-entry-get m "COLUMNS" t)))
17343 ((and (boundp 'org-columns-current-fmt)
17344 (local-variable-p 'org-columns-current-fmt)
17345 org-columns-current-fmt)
17346 (setq fmt org-columns-current-fmt))
17347 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17348 (setq m (get-text-property m 'org-hd-marker))
17349 (setq fmt (org-entry-get m "COLUMNS" t))))
17350 (setq fmt (or fmt org-columns-default-format))
17351 (org-set-local 'org-columns-current-fmt fmt)
17352 (org-columns-compile-format fmt)
17353 (save-excursion
17354 ;; Get and cache the properties
17355 (goto-char (point-min))
17356 (while (not (eobp))
17357 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17358 (get-text-property (point) 'org-marker)))
17359 (push (cons (org-current-line) (org-entry-properties m)) cache))
17360 (beginning-of-line 2))
17361 (when cache
17362 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17363 (org-set-local 'org-columns-current-maxwidths maxwidths)
17364 (org-columns-display-here-title)
17365 (mapc (lambda (x)
17366 (goto-line (car x))
17367 (org-columns-display-here (cdr x)))
17368 cache)))))
17370 (defun org-columns-get-autowidth-alist (s cache)
17371 "Derive the maximum column widths from the format and the cache."
17372 (let ((start 0) rtn)
17373 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17374 (push (cons (match-string 1 s) 1) rtn)
17375 (setq start (match-end 0)))
17376 (mapc (lambda (x)
17377 (setcdr x (apply 'max
17378 (mapcar
17379 (lambda (y)
17380 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17381 cache))))
17382 rtn)
17383 rtn))
17385 (defun org-columns-compute-all ()
17386 "Compute all columns that have operators defined."
17387 (org-unmodified
17388 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17389 (let ((columns org-columns-current-fmt-compiled) col)
17390 (while (setq col (pop columns))
17391 (when (nth 3 col)
17392 (save-excursion
17393 (org-columns-compute (car col)))))))
17395 (defun org-columns-update (property)
17396 "Recompute PROPERTY, and update the columns display for it."
17397 (org-columns-compute property)
17398 (let (fmt val pos)
17399 (save-excursion
17400 (mapc (lambda (ov)
17401 (when (equal (org-overlay-get ov 'org-columns-key) property)
17402 (setq pos (org-overlay-start ov))
17403 (goto-char pos)
17404 (when (setq val (cdr (assoc property
17405 (get-text-property
17406 (point-at-bol) 'org-summaries))))
17407 (setq fmt (org-overlay-get ov 'org-columns-format))
17408 (org-overlay-put ov 'org-columns-value val)
17409 (org-overlay-put ov 'display (format fmt val)))))
17410 org-columns-overlays))))
17412 (defun org-columns-compute (property)
17413 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17414 (interactive)
17415 (let* ((re (concat "^" outline-regexp))
17416 (lmax 30) ; Does anyone use deeper levels???
17417 (lsum (make-vector lmax 0))
17418 (lflag (make-vector lmax nil))
17419 (level 0)
17420 (ass (assoc property org-columns-current-fmt-compiled))
17421 (format (nth 4 ass))
17422 (printf (nth 5 ass))
17423 (beg org-columns-top-level-marker)
17424 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17425 (save-excursion
17426 ;; Find the region to compute
17427 (goto-char beg)
17428 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17429 (goto-char end)
17430 ;; Walk the tree from the back and do the computations
17431 (while (re-search-backward re beg t)
17432 (setq sumpos (match-beginning 0)
17433 last-level level
17434 level (org-outline-level)
17435 val (org-entry-get nil property)
17436 valflag (and val (string-match "\\S-" val)))
17437 (cond
17438 ((< level last-level)
17439 ;; put the sum of lower levels here as a property
17440 (setq sum (aref lsum last-level) ; current sum
17441 flag (aref lflag last-level) ; any valid entries from children?
17442 str (org-column-number-to-string sum format printf)
17443 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17444 useval (if flag str1 (if valflag val ""))
17445 sum-alist (get-text-property sumpos 'org-summaries))
17446 (if (assoc property sum-alist)
17447 (setcdr (assoc property sum-alist) useval)
17448 (push (cons property useval) sum-alist)
17449 (org-unmodified
17450 (add-text-properties sumpos (1+ sumpos)
17451 (list 'org-summaries sum-alist))))
17452 (when val
17453 (org-entry-put nil property (if flag str val)))
17454 ;; add current to current level accumulator
17455 (when (or flag valflag)
17456 (aset lsum level (+ (aref lsum level)
17457 (if flag sum (org-column-string-to-number
17458 (if flag str val) format))))
17459 (aset lflag level t))
17460 ;; clear accumulators for deeper levels
17461 (loop for l from (1+ level) to (1- lmax) do
17462 (aset lsum l 0)
17463 (aset lflag l nil)))
17464 ((>= level last-level)
17465 ;; add what we have here to the accumulator for this level
17466 (aset lsum level (+ (aref lsum level)
17467 (org-column-string-to-number (or val "0") format)))
17468 (and valflag (aset lflag level t)))
17469 (t (error "This should not happen")))))))
17471 (defun org-columns-redo ()
17472 "Construct the column display again."
17473 (interactive)
17474 (message "Recomputing columns...")
17475 (save-excursion
17476 (if (marker-position org-columns-begin-marker)
17477 (goto-char org-columns-begin-marker))
17478 (org-columns-remove-overlays)
17479 (if (org-mode-p)
17480 (call-interactively 'org-columns)
17481 (call-interactively 'org-agenda-columns)))
17482 (message "Recomputing columns...done"))
17484 (defun org-columns-not-in-agenda ()
17485 (if (eq major-mode 'org-agenda-mode)
17486 (error "This command is only allowed in Org-mode buffers")))
17489 (defun org-string-to-number (s)
17490 "Convert string to number, and interpret hh:mm:ss."
17491 (if (not (string-match ":" s))
17492 (string-to-number s)
17493 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17494 (while l
17495 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17496 sum)))
17498 (defun org-column-number-to-string (n fmt &optional printf)
17499 "Convert a computed column number to a string value, according to FMT."
17500 (cond
17501 ((eq fmt 'add_times)
17502 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17503 (format "%d:%02d" h m)))
17504 ((eq fmt 'checkbox)
17505 (cond ((= n (floor n)) "[X]")
17506 ((> n 1.) "[-]")
17507 (t "[ ]")))
17508 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17509 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17510 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17511 (printf (format printf n))
17512 ((eq fmt 'currency)
17513 (format "%.2f" n))
17514 (t (number-to-string n))))
17516 (defun org-nofm-to-completion (n m &optional percent)
17517 (if (not percent)
17518 (format "[%d/%d]" n m)
17519 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17521 (defun org-column-string-to-number (s fmt)
17522 "Convert a column value to a number that can be used for column computing."
17523 (cond
17524 ((string-match ":" s)
17525 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17526 (while l
17527 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17528 sum))
17529 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17530 (if (equal s "[X]") 1. 0.000001))
17531 (t (string-to-number s))))
17533 (defun org-columns-uncompile-format (cfmt)
17534 "Turn the compiled columns format back into a string representation."
17535 (let ((rtn "") e s prop title op width fmt printf)
17536 (while (setq e (pop cfmt))
17537 (setq prop (car e)
17538 title (nth 1 e)
17539 width (nth 2 e)
17540 op (nth 3 e)
17541 fmt (nth 4 e)
17542 printf (nth 5 e))
17543 (cond
17544 ((eq fmt 'add_times) (setq op ":"))
17545 ((eq fmt 'checkbox) (setq op "X"))
17546 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17547 ((eq fmt 'checkbox-percent) (setq op "X%"))
17548 ((eq fmt 'add_numbers) (setq op "+"))
17549 ((eq fmt 'currency) (setq op "$")))
17550 (if (and op printf) (setq op (concat op ";" printf)))
17551 (if (equal title prop) (setq title nil))
17552 (setq s (concat "%" (if width (number-to-string width))
17553 prop
17554 (if title (concat "(" title ")"))
17555 (if op (concat "{" op "}"))))
17556 (setq rtn (concat rtn " " s)))
17557 (org-trim rtn)))
17559 (defun org-columns-compile-format (fmt)
17560 "Turn a column format string into an alist of specifications.
17561 The alist has one entry for each column in the format. The elements of
17562 that list are:
17563 property the property
17564 title the title field for the columns
17565 width the column width in characters, can be nil for automatic
17566 operator the operator if any
17567 format the output format for computed results, derived from operator
17568 printf a printf format for computed values"
17569 (let ((start 0) width prop title op f printf)
17570 (setq org-columns-current-fmt-compiled nil)
17571 (while (string-match
17572 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17573 fmt start)
17574 (setq start (match-end 0)
17575 width (match-string 1 fmt)
17576 prop (match-string 2 fmt)
17577 title (or (match-string 3 fmt) prop)
17578 op (match-string 4 fmt)
17579 f nil
17580 printf nil)
17581 (if width (setq width (string-to-number width)))
17582 (when (and op (string-match ";" op))
17583 (setq printf (substring op (match-end 0))
17584 op (substring op 0 (match-beginning 0))))
17585 (cond
17586 ((equal op "+") (setq f 'add_numbers))
17587 ((equal op "$") (setq f 'currency))
17588 ((equal op ":") (setq f 'add_times))
17589 ((equal op "X") (setq f 'checkbox))
17590 ((equal op "X/") (setq f 'checkbox-n-of-m))
17591 ((equal op "X%") (setq f 'checkbox-percent))
17593 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17594 (setq org-columns-current-fmt-compiled
17595 (nreverse org-columns-current-fmt-compiled))))
17598 ;;; Dynamic block for Column view
17600 (defun org-columns-capture-view (&optional maxlevel skip-empty-rows)
17601 "Get the column view of the current buffer or subtree.
17602 The first optional argument MAXLEVEL sets the level limit. A
17603 second optional argument SKIP-EMPTY-ROWS tells whether to skip
17604 empty rows, an empty row being one where all the column view
17605 specifiers except ITEM are empty. This function returns a list
17606 containing the title row and all other rows. Each row is a list
17607 of fields."
17608 (save-excursion
17609 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17610 (n (length title)) row tbl)
17611 (goto-char (point-min))
17612 (while (and (re-search-forward "^\\(\\*+\\) " nil t)
17613 (or (null maxlevel)
17614 (>= maxlevel
17615 (if org-odd-levels-only
17616 (/ (1+ (length (match-string 1))) 2)
17617 (length (match-string 1))))))
17618 (when (get-char-property (match-beginning 0) 'org-columns-key)
17619 (setq row nil)
17620 (loop for i from 0 to (1- n) do
17621 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17622 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17624 row))
17625 (setq row (nreverse row))
17626 (unless (and skip-empty-rows
17627 (eq 1 (length (delete "" (delete-dups row)))))
17628 (push row tbl))))
17629 (append (list title 'hline) (nreverse tbl)))))
17631 (defun org-dblock-write:columnview (params)
17632 "Write the column view table.
17633 PARAMS is a property list of parameters:
17635 :width enforce same column widths with <N> specifiers.
17636 :id the :ID: property of the entry where the columns view
17637 should be built, as a string. When `local', call locally.
17638 When `global' call column view with the cursor at the beginning
17639 of the buffer (usually this means that the whole buffer switches
17640 to column view).
17641 :hlines When t, insert a hline before each item. When a number, insert
17642 a hline before each level <= that number.
17643 :vlines When t, make each column a colgroup to enforce vertical lines.
17644 :maxlevel When set to a number, don't capture headlines below this level.
17645 :skip-empty-rows
17646 When t, skip rows where all specifiers other than ITEM are empty."
17647 (let ((pos (move-marker (make-marker) (point)))
17648 (hlines (plist-get params :hlines))
17649 (vlines (plist-get params :vlines))
17650 (maxlevel (plist-get params :maxlevel))
17651 (skip-empty-rows (plist-get params :skip-empty-rows))
17652 tbl id idpos nfields tmp)
17653 (save-excursion
17654 (save-restriction
17655 (when (setq id (plist-get params :id))
17656 (cond ((not id) nil)
17657 ((eq id 'global) (goto-char (point-min)))
17658 ((eq id 'local) nil)
17659 ((setq idpos (org-find-entry-with-id id))
17660 (goto-char idpos))
17661 (t (error "Cannot find entry with :ID: %s" id))))
17662 (org-columns)
17663 (setq tbl (org-columns-capture-view maxlevel skip-empty-rows))
17664 (setq nfields (length (car tbl)))
17665 (org-columns-quit)))
17666 (goto-char pos)
17667 (move-marker pos nil)
17668 (when tbl
17669 (when (plist-get params :hlines)
17670 (setq tmp nil)
17671 (while tbl
17672 (if (eq (car tbl) 'hline)
17673 (push (pop tbl) tmp)
17674 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17675 (if (and (not (eq (car tmp) 'hline))
17676 (or (eq hlines t)
17677 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17678 (push 'hline tmp)))
17679 (push (pop tbl) tmp)))
17680 (setq tbl (nreverse tmp)))
17681 (when vlines
17682 (setq tbl (mapcar (lambda (x)
17683 (if (eq 'hline x) x (cons "" x)))
17684 tbl))
17685 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17686 (setq pos (point))
17687 (insert (org-listtable-to-string tbl))
17688 (when (plist-get params :width)
17689 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17690 org-columns-current-widths "|")))
17691 (goto-char pos)
17692 (org-table-align))))
17694 (defun org-listtable-to-string (tbl)
17695 "Convert a listtable TBL to a string that contains the Org-mode table.
17696 The table still need to be alligned. The resulting string has no leading
17697 and tailing newline characters."
17698 (mapconcat
17699 (lambda (x)
17700 (cond
17701 ((listp x)
17702 (concat "|" (mapconcat 'identity x "|") "|"))
17703 ((eq x 'hline) "|-|")
17704 (t (error "Garbage in listtable: %s" x))))
17705 tbl "\n"))
17707 (defun org-insert-columns-dblock ()
17708 "Create a dynamic block capturing a column view table."
17709 (interactive)
17710 (let ((defaults '(:name "columnview" :hlines 1))
17711 (id (completing-read
17712 "Capture columns (local, global, entry with :ID: property) [local]: "
17713 (append '(("global") ("local"))
17714 (mapcar 'list (org-property-values "ID"))))))
17715 (if (equal id "") (setq id 'local))
17716 (if (equal id "global") (setq id 'global))
17717 (setq defaults (append defaults (list :id id)))
17718 (org-create-dblock defaults)
17719 (org-update-dblock)))
17721 ;;;; Timestamps
17723 (defvar org-last-changed-timestamp nil)
17724 (defvar org-time-was-given) ; dynamically scoped parameter
17725 (defvar org-end-time-was-given) ; dynamically scoped parameter
17726 (defvar org-ts-what) ; dynamically scoped parameter
17728 (defun org-time-stamp (arg)
17729 "Prompt for a date/time and insert a time stamp.
17730 If the user specifies a time like HH:MM, or if this command is called
17731 with a prefix argument, the time stamp will contain date and time.
17732 Otherwise, only the date will be included. All parts of a date not
17733 specified by the user will be filled in from the current date/time.
17734 So if you press just return without typing anything, the time stamp
17735 will represent the current date/time. If there is already a timestamp
17736 at the cursor, it will be modified."
17737 (interactive "P")
17738 (let* ((ts nil)
17739 (default-time
17740 ;; Default time is either today, or, when entering a range,
17741 ;; the range start.
17742 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17743 (save-excursion
17744 (re-search-backward
17745 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17746 (- (point) 20) t)))
17747 (apply 'encode-time (org-parse-time-string (match-string 1)))
17748 (current-time)))
17749 (default-input (and ts (org-get-compact-tod ts)))
17750 org-time-was-given org-end-time-was-given time)
17751 (cond
17752 ((and (org-at-timestamp-p)
17753 (eq last-command 'org-time-stamp)
17754 (eq this-command 'org-time-stamp))
17755 (insert "--")
17756 (setq time (let ((this-command this-command))
17757 (org-read-date arg 'totime nil nil default-time default-input)))
17758 (org-insert-time-stamp time (or org-time-was-given arg)))
17759 ((org-at-timestamp-p)
17760 (setq time (let ((this-command this-command))
17761 (org-read-date arg 'totime nil nil default-time default-input)))
17762 (when (org-at-timestamp-p) ; just to get the match data
17763 (replace-match "")
17764 (setq org-last-changed-timestamp
17765 (org-insert-time-stamp
17766 time (or org-time-was-given arg)
17767 nil nil nil (list org-end-time-was-given))))
17768 (message "Timestamp updated"))
17770 (setq time (let ((this-command this-command))
17771 (org-read-date arg 'totime nil nil default-time default-input)))
17772 (org-insert-time-stamp time (or org-time-was-given arg)
17773 nil nil nil (list org-end-time-was-given))))))
17775 ;; FIXME: can we use this for something else????
17776 ;; like computing time differences?????
17777 (defun org-get-compact-tod (s)
17778 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17779 (let* ((t1 (match-string 1 s))
17780 (h1 (string-to-number (match-string 2 s)))
17781 (m1 (string-to-number (match-string 3 s)))
17782 (t2 (and (match-end 4) (match-string 5 s)))
17783 (h2 (and t2 (string-to-number (match-string 6 s))))
17784 (m2 (and t2 (string-to-number (match-string 7 s))))
17785 dh dm)
17786 (if (not t2)
17788 (setq dh (- h2 h1) dm (- m2 m1))
17789 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17790 (concat t1 "+" (number-to-string dh)
17791 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17793 (defun org-time-stamp-inactive (&optional arg)
17794 "Insert an inactive time stamp.
17795 An inactive time stamp is enclosed in square brackets instead of angle
17796 brackets. It is inactive in the sense that it does not trigger agenda entries,
17797 does not link to the calendar and cannot be changed with the S-cursor keys.
17798 So these are more for recording a certain time/date."
17799 (interactive "P")
17800 (let (org-time-was-given org-end-time-was-given time)
17801 (setq time (org-read-date arg 'totime))
17802 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17803 nil nil (list org-end-time-was-given))))
17805 (defvar org-date-ovl (org-make-overlay 1 1))
17806 (org-overlay-put org-date-ovl 'face 'org-warning)
17807 (org-detach-overlay org-date-ovl)
17809 (defvar org-ans1) ; dynamically scoped parameter
17810 (defvar org-ans2) ; dynamically scoped parameter
17812 (defvar org-plain-time-of-day-regexp) ; defined below
17814 (defvar org-read-date-overlay nil)
17815 (defvar org-dcst nil) ; dynamically scoped
17817 (defun org-read-date (&optional with-time to-time from-string prompt
17818 default-time default-input)
17819 "Read a date, possibly a time, and make things smooth for the user.
17820 The prompt will suggest to enter an ISO date, but you can also enter anything
17821 which will at least partially be understood by `parse-time-string'.
17822 Unrecognized parts of the date will default to the current day, month, year,
17823 hour and minute. If this command is called to replace a timestamp at point,
17824 of to enter the second timestamp of a range, the default time is taken from the
17825 existing stamp. For example,
17826 3-2-5 --> 2003-02-05
17827 feb 15 --> currentyear-02-15
17828 sep 12 9 --> 2009-09-12
17829 12:45 --> today 12:45
17830 22 sept 0:34 --> currentyear-09-22 0:34
17831 12 --> currentyear-currentmonth-12
17832 Fri --> nearest Friday (today or later)
17833 etc.
17835 Furthermore you can specify a relative date by giving, as the *first* thing
17836 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17837 change in days weeks, months, years.
17838 With a single plus or minus, the date is relative to today. With a double
17839 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17840 +4d --> four days from today
17841 +4 --> same as above
17842 +2w --> two weeks from today
17843 ++5 --> five days from default date
17845 The function understands only English month and weekday abbreviations,
17846 but this can be configured with the variables `parse-time-months' and
17847 `parse-time-weekdays'.
17849 While prompting, a calendar is popped up - you can also select the
17850 date with the mouse (button 1). The calendar shows a period of three
17851 months. To scroll it to other months, use the keys `>' and `<'.
17852 If you don't like the calendar, turn it off with
17853 \(setq org-read-date-popup-calendar nil)
17855 With optional argument TO-TIME, the date will immediately be converted
17856 to an internal time.
17857 With an optional argument WITH-TIME, the prompt will suggest to also
17858 insert a time. Note that when WITH-TIME is not set, you can still
17859 enter a time, and this function will inform the calling routine about
17860 this change. The calling routine may then choose to change the format
17861 used to insert the time stamp into the buffer to include the time.
17862 With optional argument FROM-STRING, read from this string instead from
17863 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17864 the time/date that is used for everything that is not specified by the
17865 user."
17866 (require 'parse-time)
17867 (let* ((org-time-stamp-rounding-minutes
17868 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
17869 (org-dcst org-display-custom-times)
17870 (ct (org-current-time))
17871 (def (or default-time ct))
17872 (defdecode (decode-time def))
17873 (dummy (progn
17874 (when (< (nth 2 defdecode) org-extend-today-until)
17875 (setcar (nthcdr 2 defdecode) -1)
17876 (setcar (nthcdr 1 defdecode) 59)
17877 (setq def (apply 'encode-time defdecode)
17878 defdecode (decode-time def)))))
17879 (calendar-move-hook nil)
17880 (view-diary-entries-initially nil)
17881 (view-calendar-holidays-initially nil)
17882 (timestr (format-time-string
17883 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17884 (prompt (concat (if prompt (concat prompt " ") "")
17885 (format "Date+time [%s]: " timestr)))
17886 ans (org-ans0 "") org-ans1 org-ans2 final)
17888 (cond
17889 (from-string (setq ans from-string))
17890 (org-read-date-popup-calendar
17891 (save-excursion
17892 (save-window-excursion
17893 (calendar)
17894 (calendar-forward-day (- (time-to-days def)
17895 (calendar-absolute-from-gregorian
17896 (calendar-current-date))))
17897 (org-eval-in-calendar nil t)
17898 (let* ((old-map (current-local-map))
17899 (map (copy-keymap calendar-mode-map))
17900 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17901 (org-defkey map (kbd "RET") 'org-calendar-select)
17902 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17903 'org-calendar-select-mouse)
17904 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17905 'org-calendar-select-mouse)
17906 (org-defkey minibuffer-local-map [(meta shift left)]
17907 (lambda () (interactive)
17908 (org-eval-in-calendar '(calendar-backward-month 1))))
17909 (org-defkey minibuffer-local-map [(meta shift right)]
17910 (lambda () (interactive)
17911 (org-eval-in-calendar '(calendar-forward-month 1))))
17912 (org-defkey minibuffer-local-map [(meta shift up)]
17913 (lambda () (interactive)
17914 (org-eval-in-calendar '(calendar-backward-year 1))))
17915 (org-defkey minibuffer-local-map [(meta shift down)]
17916 (lambda () (interactive)
17917 (org-eval-in-calendar '(calendar-forward-year 1))))
17918 (org-defkey minibuffer-local-map [(shift up)]
17919 (lambda () (interactive)
17920 (org-eval-in-calendar '(calendar-backward-week 1))))
17921 (org-defkey minibuffer-local-map [(shift down)]
17922 (lambda () (interactive)
17923 (org-eval-in-calendar '(calendar-forward-week 1))))
17924 (org-defkey minibuffer-local-map [(shift left)]
17925 (lambda () (interactive)
17926 (org-eval-in-calendar '(calendar-backward-day 1))))
17927 (org-defkey minibuffer-local-map [(shift right)]
17928 (lambda () (interactive)
17929 (org-eval-in-calendar '(calendar-forward-day 1))))
17930 (org-defkey minibuffer-local-map ">"
17931 (lambda () (interactive)
17932 (org-eval-in-calendar '(scroll-calendar-left 1))))
17933 (org-defkey minibuffer-local-map "<"
17934 (lambda () (interactive)
17935 (org-eval-in-calendar '(scroll-calendar-right 1))))
17936 (unwind-protect
17937 (progn
17938 (use-local-map map)
17939 (add-hook 'post-command-hook 'org-read-date-display)
17940 (setq org-ans0 (read-string prompt default-input nil nil))
17941 ;; org-ans0: from prompt
17942 ;; org-ans1: from mouse click
17943 ;; org-ans2: from calendar motion
17944 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17945 (remove-hook 'post-command-hook 'org-read-date-display)
17946 (use-local-map old-map)
17947 (when org-read-date-overlay
17948 (org-delete-overlay org-read-date-overlay)
17949 (setq org-read-date-overlay nil)))))))
17951 (t ; Naked prompt only
17952 (unwind-protect
17953 (setq ans (read-string prompt default-input nil timestr))
17954 (when org-read-date-overlay
17955 (org-delete-overlay org-read-date-overlay)
17956 (setq org-read-date-overlay nil)))))
17958 (setq final (org-read-date-analyze ans def defdecode))
17960 (if to-time
17961 (apply 'encode-time final)
17962 (if (and (boundp 'org-time-was-given) org-time-was-given)
17963 (format "%04d-%02d-%02d %02d:%02d"
17964 (nth 5 final) (nth 4 final) (nth 3 final)
17965 (nth 2 final) (nth 1 final))
17966 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17967 (defvar def)
17968 (defvar defdecode)
17969 (defvar with-time)
17970 (defun org-read-date-display ()
17971 "Display the currrent date prompt interpretation in the minibuffer."
17972 (when org-read-date-display-live
17973 (when org-read-date-overlay
17974 (org-delete-overlay org-read-date-overlay))
17975 (let ((p (point)))
17976 (end-of-line 1)
17977 (while (not (equal (buffer-substring
17978 (max (point-min) (- (point) 4)) (point))
17979 " "))
17980 (insert " "))
17981 (goto-char p))
17982 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17983 " " (or org-ans1 org-ans2)))
17984 (org-end-time-was-given nil)
17985 (f (org-read-date-analyze ans def defdecode))
17986 (fmts (if org-dcst
17987 org-time-stamp-custom-formats
17988 org-time-stamp-formats))
17989 (fmt (if (or with-time
17990 (and (boundp 'org-time-was-given) org-time-was-given))
17991 (cdr fmts)
17992 (car fmts)))
17993 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17994 (when (and org-end-time-was-given
17995 (string-match org-plain-time-of-day-regexp txt))
17996 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17997 org-end-time-was-given
17998 (substring txt (match-end 0)))))
17999 (setq org-read-date-overlay
18000 (make-overlay (1- (point-at-eol)) (point-at-eol)))
18001 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
18003 (defun org-read-date-analyze (ans def defdecode)
18004 "Analyze the combined answer of the date prompt."
18005 ;; FIXME: cleanup and comment
18006 (let (delta deltan deltaw deltadef year month day
18007 hour minute second wday pm h2 m2 tl wday1)
18009 (when (setq delta (org-read-date-get-relative ans (current-time) def))
18010 (setq ans (replace-match "" t t ans)
18011 deltan (car delta)
18012 deltaw (nth 1 delta)
18013 deltadef (nth 2 delta)))
18015 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
18016 (when (string-match
18017 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
18018 (setq year (if (match-end 2)
18019 (string-to-number (match-string 2 ans))
18020 (string-to-number (format-time-string "%Y")))
18021 month (string-to-number (match-string 3 ans))
18022 day (string-to-number (match-string 4 ans)))
18023 (if (< year 100) (setq year (+ 2000 year)))
18024 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
18025 t nil ans)))
18026 ;; Help matching am/pm times, because `parse-time-string' does not do that.
18027 ;; If there is a time with am/pm, and *no* time without it, we convert
18028 ;; so that matching will be successful.
18029 (loop for i from 1 to 2 do ; twice, for end time as well
18030 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
18031 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
18032 (setq hour (string-to-number (match-string 1 ans))
18033 minute (if (match-end 3)
18034 (string-to-number (match-string 3 ans))
18036 pm (equal ?p
18037 (string-to-char (downcase (match-string 4 ans)))))
18038 (if (and (= hour 12) (not pm))
18039 (setq hour 0)
18040 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
18041 (setq ans (replace-match (format "%02d:%02d" hour minute)
18042 t t ans))))
18044 ;; Check if a time range is given as a duration
18045 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
18046 (setq hour (string-to-number (match-string 1 ans))
18047 h2 (+ hour (string-to-number (match-string 3 ans)))
18048 minute (string-to-number (match-string 2 ans))
18049 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
18050 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
18051 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
18053 ;; Check if there is a time range
18054 (when (boundp 'org-end-time-was-given)
18055 (setq org-time-was-given nil)
18056 (when (and (string-match org-plain-time-of-day-regexp ans)
18057 (match-end 8))
18058 (setq org-end-time-was-given (match-string 8 ans))
18059 (setq ans (concat (substring ans 0 (match-beginning 7))
18060 (substring ans (match-end 7))))))
18062 (setq tl (parse-time-string ans)
18063 day (or (nth 3 tl) (nth 3 defdecode))
18064 month (or (nth 4 tl)
18065 (if (and org-read-date-prefer-future
18066 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
18067 (1+ (nth 4 defdecode))
18068 (nth 4 defdecode)))
18069 year (or (nth 5 tl)
18070 (if (and org-read-date-prefer-future
18071 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
18072 (1+ (nth 5 defdecode))
18073 (nth 5 defdecode)))
18074 hour (or (nth 2 tl) (nth 2 defdecode))
18075 minute (or (nth 1 tl) (nth 1 defdecode))
18076 second (or (nth 0 tl) 0)
18077 wday (nth 6 tl))
18078 (when deltan
18079 (unless deltadef
18080 (let ((now (decode-time (current-time))))
18081 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
18082 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
18083 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
18084 ((equal deltaw "m") (setq month (+ month deltan)))
18085 ((equal deltaw "y") (setq year (+ year deltan)))))
18086 (when (and wday (not (nth 3 tl)))
18087 ;; Weekday was given, but no day, so pick that day in the week
18088 ;; on or after the derived date.
18089 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
18090 (unless (equal wday wday1)
18091 (setq day (+ day (% (- wday wday1 -7) 7)))))
18092 (if (and (boundp 'org-time-was-given)
18093 (nth 2 tl))
18094 (setq org-time-was-given t))
18095 (if (< year 100) (setq year (+ 2000 year)))
18096 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
18097 (list second minute hour day month year)))
18099 (defvar parse-time-weekdays)
18101 (defun org-read-date-get-relative (s today default)
18102 "Check string S for special relative date string.
18103 TODAY and DEFAULT are internal times, for today and for a default.
18104 Return shift list (N what def-flag)
18105 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
18106 N is the number of WHATs to shift.
18107 DEF-FLAG is t when a double ++ or -- indicates shift relative to
18108 the DEFAULT date rather than TODAY."
18109 (when (string-match
18110 (concat
18111 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
18112 "\\([0-9]+\\)?"
18113 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
18114 "\\([ \t]\\|$\\)") s)
18115 (let* ((dir (if (match-end 1)
18116 (string-to-char (substring (match-string 1 s) -1))
18117 ?+))
18118 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
18119 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
18120 (what (if (match-end 3) (match-string 3 s) "d"))
18121 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
18122 (date (if rel default today))
18123 (wday (nth 6 (decode-time date)))
18124 delta)
18125 (if wday1
18126 (progn
18127 (setq delta (mod (+ 7 (- wday1 wday)) 7))
18128 (if (= dir ?-) (setq delta (- delta 7)))
18129 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
18130 (list delta "d" rel))
18131 (list (* n (if (= dir ?-) -1 1)) what rel)))))
18133 (defun org-eval-in-calendar (form &optional keepdate)
18134 "Eval FORM in the calendar window and return to current window.
18135 Also, store the cursor date in variable org-ans2."
18136 (let ((sw (selected-window)))
18137 (select-window (get-buffer-window "*Calendar*"))
18138 (eval form)
18139 (when (and (not keepdate) (calendar-cursor-to-date))
18140 (let* ((date (calendar-cursor-to-date))
18141 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18142 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
18143 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
18144 (select-window sw)))
18146 ; ;; Update the prompt to show new default date
18147 ; (save-excursion
18148 ; (goto-char (point-min))
18149 ; (when (and org-ans2
18150 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
18151 ; (get-text-property (match-end 0) 'field))
18152 ; (let ((inhibit-read-only t))
18153 ; (replace-match (concat "[" org-ans2 "]") t t)
18154 ; (add-text-properties (point-min) (1+ (match-end 0))
18155 ; (text-properties-at (1+ (point-min)))))))))
18157 (defun org-calendar-select ()
18158 "Return to `org-read-date' with the date currently selected.
18159 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18160 (interactive)
18161 (when (calendar-cursor-to-date)
18162 (let* ((date (calendar-cursor-to-date))
18163 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18164 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18165 (if (active-minibuffer-window) (exit-minibuffer))))
18167 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
18168 "Insert a date stamp for the date given by the internal TIME.
18169 WITH-HM means, use the stamp format that includes the time of the day.
18170 INACTIVE means use square brackets instead of angular ones, so that the
18171 stamp will not contribute to the agenda.
18172 PRE and POST are optional strings to be inserted before and after the
18173 stamp.
18174 The command returns the inserted time stamp."
18175 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
18176 stamp)
18177 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
18178 (insert-before-markers (or pre ""))
18179 (insert-before-markers (setq stamp (format-time-string fmt time)))
18180 (when (listp extra)
18181 (setq extra (car extra))
18182 (if (and (stringp extra)
18183 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
18184 (setq extra (format "-%02d:%02d"
18185 (string-to-number (match-string 1 extra))
18186 (string-to-number (match-string 2 extra))))
18187 (setq extra nil)))
18188 (when extra
18189 (backward-char 1)
18190 (insert-before-markers extra)
18191 (forward-char 1))
18192 (insert-before-markers (or post ""))
18193 stamp))
18195 (defun org-toggle-time-stamp-overlays ()
18196 "Toggle the use of custom time stamp formats."
18197 (interactive)
18198 (setq org-display-custom-times (not org-display-custom-times))
18199 (unless org-display-custom-times
18200 (let ((p (point-min)) (bmp (buffer-modified-p)))
18201 (while (setq p (next-single-property-change p 'display))
18202 (if (and (get-text-property p 'display)
18203 (eq (get-text-property p 'face) 'org-date))
18204 (remove-text-properties
18205 p (setq p (next-single-property-change p 'display))
18206 '(display t))))
18207 (set-buffer-modified-p bmp)))
18208 (if (featurep 'xemacs)
18209 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
18210 (org-restart-font-lock)
18211 (setq org-table-may-need-update t)
18212 (if org-display-custom-times
18213 (message "Time stamps are overlayed with custom format")
18214 (message "Time stamp overlays removed")))
18216 (defun org-display-custom-time (beg end)
18217 "Overlay modified time stamp format over timestamp between BED and END."
18218 (let* ((ts (buffer-substring beg end))
18219 t1 w1 with-hm tf time str w2 (off 0))
18220 (save-match-data
18221 (setq t1 (org-parse-time-string ts t))
18222 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
18223 (setq off (- (match-end 0) (match-beginning 0)))))
18224 (setq end (- end off))
18225 (setq w1 (- end beg)
18226 with-hm (and (nth 1 t1) (nth 2 t1))
18227 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
18228 time (org-fix-decoded-time t1)
18229 str (org-add-props
18230 (format-time-string
18231 (substring tf 1 -1) (apply 'encode-time time))
18232 nil 'mouse-face 'highlight)
18233 w2 (length str))
18234 (if (not (= w2 w1))
18235 (add-text-properties (1+ beg) (+ 2 beg)
18236 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
18237 (if (featurep 'xemacs)
18238 (progn
18239 (put-text-property beg end 'invisible t)
18240 (put-text-property beg end 'end-glyph (make-glyph str)))
18241 (put-text-property beg end 'display str))))
18243 (defun org-translate-time (string)
18244 "Translate all timestamps in STRING to custom format.
18245 But do this only if the variable `org-display-custom-times' is set."
18246 (when org-display-custom-times
18247 (save-match-data
18248 (let* ((start 0)
18249 (re org-ts-regexp-both)
18250 t1 with-hm inactive tf time str beg end)
18251 (while (setq start (string-match re string start))
18252 (setq beg (match-beginning 0)
18253 end (match-end 0)
18254 t1 (save-match-data
18255 (org-parse-time-string (substring string beg end) t))
18256 with-hm (and (nth 1 t1) (nth 2 t1))
18257 inactive (equal (substring string beg (1+ beg)) "[")
18258 tf (funcall (if with-hm 'cdr 'car)
18259 org-time-stamp-custom-formats)
18260 time (org-fix-decoded-time t1)
18261 str (format-time-string
18262 (concat
18263 (if inactive "[" "<") (substring tf 1 -1)
18264 (if inactive "]" ">"))
18265 (apply 'encode-time time))
18266 string (replace-match str t t string)
18267 start (+ start (length str)))))))
18268 string)
18270 (defun org-fix-decoded-time (time)
18271 "Set 0 instead of nil for the first 6 elements of time.
18272 Don't touch the rest."
18273 (let ((n 0))
18274 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
18276 (defun org-days-to-time (timestamp-string)
18277 "Difference between TIMESTAMP-STRING and now in days."
18278 (- (time-to-days (org-time-string-to-time timestamp-string))
18279 (time-to-days (current-time))))
18281 (defun org-deadline-close (timestamp-string &optional ndays)
18282 "Is the time in TIMESTAMP-STRING close to the current date?"
18283 (setq ndays (or ndays (org-get-wdays timestamp-string)))
18284 (and (< (org-days-to-time timestamp-string) ndays)
18285 (not (org-entry-is-done-p))))
18287 (defun org-get-wdays (ts)
18288 "Get the deadline lead time appropriate for timestring TS."
18289 (cond
18290 ((<= org-deadline-warning-days 0)
18291 ;; 0 or negative, enforce this value no matter what
18292 (- org-deadline-warning-days))
18293 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
18294 ;; lead time is specified.
18295 (floor (* (string-to-number (match-string 1 ts))
18296 (cdr (assoc (match-string 2 ts)
18297 '(("d" . 1) ("w" . 7)
18298 ("m" . 30.4) ("y" . 365.25)))))))
18299 ;; go for the default.
18300 (t org-deadline-warning-days)))
18302 (defun org-calendar-select-mouse (ev)
18303 "Return to `org-read-date' with the date currently selected.
18304 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18305 (interactive "e")
18306 (mouse-set-point ev)
18307 (when (calendar-cursor-to-date)
18308 (let* ((date (calendar-cursor-to-date))
18309 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18310 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18311 (if (active-minibuffer-window) (exit-minibuffer))))
18313 (defun org-check-deadlines (ndays)
18314 "Check if there are any deadlines due or past due.
18315 A deadline is considered due if it happens within `org-deadline-warning-days'
18316 days from today's date. If the deadline appears in an entry marked DONE,
18317 it is not shown. The prefix arg NDAYS can be used to test that many
18318 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18319 (interactive "P")
18320 (let* ((org-warn-days
18321 (cond
18322 ((equal ndays '(4)) 100000)
18323 (ndays (prefix-numeric-value ndays))
18324 (t (abs org-deadline-warning-days))))
18325 (case-fold-search nil)
18326 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18327 (callback
18328 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18330 (message "%d deadlines past-due or due within %d days"
18331 (org-occur regexp nil callback)
18332 org-warn-days)))
18334 (defun org-check-before-date (date)
18335 "Check if there are deadlines or scheduled entries before DATE."
18336 (interactive (list (org-read-date)))
18337 (let ((case-fold-search nil)
18338 (regexp (concat "\\<\\(" org-deadline-string
18339 "\\|" org-scheduled-string
18340 "\\) *<\\([^>]+\\)>"))
18341 (callback
18342 (lambda () (time-less-p
18343 (org-time-string-to-time (match-string 2))
18344 (org-time-string-to-time date)))))
18345 (message "%d entries before %s"
18346 (org-occur regexp nil callback) date)))
18348 (defun org-evaluate-time-range (&optional to-buffer)
18349 "Evaluate a time range by computing the difference between start and end.
18350 Normally the result is just printed in the echo area, but with prefix arg
18351 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18352 If the time range is actually in a table, the result is inserted into the
18353 next column.
18354 For time difference computation, a year is assumed to be exactly 365
18355 days in order to avoid rounding problems."
18356 (interactive "P")
18358 (org-clock-update-time-maybe)
18359 (save-excursion
18360 (unless (org-at-date-range-p t)
18361 (goto-char (point-at-bol))
18362 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18363 (if (not (org-at-date-range-p t))
18364 (error "Not at a time-stamp range, and none found in current line")))
18365 (let* ((ts1 (match-string 1))
18366 (ts2 (match-string 2))
18367 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18368 (match-end (match-end 0))
18369 (time1 (org-time-string-to-time ts1))
18370 (time2 (org-time-string-to-time ts2))
18371 (t1 (time-to-seconds time1))
18372 (t2 (time-to-seconds time2))
18373 (diff (abs (- t2 t1)))
18374 (negative (< (- t2 t1) 0))
18375 ;; (ys (floor (* 365 24 60 60)))
18376 (ds (* 24 60 60))
18377 (hs (* 60 60))
18378 (fy "%dy %dd %02d:%02d")
18379 (fy1 "%dy %dd")
18380 (fd "%dd %02d:%02d")
18381 (fd1 "%dd")
18382 (fh "%02d:%02d")
18383 y d h m align)
18384 (if havetime
18385 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18387 d (floor (/ diff ds)) diff (mod diff ds)
18388 h (floor (/ diff hs)) diff (mod diff hs)
18389 m (floor (/ diff 60)))
18390 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18392 d (floor (+ (/ diff ds) 0.5))
18393 h 0 m 0))
18394 (if (not to-buffer)
18395 (message "%s" (org-make-tdiff-string y d h m))
18396 (if (org-at-table-p)
18397 (progn
18398 (goto-char match-end)
18399 (setq align t)
18400 (and (looking-at " *|") (goto-char (match-end 0))))
18401 (goto-char match-end))
18402 (if (looking-at
18403 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18404 (replace-match ""))
18405 (if negative (insert " -"))
18406 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18407 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18408 (insert " " (format fh h m))))
18409 (if align (org-table-align))
18410 (message "Time difference inserted")))))
18412 (defun org-make-tdiff-string (y d h m)
18413 (let ((fmt "")
18414 (l nil))
18415 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18416 l (push y l)))
18417 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18418 l (push d l)))
18419 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18420 l (push h l)))
18421 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18422 l (push m l)))
18423 (apply 'format fmt (nreverse l))))
18425 (defun org-time-string-to-time (s)
18426 (apply 'encode-time (org-parse-time-string s)))
18428 (defun org-time-string-to-absolute (s &optional daynr prefer)
18429 "Convert a time stamp to an absolute day number.
18430 If there is a specifyer for a cyclic time stamp, get the closest date to
18431 DAYNR."
18432 (cond
18433 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18434 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18435 daynr
18436 (+ daynr 1000)))
18437 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18438 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18439 (time-to-days (current-time))) (match-string 0 s)
18440 prefer))
18441 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18443 (defun org-time-from-absolute (d)
18444 "Return the time corresponding to date D.
18445 D may be an absolute day number, or a calendar-type list (month day year)."
18446 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18447 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18449 (defun org-calendar-holiday ()
18450 "List of holidays, for Diary display in Org-mode."
18451 (require 'holidays)
18452 (let ((hl (funcall
18453 (if (fboundp 'calendar-check-holidays)
18454 'calendar-check-holidays 'check-calendar-holidays) date)))
18455 (if hl (mapconcat 'identity hl "; "))))
18457 (defun org-diary-sexp-entry (sexp entry date)
18458 "Process a SEXP diary ENTRY for DATE."
18459 (require 'diary-lib)
18460 (let ((result (if calendar-debug-sexp
18461 (let ((stack-trace-on-error t))
18462 (eval (car (read-from-string sexp))))
18463 (condition-case nil
18464 (eval (car (read-from-string sexp)))
18465 (error
18466 (beep)
18467 (message "Bad sexp at line %d in %s: %s"
18468 (org-current-line)
18469 (buffer-file-name) sexp)
18470 (sleep-for 2))))))
18471 (cond ((stringp result) result)
18472 ((and (consp result)
18473 (stringp (cdr result))) (cdr result))
18474 (result entry)
18475 (t nil))))
18477 (defun org-diary-to-ical-string (frombuf)
18478 "Get iCalendar entries from diary entries in buffer FROMBUF.
18479 This uses the icalendar.el library."
18480 (let* ((tmpdir (if (featurep 'xemacs)
18481 (temp-directory)
18482 temporary-file-directory))
18483 (tmpfile (make-temp-name
18484 (expand-file-name "orgics" tmpdir)))
18485 buf rtn b e)
18486 (save-excursion
18487 (set-buffer frombuf)
18488 (icalendar-export-region (point-min) (point-max) tmpfile)
18489 (setq buf (find-buffer-visiting tmpfile))
18490 (set-buffer buf)
18491 (goto-char (point-min))
18492 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18493 (setq b (match-beginning 0)))
18494 (goto-char (point-max))
18495 (if (re-search-backward "^END:VEVENT" nil t)
18496 (setq e (match-end 0)))
18497 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18498 (kill-buffer buf)
18499 (kill-buffer frombuf)
18500 (delete-file tmpfile)
18501 rtn))
18503 (defun org-closest-date (start current change prefer)
18504 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18505 When PREFER is `past' return a date that is either CURRENT or past.
18506 When PREFER is `future', return a date that is either CURRENT or future."
18507 ;; Make the proper lists from the dates
18508 (catch 'exit
18509 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18510 dn dw sday cday n1 n2
18511 d m y y1 y2 date1 date2 nmonths nm ny m2)
18513 (setq start (org-date-to-gregorian start)
18514 current (org-date-to-gregorian
18515 (if org-agenda-repeating-timestamp-show-all
18516 current
18517 (time-to-days (current-time))))
18518 sday (calendar-absolute-from-gregorian start)
18519 cday (calendar-absolute-from-gregorian current))
18521 (if (<= cday sday) (throw 'exit sday))
18523 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18524 (setq dn (string-to-number (match-string 1 change))
18525 dw (cdr (assoc (match-string 2 change) a1)))
18526 (error "Invalid change specifyer: %s" change))
18527 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18528 (cond
18529 ((eq dw 'day)
18530 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18531 n2 (+ n1 dn)))
18532 ((eq dw 'year)
18533 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18534 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18535 (setq date1 (list m d y1)
18536 n1 (calendar-absolute-from-gregorian date1)
18537 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18538 n2 (calendar-absolute-from-gregorian date2)))
18539 ((eq dw 'month)
18540 ;; approx number of month between the tow dates
18541 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18542 ;; How often does dn fit in there?
18543 (setq d (nth 1 start) m (car start) y (nth 2 start)
18544 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18545 m (+ m nm)
18546 ny (floor (/ m 12))
18547 y (+ y ny)
18548 m (- m (* ny 12)))
18549 (while (> m 12) (setq m (- m 12) y (1+ y)))
18550 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18551 (setq m2 (+ m dn) y2 y)
18552 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18553 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18554 (while (< n2 cday)
18555 (setq n1 n2 m m2 y y2)
18556 (setq m2 (+ m dn) y2 y)
18557 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18558 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18560 (if org-agenda-repeating-timestamp-show-all
18561 (cond
18562 ((eq prefer 'past) n1)
18563 ((eq prefer 'future) (if (= cday n1) n1 n2))
18564 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18565 (cond
18566 ((eq prefer 'past) n1)
18567 ((eq prefer 'future) (if (= cday n1) n1 n2))
18568 (t (if (= cday n1) n1 n2)))))))
18570 (defun org-date-to-gregorian (date)
18571 "Turn any specification of DATE into a gregorian date for the calendar."
18572 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18573 ((and (listp date) (= (length date) 3)) date)
18574 ((stringp date)
18575 (setq date (org-parse-time-string date))
18576 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18577 ((listp date)
18578 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18580 (defun org-parse-time-string (s &optional nodefault)
18581 "Parse the standard Org-mode time string.
18582 This should be a lot faster than the normal `parse-time-string'.
18583 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18584 hour and minute fields will be nil if not given."
18585 (if (string-match org-ts-regexp0 s)
18586 (list 0
18587 (if (or (match-beginning 8) (not nodefault))
18588 (string-to-number (or (match-string 8 s) "0")))
18589 (if (or (match-beginning 7) (not nodefault))
18590 (string-to-number (or (match-string 7 s) "0")))
18591 (string-to-number (match-string 4 s))
18592 (string-to-number (match-string 3 s))
18593 (string-to-number (match-string 2 s))
18594 nil nil nil)
18595 (make-list 9 0)))
18597 (defun org-timestamp-up (&optional arg)
18598 "Increase the date item at the cursor by one.
18599 If the cursor is on the year, change the year. If it is on the month or
18600 the day, change that.
18601 With prefix ARG, change by that many units."
18602 (interactive "p")
18603 (org-timestamp-change (prefix-numeric-value arg)))
18605 (defun org-timestamp-down (&optional arg)
18606 "Decrease the date item at the cursor by one.
18607 If the cursor is on the year, change the year. If it is on the month or
18608 the day, change that.
18609 With prefix ARG, change by that many units."
18610 (interactive "p")
18611 (org-timestamp-change (- (prefix-numeric-value arg))))
18613 (defun org-timestamp-up-day (&optional arg)
18614 "Increase the date in the time stamp by one day.
18615 With prefix ARG, change that many days."
18616 (interactive "p")
18617 (if (and (not (org-at-timestamp-p t))
18618 (org-on-heading-p))
18619 (org-todo 'up)
18620 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18622 (defun org-timestamp-down-day (&optional arg)
18623 "Decrease the date in the time stamp by one day.
18624 With prefix ARG, change that many days."
18625 (interactive "p")
18626 (if (and (not (org-at-timestamp-p t))
18627 (org-on-heading-p))
18628 (org-todo 'down)
18629 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18631 (defsubst org-pos-in-match-range (pos n)
18632 (and (match-beginning n)
18633 (<= (match-beginning n) pos)
18634 (>= (match-end n) pos)))
18636 (defun org-at-timestamp-p (&optional inactive-ok)
18637 "Determine if the cursor is in or at a timestamp."
18638 (interactive)
18639 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18640 (pos (point))
18641 (ans (or (looking-at tsr)
18642 (save-excursion
18643 (skip-chars-backward "^[<\n\r\t")
18644 (if (> (point) (point-min)) (backward-char 1))
18645 (and (looking-at tsr)
18646 (> (- (match-end 0) pos) -1))))))
18647 (and ans
18648 (boundp 'org-ts-what)
18649 (setq org-ts-what
18650 (cond
18651 ((= pos (match-beginning 0)) 'bracket)
18652 ((= pos (1- (match-end 0))) 'bracket)
18653 ((org-pos-in-match-range pos 2) 'year)
18654 ((org-pos-in-match-range pos 3) 'month)
18655 ((org-pos-in-match-range pos 7) 'hour)
18656 ((org-pos-in-match-range pos 8) 'minute)
18657 ((or (org-pos-in-match-range pos 4)
18658 (org-pos-in-match-range pos 5)) 'day)
18659 ((and (> pos (or (match-end 8) (match-end 5)))
18660 (< pos (match-end 0)))
18661 (- pos (or (match-end 8) (match-end 5))))
18662 (t 'day))))
18663 ans))
18665 (defun org-toggle-timestamp-type ()
18666 "Toggle the type (<active> or [inactive]) of a time stamp."
18667 (interactive)
18668 (when (org-at-timestamp-p t)
18669 (save-excursion
18670 (goto-char (match-beginning 0))
18671 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18672 (goto-char (1- (match-end 0)))
18673 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18674 (message "Timestamp is now %sactive"
18675 (if (equal (char-before) ?>) "in" ""))))
18677 (defun org-timestamp-change (n &optional what)
18678 "Change the date in the time stamp at point.
18679 The date will be changed by N times WHAT. WHAT can be `day', `month',
18680 `year', `minute', `second'. If WHAT is not given, the cursor position
18681 in the timestamp determines what will be changed."
18682 (let ((pos (point))
18683 with-hm inactive
18684 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18685 org-ts-what
18686 extra rem
18687 ts time time0)
18688 (if (not (org-at-timestamp-p t))
18689 (error "Not at a timestamp"))
18690 (if (and (not what) (eq org-ts-what 'bracket))
18691 (org-toggle-timestamp-type)
18692 (if (and (not what) (not (eq org-ts-what 'day))
18693 org-display-custom-times
18694 (get-text-property (point) 'display)
18695 (not (get-text-property (1- (point)) 'display)))
18696 (setq org-ts-what 'day))
18697 (setq org-ts-what (or what org-ts-what)
18698 inactive (= (char-after (match-beginning 0)) ?\[)
18699 ts (match-string 0))
18700 (replace-match "")
18701 (if (string-match
18702 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[-+][0-9]+[dwmy]\\)*\\)[]>]"
18704 (setq extra (match-string 1 ts)))
18705 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18706 (setq with-hm t))
18707 (setq time0 (org-parse-time-string ts))
18708 (when (and (eq org-ts-what 'minute)
18709 (eq current-prefix-arg nil))
18710 (setq n (* dm (org-no-warnings (signum n))))
18711 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
18712 (setcar (cdr time0) (+ (nth 1 time0)
18713 (if (> n 0) (- rem) (- dm rem))))))
18714 (setq time
18715 (encode-time (or (car time0) 0)
18716 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18717 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18718 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18719 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18720 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18721 (nthcdr 6 time0)))
18722 (when (integerp org-ts-what)
18723 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18724 (if (eq what 'calendar)
18725 (let ((cal-date (org-get-date-from-calendar)))
18726 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18727 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18728 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18729 (setcar time0 (or (car time0) 0))
18730 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18731 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18732 (setq time (apply 'encode-time time0))))
18733 (setq org-last-changed-timestamp
18734 (org-insert-time-stamp time with-hm inactive nil nil extra))
18735 (org-clock-update-time-maybe)
18736 (goto-char pos)
18737 ;; Try to recenter the calendar window, if any
18738 (if (and org-calendar-follow-timestamp-change
18739 (get-buffer-window "*Calendar*" t)
18740 (memq org-ts-what '(day month year)))
18741 (org-recenter-calendar (time-to-days time))))))
18743 ;; FIXME: does not yet work for lead times
18744 (defun org-modify-ts-extra (s pos n dm)
18745 "Change the different parts of the lead-time and repeat fields in timestamp."
18746 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18747 ng h m new rem)
18748 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18749 (cond
18750 ((or (org-pos-in-match-range pos 2)
18751 (org-pos-in-match-range pos 3))
18752 (setq m (string-to-number (match-string 3 s))
18753 h (string-to-number (match-string 2 s)))
18754 (if (org-pos-in-match-range pos 2)
18755 (setq h (+ h n))
18756 (setq n (* dm (org-no-warnings (signum n))))
18757 (when (not (= 0 (setq rem (% m dm))))
18758 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18759 (setq m (+ m n)))
18760 (if (< m 0) (setq m (+ m 60) h (1- h)))
18761 (if (> m 59) (setq m (- m 60) h (1+ h)))
18762 (setq h (min 24 (max 0 h)))
18763 (setq ng 1 new (format "-%02d:%02d" h m)))
18764 ((org-pos-in-match-range pos 6)
18765 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18766 ((org-pos-in-match-range pos 5)
18767 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18769 ((org-pos-in-match-range pos 9)
18770 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18771 ((org-pos-in-match-range pos 8)
18772 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18774 (when ng
18775 (setq s (concat
18776 (substring s 0 (match-beginning ng))
18778 (substring s (match-end ng))))))
18781 (defun org-recenter-calendar (date)
18782 "If the calendar is visible, recenter it to DATE."
18783 (let* ((win (selected-window))
18784 (cwin (get-buffer-window "*Calendar*" t))
18785 (calendar-move-hook nil))
18786 (when cwin
18787 (select-window cwin)
18788 (calendar-goto-date (if (listp date) date
18789 (calendar-gregorian-from-absolute date)))
18790 (select-window win))))
18792 (defun org-goto-calendar (&optional arg)
18793 "Go to the Emacs calendar at the current date.
18794 If there is a time stamp in the current line, go to that date.
18795 A prefix ARG can be used to force the current date."
18796 (interactive "P")
18797 (let ((tsr org-ts-regexp) diff
18798 (calendar-move-hook nil)
18799 (view-calendar-holidays-initially nil)
18800 (view-diary-entries-initially nil))
18801 (if (or (org-at-timestamp-p)
18802 (save-excursion
18803 (beginning-of-line 1)
18804 (looking-at (concat ".*" tsr))))
18805 (let ((d1 (time-to-days (current-time)))
18806 (d2 (time-to-days
18807 (org-time-string-to-time (match-string 1)))))
18808 (setq diff (- d2 d1))))
18809 (calendar)
18810 (calendar-goto-today)
18811 (if (and diff (not arg)) (calendar-forward-day diff))))
18813 (defun org-get-date-from-calendar ()
18814 "Return a list (month day year) of date at point in calendar."
18815 (with-current-buffer "*Calendar*"
18816 (save-match-data
18817 (calendar-cursor-to-date))))
18819 (defun org-date-from-calendar ()
18820 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18821 If there is already a time stamp at the cursor position, update it."
18822 (interactive)
18823 (if (org-at-timestamp-p t)
18824 (org-timestamp-change 0 'calendar)
18825 (let ((cal-date (org-get-date-from-calendar)))
18826 (org-insert-time-stamp
18827 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18829 (defvar appt-time-msg-list)
18831 ;;;###autoload
18832 (defun org-agenda-to-appt (&optional refresh filter)
18833 "Activate appointments found in `org-agenda-files'.
18834 With a \\[universal-argument] prefix, refresh the list of
18835 appointements.
18837 If FILTER is t, interactively prompt the user for a regular
18838 expression, and filter out entries that don't match it.
18840 If FILTER is a string, use this string as a regular expression
18841 for filtering entries out.
18843 FILTER can also be an alist with the car of each cell being
18844 either 'headline or 'category. For example:
18846 '((headline \"IMPORTANT\")
18847 (category \"Work\"))
18849 will only add headlines containing IMPORTANT or headlines
18850 belonging to the \"Work\" category."
18851 (interactive "P")
18852 (require 'calendar)
18853 (if refresh (setq appt-time-msg-list nil))
18854 (if (eq filter t)
18855 (setq filter (read-from-minibuffer "Regexp filter: ")))
18856 (let* ((cnt 0) ; count added events
18857 (org-agenda-new-buffers nil)
18858 (org-deadline-warning-days 0)
18859 (today (org-date-to-gregorian
18860 (time-to-days (current-time))))
18861 (files (org-agenda-files)) entries file)
18862 ;; Get all entries which may contain an appt
18863 (while (setq file (pop files))
18864 (setq entries
18865 (append entries
18866 (org-agenda-get-day-entries
18867 file today :timestamp :scheduled :deadline))))
18868 (setq entries (delq nil entries))
18869 ;; Map thru entries and find if we should filter them out
18870 (mapc
18871 (lambda(x)
18872 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18873 (cat (get-text-property 1 'org-category x))
18874 (tod (get-text-property 1 'time-of-day x))
18875 (ok (or (null filter)
18876 (and (stringp filter) (string-match filter evt))
18877 (and (listp filter)
18878 (or (string-match
18879 (cadr (assoc 'category filter)) cat)
18880 (string-match
18881 (cadr (assoc 'headline filter)) evt))))))
18882 ;; FIXME: Shall we remove text-properties for the appt text?
18883 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18884 (when (and ok tod)
18885 (setq tod (number-to-string tod)
18886 tod (when (string-match
18887 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18888 (concat (match-string 1 tod) ":"
18889 (match-string 2 tod))))
18890 (appt-add tod evt)
18891 (setq cnt (1+ cnt))))) entries)
18892 (org-release-buffers org-agenda-new-buffers)
18893 (if (eq cnt 0)
18894 (message "No event to add")
18895 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18897 ;;; The clock for measuring work time.
18899 (defvar org-mode-line-string "")
18900 (put 'org-mode-line-string 'risky-local-variable t)
18902 (defvar org-mode-line-timer nil)
18903 (defvar org-clock-heading "")
18904 (defvar org-clock-start-time "")
18906 (defun org-update-mode-line ()
18907 (let* ((delta (- (time-to-seconds (current-time))
18908 (time-to-seconds org-clock-start-time)))
18909 (h (floor delta 3600))
18910 (m (floor (- delta (* 3600 h)) 60)))
18911 (setq org-mode-line-string
18912 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18913 'help-echo "Org-mode clock is running"))
18914 (force-mode-line-update)))
18916 (defvar org-clock-marker (make-marker)
18917 "Marker recording the last clock-in.")
18918 (defvar org-clock-mode-line-entry nil
18919 "Information for the modeline about the running clock.")
18921 (defun org-clock-in ()
18922 "Start the clock on the current item.
18923 If necessary, clock-out of the currently active clock."
18924 (interactive)
18925 (org-clock-out t)
18926 (let (ts)
18927 (save-excursion
18928 (org-back-to-heading t)
18929 (when (and org-clock-in-switch-to-state
18930 (not (looking-at (concat outline-regexp "[ \t]*"
18931 org-clock-in-switch-to-state
18932 "\\>"))))
18933 (org-todo org-clock-in-switch-to-state))
18934 (if (and org-clock-heading-function
18935 (functionp org-clock-heading-function))
18936 (setq org-clock-heading (funcall org-clock-heading-function))
18937 (if (looking-at org-complex-heading-regexp)
18938 (setq org-clock-heading (match-string 4))
18939 (setq org-clock-heading "???")))
18940 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18941 (org-clock-find-position)
18943 (insert "\n") (backward-char 1)
18944 (indent-relative)
18945 (insert org-clock-string " ")
18946 (setq org-clock-start-time (current-time))
18947 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18948 (move-marker org-clock-marker (point) (buffer-base-buffer))
18949 (or global-mode-string (setq global-mode-string '("")))
18950 (or (memq 'org-mode-line-string global-mode-string)
18951 (setq global-mode-string
18952 (append global-mode-string '(org-mode-line-string))))
18953 (org-update-mode-line)
18954 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18955 (message "Clock started at %s" ts))))
18957 (defun org-clock-find-position ()
18958 "Find the location where the next clock line should be inserted."
18959 (org-back-to-heading t)
18960 (catch 'exit
18961 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18962 (re (concat "^[ \t]*" org-clock-string))
18963 (cnt 0)
18964 first last)
18965 (goto-char beg)
18966 (when (eobp) (newline) (setq end (max (point) end)))
18967 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18968 ;; we seem to have a CLOCK drawer, so go there.
18969 (beginning-of-line 2)
18970 (throw 'exit t))
18971 ;; Lets count the CLOCK lines
18972 (goto-char beg)
18973 (while (re-search-forward re end t)
18974 (setq first (or first (match-beginning 0))
18975 last (match-beginning 0)
18976 cnt (1+ cnt)))
18977 (when (and (integerp org-clock-into-drawer)
18978 (>= (1+ cnt) org-clock-into-drawer))
18979 ;; Wrap current entries into a new drawer
18980 (goto-char last)
18981 (beginning-of-line 2)
18982 (if (org-at-item-p) (org-end-of-item))
18983 (insert ":END:\n")
18984 (beginning-of-line 0)
18985 (org-indent-line-function)
18986 (goto-char first)
18987 (insert ":CLOCK:\n")
18988 (beginning-of-line 0)
18989 (org-indent-line-function)
18990 (org-flag-drawer t)
18991 (beginning-of-line 2)
18992 (throw 'exit nil))
18994 (goto-char beg)
18995 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18996 (not (equal (match-string 1) org-clock-string)))
18997 ;; Planning info, skip to after it
18998 (beginning-of-line 2)
18999 (or (bolp) (newline)))
19000 (when (eq t org-clock-into-drawer)
19001 (insert ":CLOCK:\n:END:\n")
19002 (beginning-of-line -1)
19003 (org-indent-line-function)
19004 (org-flag-drawer t)
19005 (beginning-of-line 2)
19006 (org-indent-line-function)))))
19008 (defun org-clock-out (&optional fail-quietly)
19009 "Stop the currently running clock.
19010 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
19011 (interactive)
19012 (catch 'exit
19013 (if (not (marker-buffer org-clock-marker))
19014 (if fail-quietly (throw 'exit t) (error "No active clock")))
19015 (let (ts te s h m)
19016 (save-excursion
19017 (set-buffer (marker-buffer org-clock-marker))
19018 (goto-char org-clock-marker)
19019 (beginning-of-line 1)
19020 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
19021 (equal (match-string 1) org-clock-string))
19022 (setq ts (match-string 2))
19023 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
19024 (goto-char (match-end 0))
19025 (delete-region (point) (point-at-eol))
19026 (insert "--")
19027 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
19028 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
19029 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
19030 h (floor (/ s 3600))
19031 s (- s (* 3600 h))
19032 m (floor (/ s 60))
19033 s (- s (* 60 s)))
19034 (insert " => " (format "%2d:%02d" h m))
19035 (move-marker org-clock-marker nil)
19036 (when org-log-note-clock-out
19037 (org-add-log-maybe 'clock-out))
19038 (when org-mode-line-timer
19039 (cancel-timer org-mode-line-timer)
19040 (setq org-mode-line-timer nil))
19041 (setq global-mode-string
19042 (delq 'org-mode-line-string global-mode-string))
19043 (force-mode-line-update)
19044 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
19046 (defun org-clock-cancel ()
19047 "Cancel the running clock be removing the start timestamp."
19048 (interactive)
19049 (if (not (marker-buffer org-clock-marker))
19050 (error "No active clock"))
19051 (save-excursion
19052 (set-buffer (marker-buffer org-clock-marker))
19053 (goto-char org-clock-marker)
19054 (delete-region (1- (point-at-bol)) (point-at-eol)))
19055 (setq global-mode-string
19056 (delq 'org-mode-line-string global-mode-string))
19057 (force-mode-line-update)
19058 (message "Clock canceled"))
19060 (defun org-clock-goto (&optional delete-windows)
19061 "Go to the currently clocked-in entry."
19062 (interactive "P")
19063 (if (not (marker-buffer org-clock-marker))
19064 (error "No active clock"))
19065 (switch-to-buffer-other-window
19066 (marker-buffer org-clock-marker))
19067 (if delete-windows (delete-other-windows))
19068 (goto-char org-clock-marker)
19069 (org-show-entry)
19070 (org-back-to-heading)
19071 (recenter))
19073 (defvar org-clock-file-total-minutes nil
19074 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
19075 (make-variable-buffer-local 'org-clock-file-total-minutes)
19077 (defun org-clock-sum (&optional tstart tend)
19078 "Sum the times for each subtree.
19079 Puts the resulting times in minutes as a text property on each headline."
19080 (interactive)
19081 (let* ((bmp (buffer-modified-p))
19082 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
19083 org-clock-string
19084 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
19085 (lmax 30)
19086 (ltimes (make-vector lmax 0))
19087 (t1 0)
19088 (level 0)
19089 ts te dt
19090 time)
19091 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
19092 (save-excursion
19093 (goto-char (point-max))
19094 (while (re-search-backward re nil t)
19095 (cond
19096 ((match-end 2)
19097 ;; Two time stamps
19098 (setq ts (match-string 2)
19099 te (match-string 3)
19100 ts (time-to-seconds
19101 (apply 'encode-time (org-parse-time-string ts)))
19102 te (time-to-seconds
19103 (apply 'encode-time (org-parse-time-string te)))
19104 ts (if tstart (max ts tstart) ts)
19105 te (if tend (min te tend) te)
19106 dt (- te ts)
19107 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
19108 ((match-end 4)
19109 ;; A naket time
19110 (setq t1 (+ t1 (string-to-number (match-string 5))
19111 (* 60 (string-to-number (match-string 4))))))
19112 (t ;; A headline
19113 (setq level (- (match-end 1) (match-beginning 1)))
19114 (when (or (> t1 0) (> (aref ltimes level) 0))
19115 (loop for l from 0 to level do
19116 (aset ltimes l (+ (aref ltimes l) t1)))
19117 (setq t1 0 time (aref ltimes level))
19118 (loop for l from level to (1- lmax) do
19119 (aset ltimes l 0))
19120 (goto-char (match-beginning 0))
19121 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
19122 (setq org-clock-file-total-minutes (aref ltimes 0)))
19123 (set-buffer-modified-p bmp)))
19125 (defun org-clock-display (&optional total-only)
19126 "Show subtree times in the entire buffer.
19127 If TOTAL-ONLY is non-nil, only show the total time for the entire file
19128 in the echo area."
19129 (interactive)
19130 (org-remove-clock-overlays)
19131 (let (time h m p)
19132 (org-clock-sum)
19133 (unless total-only
19134 (save-excursion
19135 (goto-char (point-min))
19136 (while (or (and (equal (setq p (point)) (point-min))
19137 (get-text-property p :org-clock-minutes))
19138 (setq p (next-single-property-change
19139 (point) :org-clock-minutes)))
19140 (goto-char p)
19141 (when (setq time (get-text-property p :org-clock-minutes))
19142 (org-put-clock-overlay time (funcall outline-level))))
19143 (setq h (/ org-clock-file-total-minutes 60)
19144 m (- org-clock-file-total-minutes (* 60 h)))
19145 ;; Arrange to remove the overlays upon next change.
19146 (when org-remove-highlights-with-change
19147 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
19148 nil 'local))))
19149 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
19151 (defvar org-clock-overlays nil)
19152 (make-variable-buffer-local 'org-clock-overlays)
19154 (defun org-put-clock-overlay (time &optional level)
19155 "Put an overlays on the current line, displaying TIME.
19156 If LEVEL is given, prefix time with a corresponding number of stars.
19157 This creates a new overlay and stores it in `org-clock-overlays', so that it
19158 will be easy to remove."
19159 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
19160 (l (if level (org-get-valid-level level 0) 0))
19161 (off 0)
19162 ov tx)
19163 (move-to-column c)
19164 (unless (eolp) (skip-chars-backward "^ \t"))
19165 (skip-chars-backward " \t")
19166 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
19167 tx (concat (buffer-substring (1- (point)) (point))
19168 (make-string (+ off (max 0 (- c (current-column)))) ?.)
19169 (org-add-props (format "%s %2d:%02d%s"
19170 (make-string l ?*) h m
19171 (make-string (- 16 l) ?\ ))
19172 '(face secondary-selection))
19173 ""))
19174 (if (not (featurep 'xemacs))
19175 (org-overlay-put ov 'display tx)
19176 (org-overlay-put ov 'invisible t)
19177 (org-overlay-put ov 'end-glyph (make-glyph tx)))
19178 (push ov org-clock-overlays)))
19180 (defun org-remove-clock-overlays (&optional beg end noremove)
19181 "Remove the occur highlights from the buffer.
19182 BEG and END are ignored. If NOREMOVE is nil, remove this function
19183 from the `before-change-functions' in the current buffer."
19184 (interactive)
19185 (unless org-inhibit-highlight-removal
19186 (mapc 'org-delete-overlay org-clock-overlays)
19187 (setq org-clock-overlays nil)
19188 (unless noremove
19189 (remove-hook 'before-change-functions
19190 'org-remove-clock-overlays 'local))))
19192 (defun org-clock-out-if-current ()
19193 "Clock out if the current entry contains the running clock.
19194 This is used to stop the clock after a TODO entry is marked DONE,
19195 and is only done if the variable `org-clock-out-when-done' is not nil."
19196 (when (and org-clock-out-when-done
19197 (member state org-done-keywords)
19198 (equal (marker-buffer org-clock-marker) (current-buffer))
19199 (< (point) org-clock-marker)
19200 (> (save-excursion (outline-next-heading) (point))
19201 org-clock-marker))
19202 ;; Clock out, but don't accept a logging message for this.
19203 (let ((org-log-note-clock-out nil))
19204 (org-clock-out))))
19206 (add-hook 'org-after-todo-state-change-hook
19207 'org-clock-out-if-current)
19209 (defun org-check-running-clock ()
19210 "Check if the current buffer contains the running clock.
19211 If yes, offer to stop it and to save the buffer with the changes."
19212 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
19213 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
19214 (buffer-name))))
19215 (org-clock-out)
19216 (when (y-or-n-p "Save changed buffer?")
19217 (save-buffer))))
19219 (defun org-clock-report (&optional arg)
19220 "Create a table containing a report about clocked time.
19221 If the cursor is inside an existing clocktable block, then the table
19222 will be updated. If not, a new clocktable will be inserted.
19223 When called with a prefix argument, move to the first clock table in the
19224 buffer and update it."
19225 (interactive "P")
19226 (org-remove-clock-overlays)
19227 (when arg
19228 (org-find-dblock "clocktable")
19229 (org-show-entry))
19230 (if (org-in-clocktable-p)
19231 (goto-char (org-in-clocktable-p))
19232 (org-create-dblock (list :name "clocktable"
19233 :maxlevel 2 :scope 'file)))
19234 (org-update-dblock))
19236 (defun org-in-clocktable-p ()
19237 "Check if the cursor is in a clocktable."
19238 (let ((pos (point)) start)
19239 (save-excursion
19240 (end-of-line 1)
19241 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
19242 (setq start (match-beginning 0))
19243 (re-search-forward "^#\\+END:.*" nil t)
19244 (>= (match-end 0) pos)
19245 start))))
19247 (defun org-clock-update-time-maybe ()
19248 "If this is a CLOCK line, update it and return t.
19249 Otherwise, return nil."
19250 (interactive)
19251 (save-excursion
19252 (beginning-of-line 1)
19253 (skip-chars-forward " \t")
19254 (when (looking-at org-clock-string)
19255 (let ((re (concat "[ \t]*" org-clock-string
19256 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
19257 "\\([ \t]*=>.*\\)?"))
19258 ts te h m s)
19259 (if (not (looking-at re))
19261 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
19262 (end-of-line 1)
19263 (setq ts (match-string 1)
19264 te (match-string 2))
19265 (setq s (- (time-to-seconds
19266 (apply 'encode-time (org-parse-time-string te)))
19267 (time-to-seconds
19268 (apply 'encode-time (org-parse-time-string ts))))
19269 h (floor (/ s 3600))
19270 s (- s (* 3600 h))
19271 m (floor (/ s 60))
19272 s (- s (* 60 s)))
19273 (insert " => " (format "%2d:%02d" h m))
19274 t)))))
19276 (defun org-clock-special-range (key &optional time as-strings)
19277 "Return two times bordering a special time range.
19278 Key is a symbol specifying the range and can be one of `today', `yesterday',
19279 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
19280 A week starts Monday 0:00 and ends Sunday 24:00.
19281 The range is determined relative to TIME. TIME defaults to the current time.
19282 The return value is a cons cell with two internal times like the ones
19283 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
19284 the returned times will be formatted strings."
19285 (let* ((tm (decode-time (or time (current-time))))
19286 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
19287 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
19288 (dow (nth 6 tm))
19289 s1 m1 h1 d1 month1 y1 diff ts te fm)
19290 (cond
19291 ((eq key 'today)
19292 (setq h 0 m 0 h1 24 m1 0))
19293 ((eq key 'yesterday)
19294 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19295 ((eq key 'thisweek)
19296 (setq diff (if (= dow 0) 6 (1- dow))
19297 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19298 ((eq key 'lastweek)
19299 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19300 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19301 ((eq key 'thismonth)
19302 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19303 ((eq key 'lastmonth)
19304 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19305 ((eq key 'thisyear)
19306 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19307 ((eq key 'lastyear)
19308 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19309 (t (error "No such time block %s" key)))
19310 (setq ts (encode-time s m h d month y)
19311 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19312 (or d1 d) (or month1 month) (or y1 y)))
19313 (setq fm (cdr org-time-stamp-formats))
19314 (if as-strings
19315 (cons (format-time-string fm ts) (format-time-string fm te))
19316 (cons ts te))))
19318 (defun org-dblock-write:clocktable (params)
19319 "Write the standard clocktable."
19320 (catch 'exit
19321 (let* ((hlchars '((1 . "*") (2 . "/")))
19322 (ins (make-marker))
19323 (total-time nil)
19324 (scope (plist-get params :scope))
19325 (tostring (plist-get params :tostring))
19326 (multifile (plist-get params :multifile))
19327 (header (plist-get params :header))
19328 (maxlevel (or (plist-get params :maxlevel) 3))
19329 (step (plist-get params :step))
19330 (emph (plist-get params :emphasize))
19331 (ts (plist-get params :tstart))
19332 (te (plist-get params :tend))
19333 (block (plist-get params :block))
19334 (link (plist-get params :link))
19335 ipos time h m p level hlc hdl
19336 cc beg end pos tbl)
19337 (when step
19338 (org-clocktable-steps params)
19339 (throw 'exit nil))
19340 (when block
19341 (setq cc (org-clock-special-range block nil t)
19342 ts (car cc) te (cdr cc)))
19343 (if ts (setq ts (time-to-seconds
19344 (apply 'encode-time (org-parse-time-string ts)))))
19345 (if te (setq te (time-to-seconds
19346 (apply 'encode-time (org-parse-time-string te)))))
19347 (move-marker ins (point))
19348 (setq ipos (point))
19350 ;; Get the right scope
19351 (setq pos (point))
19352 (save-restriction
19353 (cond
19354 ((not scope))
19355 ((eq scope 'file) (widen))
19356 ((eq scope 'subtree) (org-narrow-to-subtree))
19357 ((eq scope 'tree)
19358 (while (org-up-heading-safe))
19359 (org-narrow-to-subtree))
19360 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19361 (symbol-name scope)))
19362 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19363 (catch 'exit
19364 (while (org-up-heading-safe)
19365 (looking-at outline-regexp)
19366 (if (<= (org-reduced-level (funcall outline-level)) level)
19367 (throw 'exit nil))))
19368 (org-narrow-to-subtree))
19369 ((or (listp scope) (eq scope 'agenda))
19370 (let* ((files (if (listp scope) scope (org-agenda-files)))
19371 (scope 'agenda)
19372 (p1 (copy-sequence params))
19373 file)
19374 (plist-put p1 :tostring t)
19375 (plist-put p1 :multifile t)
19376 (plist-put p1 :scope 'file)
19377 (org-prepare-agenda-buffers files)
19378 (while (setq file (pop files))
19379 (with-current-buffer (find-buffer-visiting file)
19380 (push (org-clocktable-add-file
19381 file (org-dblock-write:clocktable p1)) tbl)
19382 (setq total-time (+ (or total-time 0)
19383 org-clock-file-total-minutes)))))))
19384 (goto-char pos)
19386 (unless (eq scope 'agenda)
19387 (org-clock-sum ts te)
19388 (goto-char (point-min))
19389 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19390 (goto-char p)
19391 (when (setq time (get-text-property p :org-clock-minutes))
19392 (save-excursion
19393 (beginning-of-line 1)
19394 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19395 (setq level (org-reduced-level
19396 (- (match-end 1) (match-beginning 1))))
19397 (<= level maxlevel))
19398 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19399 hdl (if (not link)
19400 (match-string 2)
19401 (org-make-link-string
19402 (format "file:%s::%s"
19403 (buffer-file-name)
19404 (save-match-data
19405 (org-make-org-heading-search-string
19406 (match-string 2))))
19407 (match-string 2)))
19408 h (/ time 60)
19409 m (- time (* 60 h)))
19410 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19411 (push (concat
19412 "| " (int-to-string level) "|" hlc hdl hlc " |"
19413 (make-string (1- level) ?|)
19414 hlc (format "%d:%02d" h m) hlc
19415 " |") tbl))))))
19416 (setq tbl (nreverse tbl))
19417 (if tostring
19418 (if tbl (mapconcat 'identity tbl "\n") nil)
19419 (goto-char ins)
19420 (insert-before-markers
19421 (or header
19422 (concat
19423 "Clock summary at ["
19424 (substring
19425 (format-time-string (cdr org-time-stamp-formats))
19426 1 -1)
19427 "]."
19428 (if block
19429 (format " Considered range is /%s/." block)
19431 "\n\n"))
19432 (if (eq scope 'agenda) "|File" "")
19433 "|L|Headline|Time|\n")
19434 (setq total-time (or total-time org-clock-file-total-minutes)
19435 h (/ total-time 60)
19436 m (- total-time (* 60 h)))
19437 (insert-before-markers
19438 "|-\n|"
19439 (if (eq scope 'agenda) "|" "")
19441 "*Total time*| "
19442 (format "*%d:%02d*" h m)
19443 "|\n|-\n")
19444 (setq tbl (delq nil tbl))
19445 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19446 (equal (substring (car tbl) 0 2) "|-"))
19447 (pop tbl))
19448 (insert-before-markers (mapconcat
19449 'identity (delq nil tbl)
19450 (if (eq scope 'agenda) "\n|-\n" "\n")))
19451 (backward-delete-char 1)
19452 (goto-char ipos)
19453 (skip-chars-forward "^|")
19454 (org-table-align))))))
19456 (defun org-clocktable-steps (params)
19457 (let* ((p1 (copy-sequence params))
19458 (ts (plist-get p1 :tstart))
19459 (te (plist-get p1 :tend))
19460 (step0 (plist-get p1 :step))
19461 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19462 (block (plist-get p1 :block))
19464 (when block
19465 (setq cc (org-clock-special-range block nil t)
19466 ts (car cc) te (cdr cc)))
19467 (if ts (setq ts (time-to-seconds
19468 (apply 'encode-time (org-parse-time-string ts)))))
19469 (if te (setq te (time-to-seconds
19470 (apply 'encode-time (org-parse-time-string te)))))
19471 (plist-put p1 :header "")
19472 (plist-put p1 :step nil)
19473 (plist-put p1 :block nil)
19474 (while (< ts te)
19475 (or (bolp) (insert "\n"))
19476 (plist-put p1 :tstart (format-time-string
19477 (car org-time-stamp-formats)
19478 (seconds-to-time ts)))
19479 (plist-put p1 :tend (format-time-string
19480 (car org-time-stamp-formats)
19481 (seconds-to-time (setq ts (+ ts step)))))
19482 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19483 (plist-get p1 :tstart) "\n")
19484 (org-dblock-write:clocktable p1)
19485 (re-search-forward "#\\+END:")
19486 (end-of-line 0))))
19489 (defun org-clocktable-add-file (file table)
19490 (if table
19491 (let ((lines (org-split-string table "\n"))
19492 (ff (file-name-nondirectory file)))
19493 (mapconcat 'identity
19494 (mapcar (lambda (x)
19495 (if (string-match org-table-dataline-regexp x)
19496 (concat "|" ff x)
19498 lines)
19499 "\n"))))
19501 ;; FIXME: I don't think anybody uses this, ask David
19502 (defun org-collect-clock-time-entries ()
19503 "Return an internal list with clocking information.
19504 This list has one entry for each CLOCK interval.
19505 FIXME: describe the elements."
19506 (interactive)
19507 (let ((re (concat "^[ \t]*" org-clock-string
19508 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19509 rtn beg end next cont level title total closedp leafp
19510 clockpos titlepos h m donep)
19511 (save-excursion
19512 (org-clock-sum)
19513 (goto-char (point-min))
19514 (while (re-search-forward re nil t)
19515 (setq clockpos (match-beginning 0)
19516 beg (match-string 1) end (match-string 2)
19517 cont (match-end 0))
19518 (setq beg (apply 'encode-time (org-parse-time-string beg))
19519 end (apply 'encode-time (org-parse-time-string end)))
19520 (org-back-to-heading t)
19521 (setq donep (org-entry-is-done-p))
19522 (setq titlepos (point)
19523 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19524 h (/ total 60) m (- total (* 60 h))
19525 total (cons h m))
19526 (looking-at "\\(\\*+\\) +\\(.*\\)")
19527 (setq level (- (match-end 1) (match-beginning 1))
19528 title (org-match-string-no-properties 2))
19529 (save-excursion (outline-next-heading) (setq next (point)))
19530 (setq closedp (re-search-forward org-closed-time-regexp next t))
19531 (goto-char next)
19532 (setq leafp (and (looking-at "^\\*+ ")
19533 (<= (- (match-end 0) (point)) level)))
19534 (push (list beg end clockpos closedp donep
19535 total title titlepos level leafp)
19536 rtn)
19537 (goto-char cont)))
19538 (nreverse rtn)))
19540 ;;;; Agenda, and Diary Integration
19542 ;;; Define the Org-agenda-mode
19544 (defvar org-agenda-mode-map (make-sparse-keymap)
19545 "Keymap for `org-agenda-mode'.")
19547 (defvar org-agenda-menu) ; defined later in this file.
19548 (defvar org-agenda-follow-mode nil)
19549 (defvar org-agenda-show-log nil)
19550 (defvar org-agenda-redo-command nil)
19551 (defvar org-agenda-query-string nil)
19552 (defvar org-agenda-mode-hook nil)
19553 (defvar org-agenda-type nil)
19554 (defvar org-agenda-force-single-file nil)
19556 (defun org-agenda-mode ()
19557 "Mode for time-sorted view on action items in Org-mode files.
19559 The following commands are available:
19561 \\{org-agenda-mode-map}"
19562 (interactive)
19563 (kill-all-local-variables)
19564 (setq org-agenda-undo-list nil
19565 org-agenda-pending-undo-list nil)
19566 (setq major-mode 'org-agenda-mode)
19567 ;; Keep global-font-lock-mode from turning on font-lock-mode
19568 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19569 (setq mode-name "Org-Agenda")
19570 (use-local-map org-agenda-mode-map)
19571 (easy-menu-add org-agenda-menu)
19572 (if org-startup-truncated (setq truncate-lines t))
19573 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19574 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19575 ;; Make sure properties are removed when copying text
19576 (when (boundp 'buffer-substring-filters)
19577 (org-set-local 'buffer-substring-filters
19578 (cons (lambda (x)
19579 (set-text-properties 0 (length x) nil x) x)
19580 buffer-substring-filters)))
19581 (unless org-agenda-keep-modes
19582 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19583 org-agenda-show-log nil))
19584 (easy-menu-change
19585 '("Agenda") "Agenda Files"
19586 (append
19587 (list
19588 (vector
19589 (if (get 'org-agenda-files 'org-restrict)
19590 "Restricted to single file"
19591 "Edit File List")
19592 '(org-edit-agenda-file-list)
19593 (not (get 'org-agenda-files 'org-restrict)))
19594 "--")
19595 (mapcar 'org-file-menu-entry (org-agenda-files))))
19596 (org-agenda-set-mode-name)
19597 (apply
19598 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19599 (list 'org-agenda-mode-hook)))
19601 (substitute-key-definition 'undo 'org-agenda-undo
19602 org-agenda-mode-map global-map)
19603 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19604 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19605 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19606 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19607 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19608 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19609 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19610 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19611 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19612 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19613 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19614 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19615 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19616 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19617 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19618 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19619 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19620 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19621 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19622 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19623 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19624 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19625 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19626 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19627 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19628 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19629 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19630 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19631 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19633 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19634 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19635 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19636 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19637 (while l (org-defkey org-agenda-mode-map
19638 (int-to-string (pop l)) 'digit-argument)))
19640 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19641 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19642 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19643 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19644 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19645 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19646 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19647 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19648 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19649 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19650 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19651 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19652 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19653 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19654 (org-defkey org-agenda-mode-map "n" 'next-line)
19655 (org-defkey org-agenda-mode-map "p" 'previous-line)
19656 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19657 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19658 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19659 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19660 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19661 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19662 (eval-after-load "calendar"
19663 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19664 'org-calendar-goto-agenda))
19665 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19666 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19667 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19668 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19669 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19670 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19671 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19672 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19673 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19674 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19675 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19676 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19677 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19678 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19679 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19680 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19681 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19682 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19683 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19684 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19685 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19686 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19688 (org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add)
19689 (org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract)
19690 (org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re)
19691 (org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re)
19693 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19694 "Local keymap for agenda entries from Org-mode.")
19696 (org-defkey org-agenda-keymap
19697 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19698 (org-defkey org-agenda-keymap
19699 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19700 (when org-agenda-mouse-1-follows-link
19701 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19702 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19703 '("Agenda"
19704 ("Agenda Files")
19705 "--"
19706 ["Show" org-agenda-show t]
19707 ["Go To (other window)" org-agenda-goto t]
19708 ["Go To (this window)" org-agenda-switch-to t]
19709 ["Follow Mode" org-agenda-follow-mode
19710 :style toggle :selected org-agenda-follow-mode :active t]
19711 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19712 "--"
19713 ["Cycle TODO" org-agenda-todo t]
19714 ["Archive subtree" org-agenda-archive t]
19715 ["Delete subtree" org-agenda-kill t]
19716 "--"
19717 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19718 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19719 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19720 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19721 "--"
19722 ("Tags and Properties"
19723 ["Show all Tags" org-agenda-show-tags t]
19724 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19725 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19726 "--"
19727 ["Column View" org-columns t])
19728 ("Date/Schedule"
19729 ["Schedule" org-agenda-schedule t]
19730 ["Set Deadline" org-agenda-deadline t]
19731 "--"
19732 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19733 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19734 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19735 ("Clock"
19736 ["Clock in" org-agenda-clock-in t]
19737 ["Clock out" org-agenda-clock-out t]
19738 ["Clock cancel" org-agenda-clock-cancel t]
19739 ["Goto running clock" org-clock-goto t])
19740 ("Priority"
19741 ["Set Priority" org-agenda-priority t]
19742 ["Increase Priority" org-agenda-priority-up t]
19743 ["Decrease Priority" org-agenda-priority-down t]
19744 ["Show Priority" org-agenda-show-priority t])
19745 ("Calendar/Diary"
19746 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19747 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19748 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19749 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19750 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19751 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19752 "--"
19753 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19754 "--"
19755 ("View"
19756 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19757 :style radio :selected (equal org-agenda-ndays 1)]
19758 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19759 :style radio :selected (equal org-agenda-ndays 7)]
19760 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19761 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19762 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19763 :style radio :selected (member org-agenda-ndays '(365 366))]
19764 "--"
19765 ["Show Logbook entries" org-agenda-log-mode
19766 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19767 ["Include Diary" org-agenda-toggle-diary
19768 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19769 ["Use Time Grid" org-agenda-toggle-time-grid
19770 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19771 ["Write view to file" org-write-agenda t]
19772 ["Rebuild buffer" org-agenda-redo t]
19773 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19774 "--"
19775 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19776 "--"
19777 ["Quit" org-agenda-quit t]
19778 ["Exit and Release Buffers" org-agenda-exit t]
19781 ;;; Agenda undo
19783 (defvar org-agenda-allow-remote-undo t
19784 "Non-nil means, allow remote undo from the agenda buffer.")
19785 (defvar org-agenda-undo-list nil
19786 "List of undoable operations in the agenda since last refresh.")
19787 (defvar org-agenda-undo-has-started-in nil
19788 "Buffers that have already seen `undo-start' in the current undo sequence.")
19789 (defvar org-agenda-pending-undo-list nil
19790 "In a series of undo commands, this is the list of remaning undo items.")
19792 (defmacro org-if-unprotected (&rest body)
19793 "Execute BODY if there is no `org-protected' text property at point."
19794 (declare (debug t))
19795 `(unless (get-text-property (point) 'org-protected)
19796 ,@body))
19798 (defmacro org-with-remote-undo (_buffer &rest _body)
19799 "Execute BODY while recording undo information in two buffers."
19800 (declare (indent 1) (debug t))
19801 `(let ((_cline (org-current-line))
19802 (_cmd this-command)
19803 (_buf1 (current-buffer))
19804 (_buf2 ,_buffer)
19805 (_undo1 buffer-undo-list)
19806 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19807 _c1 _c2)
19808 ,@_body
19809 (when org-agenda-allow-remote-undo
19810 (setq _c1 (org-verify-change-for-undo
19811 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19812 _c2 (org-verify-change-for-undo
19813 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19814 (when (or _c1 _c2)
19815 ;; make sure there are undo boundaries
19816 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19817 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19818 ;; remember which buffer to undo
19819 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19820 org-agenda-undo-list)))))
19822 (defun org-agenda-undo ()
19823 "Undo a remote editing step in the agenda.
19824 This undoes changes both in the agenda buffer and in the remote buffer
19825 that have been changed along."
19826 (interactive)
19827 (or org-agenda-allow-remote-undo
19828 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19829 (if (not (eq this-command last-command))
19830 (setq org-agenda-undo-has-started-in nil
19831 org-agenda-pending-undo-list org-agenda-undo-list))
19832 (if (not org-agenda-pending-undo-list)
19833 (error "No further undo information"))
19834 (let* ((entry (pop org-agenda-pending-undo-list))
19835 buf line cmd rembuf)
19836 (setq cmd (pop entry) line (pop entry))
19837 (setq rembuf (nth 2 entry))
19838 (org-with-remote-undo rembuf
19839 (while (bufferp (setq buf (pop entry)))
19840 (if (pop entry)
19841 (with-current-buffer buf
19842 (let ((last-undo-buffer buf)
19843 (inhibit-read-only t))
19844 (unless (memq buf org-agenda-undo-has-started-in)
19845 (push buf org-agenda-undo-has-started-in)
19846 (make-local-variable 'pending-undo-list)
19847 (undo-start))
19848 (while (and pending-undo-list
19849 (listp pending-undo-list)
19850 (not (car pending-undo-list)))
19851 (pop pending-undo-list))
19852 (undo-more 1))))))
19853 (goto-line line)
19854 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19856 (defun org-verify-change-for-undo (l1 l2)
19857 "Verify that a real change occurred between the undo lists L1 and L2."
19858 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19859 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19860 (not (eq l1 l2)))
19862 ;;; Agenda dispatch
19864 (defvar org-agenda-restrict nil)
19865 (defvar org-agenda-restrict-begin (make-marker))
19866 (defvar org-agenda-restrict-end (make-marker))
19867 (defvar org-agenda-last-dispatch-buffer nil)
19868 (defvar org-agenda-overriding-restriction nil)
19870 ;;;###autoload
19871 (defun org-agenda (arg &optional keys restriction)
19872 "Dispatch agenda commands to collect entries to the agenda buffer.
19873 Prompts for a command to execute. Any prefix arg will be passed
19874 on to the selected command. The default selections are:
19876 a Call `org-agenda-list' to display the agenda for current day or week.
19877 t Call `org-todo-list' to display the global todo list.
19878 T Call `org-todo-list' to display the global todo list, select only
19879 entries with a specific TODO keyword (the user gets a prompt).
19880 m Call `org-tags-view' to display headlines with tags matching
19881 a condition (the user is prompted for the condition).
19882 M Like `m', but select only TODO entries, no ordinary headlines.
19883 L Create a timeline for the current buffer.
19884 e Export views to associated files.
19886 More commands can be added by configuring the variable
19887 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19888 searches can be pre-defined in this way.
19890 If the current buffer is in Org-mode and visiting a file, you can also
19891 first press `<' once to indicate that the agenda should be temporarily
19892 \(until the next use of \\[org-agenda]) restricted to the current file.
19893 Pressing `<' twice means to restrict to the current subtree or region
19894 \(if active)."
19895 (interactive "P")
19896 (catch 'exit
19897 (let* ((prefix-descriptions nil)
19898 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19899 (org-agenda-custom-commands
19900 ;; normalize different versions
19901 (delq nil
19902 (mapcar
19903 (lambda (x)
19904 (cond ((stringp (cdr x))
19905 (push x prefix-descriptions)
19906 nil)
19907 ((stringp (nth 1 x)) x)
19908 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19909 (t (cons (car x) (cons "" (cdr x))))))
19910 org-agenda-custom-commands)))
19911 (buf (current-buffer))
19912 (bfn (buffer-file-name (buffer-base-buffer)))
19913 entry key type match lprops ans)
19914 ;; Turn off restriction unless there is an overriding one
19915 (unless org-agenda-overriding-restriction
19916 (put 'org-agenda-files 'org-restrict nil)
19917 (setq org-agenda-restrict nil)
19918 (move-marker org-agenda-restrict-begin nil)
19919 (move-marker org-agenda-restrict-end nil))
19920 ;; Delete old local properties
19921 (put 'org-agenda-redo-command 'org-lprops nil)
19922 ;; Remember where this call originated
19923 (setq org-agenda-last-dispatch-buffer (current-buffer))
19924 (unless keys
19925 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19926 keys (car ans)
19927 restriction (cdr ans)))
19928 ;; Estabish the restriction, if any
19929 (when (and (not org-agenda-overriding-restriction) restriction)
19930 (put 'org-agenda-files 'org-restrict (list bfn))
19931 (cond
19932 ((eq restriction 'region)
19933 (setq org-agenda-restrict t)
19934 (move-marker org-agenda-restrict-begin (region-beginning))
19935 (move-marker org-agenda-restrict-end (region-end)))
19936 ((eq restriction 'subtree)
19937 (save-excursion
19938 (setq org-agenda-restrict t)
19939 (org-back-to-heading t)
19940 (move-marker org-agenda-restrict-begin (point))
19941 (move-marker org-agenda-restrict-end
19942 (progn (org-end-of-subtree t)))))))
19944 (require 'calendar) ; FIXME: can we avoid this for some commands?
19945 ;; For example the todo list should not need it (but does...)
19946 (cond
19947 ((setq entry (assoc keys org-agenda-custom-commands))
19948 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19949 (progn
19950 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19951 (put 'org-agenda-redo-command 'org-lprops lprops)
19952 (cond
19953 ((eq type 'agenda)
19954 (org-let lprops '(org-agenda-list current-prefix-arg)))
19955 ((eq type 'alltodo)
19956 (org-let lprops '(org-todo-list current-prefix-arg)))
19957 ((eq type 'search)
19958 (org-let lprops '(org-search-view current-prefix-arg match)))
19959 ((eq type 'stuck)
19960 (org-let lprops '(org-agenda-list-stuck-projects
19961 current-prefix-arg)))
19962 ((eq type 'tags)
19963 (org-let lprops '(org-tags-view current-prefix-arg match)))
19964 ((eq type 'tags-todo)
19965 (org-let lprops '(org-tags-view '(4) match)))
19966 ((eq type 'todo)
19967 (org-let lprops '(org-todo-list match)))
19968 ((eq type 'tags-tree)
19969 (org-check-for-org-mode)
19970 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19971 ((eq type 'todo-tree)
19972 (org-check-for-org-mode)
19973 (org-let lprops
19974 '(org-occur (concat "^" outline-regexp "[ \t]*"
19975 (regexp-quote match) "\\>"))))
19976 ((eq type 'occur-tree)
19977 (org-check-for-org-mode)
19978 (org-let lprops '(org-occur match)))
19979 ((functionp type)
19980 (org-let lprops '(funcall type match)))
19981 ((fboundp type)
19982 (org-let lprops '(funcall type match)))
19983 (t (error "Invalid custom agenda command type %s" type))))
19984 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19985 ((equal keys "C")
19986 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19987 (customize-variable 'org-agenda-custom-commands))
19988 ((equal keys "a") (call-interactively 'org-agenda-list))
19989 ((equal keys "s") (call-interactively 'org-search-view))
19990 ((equal keys "t") (call-interactively 'org-todo-list))
19991 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19992 ((equal keys "m") (call-interactively 'org-tags-view))
19993 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19994 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19995 ((equal keys "L")
19996 (unless (org-mode-p)
19997 (error "This is not an Org-mode file"))
19998 (unless restriction
19999 (put 'org-agenda-files 'org-restrict (list bfn))
20000 (org-call-with-arg 'org-timeline arg)))
20001 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
20002 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
20003 ((equal keys "!") (customize-variable 'org-stuck-projects))
20004 (t (error "Invalid agenda key"))))))
20006 (defun org-agenda-normalize-custom-commands (cmds)
20007 (delq nil
20008 (mapcar
20009 (lambda (x)
20010 (cond ((stringp (cdr x)) nil)
20011 ((stringp (nth 1 x)) x)
20012 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
20013 (t (cons (car x) (cons "" (cdr x))))))
20014 cmds)))
20016 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
20017 "The user interface for selecting an agenda command."
20018 (catch 'exit
20019 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
20020 (restrict-ok (and bfn (org-mode-p)))
20021 (region-p (org-region-active-p))
20022 (custom org-agenda-custom-commands)
20023 (selstring "")
20024 restriction second-time
20025 c entry key type match prefixes rmheader header-end custom1 desc)
20026 (save-window-excursion
20027 (delete-other-windows)
20028 (org-switch-to-buffer-other-window " *Agenda Commands*")
20029 (erase-buffer)
20030 (insert (eval-when-compile
20031 (let ((header
20033 Press key for an agenda command: < Buffer,subtree/region restriction
20034 -------------------------------- > Remove restriction
20035 a Agenda for current week or day e Export agenda views
20036 t List of all TODO entries T Entries with special TODO kwd
20037 m Match a TAGS query M Like m, but only TODO entries
20038 L Timeline for current buffer # List stuck projects (!=configure)
20039 s Search for keywords C Configure custom agenda commands
20040 / Multi-occur
20042 (start 0))
20043 (while (string-match
20044 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
20045 header start)
20046 (setq start (match-end 0))
20047 (add-text-properties (match-beginning 2) (match-end 2)
20048 '(face bold) header))
20049 header)))
20050 (setq header-end (move-marker (make-marker) (point)))
20051 (while t
20052 (setq custom1 custom)
20053 (when (eq rmheader t)
20054 (goto-line 1)
20055 (re-search-forward ":" nil t)
20056 (delete-region (match-end 0) (point-at-eol))
20057 (forward-char 1)
20058 (looking-at "-+")
20059 (delete-region (match-end 0) (point-at-eol))
20060 (move-marker header-end (match-end 0)))
20061 (goto-char header-end)
20062 (delete-region (point) (point-max))
20063 (while (setq entry (pop custom1))
20064 (setq key (car entry) desc (nth 1 entry)
20065 type (nth 2 entry) match (nth 3 entry))
20066 (if (> (length key) 1)
20067 (add-to-list 'prefixes (string-to-char key))
20068 (insert
20069 (format
20070 "\n%-4s%-14s: %s"
20071 (org-add-props (copy-sequence key)
20072 '(face bold))
20073 (cond
20074 ((string-match "\\S-" desc) desc)
20075 ((eq type 'agenda) "Agenda for current week or day")
20076 ((eq type 'alltodo) "List of all TODO entries")
20077 ((eq type 'search) "Word search")
20078 ((eq type 'stuck) "List of stuck projects")
20079 ((eq type 'todo) "TODO keyword")
20080 ((eq type 'tags) "Tags query")
20081 ((eq type 'tags-todo) "Tags (TODO)")
20082 ((eq type 'tags-tree) "Tags tree")
20083 ((eq type 'todo-tree) "TODO kwd tree")
20084 ((eq type 'occur-tree) "Occur tree")
20085 ((functionp type) (if (symbolp type)
20086 (symbol-name type)
20087 "Lambda expression"))
20088 (t "???"))
20089 (cond
20090 ((stringp match)
20091 (org-add-props match nil 'face 'org-warning))
20092 (match
20093 (format "set of %d commands" (length match)))
20094 (t ""))))))
20095 (when prefixes
20096 (mapc (lambda (x)
20097 (insert
20098 (format "\n%s %s"
20099 (org-add-props (char-to-string x)
20100 nil 'face 'bold)
20101 (or (cdr (assoc (concat selstring (char-to-string x))
20102 prefix-descriptions))
20103 "Prefix key"))))
20104 prefixes))
20105 (goto-char (point-min))
20106 (when (fboundp 'fit-window-to-buffer)
20107 (if second-time
20108 (if (not (pos-visible-in-window-p (point-max)))
20109 (fit-window-to-buffer))
20110 (setq second-time t)
20111 (fit-window-to-buffer)))
20112 (message "Press key for agenda command%s:"
20113 (if (or restrict-ok org-agenda-overriding-restriction)
20114 (if org-agenda-overriding-restriction
20115 " (restriction lock active)"
20116 (if restriction
20117 (format " (restricted to %s)" restriction)
20118 " (unrestricted)"))
20119 ""))
20120 (setq c (read-char-exclusive))
20121 (message "")
20122 (cond
20123 ((assoc (char-to-string c) custom)
20124 (setq selstring (concat selstring (char-to-string c)))
20125 (throw 'exit (cons selstring restriction)))
20126 ((memq c prefixes)
20127 (setq selstring (concat selstring (char-to-string c))
20128 prefixes nil
20129 rmheader (or rmheader t)
20130 custom (delq nil (mapcar
20131 (lambda (x)
20132 (if (or (= (length (car x)) 1)
20133 (/= (string-to-char (car x)) c))
20135 (cons (substring (car x) 1) (cdr x))))
20136 custom))))
20137 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
20138 (message "Restriction is only possible in Org-mode buffers")
20139 (ding) (sit-for 1))
20140 ((eq c ?1)
20141 (org-agenda-remove-restriction-lock 'noupdate)
20142 (setq restriction 'buffer))
20143 ((eq c ?0)
20144 (org-agenda-remove-restriction-lock 'noupdate)
20145 (setq restriction (if region-p 'region 'subtree)))
20146 ((eq c ?<)
20147 (org-agenda-remove-restriction-lock 'noupdate)
20148 (setq restriction
20149 (cond
20150 ((eq restriction 'buffer)
20151 (if region-p 'region 'subtree))
20152 ((memq restriction '(subtree region))
20153 nil)
20154 (t 'buffer))))
20155 ((eq c ?>)
20156 (org-agenda-remove-restriction-lock 'noupdate)
20157 (setq restriction nil))
20158 ((and (equal selstring "") (memq c '(?s ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
20159 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
20160 ((and (> (length selstring) 0) (eq c ?\d))
20161 (delete-window)
20162 (org-agenda-get-restriction-and-command prefix-descriptions))
20164 ((equal c ?q) (error "Abort"))
20165 (t (error "Invalid key %c" c))))))))
20167 (defun org-run-agenda-series (name series)
20168 (org-prepare-agenda name)
20169 (let* ((org-agenda-multi t)
20170 (redo (list 'org-run-agenda-series name (list 'quote series)))
20171 (cmds (car series))
20172 (gprops (nth 1 series))
20173 match ;; The byte compiler incorrectly complains about this. Keep it!
20174 cmd type lprops)
20175 (while (setq cmd (pop cmds))
20176 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
20177 (cond
20178 ((eq type 'agenda)
20179 (org-let2 gprops lprops
20180 '(call-interactively 'org-agenda-list)))
20181 ((eq type 'alltodo)
20182 (org-let2 gprops lprops
20183 '(call-interactively 'org-todo-list)))
20184 ((eq type 'search)
20185 (org-let2 gprops lprops
20186 '(org-search-view current-prefix-arg match)))
20187 ((eq type 'stuck)
20188 (org-let2 gprops lprops
20189 '(call-interactively 'org-agenda-list-stuck-projects)))
20190 ((eq type 'tags)
20191 (org-let2 gprops lprops
20192 '(org-tags-view current-prefix-arg match)))
20193 ((eq type 'tags-todo)
20194 (org-let2 gprops lprops
20195 '(org-tags-view '(4) match)))
20196 ((eq type 'todo)
20197 (org-let2 gprops lprops
20198 '(org-todo-list match)))
20199 ((fboundp type)
20200 (org-let2 gprops lprops
20201 '(funcall type match)))
20202 (t (error "Invalid type in command series"))))
20203 (widen)
20204 (setq org-agenda-redo-command redo)
20205 (goto-char (point-min)))
20206 (org-finalize-agenda))
20208 ;;;###autoload
20209 (defmacro org-batch-agenda (cmd-key &rest parameters)
20210 "Run an agenda command in batch mode and send the result to STDOUT.
20211 If CMD-KEY is a string of length 1, it is used as a key in
20212 `org-agenda-custom-commands' and triggers this command. If it is a
20213 longer string it is used as a tags/todo match string.
20214 Paramters are alternating variable names and values that will be bound
20215 before running the agenda command."
20216 (let (pars)
20217 (while parameters
20218 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20219 (if (> (length cmd-key) 2)
20220 (eval (list 'let (nreverse pars)
20221 (list 'org-tags-view nil cmd-key)))
20222 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20223 (set-buffer org-agenda-buffer-name)
20224 (princ (org-encode-for-stdout (buffer-string)))))
20226 (defun org-encode-for-stdout (string)
20227 (if (fboundp 'encode-coding-string)
20228 (encode-coding-string string buffer-file-coding-system)
20229 string))
20231 (defvar org-agenda-info nil)
20233 ;;;###autoload
20234 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
20235 "Run an agenda command in batch mode and send the result to STDOUT.
20236 If CMD-KEY is a string of length 1, it is used as a key in
20237 `org-agenda-custom-commands' and triggers this command. If it is a
20238 longer string it is used as a tags/todo match string.
20239 Paramters are alternating variable names and values that will be bound
20240 before running the agenda command.
20242 The output gives a line for each selected agenda item. Each
20243 item is a list of comma-separated values, like this:
20245 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
20247 category The category of the item
20248 head The headline, without TODO kwd, TAGS and PRIORITY
20249 type The type of the agenda entry, can be
20250 todo selected in TODO match
20251 tagsmatch selected in tags match
20252 diary imported from diary
20253 deadline a deadline on given date
20254 scheduled scheduled on given date
20255 timestamp entry has timestamp on given date
20256 closed entry was closed on given date
20257 upcoming-deadline warning about deadline
20258 past-scheduled forwarded scheduled item
20259 block entry has date block including g. date
20260 todo The todo keyword, if any
20261 tags All tags including inherited ones, separated by colons
20262 date The relevant date, like 2007-2-14
20263 time The time, like 15:00-16:50
20264 extra Sting with extra planning info
20265 priority-l The priority letter if any was given
20266 priority-n The computed numerical priority
20267 agenda-day The day in the agenda where this is listed"
20269 (let (pars)
20270 (while parameters
20271 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20272 (push (list 'org-agenda-remove-tags t) pars)
20273 (if (> (length cmd-key) 2)
20274 (eval (list 'let (nreverse pars)
20275 (list 'org-tags-view nil cmd-key)))
20276 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20277 (set-buffer org-agenda-buffer-name)
20278 (let* ((lines (org-split-string (buffer-string) "\n"))
20279 line)
20280 (while (setq line (pop lines))
20281 (catch 'next
20282 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
20283 (setq org-agenda-info
20284 (org-fix-agenda-info (text-properties-at 0 line)))
20285 (princ
20286 (org-encode-for-stdout
20287 (mapconcat 'org-agenda-export-csv-mapper
20288 '(org-category txt type todo tags date time-of-day extra
20289 priority-letter priority agenda-day)
20290 ",")))
20291 (princ "\n"))))))
20293 (defun org-fix-agenda-info (props)
20294 "Make sure all properties on an agenda item have a canonical form,
20295 so the export commands can easily use it."
20296 (let (tmp re)
20297 (when (setq tmp (plist-get props 'tags))
20298 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20299 (when (setq tmp (plist-get props 'date))
20300 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20301 (let ((calendar-date-display-form '(year "-" month "-" day)))
20302 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20304 (setq tmp (calendar-date-string tmp)))
20305 (setq props (plist-put props 'date tmp)))
20306 (when (setq tmp (plist-get props 'day))
20307 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20308 (let ((calendar-date-display-form '(year "-" month "-" day)))
20309 (setq tmp (calendar-date-string tmp)))
20310 (setq props (plist-put props 'day tmp))
20311 (setq props (plist-put props 'agenda-day tmp)))
20312 (when (setq tmp (plist-get props 'txt))
20313 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20314 (plist-put props 'priority-letter (match-string 1 tmp))
20315 (setq tmp (replace-match "" t t tmp)))
20316 (when (and (setq re (plist-get props 'org-todo-regexp))
20317 (setq re (concat "\\`\\.*" re " ?"))
20318 (string-match re tmp))
20319 (plist-put props 'todo (match-string 1 tmp))
20320 (setq tmp (replace-match "" t t tmp)))
20321 (plist-put props 'txt tmp)))
20322 props)
20324 (defun org-agenda-export-csv-mapper (prop)
20325 (let ((res (plist-get org-agenda-info prop)))
20326 (setq res
20327 (cond
20328 ((not res) "")
20329 ((stringp res) res)
20330 (t (prin1-to-string res))))
20331 (while (string-match "," res)
20332 (setq res (replace-match ";" t t res)))
20333 (org-trim res)))
20336 ;;;###autoload
20337 (defun org-store-agenda-views (&rest parameters)
20338 (interactive)
20339 (eval (list 'org-batch-store-agenda-views)))
20341 ;; FIXME, why is this a macro?????
20342 ;;;###autoload
20343 (defmacro org-batch-store-agenda-views (&rest parameters)
20344 "Run all custom agenda commands that have a file argument."
20345 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20346 (pop-up-frames nil)
20347 (dir default-directory)
20348 pars cmd thiscmdkey files opts)
20349 (while parameters
20350 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20351 (setq pars (reverse pars))
20352 (save-window-excursion
20353 (while cmds
20354 (setq cmd (pop cmds)
20355 thiscmdkey (car cmd)
20356 opts (nth 4 cmd)
20357 files (nth 5 cmd))
20358 (if (stringp files) (setq files (list files)))
20359 (when files
20360 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20361 (list 'org-agenda nil thiscmdkey)))
20362 (set-buffer org-agenda-buffer-name)
20363 (while files
20364 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20365 (list 'org-write-agenda
20366 (expand-file-name (pop files) dir) t))))
20367 (and (get-buffer org-agenda-buffer-name)
20368 (kill-buffer org-agenda-buffer-name)))))))
20370 (defun org-write-agenda (file &optional nosettings)
20371 "Write the current buffer (an agenda view) as a file.
20372 Depending on the extension of the file name, plain text (.txt),
20373 HTML (.html or .htm) or Postscript (.ps) is produced.
20374 If NOSETTINGS is given, do not scope the settings of
20375 `org-agenda-exporter-settings' into the export commands. This is used when
20376 the settings have already been scoped and we do not wish to overrule other,
20377 higher priority settings."
20378 (interactive "FWrite agenda to file: ")
20379 (if (not (file-writable-p file))
20380 (error "Cannot write agenda to file %s" file))
20381 (cond
20382 ((string-match "\\.html?\\'" file) (require 'htmlize))
20383 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20384 (org-let (if nosettings nil org-agenda-exporter-settings)
20385 '(save-excursion
20386 (save-window-excursion
20387 (cond
20388 ((string-match "\\.html?\\'" file)
20389 (set-buffer (htmlize-buffer (current-buffer)))
20391 (when (and org-agenda-export-html-style
20392 (string-match "<style>" org-agenda-export-html-style))
20393 ;; replace <style> section with org-agenda-export-html-style
20394 (goto-char (point-min))
20395 (kill-region (- (search-forward "<style") 6)
20396 (search-forward "</style>"))
20397 (insert org-agenda-export-html-style))
20398 (write-file file)
20399 (kill-buffer (current-buffer))
20400 (message "HTML written to %s" file))
20401 ((string-match "\\.ps\\'" file)
20402 (ps-print-buffer-with-faces file)
20403 (message "Postscript written to %s" file))
20405 (let ((bs (buffer-string)))
20406 (find-file file)
20407 (insert bs)
20408 (save-buffer 0)
20409 (kill-buffer (current-buffer))
20410 (message "Plain text written to %s" file))))))
20411 (set-buffer org-agenda-buffer-name)))
20413 (defmacro org-no-read-only (&rest body)
20414 "Inhibit read-only for BODY."
20415 `(let ((inhibit-read-only t)) ,@body))
20417 (defun org-check-for-org-mode ()
20418 "Make sure current buffer is in org-mode. Error if not."
20419 (or (org-mode-p)
20420 (error "Cannot execute org-mode agenda command on buffer in %s."
20421 major-mode)))
20423 (defun org-fit-agenda-window ()
20424 "Fit the window to the buffer size."
20425 (and (memq org-agenda-window-setup '(reorganize-frame))
20426 (fboundp 'fit-window-to-buffer)
20427 (fit-window-to-buffer
20429 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20430 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20432 ;;; Agenda file list
20434 (defun org-agenda-files (&optional unrestricted)
20435 "Get the list of agenda files.
20436 Optional UNRESTRICTED means return the full list even if a restriction
20437 is currently in place."
20438 (let ((files
20439 (cond
20440 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20441 ((stringp org-agenda-files) (org-read-agenda-file-list))
20442 ((listp org-agenda-files) org-agenda-files)
20443 (t (error "Invalid value of `org-agenda-files'")))))
20444 (setq files (apply 'append
20445 (mapcar (lambda (f)
20446 (if (file-directory-p f)
20447 (directory-files f t
20448 org-agenda-file-regexp)
20449 (list f)))
20450 files)))
20451 (if org-agenda-skip-unavailable-files
20452 (delq nil
20453 (mapcar (function
20454 (lambda (file)
20455 (and (file-readable-p file) file)))
20456 files))
20457 files))) ; `org-check-agenda-file' will remove them from the list
20459 (defun org-edit-agenda-file-list ()
20460 "Edit the list of agenda files.
20461 Depending on setup, this either uses customize to edit the variable
20462 `org-agenda-files', or it visits the file that is holding the list. In the
20463 latter case, the buffer is set up in a way that saving it automatically kills
20464 the buffer and restores the previous window configuration."
20465 (interactive)
20466 (if (stringp org-agenda-files)
20467 (let ((cw (current-window-configuration)))
20468 (find-file org-agenda-files)
20469 (org-set-local 'org-window-configuration cw)
20470 (org-add-hook 'after-save-hook
20471 (lambda ()
20472 (set-window-configuration
20473 (prog1 org-window-configuration
20474 (kill-buffer (current-buffer))))
20475 (org-install-agenda-files-menu)
20476 (message "New agenda file list installed"))
20477 nil 'local)
20478 (message "%s" (substitute-command-keys
20479 "Edit list and finish with \\[save-buffer]")))
20480 (customize-variable 'org-agenda-files)))
20482 (defun org-store-new-agenda-file-list (list)
20483 "Set new value for the agenda file list and save it correcly."
20484 (if (stringp org-agenda-files)
20485 (let ((f org-agenda-files) b)
20486 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20487 (with-temp-file f
20488 (insert (mapconcat 'identity list "\n") "\n")))
20489 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20490 (setq org-agenda-files list)
20491 (customize-save-variable 'org-agenda-files org-agenda-files))))
20493 (defun org-read-agenda-file-list ()
20494 "Read the list of agenda files from a file."
20495 (when (stringp org-agenda-files)
20496 (with-temp-buffer
20497 (insert-file-contents org-agenda-files)
20498 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20501 ;;;###autoload
20502 (defun org-cycle-agenda-files ()
20503 "Cycle through the files in `org-agenda-files'.
20504 If the current buffer visits an agenda file, find the next one in the list.
20505 If the current buffer does not, find the first agenda file."
20506 (interactive)
20507 (let* ((fs (org-agenda-files t))
20508 (files (append fs (list (car fs))))
20509 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20510 file)
20511 (unless files (error "No agenda files"))
20512 (catch 'exit
20513 (while (setq file (pop files))
20514 (if (equal (file-truename file) tcf)
20515 (when (car files)
20516 (find-file (car files))
20517 (throw 'exit t))))
20518 (find-file (car fs)))
20519 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20521 (defun org-agenda-file-to-front (&optional to-end)
20522 "Move/add the current file to the top of the agenda file list.
20523 If the file is not present in the list, it is added to the front. If it is
20524 present, it is moved there. With optional argument TO-END, add/move to the
20525 end of the list."
20526 (interactive "P")
20527 (let ((org-agenda-skip-unavailable-files nil)
20528 (file-alist (mapcar (lambda (x)
20529 (cons (file-truename x) x))
20530 (org-agenda-files t)))
20531 (ctf (file-truename buffer-file-name))
20532 x had)
20533 (setq x (assoc ctf file-alist) had x)
20535 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20536 (if to-end
20537 (setq file-alist (append (delq x file-alist) (list x)))
20538 (setq file-alist (cons x (delq x file-alist))))
20539 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20540 (org-install-agenda-files-menu)
20541 (message "File %s to %s of agenda file list"
20542 (if had "moved" "added") (if to-end "end" "front"))))
20544 (defun org-remove-file (&optional file)
20545 "Remove current file from the list of files in variable `org-agenda-files'.
20546 These are the files which are being checked for agenda entries.
20547 Optional argument FILE means, use this file instead of the current."
20548 (interactive)
20549 (let* ((org-agenda-skip-unavailable-files nil)
20550 (file (or file buffer-file-name))
20551 (true-file (file-truename file))
20552 (afile (abbreviate-file-name file))
20553 (files (delq nil (mapcar
20554 (lambda (x)
20555 (if (equal true-file
20556 (file-truename x))
20557 nil x))
20558 (org-agenda-files t)))))
20559 (if (not (= (length files) (length (org-agenda-files t))))
20560 (progn
20561 (org-store-new-agenda-file-list files)
20562 (org-install-agenda-files-menu)
20563 (message "Removed file: %s" afile))
20564 (message "File was not in list: %s (not removed)" afile))))
20566 (defun org-file-menu-entry (file)
20567 (vector file (list 'find-file file) t))
20569 (defun org-check-agenda-file (file)
20570 "Make sure FILE exists. If not, ask user what to do."
20571 (when (not (file-exists-p file))
20572 (message "non-existent file %s. [R]emove from list or [A]bort?"
20573 (abbreviate-file-name file))
20574 (let ((r (downcase (read-char-exclusive))))
20575 (cond
20576 ((equal r ?r)
20577 (org-remove-file file)
20578 (throw 'nextfile t))
20579 (t (error "Abort"))))))
20581 ;;; Agenda prepare and finalize
20583 (defvar org-agenda-multi nil) ; dynammically scoped
20584 (defvar org-agenda-buffer-name "*Org Agenda*")
20585 (defvar org-pre-agenda-window-conf nil)
20586 (defvar org-agenda-name nil)
20587 (defun org-prepare-agenda (&optional name)
20588 (setq org-todo-keywords-for-agenda nil)
20589 (setq org-done-keywords-for-agenda nil)
20590 (if org-agenda-multi
20591 (progn
20592 (setq buffer-read-only nil)
20593 (goto-char (point-max))
20594 (unless (or (bobp) org-agenda-compact-blocks)
20595 (insert "\n" (make-string (window-width) ?=) "\n"))
20596 (narrow-to-region (point) (point-max)))
20597 (org-agenda-reset-markers)
20598 (org-prepare-agenda-buffers (org-agenda-files))
20599 (setq org-todo-keywords-for-agenda
20600 (org-uniquify org-todo-keywords-for-agenda))
20601 (setq org-done-keywords-for-agenda
20602 (org-uniquify org-done-keywords-for-agenda))
20603 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20604 (awin (get-buffer-window abuf)))
20605 (cond
20606 ((equal (current-buffer) abuf) nil)
20607 (awin (select-window awin))
20608 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20609 ((equal org-agenda-window-setup 'current-window)
20610 (switch-to-buffer abuf))
20611 ((equal org-agenda-window-setup 'other-window)
20612 (org-switch-to-buffer-other-window abuf))
20613 ((equal org-agenda-window-setup 'other-frame)
20614 (switch-to-buffer-other-frame abuf))
20615 ((equal org-agenda-window-setup 'reorganize-frame)
20616 (delete-other-windows)
20617 (org-switch-to-buffer-other-window abuf))))
20618 (setq buffer-read-only nil)
20619 (erase-buffer)
20620 (org-agenda-mode)
20621 (and name (not org-agenda-name)
20622 (org-set-local 'org-agenda-name name)))
20623 (setq buffer-read-only nil))
20625 (defun org-finalize-agenda ()
20626 "Finishing touch for the agenda buffer, called just before displaying it."
20627 (unless org-agenda-multi
20628 (save-excursion
20629 (let ((inhibit-read-only t))
20630 (goto-char (point-min))
20631 (while (org-activate-bracket-links (point-max))
20632 (add-text-properties (match-beginning 0) (match-end 0)
20633 '(face org-link)))
20634 (org-agenda-align-tags)
20635 (unless org-agenda-with-colors
20636 (remove-text-properties (point-min) (point-max) '(face nil))))
20637 (if (and (boundp 'org-overriding-columns-format)
20638 org-overriding-columns-format)
20639 (org-set-local 'org-overriding-columns-format
20640 org-overriding-columns-format))
20641 (if (and (boundp 'org-agenda-view-columns-initially)
20642 org-agenda-view-columns-initially)
20643 (org-agenda-columns))
20644 (when org-agenda-fontify-priorities
20645 (org-fontify-priorities))
20646 (run-hooks 'org-finalize-agenda-hook)
20647 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20650 (defun org-fontify-priorities ()
20651 "Make highest priority lines bold, and lowest italic."
20652 (interactive)
20653 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20654 (org-delete-overlay o)))
20655 (org-overlays-in (point-min) (point-max)))
20656 (save-excursion
20657 (let ((inhibit-read-only t)
20658 b e p ov h l)
20659 (goto-char (point-min))
20660 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20661 (setq h (or (get-char-property (point) 'org-highest-priority)
20662 org-highest-priority)
20663 l (or (get-char-property (point) 'org-lowest-priority)
20664 org-lowest-priority)
20665 p (string-to-char (match-string 1))
20666 b (match-beginning 0) e (point-at-eol)
20667 ov (org-make-overlay b e))
20668 (org-overlay-put
20669 ov 'face
20670 (cond ((listp org-agenda-fontify-priorities)
20671 (cdr (assoc p org-agenda-fontify-priorities)))
20672 ((equal p l) 'italic)
20673 ((equal p h) 'bold)))
20674 (org-overlay-put ov 'org-type 'org-priority)))))
20676 (defun org-prepare-agenda-buffers (files)
20677 "Create buffers for all agenda files, protect archived trees and comments."
20678 (interactive)
20679 (let ((pa '(:org-archived t))
20680 (pc '(:org-comment t))
20681 (pall '(:org-archived t :org-comment t))
20682 (inhibit-read-only t)
20683 (rea (concat ":" org-archive-tag ":"))
20684 bmp file re)
20685 (save-excursion
20686 (save-restriction
20687 (while (setq file (pop files))
20688 (if (bufferp file)
20689 (set-buffer file)
20690 (org-check-agenda-file file)
20691 (set-buffer (org-get-agenda-file-buffer file)))
20692 (widen)
20693 (setq bmp (buffer-modified-p))
20694 (org-refresh-category-properties)
20695 (setq org-todo-keywords-for-agenda
20696 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20697 (setq org-done-keywords-for-agenda
20698 (append org-done-keywords-for-agenda org-done-keywords))
20699 (save-excursion
20700 (remove-text-properties (point-min) (point-max) pall)
20701 (when org-agenda-skip-archived-trees
20702 (goto-char (point-min))
20703 (while (re-search-forward rea nil t)
20704 (if (org-on-heading-p t)
20705 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20706 (goto-char (point-min))
20707 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20708 (while (re-search-forward re nil t)
20709 (add-text-properties
20710 (match-beginning 0) (org-end-of-subtree t) pc)))
20711 (set-buffer-modified-p bmp))))))
20713 (defvar org-agenda-skip-function nil
20714 "Function to be called at each match during agenda construction.
20715 If this function returns nil, the current match should not be skipped.
20716 Otherwise, the function must return a position from where the search
20717 should be continued.
20718 This may also be a Lisp form, it will be evaluated.
20719 Never set this variable using `setq' or so, because then it will apply
20720 to all future agenda commands. Instead, bind it with `let' to scope
20721 it dynamically into the agenda-constructing command. A good way to set
20722 it is through options in org-agenda-custom-commands.")
20724 (defun org-agenda-skip ()
20725 "Throw to `:skip' in places that should be skipped.
20726 Also moves point to the end of the skipped region, so that search can
20727 continue from there."
20728 (let ((p (point-at-bol)) to fp)
20729 (and org-agenda-skip-archived-trees
20730 (get-text-property p :org-archived)
20731 (org-end-of-subtree t)
20732 (throw :skip t))
20733 (and (get-text-property p :org-comment)
20734 (org-end-of-subtree t)
20735 (throw :skip t))
20736 (if (equal (char-after p) ?#) (throw :skip t))
20737 (when (and (or (setq fp (functionp org-agenda-skip-function))
20738 (consp org-agenda-skip-function))
20739 (setq to (save-excursion
20740 (save-match-data
20741 (if fp
20742 (funcall org-agenda-skip-function)
20743 (eval org-agenda-skip-function))))))
20744 (goto-char to)
20745 (throw :skip t))))
20747 (defvar org-agenda-markers nil
20748 "List of all currently active markers created by `org-agenda'.")
20749 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20750 "Creation time of the last agenda marker.")
20752 (defun org-agenda-new-marker (&optional pos)
20753 "Return a new agenda marker.
20754 Org-mode keeps a list of these markers and resets them when they are
20755 no longer in use."
20756 (let ((m (copy-marker (or pos (point)))))
20757 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20758 (push m org-agenda-markers)
20761 (defun org-agenda-reset-markers ()
20762 "Reset markers created by `org-agenda'."
20763 (while org-agenda-markers
20764 (move-marker (pop org-agenda-markers) nil)))
20766 (defun org-get-agenda-file-buffer (file)
20767 "Get a buffer visiting FILE. If the buffer needs to be created, add
20768 it to the list of buffers which might be released later."
20769 (let ((buf (org-find-base-buffer-visiting file)))
20770 (if buf
20771 buf ; just return it
20772 ;; Make a new buffer and remember it
20773 (setq buf (find-file-noselect file))
20774 (if buf (push buf org-agenda-new-buffers))
20775 buf)))
20777 (defun org-release-buffers (blist)
20778 "Release all buffers in list, asking the user for confirmation when needed.
20779 When a buffer is unmodified, it is just killed. When modified, it is saved
20780 \(if the user agrees) and then killed."
20781 (let (buf file)
20782 (while (setq buf (pop blist))
20783 (setq file (buffer-file-name buf))
20784 (when (and (buffer-modified-p buf)
20785 file
20786 (y-or-n-p (format "Save file %s? " file)))
20787 (with-current-buffer buf (save-buffer)))
20788 (kill-buffer buf))))
20790 (defun org-get-category (&optional pos)
20791 "Get the category applying to position POS."
20792 (get-text-property (or pos (point)) 'org-category))
20794 ;;; Agenda timeline
20796 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20798 (defun org-timeline (&optional include-all)
20799 "Show a time-sorted view of the entries in the current org file.
20800 Only entries with a time stamp of today or later will be listed. With
20801 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20802 under the current date.
20803 If the buffer contains an active region, only check the region for
20804 dates."
20805 (interactive "P")
20806 (require 'calendar)
20807 (org-compile-prefix-format 'timeline)
20808 (org-set-sorting-strategy 'timeline)
20809 (let* ((dopast t)
20810 (dotodo include-all)
20811 (doclosed org-agenda-show-log)
20812 (entry buffer-file-name)
20813 (date (calendar-current-date))
20814 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20815 (end (if (org-region-active-p) (region-end) (point-max)))
20816 (day-numbers (org-get-all-dates beg end 'no-ranges
20817 t doclosed ; always include today
20818 org-timeline-show-empty-dates))
20819 (org-deadline-warning-days 0)
20820 (org-agenda-only-exact-dates t)
20821 (today (time-to-days (current-time)))
20822 (past t)
20823 args
20824 s e rtn d emptyp)
20825 (setq org-agenda-redo-command
20826 (list 'progn
20827 (list 'org-switch-to-buffer-other-window (current-buffer))
20828 (list 'org-timeline (list 'quote include-all))))
20829 (if (not dopast)
20830 ;; Remove past dates from the list of dates.
20831 (setq day-numbers (delq nil (mapcar (lambda(x)
20832 (if (>= x today) x nil))
20833 day-numbers))))
20834 (org-prepare-agenda (concat "Timeline "
20835 (file-name-nondirectory buffer-file-name)))
20836 (if doclosed (push :closed args))
20837 (push :timestamp args)
20838 (push :deadline args)
20839 (push :scheduled args)
20840 (push :sexp args)
20841 (if dotodo (push :todo args))
20842 (while (setq d (pop day-numbers))
20843 (if (and (listp d) (eq (car d) :omitted))
20844 (progn
20845 (setq s (point))
20846 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20847 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20848 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20849 (if (and (>= d today)
20850 dopast
20851 past)
20852 (progn
20853 (setq past nil)
20854 (insert (make-string 79 ?-) "\n")))
20855 (setq date (calendar-gregorian-from-absolute d))
20856 (setq s (point))
20857 (setq rtn (and (not emptyp)
20858 (apply 'org-agenda-get-day-entries entry
20859 date args)))
20860 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20861 (progn
20862 (insert
20863 (if (stringp org-agenda-format-date)
20864 (format-time-string org-agenda-format-date
20865 (org-time-from-absolute date))
20866 (funcall org-agenda-format-date date))
20867 "\n")
20868 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20869 (put-text-property s (1- (point)) 'org-date-line t)
20870 (if (equal d today)
20871 (put-text-property s (1- (point)) 'org-today t))
20872 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20873 (put-text-property s (1- (point)) 'day d)))))
20874 (goto-char (point-min))
20875 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20876 (point-min)))
20877 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20878 (org-finalize-agenda)
20879 (setq buffer-read-only t)))
20881 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20882 "Return a list of all relevant day numbers from BEG to END buffer positions.
20883 If NO-RANGES is non-nil, include only the start and end dates of a range,
20884 not every single day in the range. If FORCE-TODAY is non-nil, make
20885 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20886 inactive time stamps (those in square brackets) are included.
20887 When EMPTY is non-nil, also include days without any entries."
20888 (let ((re (concat
20889 (if pre-re pre-re "")
20890 (if inactive org-ts-regexp-both org-ts-regexp)))
20891 dates dates1 date day day1 day2 ts1 ts2)
20892 (if force-today
20893 (setq dates (list (time-to-days (current-time)))))
20894 (save-excursion
20895 (goto-char beg)
20896 (while (re-search-forward re end t)
20897 (setq day (time-to-days (org-time-string-to-time
20898 (substring (match-string 1) 0 10))))
20899 (or (memq day dates) (push day dates)))
20900 (unless no-ranges
20901 (goto-char beg)
20902 (while (re-search-forward org-tr-regexp end t)
20903 (setq ts1 (substring (match-string 1) 0 10)
20904 ts2 (substring (match-string 2) 0 10)
20905 day1 (time-to-days (org-time-string-to-time ts1))
20906 day2 (time-to-days (org-time-string-to-time ts2)))
20907 (while (< (setq day1 (1+ day1)) day2)
20908 (or (memq day1 dates) (push day1 dates)))))
20909 (setq dates (sort dates '<))
20910 (when empty
20911 (while (setq day (pop dates))
20912 (setq day2 (car dates))
20913 (push day dates1)
20914 (when (and day2 empty)
20915 (if (or (eq empty t)
20916 (and (numberp empty) (<= (- day2 day) empty)))
20917 (while (< (setq day (1+ day)) day2)
20918 (push (list day) dates1))
20919 (push (cons :omitted (- day2 day)) dates1))))
20920 (setq dates (nreverse dates1)))
20921 dates)))
20923 ;;; Agenda Daily/Weekly
20925 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20926 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20927 (defvar org-agenda-last-arguments nil
20928 "The arguments of the previous call to org-agenda")
20929 (defvar org-starting-day nil) ; local variable in the agenda buffer
20930 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20931 (defvar org-include-all-loc nil) ; local variable
20932 (defvar org-agenda-remove-date nil) ; dynamically scoped FIXME: not used???
20934 ;;;###autoload
20935 (defun org-agenda-list (&optional include-all start-day ndays)
20936 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20937 The view will be for the current day or week, but from the overview buffer
20938 you will be able to go to other days/weeks.
20940 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20941 all unfinished TODO items will also be shown, before the agenda.
20942 This feature is considered obsolete, please use the TODO list or a block
20943 agenda instead.
20945 With a numeric prefix argument in an interactive call, the agenda will
20946 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20947 the number of days. NDAYS defaults to `org-agenda-ndays'.
20949 START-DAY defaults to TODAY, or to the most recent match for the weekday
20950 given in `org-agenda-start-on-weekday'."
20951 (interactive "P")
20952 (if (and (integerp include-all) (> include-all 0))
20953 (setq ndays include-all include-all nil))
20954 (setq ndays (or ndays org-agenda-ndays)
20955 start-day (or start-day org-agenda-start-day))
20956 (if org-agenda-overriding-arguments
20957 (setq include-all (car org-agenda-overriding-arguments)
20958 start-day (nth 1 org-agenda-overriding-arguments)
20959 ndays (nth 2 org-agenda-overriding-arguments)))
20960 (if (stringp start-day)
20961 ;; Convert to an absolute day number
20962 (setq start-day (time-to-days (org-read-date nil t start-day))))
20963 (setq org-agenda-last-arguments (list include-all start-day ndays))
20964 (org-compile-prefix-format 'agenda)
20965 (org-set-sorting-strategy 'agenda)
20966 (require 'calendar)
20967 (let* ((org-agenda-start-on-weekday
20968 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20969 org-agenda-start-on-weekday nil))
20970 (thefiles (org-agenda-files))
20971 (files thefiles)
20972 (today (time-to-days
20973 (time-subtract (current-time)
20974 (list 0 (* 3600 org-extend-today-until) 0))))
20975 (sd (or start-day today))
20976 (start (if (or (null org-agenda-start-on-weekday)
20977 (< org-agenda-ndays 7))
20979 (let* ((nt (calendar-day-of-week
20980 (calendar-gregorian-from-absolute sd)))
20981 (n1 org-agenda-start-on-weekday)
20982 (d (- nt n1)))
20983 (- sd (+ (if (< d 0) 7 0) d)))))
20984 (day-numbers (list start))
20985 (day-cnt 0)
20986 (inhibit-redisplay (not debug-on-error))
20987 s e rtn rtnall file date d start-pos end-pos todayp nd)
20988 (setq org-agenda-redo-command
20989 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20990 ;; Make the list of days
20991 (setq ndays (or ndays org-agenda-ndays)
20992 nd ndays)
20993 (while (> ndays 1)
20994 (push (1+ (car day-numbers)) day-numbers)
20995 (setq ndays (1- ndays)))
20996 (setq day-numbers (nreverse day-numbers))
20997 (org-prepare-agenda "Day/Week")
20998 (org-set-local 'org-starting-day (car day-numbers))
20999 (org-set-local 'org-include-all-loc include-all)
21000 (org-set-local 'org-agenda-span
21001 (org-agenda-ndays-to-span nd))
21002 (when (and (or include-all org-agenda-include-all-todo)
21003 (member today day-numbers))
21004 (setq files thefiles
21005 rtnall nil)
21006 (while (setq file (pop files))
21007 (catch 'nextfile
21008 (org-check-agenda-file file)
21009 (setq date (calendar-gregorian-from-absolute today)
21010 rtn (org-agenda-get-day-entries
21011 file date :todo))
21012 (setq rtnall (append rtnall rtn))))
21013 (when rtnall
21014 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
21015 (add-text-properties (point-min) (1- (point))
21016 (list 'face 'org-agenda-structure))
21017 (insert (org-finalize-agenda-entries rtnall) "\n")))
21018 (unless org-agenda-compact-blocks
21019 (setq s (point))
21020 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
21021 "-agenda:\n")
21022 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
21023 'org-date-line t)))
21024 (while (setq d (pop day-numbers))
21025 (setq date (calendar-gregorian-from-absolute d)
21026 s (point))
21027 (if (or (setq todayp (= d today))
21028 (and (not start-pos) (= d sd)))
21029 (setq start-pos (point))
21030 (if (and start-pos (not end-pos))
21031 (setq end-pos (point))))
21032 (setq files thefiles
21033 rtnall nil)
21034 (while (setq file (pop files))
21035 (catch 'nextfile
21036 (org-check-agenda-file file)
21037 (if org-agenda-show-log
21038 (setq rtn (org-agenda-get-day-entries
21039 file date
21040 :deadline :scheduled :timestamp :sexp :closed))
21041 (setq rtn (org-agenda-get-day-entries
21042 file date
21043 :deadline :scheduled :sexp :timestamp)))
21044 (setq rtnall (append rtnall rtn))))
21045 (if org-agenda-include-diary
21046 (progn
21047 (require 'diary-lib)
21048 (setq rtn (org-get-entries-from-diary date))
21049 (setq rtnall (append rtnall rtn))))
21050 (if (or rtnall org-agenda-show-all-dates)
21051 (progn
21052 (setq day-cnt (1+ day-cnt))
21053 (insert
21054 (if (stringp org-agenda-format-date)
21055 (format-time-string org-agenda-format-date
21056 (org-time-from-absolute date))
21057 (funcall org-agenda-format-date date))
21058 "\n")
21059 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
21060 (put-text-property s (1- (point)) 'org-date-line t)
21061 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
21062 (if todayp (put-text-property s (1- (point)) 'org-today t))
21063 (if rtnall (insert
21064 (org-finalize-agenda-entries
21065 (org-agenda-add-time-grid-maybe
21066 rtnall nd todayp))
21067 "\n"))
21068 (put-text-property s (1- (point)) 'day d)
21069 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
21070 (goto-char (point-min))
21071 (org-fit-agenda-window)
21072 (unless (and (pos-visible-in-window-p (point-min))
21073 (pos-visible-in-window-p (point-max)))
21074 (goto-char (1- (point-max)))
21075 (recenter -1)
21076 (if (not (pos-visible-in-window-p (or start-pos 1)))
21077 (progn
21078 (goto-char (or start-pos 1))
21079 (recenter 1))))
21080 (goto-char (or start-pos 1))
21081 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
21082 (org-finalize-agenda)
21083 (setq buffer-read-only t)
21084 (message "")))
21086 (defun org-agenda-ndays-to-span (n)
21087 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
21089 ;;; Agenda word search
21091 (defvar org-agenda-search-history nil)
21093 ;;;###autoload
21094 (defun org-search-view (&optional arg string)
21095 "Show all entries that contain words or regular expressions.
21096 If the first character of the search string is an asterisks,
21097 search only the headlines.
21099 The search string is broken into \"words\" by splitting at whitespace.
21100 The individual words are then interpreted as a boolean expression with
21101 logical AND. Words prefixed with a minus must not occur in the entry.
21102 Words without a prefix or prefixed with a plus must occur in the entry.
21103 Matching is case-insensitive and the words are enclosed by word delimiters.
21105 Words enclosed by curly braces are interpreted as regular expressions
21106 that must or must not match in the entry.
21108 This command searches the agenda files, and in addition the files listed
21109 in `org-agenda-text-search-extra-files'."
21110 (interactive "P")
21111 (org-compile-prefix-format 'search)
21112 (org-set-sorting-strategy 'search)
21113 (org-prepare-agenda "SEARCH")
21114 (let* ((props (list 'face nil
21115 'done-face 'org-done
21116 'org-not-done-regexp org-not-done-regexp
21117 'org-todo-regexp org-todo-regexp
21118 'mouse-face 'highlight
21119 'keymap org-agenda-keymap
21120 'help-echo (format "mouse-2 or RET jump to location")))
21121 regexp rtn rtnall files file pos
21122 marker priority category tags c neg re
21123 ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
21124 (unless (and (not arg)
21125 (stringp string)
21126 (string-match "\\S-" string))
21127 (setq string (read-string "[+-]Word/{Regexp} ...: "
21128 (cond
21129 ((integerp arg) (cons string arg))
21130 (arg string))
21131 'org-agenda-search-history)))
21132 (setq org-agenda-redo-command
21133 (list 'org-search-view 'current-prefix-arg string))
21134 (setq org-agenda-query-string string)
21136 (if (equal (string-to-char string) ?*)
21137 (setq hdl-only t
21138 words (substring string 1))
21139 (setq words string))
21140 (setq words (org-split-string words))
21141 (mapc (lambda (w)
21142 (setq c (string-to-char w))
21143 (if (equal c ?-)
21144 (setq neg t w (substring w 1))
21145 (if (equal c ?+)
21146 (setq neg nil w (substring w 1))
21147 (setq neg nil)))
21148 (if (string-match "\\`{.*}\\'" w)
21149 (setq re (substring w 1 -1))
21150 (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>")))
21151 (if neg (push re regexps-) (push re regexps+)))
21152 words)
21153 (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b)))))
21154 (if (not regexps+)
21155 (setq regexp (concat "^" org-outline-regexp))
21156 (setq regexp (pop regexps+))
21157 (if hdl-only (setq regexp (concat "^" org-outline-regexp ".*?"
21158 regexp))))
21159 (setq files (append (org-agenda-files) org-agenda-text-search-extra-files)
21160 rtnall nil)
21161 (while (setq file (pop files))
21162 (setq ee nil)
21163 (catch 'nextfile
21164 (org-check-agenda-file file)
21165 (setq buffer (if (file-exists-p file)
21166 (org-get-agenda-file-buffer file)
21167 (error "No such file %s" file)))
21168 (if (not buffer)
21169 ;; If file does not exist, make sure an error message is sent
21170 (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s"
21171 file))))
21172 (with-current-buffer buffer
21173 (unless (org-mode-p)
21174 (error "Agenda file %s is not in `org-mode'" file))
21175 (let ((case-fold-search t))
21176 (save-excursion
21177 (save-restriction
21178 (if org-agenda-restrict
21179 (narrow-to-region org-agenda-restrict-begin
21180 org-agenda-restrict-end)
21181 (widen))
21182 (goto-char (point-min))
21183 (unless (or (org-on-heading-p)
21184 (outline-next-heading))
21185 (throw 'nextfile t))
21186 (goto-char (max (point-min) (1- (point))))
21187 (while (re-search-forward regexp nil t)
21188 (org-back-to-heading t)
21189 (skip-chars-forward "* ")
21190 (setq beg (point-at-bol)
21191 beg1 (point)
21192 end (progn (outline-next-heading) (point)))
21193 (catch :skip
21194 (goto-char beg)
21195 (org-agenda-skip)
21196 (setq str (buffer-substring-no-properties
21197 (point-at-bol)
21198 (if hdl-only (point-at-eol) end)))
21199 (mapc (lambda (wr) (when (string-match wr str)
21200 (goto-char (1- end))
21201 (throw :skip t)))
21202 regexps-)
21203 (mapc (lambda (wr) (unless (string-match wr str)
21204 (goto-char (1- end))
21205 (throw :skip t)))
21206 regexps+)
21207 (goto-char beg)
21208 (setq marker (org-agenda-new-marker (point))
21209 category (org-get-category)
21210 tags (org-get-tags-at (point))
21211 txt (org-format-agenda-item
21213 (buffer-substring-no-properties
21214 beg1 (point-at-eol))
21215 category tags))
21216 (org-add-props txt props
21217 'org-marker marker 'org-hd-marker marker
21218 'priority 1000 'org-category category
21219 'type "search")
21220 (push txt ee)
21221 (goto-char (1- end)))))))))
21222 (setq rtn (nreverse ee))
21223 (setq rtnall (append rtnall rtn)))
21224 (if org-agenda-overriding-header
21225 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21226 nil 'face 'org-agenda-structure) "\n")
21227 (insert "Search words: ")
21228 (add-text-properties (point-min) (1- (point))
21229 (list 'face 'org-agenda-structure))
21230 (setq pos (point))
21231 (insert string "\n")
21232 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21233 (setq pos (point))
21234 (unless org-agenda-multi
21235 (insert "Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit\n")
21236 (add-text-properties pos (1- (point))
21237 (list 'face 'org-agenda-structure))))
21238 (when rtnall
21239 (insert (org-finalize-agenda-entries rtnall) "\n"))
21240 (goto-char (point-min))
21241 (org-fit-agenda-window)
21242 (add-text-properties (point-min) (point-max) '(org-agenda-type search))
21243 (org-finalize-agenda)
21244 (setq buffer-read-only t)))
21246 ;;; Agenda TODO list
21248 (defvar org-select-this-todo-keyword nil)
21249 (defvar org-last-arg nil)
21251 ;;;###autoload
21252 (defun org-todo-list (arg)
21253 "Show all TODO entries from all agenda file in a single list.
21254 The prefix arg can be used to select a specific TODO keyword and limit
21255 the list to these. When using \\[universal-argument], you will be prompted
21256 for a keyword. A numeric prefix directly selects the Nth keyword in
21257 `org-todo-keywords-1'."
21258 (interactive "P")
21259 (require 'calendar)
21260 (org-compile-prefix-format 'todo)
21261 (org-set-sorting-strategy 'todo)
21262 (org-prepare-agenda "TODO")
21263 (let* ((today (time-to-days (current-time)))
21264 (date (calendar-gregorian-from-absolute today))
21265 (kwds org-todo-keywords-for-agenda)
21266 (completion-ignore-case t)
21267 (org-select-this-todo-keyword
21268 (if (stringp arg) arg
21269 (and arg (integerp arg) (> arg 0)
21270 (nth (1- arg) kwds))))
21271 rtn rtnall files file pos)
21272 (when (equal arg '(4))
21273 (setq org-select-this-todo-keyword
21274 (completing-read "Keyword (or KWD1|K2D2|...): "
21275 (mapcar 'list kwds) nil nil)))
21276 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
21277 (org-set-local 'org-last-arg arg)
21278 (setq org-agenda-redo-command
21279 '(org-todo-list (or current-prefix-arg org-last-arg)))
21280 (setq files (org-agenda-files)
21281 rtnall nil)
21282 (while (setq file (pop files))
21283 (catch 'nextfile
21284 (org-check-agenda-file file)
21285 (setq rtn (org-agenda-get-day-entries file date :todo))
21286 (setq rtnall (append rtnall rtn))))
21287 (if org-agenda-overriding-header
21288 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21289 nil 'face 'org-agenda-structure) "\n")
21290 (insert "Global list of TODO items of type: ")
21291 (add-text-properties (point-min) (1- (point))
21292 (list 'face 'org-agenda-structure))
21293 (setq pos (point))
21294 (insert (or org-select-this-todo-keyword "ALL") "\n")
21295 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21296 (setq pos (point))
21297 (unless org-agenda-multi
21298 (insert "Available with `N r': (0)ALL")
21299 (let ((n 0) s)
21300 (mapc (lambda (x)
21301 (setq s (format "(%d)%s" (setq n (1+ n)) x))
21302 (if (> (+ (current-column) (string-width s) 1) (frame-width))
21303 (insert "\n "))
21304 (insert " " s))
21305 kwds))
21306 (insert "\n"))
21307 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21308 (when rtnall
21309 (insert (org-finalize-agenda-entries rtnall) "\n"))
21310 (goto-char (point-min))
21311 (org-fit-agenda-window)
21312 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
21313 (org-finalize-agenda)
21314 (setq buffer-read-only t)))
21316 ;;; Agenda tags match
21318 ;;;###autoload
21319 (defun org-tags-view (&optional todo-only match)
21320 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
21321 The prefix arg TODO-ONLY limits the search to TODO entries."
21322 (interactive "P")
21323 (org-compile-prefix-format 'tags)
21324 (org-set-sorting-strategy 'tags)
21325 (let* ((org-tags-match-list-sublevels
21326 (if todo-only t org-tags-match-list-sublevels))
21327 (completion-ignore-case t)
21328 rtn rtnall files file pos matcher
21329 buffer)
21330 (setq matcher (org-make-tags-matcher match)
21331 match (car matcher) matcher (cdr matcher))
21332 (org-prepare-agenda (concat "TAGS " match))
21333 (setq org-agenda-query-string match)
21334 (setq org-agenda-redo-command
21335 (list 'org-tags-view (list 'quote todo-only)
21336 (list 'if 'current-prefix-arg nil 'org-agenda-query-string)))
21337 (setq files (org-agenda-files)
21338 rtnall nil)
21339 (while (setq file (pop files))
21340 (catch 'nextfile
21341 (org-check-agenda-file file)
21342 (setq buffer (if (file-exists-p file)
21343 (org-get-agenda-file-buffer file)
21344 (error "No such file %s" file)))
21345 (if (not buffer)
21346 ;; If file does not exist, merror message to agenda
21347 (setq rtn (list
21348 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21349 rtnall (append rtnall rtn))
21350 (with-current-buffer buffer
21351 (unless (org-mode-p)
21352 (error "Agenda file %s is not in `org-mode'" file))
21353 (save-excursion
21354 (save-restriction
21355 (if org-agenda-restrict
21356 (narrow-to-region org-agenda-restrict-begin
21357 org-agenda-restrict-end)
21358 (widen))
21359 (setq rtn (org-scan-tags 'agenda matcher todo-only))
21360 (setq rtnall (append rtnall rtn))))))))
21361 (if org-agenda-overriding-header
21362 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21363 nil 'face 'org-agenda-structure) "\n")
21364 (insert "Headlines with TAGS match: ")
21365 (add-text-properties (point-min) (1- (point))
21366 (list 'face 'org-agenda-structure))
21367 (setq pos (point))
21368 (insert match "\n")
21369 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21370 (setq pos (point))
21371 (unless org-agenda-multi
21372 (insert "Press `C-u r' to search again with new search string\n"))
21373 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21374 (when rtnall
21375 (insert (org-finalize-agenda-entries rtnall) "\n"))
21376 (goto-char (point-min))
21377 (org-fit-agenda-window)
21378 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
21379 (org-finalize-agenda)
21380 (setq buffer-read-only t)))
21382 ;;; Agenda Finding stuck projects
21384 (defvar org-agenda-skip-regexp nil
21385 "Regular expression used in skipping subtrees for the agenda.
21386 This is basically a temporary global variable that can be set and then
21387 used by user-defined selections using `org-agenda-skip-function'.")
21389 (defvar org-agenda-overriding-header nil
21390 "When this is set during todo and tags searches, will replace header.")
21392 (defun org-agenda-skip-subtree-when-regexp-matches ()
21393 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
21394 If yes, it returns the end position of this tree, causing agenda commands
21395 to skip this subtree. This is a function that can be put into
21396 `org-agenda-skip-function' for the duration of a command."
21397 (let ((end (save-excursion (org-end-of-subtree t)))
21398 skip)
21399 (save-excursion
21400 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
21401 (and skip end)))
21403 (defun org-agenda-skip-entry-if (&rest conditions)
21404 "Skip entry if any of CONDITIONS is true.
21405 See `org-agenda-skip-if' for details."
21406 (org-agenda-skip-if nil conditions))
21408 (defun org-agenda-skip-subtree-if (&rest conditions)
21409 "Skip entry if any of CONDITIONS is true.
21410 See `org-agenda-skip-if' for details."
21411 (org-agenda-skip-if t conditions))
21413 (defun org-agenda-skip-if (subtree conditions)
21414 "Checks current entity for CONDITIONS.
21415 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21416 the entry, i.e. the text before the next heading is checked.
21418 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21419 from different tests. Valid conditions are:
21421 scheduled Check if there is a scheduled cookie
21422 notscheduled Check if there is no scheduled cookie
21423 deadline Check if there is a deadline
21424 notdeadline Check if there is no deadline
21425 regexp Check if regexp matches
21426 notregexp Check if regexp does not match.
21428 The regexp is taken from the conditions list, it must come right after
21429 the `regexp' or `notregexp' element.
21431 If any of these conditions is met, this function returns the end point of
21432 the entity, causing the search to continue from there. This is a function
21433 that can be put into `org-agenda-skip-function' for the duration of a command."
21434 (let (beg end m)
21435 (org-back-to-heading t)
21436 (setq beg (point)
21437 end (if subtree
21438 (progn (org-end-of-subtree t) (point))
21439 (progn (outline-next-heading) (1- (point)))))
21440 (goto-char beg)
21441 (and
21443 (and (memq 'scheduled conditions)
21444 (re-search-forward org-scheduled-time-regexp end t))
21445 (and (memq 'notscheduled conditions)
21446 (not (re-search-forward org-scheduled-time-regexp end t)))
21447 (and (memq 'deadline conditions)
21448 (re-search-forward org-deadline-time-regexp end t))
21449 (and (memq 'notdeadline conditions)
21450 (not (re-search-forward org-deadline-time-regexp end t)))
21451 (and (setq m (memq 'regexp conditions))
21452 (stringp (nth 1 m))
21453 (re-search-forward (nth 1 m) end t))
21454 (and (setq m (memq 'notregexp conditions))
21455 (stringp (nth 1 m))
21456 (not (re-search-forward (nth 1 m) end t))))
21457 end)))
21459 ;;;###autoload
21460 (defun org-agenda-list-stuck-projects (&rest ignore)
21461 "Create agenda view for projects that are stuck.
21462 Stuck projects are project that have no next actions. For the definitions
21463 of what a project is and how to check if it stuck, customize the variable
21464 `org-stuck-projects'.
21465 MATCH is being ignored."
21466 (interactive)
21467 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21468 ;; FIXME: we could have used org-agenda-skip-if here.
21469 (org-agenda-overriding-header "List of stuck projects: ")
21470 (matcher (nth 0 org-stuck-projects))
21471 (todo (nth 1 org-stuck-projects))
21472 (todo-wds (if (member "*" todo)
21473 (progn
21474 (org-prepare-agenda-buffers (org-agenda-files))
21475 (org-delete-all
21476 org-done-keywords-for-agenda
21477 (copy-sequence org-todo-keywords-for-agenda)))
21478 todo))
21479 (todo-re (concat "^\\*+[ \t]+\\("
21480 (mapconcat 'identity todo-wds "\\|")
21481 "\\)\\>"))
21482 (tags (nth 2 org-stuck-projects))
21483 (tags-re (if (member "*" tags)
21484 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21485 (concat "^\\*+ .*:\\("
21486 (mapconcat 'identity tags "\\|")
21487 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21488 (gen-re (nth 3 org-stuck-projects))
21489 (re-list
21490 (delq nil
21491 (list
21492 (if todo todo-re)
21493 (if tags tags-re)
21494 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21495 gen-re)))))
21496 (setq org-agenda-skip-regexp
21497 (if re-list
21498 (mapconcat 'identity re-list "\\|")
21499 (error "No information how to identify unstuck projects")))
21500 (org-tags-view nil matcher)
21501 (with-current-buffer org-agenda-buffer-name
21502 (setq org-agenda-redo-command
21503 '(org-agenda-list-stuck-projects
21504 (or current-prefix-arg org-last-arg))))))
21506 ;;; Diary integration
21508 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21510 (defun org-get-entries-from-diary (date)
21511 "Get the (Emacs Calendar) diary entries for DATE."
21512 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21513 (diary-display-hook '(fancy-diary-display))
21514 (pop-up-frames nil)
21515 (list-diary-entries-hook
21516 (cons 'org-diary-default-entry list-diary-entries-hook))
21517 (diary-file-name-prefix-function nil) ; turn this feature off
21518 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21519 entries
21520 (org-disable-agenda-to-diary t))
21521 (save-excursion
21522 (save-window-excursion
21523 (funcall (if (fboundp 'diary-list-entries)
21524 'diary-list-entries 'list-diary-entries)
21525 date 1)))
21526 (if (not (get-buffer fancy-diary-buffer))
21527 (setq entries nil)
21528 (with-current-buffer fancy-diary-buffer
21529 (setq buffer-read-only nil)
21530 (if (zerop (buffer-size))
21531 ;; No entries
21532 (setq entries nil)
21533 ;; Omit the date and other unnecessary stuff
21534 (org-agenda-cleanup-fancy-diary)
21535 ;; Add prefix to each line and extend the text properties
21536 (if (zerop (buffer-size))
21537 (setq entries nil)
21538 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21539 (set-buffer-modified-p nil)
21540 (kill-buffer fancy-diary-buffer)))
21541 (when entries
21542 (setq entries (org-split-string entries "\n"))
21543 (setq entries
21544 (mapcar
21545 (lambda (x)
21546 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21547 ;; Extend the text properties to the beginning of the line
21548 (org-add-props x (text-properties-at (1- (length x)) x)
21549 'type "diary" 'date date))
21550 entries)))))
21552 (defun org-agenda-cleanup-fancy-diary ()
21553 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21554 This gets rid of the date, the underline under the date, and
21555 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21556 date. It also removes lines that contain only whitespace."
21557 (goto-char (point-min))
21558 (if (looking-at ".*?:[ \t]*")
21559 (progn
21560 (replace-match "")
21561 (re-search-forward "\n=+$" nil t)
21562 (replace-match "")
21563 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21564 (re-search-forward "\n=+$" nil t)
21565 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21566 (goto-char (point-min))
21567 (while (re-search-forward "^ +\n" nil t)
21568 (replace-match ""))
21569 (goto-char (point-min))
21570 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21571 (replace-match "")))
21573 ;; Make sure entries from the diary have the right text properties.
21574 (eval-after-load "diary-lib"
21575 '(if (boundp 'diary-modify-entry-list-string-function)
21576 ;; We can rely on the hook, nothing to do
21578 ;; Hook not avaiable, must use advice to make this work
21579 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21580 "Make the position visible."
21581 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21582 (stringp string)
21583 buffer-file-name)
21584 (setq string (org-modify-diary-entry-string string))))))
21586 (defun org-modify-diary-entry-string (string)
21587 "Add text properties to string, allowing org-mode to act on it."
21588 (org-add-props string nil
21589 'mouse-face 'highlight
21590 'keymap org-agenda-keymap
21591 'help-echo (if buffer-file-name
21592 (format "mouse-2 or RET jump to diary file %s"
21593 (abbreviate-file-name buffer-file-name))
21595 'org-agenda-diary-link t
21596 'org-marker (org-agenda-new-marker (point-at-bol))))
21598 (defun org-diary-default-entry ()
21599 "Add a dummy entry to the diary.
21600 Needed to avoid empty dates which mess up holiday display."
21601 ;; Catch the error if dealing with the new add-to-diary-alist
21602 (when org-disable-agenda-to-diary
21603 (condition-case nil
21604 (add-to-diary-list original-date "Org-mode dummy" "")
21605 (error
21606 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21608 ;;;###autoload
21609 (defun org-diary (&rest args)
21610 "Return diary information from org-files.
21611 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21612 It accesses org files and extracts information from those files to be
21613 listed in the diary. The function accepts arguments specifying what
21614 items should be listed. The following arguments are allowed:
21616 :timestamp List the headlines of items containing a date stamp or
21617 date range matching the selected date. Deadlines will
21618 also be listed, on the expiration day.
21620 :sexp List entries resulting from diary-like sexps.
21622 :deadline List any deadlines past due, or due within
21623 `org-deadline-warning-days'. The listing occurs only
21624 in the diary for *today*, not at any other date. If
21625 an entry is marked DONE, it is no longer listed.
21627 :scheduled List all items which are scheduled for the given date.
21628 The diary for *today* also contains items which were
21629 scheduled earlier and are not yet marked DONE.
21631 :todo List all TODO items from the org-file. This may be a
21632 long list - so this is not turned on by default.
21633 Like deadlines, these entries only show up in the
21634 diary for *today*, not at any other date.
21636 The call in the diary file should look like this:
21638 &%%(org-diary) ~/path/to/some/orgfile.org
21640 Use a separate line for each org file to check. Or, if you omit the file name,
21641 all files listed in `org-agenda-files' will be checked automatically:
21643 &%%(org-diary)
21645 If you don't give any arguments (as in the example above), the default
21646 arguments (:deadline :scheduled :timestamp :sexp) are used.
21647 So the example above may also be written as
21649 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21651 The function expects the lisp variables `entry' and `date' to be provided
21652 by the caller, because this is how the calendar works. Don't use this
21653 function from a program - use `org-agenda-get-day-entries' instead."
21654 (when (> (- (time-to-seconds (current-time))
21655 org-agenda-last-marker-time)
21657 (org-agenda-reset-markers))
21658 (org-compile-prefix-format 'agenda)
21659 (org-set-sorting-strategy 'agenda)
21660 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21661 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21662 (list entry)
21663 (org-agenda-files t)))
21664 file rtn results)
21665 (org-prepare-agenda-buffers files)
21666 ;; If this is called during org-agenda, don't return any entries to
21667 ;; the calendar. Org Agenda will list these entries itself.
21668 (if org-disable-agenda-to-diary (setq files nil))
21669 (while (setq file (pop files))
21670 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21671 (setq results (append results rtn)))
21672 (if results
21673 (concat (org-finalize-agenda-entries results) "\n"))))
21675 ;;; Agenda entry finders
21677 (defun org-agenda-get-day-entries (file date &rest args)
21678 "Does the work for `org-diary' and `org-agenda'.
21679 FILE is the path to a file to be checked for entries. DATE is date like
21680 the one returned by `calendar-current-date'. ARGS are symbols indicating
21681 which kind of entries should be extracted. For details about these, see
21682 the documentation of `org-diary'."
21683 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21684 (let* ((org-startup-folded nil)
21685 (org-startup-align-all-tables nil)
21686 (buffer (if (file-exists-p file)
21687 (org-get-agenda-file-buffer file)
21688 (error "No such file %s" file)))
21689 arg results rtn)
21690 (if (not buffer)
21691 ;; If file does not exist, make sure an error message ends up in diary
21692 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21693 (with-current-buffer buffer
21694 (unless (org-mode-p)
21695 (error "Agenda file %s is not in `org-mode'" file))
21696 (let ((case-fold-search nil))
21697 (save-excursion
21698 (save-restriction
21699 (if org-agenda-restrict
21700 (narrow-to-region org-agenda-restrict-begin
21701 org-agenda-restrict-end)
21702 (widen))
21703 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21704 (while (setq arg (pop args))
21705 (cond
21706 ((and (eq arg :todo)
21707 (equal date (calendar-current-date)))
21708 (setq rtn (org-agenda-get-todos))
21709 (setq results (append results rtn)))
21710 ((eq arg :timestamp)
21711 (setq rtn (org-agenda-get-blocks))
21712 (setq results (append results rtn))
21713 (setq rtn (org-agenda-get-timestamps))
21714 (setq results (append results rtn)))
21715 ((eq arg :sexp)
21716 (setq rtn (org-agenda-get-sexps))
21717 (setq results (append results rtn)))
21718 ((eq arg :scheduled)
21719 (setq rtn (org-agenda-get-scheduled))
21720 (setq results (append results rtn)))
21721 ((eq arg :closed)
21722 (setq rtn (org-agenda-get-closed))
21723 (setq results (append results rtn)))
21724 ((eq arg :deadline)
21725 (setq rtn (org-agenda-get-deadlines))
21726 (setq results (append results rtn))))))))
21727 results))))
21729 (defun org-entry-is-todo-p ()
21730 (member (org-get-todo-state) org-not-done-keywords))
21732 (defun org-entry-is-done-p ()
21733 (member (org-get-todo-state) org-done-keywords))
21735 (defun org-get-todo-state ()
21736 (save-excursion
21737 (org-back-to-heading t)
21738 (and (looking-at org-todo-line-regexp)
21739 (match-end 2)
21740 (match-string 2))))
21742 (defun org-at-date-range-p (&optional inactive-ok)
21743 "Is the cursor inside a date range?"
21744 (interactive)
21745 (save-excursion
21746 (catch 'exit
21747 (let ((pos (point)))
21748 (skip-chars-backward "^[<\r\n")
21749 (skip-chars-backward "<[")
21750 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21751 (>= (match-end 0) pos)
21752 (throw 'exit t))
21753 (skip-chars-backward "^<[\r\n")
21754 (skip-chars-backward "<[")
21755 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21756 (>= (match-end 0) pos)
21757 (throw 'exit t)))
21758 nil)))
21760 (defun org-agenda-get-todos ()
21761 "Return the TODO information for agenda display."
21762 (let* ((props (list 'face nil
21763 'done-face 'org-done
21764 'org-not-done-regexp org-not-done-regexp
21765 'org-todo-regexp org-todo-regexp
21766 'mouse-face 'highlight
21767 'keymap org-agenda-keymap
21768 'help-echo
21769 (format "mouse-2 or RET jump to org file %s"
21770 (abbreviate-file-name buffer-file-name))))
21771 ;; FIXME: get rid of the \n at some point but watch out
21772 (regexp (concat "^\\*+[ \t]+\\("
21773 (if org-select-this-todo-keyword
21774 (if (equal org-select-this-todo-keyword "*")
21775 org-todo-regexp
21776 (concat "\\<\\("
21777 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21778 "\\)\\>"))
21779 org-not-done-regexp)
21780 "[^\n\r]*\\)"))
21781 marker priority category tags
21782 ee txt beg end)
21783 (goto-char (point-min))
21784 (while (re-search-forward regexp nil t)
21785 (catch :skip
21786 (save-match-data
21787 (beginning-of-line)
21788 (setq beg (point) end (progn (outline-next-heading) (point)))
21789 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21790 (re-search-forward org-ts-regexp end t))
21791 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21792 (re-search-forward org-scheduled-time-regexp end t))
21793 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21794 (re-search-forward org-deadline-time-regexp end t)
21795 (org-deadline-close (match-string 1))))
21796 (goto-char (1+ beg))
21797 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21798 (throw :skip nil)))
21799 (goto-char beg)
21800 (org-agenda-skip)
21801 (goto-char (match-beginning 1))
21802 (setq marker (org-agenda-new-marker (match-beginning 0))
21803 category (org-get-category)
21804 tags (org-get-tags-at (point))
21805 txt (org-format-agenda-item "" (match-string 1) category tags)
21806 priority (1+ (org-get-priority txt)))
21807 (org-add-props txt props
21808 'org-marker marker 'org-hd-marker marker
21809 'priority priority 'org-category category
21810 'type "todo")
21811 (push txt ee)
21812 (if org-agenda-todo-list-sublevels
21813 (goto-char (match-end 1))
21814 (org-end-of-subtree 'invisible))))
21815 (nreverse ee)))
21817 (defconst org-agenda-no-heading-message
21818 "No heading for this item in buffer or region.")
21820 (defun org-agenda-get-timestamps ()
21821 "Return the date stamp information for agenda display."
21822 (let* ((props (list 'face nil
21823 'org-not-done-regexp org-not-done-regexp
21824 'org-todo-regexp org-todo-regexp
21825 'mouse-face 'highlight
21826 'keymap org-agenda-keymap
21827 'help-echo
21828 (format "mouse-2 or RET jump to org file %s"
21829 (abbreviate-file-name buffer-file-name))))
21830 (d1 (calendar-absolute-from-gregorian date))
21831 (remove-re
21832 (concat
21833 (regexp-quote
21834 (format-time-string
21835 "<%Y-%m-%d"
21836 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21837 ".*?>"))
21838 (regexp
21839 (concat
21840 (regexp-quote
21841 (substring
21842 (format-time-string
21843 (car org-time-stamp-formats)
21844 (apply 'encode-time ; DATE bound by calendar
21845 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21846 0 11))
21847 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21848 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21849 marker hdmarker deadlinep scheduledp donep tmp priority category
21850 ee txt timestr tags b0 b3 e3 head)
21851 (goto-char (point-min))
21852 (while (re-search-forward regexp nil t)
21853 (setq b0 (match-beginning 0)
21854 b3 (match-beginning 3) e3 (match-end 3))
21855 (catch :skip
21856 (and (org-at-date-range-p) (throw :skip nil))
21857 (org-agenda-skip)
21858 (if (and (match-end 1)
21859 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21860 (throw :skip nil))
21861 (if (and e3
21862 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21863 (throw :skip nil))
21864 (setq marker (org-agenda-new-marker b0)
21865 category (org-get-category b0)
21866 tmp (buffer-substring (max (point-min)
21867 (- b0 org-ds-keyword-length))
21869 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21870 deadlinep (string-match org-deadline-regexp tmp)
21871 scheduledp (string-match org-scheduled-regexp tmp)
21872 donep (org-entry-is-done-p))
21873 (if (or scheduledp deadlinep) (throw :skip t))
21874 (if (string-match ">" timestr)
21875 ;; substring should only run to end of time stamp
21876 (setq timestr (substring timestr 0 (match-end 0))))
21877 (save-excursion
21878 (if (re-search-backward "^\\*+ " nil t)
21879 (progn
21880 (goto-char (match-beginning 0))
21881 (setq hdmarker (org-agenda-new-marker)
21882 tags (org-get-tags-at))
21883 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21884 (setq head (match-string 1))
21885 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21886 (setq txt (org-format-agenda-item
21887 nil head category tags timestr nil
21888 remove-re)))
21889 (setq txt org-agenda-no-heading-message))
21890 (setq priority (org-get-priority txt))
21891 (org-add-props txt props
21892 'org-marker marker 'org-hd-marker hdmarker)
21893 (org-add-props txt nil 'priority priority
21894 'org-category category 'date date
21895 'type "timestamp")
21896 (push txt ee))
21897 (outline-next-heading)))
21898 (nreverse ee)))
21900 (defun org-agenda-get-sexps ()
21901 "Return the sexp information for agenda display."
21902 (require 'diary-lib)
21903 (let* ((props (list 'face nil
21904 'mouse-face 'highlight
21905 'keymap org-agenda-keymap
21906 'help-echo
21907 (format "mouse-2 or RET jump to org file %s"
21908 (abbreviate-file-name buffer-file-name))))
21909 (regexp "^&?%%(")
21910 marker category ee txt tags entry result beg b sexp sexp-entry)
21911 (goto-char (point-min))
21912 (while (re-search-forward regexp nil t)
21913 (catch :skip
21914 (org-agenda-skip)
21915 (setq beg (match-beginning 0))
21916 (goto-char (1- (match-end 0)))
21917 (setq b (point))
21918 (forward-sexp 1)
21919 (setq sexp (buffer-substring b (point)))
21920 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21921 (org-trim (match-string 1))
21922 ""))
21923 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21924 (when result
21925 (setq marker (org-agenda-new-marker beg)
21926 category (org-get-category beg))
21928 (if (string-match "\\S-" result)
21929 (setq txt result)
21930 (setq txt "SEXP entry returned empty string"))
21932 (setq txt (org-format-agenda-item
21933 "" txt category tags 'time))
21934 (org-add-props txt props 'org-marker marker)
21935 (org-add-props txt nil
21936 'org-category category 'date date
21937 'type "sexp")
21938 (push txt ee))))
21939 (nreverse ee)))
21941 (defun org-agenda-get-closed ()
21942 "Return the logged TODO entries for agenda display."
21943 (let* ((props (list 'mouse-face 'highlight
21944 'org-not-done-regexp org-not-done-regexp
21945 'org-todo-regexp org-todo-regexp
21946 'keymap org-agenda-keymap
21947 'help-echo
21948 (format "mouse-2 or RET jump to org file %s"
21949 (abbreviate-file-name buffer-file-name))))
21950 (regexp (concat
21951 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21952 (regexp-quote
21953 (substring
21954 (format-time-string
21955 (car org-time-stamp-formats)
21956 (apply 'encode-time ; DATE bound by calendar
21957 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21958 1 11))))
21959 marker hdmarker priority category tags closedp
21960 ee txt timestr)
21961 (goto-char (point-min))
21962 (while (re-search-forward regexp nil t)
21963 (catch :skip
21964 (org-agenda-skip)
21965 (setq marker (org-agenda-new-marker (match-beginning 0))
21966 closedp (equal (match-string 1) org-closed-string)
21967 category (org-get-category (match-beginning 0))
21968 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21969 ;; donep (org-entry-is-done-p)
21971 (if (string-match "\\]" timestr)
21972 ;; substring should only run to end of time stamp
21973 (setq timestr (substring timestr 0 (match-end 0))))
21974 (save-excursion
21975 (if (re-search-backward "^\\*+ " nil t)
21976 (progn
21977 (goto-char (match-beginning 0))
21978 (setq hdmarker (org-agenda-new-marker)
21979 tags (org-get-tags-at))
21980 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21981 (setq txt (org-format-agenda-item
21982 (if closedp "Closed: " "Clocked: ")
21983 (match-string 1) category tags timestr)))
21984 (setq txt org-agenda-no-heading-message))
21985 (setq priority 100000)
21986 (org-add-props txt props
21987 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21988 'priority priority 'org-category category
21989 'type "closed" 'date date
21990 'undone-face 'org-warning 'done-face 'org-done)
21991 (push txt ee))
21992 (goto-char (point-at-eol))))
21993 (nreverse ee)))
21995 (defun org-agenda-get-deadlines ()
21996 "Return the deadline information for agenda display."
21997 (let* ((props (list 'mouse-face 'highlight
21998 'org-not-done-regexp org-not-done-regexp
21999 'org-todo-regexp org-todo-regexp
22000 'keymap org-agenda-keymap
22001 'help-echo
22002 (format "mouse-2 or RET jump to org file %s"
22003 (abbreviate-file-name buffer-file-name))))
22004 (regexp org-deadline-time-regexp)
22005 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
22006 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
22007 d2 diff dfrac wdays pos pos1 category tags
22008 ee txt head face s upcomingp donep timestr)
22009 (goto-char (point-min))
22010 (while (re-search-forward regexp nil t)
22011 (catch :skip
22012 (org-agenda-skip)
22013 (setq s (match-string 1)
22014 pos (1- (match-beginning 1))
22015 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
22016 diff (- d2 d1)
22017 wdays (org-get-wdays s)
22018 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
22019 upcomingp (and todayp (> diff 0)))
22020 ;; When to show a deadline in the calendar:
22021 ;; If the expiration is within wdays warning time.
22022 ;; Past-due deadlines are only shown on the current date
22023 (if (or (and (<= diff wdays)
22024 (and todayp (not org-agenda-only-exact-dates)))
22025 (= diff 0))
22026 (save-excursion
22027 (setq category (org-get-category))
22028 (if (re-search-backward "^\\*+[ \t]+" nil t)
22029 (progn
22030 (goto-char (match-end 0))
22031 (setq pos1 (match-beginning 0))
22032 (setq tags (org-get-tags-at pos1))
22033 (setq head (buffer-substring-no-properties
22034 (point)
22035 (progn (skip-chars-forward "^\r\n")
22036 (point))))
22037 (setq donep (string-match org-looking-at-done-regexp head))
22038 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
22039 (setq timestr
22040 (concat (substring s (match-beginning 1)) " "))
22041 (setq timestr 'time))
22042 (if (and donep
22043 (or org-agenda-skip-deadline-if-done
22044 (not (= diff 0))))
22045 (setq txt nil)
22046 (setq txt (org-format-agenda-item
22047 (if (= diff 0)
22048 (car org-agenda-deadline-leaders)
22049 (format (nth 1 org-agenda-deadline-leaders)
22050 diff))
22051 head category tags timestr))))
22052 (setq txt org-agenda-no-heading-message))
22053 (when txt
22054 (setq face (org-agenda-deadline-face dfrac wdays))
22055 (org-add-props txt props
22056 'org-marker (org-agenda-new-marker pos)
22057 'org-hd-marker (org-agenda-new-marker pos1)
22058 'priority (+ (- diff)
22059 (org-get-priority txt))
22060 'org-category category
22061 'type (if upcomingp "upcoming-deadline" "deadline")
22062 'date (if upcomingp date d2)
22063 'face (if donep 'org-done face)
22064 'undone-face face 'done-face 'org-done)
22065 (push txt ee))))))
22066 (nreverse ee)))
22068 (defun org-agenda-deadline-face (fraction &optional wdays)
22069 "Return the face to displaying a deadline item.
22070 FRACTION is what fraction of the head-warning time has passed."
22071 (if (equal wdays 0) (setq fraction 1.))
22072 (let ((faces org-agenda-deadline-faces) f)
22073 (catch 'exit
22074 (while (setq f (pop faces))
22075 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
22077 (defun org-agenda-get-scheduled ()
22078 "Return the scheduled information for agenda display."
22079 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
22080 'org-todo-regexp org-todo-regexp
22081 'done-face 'org-done
22082 'mouse-face 'highlight
22083 'keymap org-agenda-keymap
22084 'help-echo
22085 (format "mouse-2 or RET jump to org file %s"
22086 (abbreviate-file-name buffer-file-name))))
22087 (regexp org-scheduled-time-regexp)
22088 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
22089 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
22090 d2 diff pos pos1 category tags
22091 ee txt head pastschedp donep face timestr s)
22092 (goto-char (point-min))
22093 (while (re-search-forward regexp nil t)
22094 (catch :skip
22095 (org-agenda-skip)
22096 (setq s (match-string 1)
22097 pos (1- (match-beginning 1))
22098 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
22099 ;;; is this right?
22100 ;;; do we need to do this for deadleine too????
22101 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
22102 diff (- d2 d1))
22103 (setq pastschedp (and todayp (< diff 0)))
22104 ;; When to show a scheduled item in the calendar:
22105 ;; If it is on or past the date.
22106 (if (or (and (< diff 0)
22107 (and todayp (not org-agenda-only-exact-dates)))
22108 (= diff 0))
22109 (save-excursion
22110 (setq category (org-get-category))
22111 (if (re-search-backward "^\\*+[ \t]+" nil t)
22112 (progn
22113 (goto-char (match-end 0))
22114 (setq pos1 (match-beginning 0))
22115 (setq tags (org-get-tags-at))
22116 (setq head (buffer-substring-no-properties
22117 (point)
22118 (progn (skip-chars-forward "^\r\n") (point))))
22119 (setq donep (string-match org-looking-at-done-regexp head))
22120 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
22121 (setq timestr
22122 (concat (substring s (match-beginning 1)) " "))
22123 (setq timestr 'time))
22124 (if (and donep
22125 (or org-agenda-skip-scheduled-if-done
22126 (not (= diff 0))))
22127 (setq txt nil)
22128 (setq txt (org-format-agenda-item
22129 (if (= diff 0)
22130 (car org-agenda-scheduled-leaders)
22131 (format (nth 1 org-agenda-scheduled-leaders)
22132 (- 1 diff)))
22133 head category tags timestr))))
22134 (setq txt org-agenda-no-heading-message))
22135 (when txt
22136 (setq face (if pastschedp
22137 'org-scheduled-previously
22138 'org-scheduled-today))
22139 (org-add-props txt props
22140 'undone-face face
22141 'face (if donep 'org-done face)
22142 'org-marker (org-agenda-new-marker pos)
22143 'org-hd-marker (org-agenda-new-marker pos1)
22144 'type (if pastschedp "past-scheduled" "scheduled")
22145 'date (if pastschedp d2 date)
22146 'priority (+ 94 (- 5 diff) (org-get-priority txt))
22147 'org-category category)
22148 (push txt ee))))))
22149 (nreverse ee)))
22151 (defun org-agenda-get-blocks ()
22152 "Return the date-range information for agenda display."
22153 (let* ((props (list 'face nil
22154 'org-not-done-regexp org-not-done-regexp
22155 'org-todo-regexp org-todo-regexp
22156 'mouse-face 'highlight
22157 'keymap org-agenda-keymap
22158 'help-echo
22159 (format "mouse-2 or RET jump to org file %s"
22160 (abbreviate-file-name buffer-file-name))))
22161 (regexp org-tr-regexp)
22162 (d0 (calendar-absolute-from-gregorian date))
22163 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
22164 donep head)
22165 (goto-char (point-min))
22166 (while (re-search-forward regexp nil t)
22167 (catch :skip
22168 (org-agenda-skip)
22169 (setq pos (point))
22170 (setq timestr (match-string 0)
22171 s1 (match-string 1)
22172 s2 (match-string 2)
22173 d1 (time-to-days (org-time-string-to-time s1))
22174 d2 (time-to-days (org-time-string-to-time s2)))
22175 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
22176 ;; Only allow days between the limits, because the normal
22177 ;; date stamps will catch the limits.
22178 (save-excursion
22179 (setq marker (org-agenda-new-marker (point)))
22180 (setq category (org-get-category))
22181 (if (re-search-backward "^\\*+ " nil t)
22182 (progn
22183 (goto-char (match-beginning 0))
22184 (setq hdmarker (org-agenda-new-marker (point)))
22185 (setq tags (org-get-tags-at))
22186 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
22187 (setq head (match-string 1))
22188 (and org-agenda-skip-timestamp-if-done
22189 (org-entry-is-done-p)
22190 (throw :skip t))
22191 (setq txt (org-format-agenda-item
22192 (format (if (= d1 d2) "" "(%d/%d): ")
22193 (1+ (- d0 d1)) (1+ (- d2 d1)))
22194 head category tags
22195 (if (= d0 d1) timestr))))
22196 (setq txt org-agenda-no-heading-message))
22197 (org-add-props txt props
22198 'org-marker marker 'org-hd-marker hdmarker
22199 'type "block" 'date date
22200 'priority (org-get-priority txt) 'org-category category)
22201 (push txt ee)))
22202 (goto-char pos)))
22203 ;; Sort the entries by expiration date.
22204 (nreverse ee)))
22206 ;;; Agenda presentation and sorting
22208 (defconst org-plain-time-of-day-regexp
22209 (concat
22210 "\\(\\<[012]?[0-9]"
22211 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22212 "\\(--?"
22213 "\\(\\<[012]?[0-9]"
22214 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22215 "\\)?")
22216 "Regular expression to match a plain time or time range.
22217 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22218 groups carry important information:
22219 0 the full match
22220 1 the first time, range or not
22221 8 the second time, if it is a range.")
22223 (defconst org-plain-time-extension-regexp
22224 (concat
22225 "\\(\\<[012]?[0-9]"
22226 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22227 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
22228 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
22229 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22230 groups carry important information:
22231 0 the full match
22232 7 hours of duration
22233 9 minutes of duration")
22235 (defconst org-stamp-time-of-day-regexp
22236 (concat
22237 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
22238 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
22239 "\\(--?"
22240 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
22241 "Regular expression to match a timestamp time or time range.
22242 After a match, the following groups carry important information:
22243 0 the full match
22244 1 date plus weekday, for backreferencing to make sure both times on same day
22245 2 the first time, range or not
22246 4 the second time, if it is a range.")
22248 (defvar org-prefix-has-time nil
22249 "A flag, set by `org-compile-prefix-format'.
22250 The flag is set if the currently compiled format contains a `%t'.")
22251 (defvar org-prefix-has-tag nil
22252 "A flag, set by `org-compile-prefix-format'.
22253 The flag is set if the currently compiled format contains a `%T'.")
22255 (defun org-format-agenda-item (extra txt &optional category tags dotime
22256 noprefix remove-re)
22257 "Format TXT to be inserted into the agenda buffer.
22258 In particular, it adds the prefix and corresponding text properties. EXTRA
22259 must be a string and replaces the `%s' specifier in the prefix format.
22260 CATEGORY (string, symbol or nil) may be used to overrule the default
22261 category taken from local variable or file name. It will replace the `%c'
22262 specifier in the format. DOTIME, when non-nil, indicates that a
22263 time-of-day should be extracted from TXT for sorting of this entry, and for
22264 the `%t' specifier in the format. When DOTIME is a string, this string is
22265 searched for a time before TXT is. NOPREFIX is a flag and indicates that
22266 only the correctly processes TXT should be returned - this is used by
22267 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
22268 Any match of REMOVE-RE will be removed from TXT."
22269 (save-match-data
22270 ;; Diary entries sometimes have extra whitespace at the beginning
22271 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
22272 (let* ((category (or category
22273 org-category
22274 (if buffer-file-name
22275 (file-name-sans-extension
22276 (file-name-nondirectory buffer-file-name))
22277 "")))
22278 (tag (if tags (nth (1- (length tags)) tags) ""))
22279 time ; time and tag are needed for the eval of the prefix format
22280 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
22281 (time-of-day (and dotime (org-get-time-of-day ts)))
22282 stamp plain s0 s1 s2 rtn srp)
22283 (when (and dotime time-of-day org-prefix-has-time)
22284 ;; Extract starting and ending time and move them to prefix
22285 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
22286 (setq plain (string-match org-plain-time-of-day-regexp ts)))
22287 (setq s0 (match-string 0 ts)
22288 srp (and stamp (match-end 3))
22289 s1 (match-string (if plain 1 2) ts)
22290 s2 (match-string (if plain 8 (if srp 4 6)) ts))
22292 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
22293 ;; them, we might want to remove them there to avoid duplication.
22294 ;; The user can turn this off with a variable.
22295 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
22296 (string-match (concat (regexp-quote s0) " *") txt)
22297 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
22298 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
22299 (= (match-beginning 0) 0)
22301 (setq txt (replace-match "" nil nil txt))))
22302 ;; Normalize the time(s) to 24 hour
22303 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
22304 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
22306 (when (and s1 (not s2) org-agenda-default-appointment-duration
22307 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
22308 (let ((m (+ (string-to-number (match-string 2 s1))
22309 (* 60 (string-to-number (match-string 1 s1)))
22310 org-agenda-default-appointment-duration))
22312 (setq h (/ m 60) m (- m (* h 60)))
22313 (setq s2 (format "%02d:%02d" h m))))
22315 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22316 txt)
22317 ;; Tags are in the string
22318 (if (or (eq org-agenda-remove-tags t)
22319 (and org-agenda-remove-tags
22320 org-prefix-has-tag))
22321 (setq txt (replace-match "" t t txt))
22322 (setq txt (replace-match
22323 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
22324 (match-string 2 txt))
22325 t t txt))))
22327 (when remove-re
22328 (while (string-match remove-re txt)
22329 (setq txt (replace-match "" t t txt))))
22331 ;; Create the final string
22332 (if noprefix
22333 (setq rtn txt)
22334 ;; Prepare the variables needed in the eval of the compiled format
22335 (setq time (cond (s2 (concat s1 "-" s2))
22336 (s1 (concat s1 "......"))
22337 (t ""))
22338 extra (or extra "")
22339 category (if (symbolp category) (symbol-name category) category))
22340 ;; Evaluate the compiled format
22341 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
22343 ;; And finally add the text properties
22344 (org-add-props rtn nil
22345 'org-category (downcase category) 'tags tags
22346 'org-highest-priority org-highest-priority
22347 'org-lowest-priority org-lowest-priority
22348 'prefix-length (- (length rtn) (length txt))
22349 'time-of-day time-of-day
22350 'txt txt
22351 'time time
22352 'extra extra
22353 'dotime dotime))))
22355 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
22356 (defvar org-agenda-sorting-strategy-selected nil)
22358 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
22359 (catch 'exit
22360 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
22361 ((and todayp (member 'today (car org-agenda-time-grid))))
22362 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
22363 ((member 'weekly (car org-agenda-time-grid)))
22364 (t (throw 'exit list)))
22365 (let* ((have (delq nil (mapcar
22366 (lambda (x) (get-text-property 1 'time-of-day x))
22367 list)))
22368 (string (nth 1 org-agenda-time-grid))
22369 (gridtimes (nth 2 org-agenda-time-grid))
22370 (req (car org-agenda-time-grid))
22371 (remove (member 'remove-match req))
22372 new time)
22373 (if (and (member 'require-timed req) (not have))
22374 ;; don't show empty grid
22375 (throw 'exit list))
22376 (while (setq time (pop gridtimes))
22377 (unless (and remove (member time have))
22378 (setq time (int-to-string time))
22379 (push (org-format-agenda-item
22380 nil string "" nil
22381 (concat (substring time 0 -2) ":" (substring time -2)))
22382 new)
22383 (put-text-property
22384 1 (length (car new)) 'face 'org-time-grid (car new))))
22385 (if (member 'time-up org-agenda-sorting-strategy-selected)
22386 (append new list)
22387 (append list new)))))
22389 (defun org-compile-prefix-format (key)
22390 "Compile the prefix format into a Lisp form that can be evaluated.
22391 The resulting form is returned and stored in the variable
22392 `org-prefix-format-compiled'."
22393 (setq org-prefix-has-time nil org-prefix-has-tag nil)
22394 (let ((s (cond
22395 ((stringp org-agenda-prefix-format)
22396 org-agenda-prefix-format)
22397 ((assq key org-agenda-prefix-format)
22398 (cdr (assq key org-agenda-prefix-format)))
22399 (t " %-12:c%?-12t% s")))
22400 (start 0)
22401 varform vars var e c f opt)
22402 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
22403 s start)
22404 (setq var (cdr (assoc (match-string 4 s)
22405 '(("c" . category) ("t" . time) ("s" . extra)
22406 ("T" . tag))))
22407 c (or (match-string 3 s) "")
22408 opt (match-beginning 1)
22409 start (1+ (match-beginning 0)))
22410 (if (equal var 'time) (setq org-prefix-has-time t))
22411 (if (equal var 'tag) (setq org-prefix-has-tag t))
22412 (setq f (concat "%" (match-string 2 s) "s"))
22413 (if opt
22414 (setq varform
22415 `(if (equal "" ,var)
22417 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22418 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22419 (setq s (replace-match "%s" t nil s))
22420 (push varform vars))
22421 (setq vars (nreverse vars))
22422 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22424 (defun org-set-sorting-strategy (key)
22425 (if (symbolp (car org-agenda-sorting-strategy))
22426 ;; the old format
22427 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22428 (setq org-agenda-sorting-strategy-selected
22429 (or (cdr (assq key org-agenda-sorting-strategy))
22430 (cdr (assq 'agenda org-agenda-sorting-strategy))
22431 '(time-up category-keep priority-down)))))
22433 (defun org-get-time-of-day (s &optional string mod24)
22434 "Check string S for a time of day.
22435 If found, return it as a military time number between 0 and 2400.
22436 If not found, return nil.
22437 The optional STRING argument forces conversion into a 5 character wide string
22438 HH:MM."
22439 (save-match-data
22440 (when
22441 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22442 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22443 (let* ((h (string-to-number (match-string 1 s)))
22444 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22445 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22446 (am-p (equal ampm "am"))
22447 (h1 (cond ((not ampm) h)
22448 ((= h 12) (if am-p 0 12))
22449 (t (+ h (if am-p 0 12)))))
22450 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22451 (mod h1 24) h1))
22452 (t0 (+ (* 100 h2) m))
22453 (t1 (concat (if (>= h1 24) "+" " ")
22454 (if (< t0 100) "0" "")
22455 (if (< t0 10) "0" "")
22456 (int-to-string t0))))
22457 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22459 (defun org-finalize-agenda-entries (list &optional nosort)
22460 "Sort and concatenate the agenda items."
22461 (setq list (mapcar 'org-agenda-highlight-todo list))
22462 (if nosort
22463 list
22464 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22466 (defun org-agenda-highlight-todo (x)
22467 (let (re pl)
22468 (if (eq x 'line)
22469 (save-excursion
22470 (beginning-of-line 1)
22471 (setq re (get-text-property (point) 'org-todo-regexp))
22472 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22473 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22474 (add-text-properties (match-beginning 0) (match-end 0)
22475 (list 'face (org-get-todo-face 0)))
22476 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22477 (delete-region (match-beginning 1) (1- (match-end 0)))
22478 (goto-char (match-beginning 1))
22479 (insert (format org-agenda-todo-keyword-format s)))))
22480 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22481 pl (get-text-property 0 'prefix-length x))
22482 (when (and re
22483 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22484 x (or pl 0)) pl))
22485 (add-text-properties
22486 (or (match-end 1) (match-end 0)) (match-end 0)
22487 (list 'face (org-get-todo-face (match-string 2 x)))
22489 (setq x (concat (substring x 0 (match-end 1))
22490 (format org-agenda-todo-keyword-format
22491 (match-string 2 x))
22493 (substring x (match-end 3)))))
22494 x)))
22496 (defsubst org-cmp-priority (a b)
22497 "Compare the priorities of string A and B."
22498 (let ((pa (or (get-text-property 1 'priority a) 0))
22499 (pb (or (get-text-property 1 'priority b) 0)))
22500 (cond ((> pa pb) +1)
22501 ((< pa pb) -1)
22502 (t nil))))
22504 (defsubst org-cmp-category (a b)
22505 "Compare the string values of categories of strings A and B."
22506 (let ((ca (or (get-text-property 1 'org-category a) ""))
22507 (cb (or (get-text-property 1 'org-category b) "")))
22508 (cond ((string-lessp ca cb) -1)
22509 ((string-lessp cb ca) +1)
22510 (t nil))))
22512 (defsubst org-cmp-tag (a b)
22513 "Compare the string values of categories of strings A and B."
22514 (let ((ta (car (last (get-text-property 1 'tags a))))
22515 (tb (car (last (get-text-property 1 'tags b)))))
22516 (cond ((not ta) +1)
22517 ((not tb) -1)
22518 ((string-lessp ta tb) -1)
22519 ((string-lessp tb ta) +1)
22520 (t nil))))
22522 (defsubst org-cmp-time (a b)
22523 "Compare the time-of-day values of strings A and B."
22524 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22525 (ta (or (get-text-property 1 'time-of-day a) def))
22526 (tb (or (get-text-property 1 'time-of-day b) def)))
22527 (cond ((< ta tb) -1)
22528 ((< tb ta) +1)
22529 (t nil))))
22531 (defun org-entries-lessp (a b)
22532 "Predicate for sorting agenda entries."
22533 ;; The following variables will be used when the form is evaluated.
22534 ;; So even though the compiler complains, keep them.
22535 (let* ((time-up (org-cmp-time a b))
22536 (time-down (if time-up (- time-up) nil))
22537 (priority-up (org-cmp-priority a b))
22538 (priority-down (if priority-up (- priority-up) nil))
22539 (category-up (org-cmp-category a b))
22540 (category-down (if category-up (- category-up) nil))
22541 (category-keep (if category-up +1 nil))
22542 (tag-up (org-cmp-tag a b))
22543 (tag-down (if tag-up (- tag-up) nil)))
22544 (cdr (assoc
22545 (eval (cons 'or org-agenda-sorting-strategy-selected))
22546 '((-1 . t) (1 . nil) (nil . nil))))))
22548 ;;; Agenda restriction lock
22550 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22551 "Overlay to mark the headline to which arenda commands are restricted.")
22552 (org-overlay-put org-agenda-restriction-lock-overlay
22553 'face 'org-agenda-restriction-lock)
22554 (org-overlay-put org-agenda-restriction-lock-overlay
22555 'help-echo "Agendas are currently limited to this subtree.")
22556 (org-detach-overlay org-agenda-restriction-lock-overlay)
22557 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22558 "Overlay marking the agenda restriction line in speedbar.")
22559 (org-overlay-put org-speedbar-restriction-lock-overlay
22560 'face 'org-agenda-restriction-lock)
22561 (org-overlay-put org-speedbar-restriction-lock-overlay
22562 'help-echo "Agendas are currently limited to this item.")
22563 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22565 (defun org-agenda-set-restriction-lock (&optional type)
22566 "Set restriction lock for agenda, to current subtree or file.
22567 Restriction will be the file if TYPE is `file', or if type is the
22568 universal prefix '(4), or if the cursor is before the first headline
22569 in the file. Otherwise, restriction will be to the current subtree."
22570 (interactive "P")
22571 (and (equal type '(4)) (setq type 'file))
22572 (setq type (cond
22573 (type type)
22574 ((org-at-heading-p) 'subtree)
22575 ((condition-case nil (org-back-to-heading t) (error nil))
22576 'subtree)
22577 (t 'file)))
22578 (if (eq type 'subtree)
22579 (progn
22580 (setq org-agenda-restrict t)
22581 (setq org-agenda-overriding-restriction 'subtree)
22582 (put 'org-agenda-files 'org-restrict
22583 (list (buffer-file-name (buffer-base-buffer))))
22584 (org-back-to-heading t)
22585 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22586 (move-marker org-agenda-restrict-begin (point))
22587 (move-marker org-agenda-restrict-end
22588 (save-excursion (org-end-of-subtree t)))
22589 (message "Locking agenda restriction to subtree"))
22590 (put 'org-agenda-files 'org-restrict
22591 (list (buffer-file-name (buffer-base-buffer))))
22592 (setq org-agenda-restrict nil)
22593 (setq org-agenda-overriding-restriction 'file)
22594 (move-marker org-agenda-restrict-begin nil)
22595 (move-marker org-agenda-restrict-end nil)
22596 (message "Locking agenda restriction to file"))
22597 (setq current-prefix-arg nil)
22598 (org-agenda-maybe-redo))
22600 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22601 "Remove the agenda restriction lock."
22602 (interactive "P")
22603 (org-detach-overlay org-agenda-restriction-lock-overlay)
22604 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22605 (setq org-agenda-overriding-restriction nil)
22606 (setq org-agenda-restrict nil)
22607 (put 'org-agenda-files 'org-restrict nil)
22608 (move-marker org-agenda-restrict-begin nil)
22609 (move-marker org-agenda-restrict-end nil)
22610 (setq current-prefix-arg nil)
22611 (message "Agenda restriction lock removed")
22612 (or noupdate (org-agenda-maybe-redo)))
22614 (defun org-agenda-maybe-redo ()
22615 "If there is any window showing the agenda view, update it."
22616 (let ((w (get-buffer-window org-agenda-buffer-name t))
22617 (w0 (selected-window)))
22618 (when w
22619 (select-window w)
22620 (org-agenda-redo)
22621 (select-window w0)
22622 (if org-agenda-overriding-restriction
22623 (message "Agenda view shifted to new %s restriction"
22624 org-agenda-overriding-restriction)
22625 (message "Agenda restriction lock removed")))))
22627 ;;; Agenda commands
22629 (defun org-agenda-check-type (error &rest types)
22630 "Check if agenda buffer is of allowed type.
22631 If ERROR is non-nil, throw an error, otherwise just return nil."
22632 (if (memq org-agenda-type types)
22634 (if error
22635 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22636 nil)))
22638 (defun org-agenda-quit ()
22639 "Exit agenda by removing the window or the buffer."
22640 (interactive)
22641 (let ((buf (current-buffer)))
22642 (if (not (one-window-p)) (delete-window))
22643 (kill-buffer buf)
22644 (org-agenda-reset-markers)
22645 (org-columns-remove-overlays))
22646 ;; Maybe restore the pre-agenda window configuration.
22647 (and org-agenda-restore-windows-after-quit
22648 (not (eq org-agenda-window-setup 'other-frame))
22649 org-pre-agenda-window-conf
22650 (set-window-configuration org-pre-agenda-window-conf)))
22652 (defun org-agenda-exit ()
22653 "Exit agenda by removing the window or the buffer.
22654 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22655 Org-mode buffers visited directly by the user will not be touched."
22656 (interactive)
22657 (org-release-buffers org-agenda-new-buffers)
22658 (setq org-agenda-new-buffers nil)
22659 (org-agenda-quit))
22661 (defun org-agenda-execute (arg)
22662 "Execute another agenda command, keeping same window.\\<global-map>
22663 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22664 (interactive "P")
22665 (let ((org-agenda-window-setup 'current-window))
22666 (org-agenda arg)))
22668 (defun org-save-all-org-buffers ()
22669 "Save all Org-mode buffers without user confirmation."
22670 (interactive)
22671 (message "Saving all Org-mode buffers...")
22672 (save-some-buffers t 'org-mode-p)
22673 (message "Saving all Org-mode buffers... done"))
22675 (defun org-agenda-redo ()
22676 "Rebuild Agenda.
22677 When this is the global TODO list, a prefix argument will be interpreted."
22678 (interactive)
22679 (let* ((org-agenda-keep-modes t)
22680 (line (org-current-line))
22681 (window-line (- line (org-current-line (window-start))))
22682 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22683 (message "Rebuilding agenda buffer...")
22684 (org-let lprops '(eval org-agenda-redo-command))
22685 (setq org-agenda-undo-list nil
22686 org-agenda-pending-undo-list nil)
22687 (message "Rebuilding agenda buffer...done")
22688 (goto-line line)
22689 (recenter window-line)))
22691 (defun org-agenda-manipulate-query-add ()
22692 "Manipulate the query by adding a search term with positive selection.
22693 Positive selection means, the term must be matched for selection of an entry."
22694 (interactive)
22695 (org-agenda-manipulate-query ?\[))
22696 (defun org-agenda-manipulate-query-subtract ()
22697 "Manipulate the query by adding a search term with negative selection.
22698 Negative selection means, term must not be matched for selection of an entry."
22699 (interactive)
22700 (org-agenda-manipulate-query ?\]))
22701 (defun org-agenda-manipulate-query-add-re ()
22702 "Manipulate the query by adding a search regexp with positive selection.
22703 Positive selection means, the regexp must match for selection of an entry."
22704 (interactive)
22705 (org-agenda-manipulate-query ?\{))
22706 (defun org-agenda-manipulate-query-subtract-re ()
22707 "Manipulate the query by adding a search regexp with negative selection.
22708 Negative selection means, regexp must not match for selection of an entry."
22709 (interactive)
22710 (org-agenda-manipulate-query ?\}))
22711 (defun org-agenda-manipulate-query (char)
22712 (cond
22713 ((eq org-agenda-type 'search)
22714 (org-add-to-string
22715 'org-agenda-query-string
22716 (cdr (assoc char '((?\[ . " +") (?\] . " -")
22717 (?\{ . " +{}") (?\} . " -{}")))))
22718 (setq org-agenda-redo-command
22719 (list 'org-search-view
22720 (+ (length org-agenda-query-string)
22721 (if (member char '(?\{ ?\})) 0 1))
22722 org-agenda-query-string))
22723 (set-register org-agenda-query-register org-agenda-query-string)
22724 (org-agenda-redo))
22725 (t (error "Canot manipulate query for %s-type agenda buffers"
22726 org-agenda-type))))
22728 (defun org-add-to-string (var string)
22729 (set var (concat (symbol-value var) string)))
22731 (defun org-agenda-goto-date (date)
22732 "Jump to DATE in agenda."
22733 (interactive (list (org-read-date)))
22734 (org-agenda-list nil date))
22736 (defun org-agenda-goto-today ()
22737 "Go to today."
22738 (interactive)
22739 (org-agenda-check-type t 'timeline 'agenda)
22740 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22741 (cond
22742 (tdpos (goto-char tdpos))
22743 ((eq org-agenda-type 'agenda)
22744 (let* ((sd (time-to-days
22745 (time-subtract (current-time)
22746 (list 0 (* 3600 org-extend-today-until) 0))))
22747 (comp (org-agenda-compute-time-span sd org-agenda-span))
22748 (org-agenda-overriding-arguments org-agenda-last-arguments))
22749 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22750 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22751 (org-agenda-redo)
22752 (org-agenda-find-same-or-today-or-agenda)))
22753 (t (error "Cannot find today")))))
22755 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22756 (goto-char
22757 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22758 (text-property-any (point-min) (point-max) 'org-today t)
22759 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22760 (point-min))))
22762 (defun org-agenda-later (arg)
22763 "Go forward in time by thee current span.
22764 With prefix ARG, go forward that many times the current span."
22765 (interactive "p")
22766 (org-agenda-check-type t 'agenda)
22767 (let* ((span org-agenda-span)
22768 (sd org-starting-day)
22769 (greg (calendar-gregorian-from-absolute sd))
22770 (cnt (get-text-property (point) 'org-day-cnt))
22771 greg2 nd)
22772 (cond
22773 ((eq span 'day)
22774 (setq sd (+ arg sd) nd 1))
22775 ((eq span 'week)
22776 (setq sd (+ (* 7 arg) sd) nd 7))
22777 ((eq span 'month)
22778 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22779 sd (calendar-absolute-from-gregorian greg2))
22780 (setcar greg2 (1+ (car greg2)))
22781 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22782 ((eq span 'year)
22783 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22784 sd (calendar-absolute-from-gregorian greg2))
22785 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22786 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22787 (let ((org-agenda-overriding-arguments
22788 (list (car org-agenda-last-arguments) sd nd t)))
22789 (org-agenda-redo)
22790 (org-agenda-find-same-or-today-or-agenda cnt))))
22792 (defun org-agenda-earlier (arg)
22793 "Go backward in time by the current span.
22794 With prefix ARG, go backward that many times the current span."
22795 (interactive "p")
22796 (org-agenda-later (- arg)))
22798 (defun org-agenda-day-view ()
22799 "Switch to daily view for agenda."
22800 (interactive)
22801 (setq org-agenda-ndays 1)
22802 (org-agenda-change-time-span 'day))
22803 (defun org-agenda-week-view ()
22804 "Switch to daily view for agenda."
22805 (interactive)
22806 (setq org-agenda-ndays 7)
22807 (org-agenda-change-time-span 'week))
22808 (defun org-agenda-month-view ()
22809 "Switch to daily view for agenda."
22810 (interactive)
22811 (org-agenda-change-time-span 'month))
22812 (defun org-agenda-year-view ()
22813 "Switch to daily view for agenda."
22814 (interactive)
22815 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22816 (org-agenda-change-time-span 'year)
22817 (error "Abort")))
22819 (defun org-agenda-change-time-span (span)
22820 "Change the agenda view to SPAN.
22821 SPAN may be `day', `week', `month', `year'."
22822 (org-agenda-check-type t 'agenda)
22823 (if (equal org-agenda-span span)
22824 (error "Viewing span is already \"%s\"" span))
22825 (let* ((sd (or (get-text-property (point) 'day)
22826 org-starting-day))
22827 (computed (org-agenda-compute-time-span sd span))
22828 (org-agenda-overriding-arguments
22829 (list (car org-agenda-last-arguments)
22830 (car computed) (cdr computed) t)))
22831 (org-agenda-redo)
22832 (org-agenda-find-same-or-today-or-agenda))
22833 (org-agenda-set-mode-name)
22834 (message "Switched to %s view" span))
22836 (defun org-agenda-compute-time-span (sd span)
22837 "Compute starting date and number of days for agenda.
22838 SPAN may be `day', `week', `month', `year'. The return value
22839 is a cons cell with the starting date and the number of days,
22840 so that the date SD will be in that range."
22841 (let* ((greg (calendar-gregorian-from-absolute sd))
22843 (cond
22844 ((eq span 'day)
22845 (setq nd 1))
22846 ((eq span 'week)
22847 (let* ((nt (calendar-day-of-week
22848 (calendar-gregorian-from-absolute sd)))
22849 (d (if org-agenda-start-on-weekday
22850 (- nt org-agenda-start-on-weekday)
22851 0)))
22852 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22853 (setq nd 7)))
22854 ((eq span 'month)
22855 (setq sd (calendar-absolute-from-gregorian
22856 (list (car greg) 1 (nth 2 greg)))
22857 nd (- (calendar-absolute-from-gregorian
22858 (list (1+ (car greg)) 1 (nth 2 greg)))
22859 sd)))
22860 ((eq span 'year)
22861 (setq sd (calendar-absolute-from-gregorian
22862 (list 1 1 (nth 2 greg)))
22863 nd (- (calendar-absolute-from-gregorian
22864 (list 1 1 (1+ (nth 2 greg))))
22865 sd))))
22866 (cons sd nd)))
22868 ;; FIXME: does not work if user makes date format that starts with a blank
22869 (defun org-agenda-next-date-line (&optional arg)
22870 "Jump to the next line indicating a date in agenda buffer."
22871 (interactive "p")
22872 (org-agenda-check-type t 'agenda 'timeline)
22873 (beginning-of-line 1)
22874 (if (looking-at "^\\S-") (forward-char 1))
22875 (if (not (re-search-forward "^\\S-" nil t arg))
22876 (progn
22877 (backward-char 1)
22878 (error "No next date after this line in this buffer")))
22879 (goto-char (match-beginning 0)))
22881 (defun org-agenda-previous-date-line (&optional arg)
22882 "Jump to the previous line indicating a date in agenda buffer."
22883 (interactive "p")
22884 (org-agenda-check-type t 'agenda 'timeline)
22885 (beginning-of-line 1)
22886 (if (not (re-search-backward "^\\S-" nil t arg))
22887 (error "No previous date before this line in this buffer")))
22889 ;; Initialize the highlight
22890 (defvar org-hl (org-make-overlay 1 1))
22891 (org-overlay-put org-hl 'face 'highlight)
22893 (defun org-highlight (begin end &optional buffer)
22894 "Highlight a region with overlay."
22895 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22896 org-hl begin end (or buffer (current-buffer))))
22898 (defun org-unhighlight ()
22899 "Detach overlay INDEX."
22900 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22902 ;; FIXME this is currently not used.
22903 (defun org-highlight-until-next-command (beg end &optional buffer)
22904 (org-highlight beg end buffer)
22905 (add-hook 'pre-command-hook 'org-unhighlight-once))
22906 (defun org-unhighlight-once ()
22907 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22908 (org-unhighlight))
22910 (defun org-agenda-follow-mode ()
22911 "Toggle follow mode in an agenda buffer."
22912 (interactive)
22913 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22914 (org-agenda-set-mode-name)
22915 (message "Follow mode is %s"
22916 (if org-agenda-follow-mode "on" "off")))
22918 (defun org-agenda-log-mode ()
22919 "Toggle log mode in an agenda buffer."
22920 (interactive)
22921 (org-agenda-check-type t 'agenda 'timeline)
22922 (setq org-agenda-show-log (not org-agenda-show-log))
22923 (org-agenda-set-mode-name)
22924 (org-agenda-redo)
22925 (message "Log mode is %s"
22926 (if org-agenda-show-log "on" "off")))
22928 (defun org-agenda-toggle-diary ()
22929 "Toggle diary inclusion in an agenda buffer."
22930 (interactive)
22931 (org-agenda-check-type t 'agenda)
22932 (setq org-agenda-include-diary (not org-agenda-include-diary))
22933 (org-agenda-redo)
22934 (org-agenda-set-mode-name)
22935 (message "Diary inclusion turned %s"
22936 (if org-agenda-include-diary "on" "off")))
22938 (defun org-agenda-toggle-time-grid ()
22939 "Toggle time grid in an agenda buffer."
22940 (interactive)
22941 (org-agenda-check-type t 'agenda)
22942 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22943 (org-agenda-redo)
22944 (org-agenda-set-mode-name)
22945 (message "Time-grid turned %s"
22946 (if org-agenda-use-time-grid "on" "off")))
22948 (defun org-agenda-set-mode-name ()
22949 "Set the mode name to indicate all the small mode settings."
22950 (setq mode-name
22951 (concat "Org-Agenda"
22952 (if (equal org-agenda-ndays 1) " Day" "")
22953 (if (equal org-agenda-ndays 7) " Week" "")
22954 (if org-agenda-follow-mode " Follow" "")
22955 (if org-agenda-include-diary " Diary" "")
22956 (if org-agenda-use-time-grid " Grid" "")
22957 (if org-agenda-show-log " Log" "")))
22958 (force-mode-line-update))
22960 (defun org-agenda-post-command-hook ()
22961 (and (eolp) (not (bolp)) (backward-char 1))
22962 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22963 (if (and org-agenda-follow-mode
22964 (get-text-property (point) 'org-marker))
22965 (org-agenda-show)))
22967 (defun org-agenda-show-priority ()
22968 "Show the priority of the current item.
22969 This priority is composed of the main priority given with the [#A] cookies,
22970 and by additional input from the age of a schedules or deadline entry."
22971 (interactive)
22972 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22973 (message "Priority is %d" (if pri pri -1000))))
22975 (defun org-agenda-show-tags ()
22976 "Show the tags applicable to the current item."
22977 (interactive)
22978 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22979 (if tags
22980 (message "Tags are :%s:"
22981 (org-no-properties (mapconcat 'identity tags ":")))
22982 (message "No tags associated with this line"))))
22984 (defun org-agenda-goto (&optional highlight)
22985 "Go to the Org-mode file which contains the item at point."
22986 (interactive)
22987 (let* ((marker (or (get-text-property (point) 'org-marker)
22988 (org-agenda-error)))
22989 (buffer (marker-buffer marker))
22990 (pos (marker-position marker)))
22991 (switch-to-buffer-other-window buffer)
22992 (widen)
22993 (goto-char pos)
22994 (when (org-mode-p)
22995 (org-show-context 'agenda)
22996 (save-excursion
22997 (and (outline-next-heading)
22998 (org-flag-heading nil)))) ; show the next heading
22999 (recenter (/ (window-height) 2))
23000 (run-hooks 'org-agenda-after-show-hook)
23001 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
23003 (defvar org-agenda-after-show-hook nil
23004 "Normal hook run after an item has been shown from the agenda.
23005 Point is in the buffer where the item originated.")
23007 (defun org-agenda-kill ()
23008 "Kill the entry or subtree belonging to the current agenda entry."
23009 (interactive)
23010 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
23011 (let* ((marker (or (get-text-property (point) 'org-marker)
23012 (org-agenda-error)))
23013 (buffer (marker-buffer marker))
23014 (pos (marker-position marker))
23015 (type (get-text-property (point) 'type))
23016 dbeg dend (n 0) conf)
23017 (org-with-remote-undo buffer
23018 (with-current-buffer buffer
23019 (save-excursion
23020 (goto-char pos)
23021 (if (and (org-mode-p) (not (member type '("sexp"))))
23022 (setq dbeg (progn (org-back-to-heading t) (point))
23023 dend (org-end-of-subtree t t))
23024 (setq dbeg (point-at-bol)
23025 dend (min (point-max) (1+ (point-at-eol)))))
23026 (goto-char dbeg)
23027 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
23028 (setq conf (or (eq t org-agenda-confirm-kill)
23029 (and (numberp org-agenda-confirm-kill)
23030 (> n org-agenda-confirm-kill))))
23031 (and conf
23032 (not (y-or-n-p
23033 (format "Delete entry with %d lines in buffer \"%s\"? "
23034 n (buffer-name buffer))))
23035 (error "Abort"))
23036 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
23037 (with-current-buffer buffer (delete-region dbeg dend))
23038 (message "Agenda item and source killed"))))
23040 (defun org-agenda-archive ()
23041 "Kill the entry or subtree belonging to the current agenda entry."
23042 (interactive)
23043 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
23044 (let* ((marker (or (get-text-property (point) 'org-marker)
23045 (org-agenda-error)))
23046 (buffer (marker-buffer marker))
23047 (pos (marker-position marker)))
23048 (org-with-remote-undo buffer
23049 (with-current-buffer buffer
23050 (if (org-mode-p)
23051 (save-excursion
23052 (goto-char pos)
23053 (org-remove-subtree-entries-from-agenda)
23054 (org-back-to-heading t)
23055 (org-archive-subtree))
23056 (error "Archiving works only in Org-mode files"))))))
23058 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
23059 "Remove all lines in the agenda that correspond to a given subtree.
23060 The subtree is the one in buffer BUF, starting at BEG and ending at END.
23061 If this information is not given, the function uses the tree at point."
23062 (let ((buf (or buf (current-buffer))) m p)
23063 (save-excursion
23064 (unless (and beg end)
23065 (org-back-to-heading t)
23066 (setq beg (point))
23067 (org-end-of-subtree t)
23068 (setq end (point)))
23069 (set-buffer (get-buffer org-agenda-buffer-name))
23070 (save-excursion
23071 (goto-char (point-max))
23072 (beginning-of-line 1)
23073 (while (not (bobp))
23074 (when (and (setq m (get-text-property (point) 'org-marker))
23075 (equal buf (marker-buffer m))
23076 (setq p (marker-position m))
23077 (>= p beg)
23078 (<= p end))
23079 (let ((inhibit-read-only t))
23080 (delete-region (point-at-bol) (1+ (point-at-eol)))))
23081 (beginning-of-line 0))))))
23083 (defun org-agenda-open-link ()
23084 "Follow the link in the current line, if any."
23085 (interactive)
23086 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
23087 (save-excursion
23088 (save-restriction
23089 (narrow-to-region (point-at-bol) (point-at-eol))
23090 (org-open-at-point))))
23092 (defun org-agenda-copy-local-variable (var)
23093 "Get a variable from a referenced buffer and install it here."
23094 (let ((m (get-text-property (point) 'org-marker)))
23095 (when (and m (buffer-live-p (marker-buffer m)))
23096 (org-set-local var (with-current-buffer (marker-buffer m)
23097 (symbol-value var))))))
23099 (defun org-agenda-switch-to (&optional delete-other-windows)
23100 "Go to the Org-mode file which contains the item at point."
23101 (interactive)
23102 (let* ((marker (or (get-text-property (point) 'org-marker)
23103 (org-agenda-error)))
23104 (buffer (marker-buffer marker))
23105 (pos (marker-position marker)))
23106 (switch-to-buffer buffer)
23107 (and delete-other-windows (delete-other-windows))
23108 (widen)
23109 (goto-char pos)
23110 (when (org-mode-p)
23111 (org-show-context 'agenda)
23112 (save-excursion
23113 (and (outline-next-heading)
23114 (org-flag-heading nil)))))) ; show the next heading
23116 (defun org-agenda-goto-mouse (ev)
23117 "Go to the Org-mode file which contains the item at the mouse click."
23118 (interactive "e")
23119 (mouse-set-point ev)
23120 (org-agenda-goto))
23122 (defun org-agenda-show ()
23123 "Display the Org-mode file which contains the item at point."
23124 (interactive)
23125 (let ((win (selected-window)))
23126 (org-agenda-goto t)
23127 (select-window win)))
23129 (defun org-agenda-recenter (arg)
23130 "Display the Org-mode file which contains the item at point and recenter."
23131 (interactive "P")
23132 (let ((win (selected-window)))
23133 (org-agenda-goto t)
23134 (recenter arg)
23135 (select-window win)))
23137 (defun org-agenda-show-mouse (ev)
23138 "Display the Org-mode file which contains the item at the mouse click."
23139 (interactive "e")
23140 (mouse-set-point ev)
23141 (org-agenda-show))
23143 (defun org-agenda-check-no-diary ()
23144 "Check if the entry is a diary link and abort if yes."
23145 (if (get-text-property (point) 'org-agenda-diary-link)
23146 (org-agenda-error)))
23148 (defun org-agenda-error ()
23149 (error "Command not allowed in this line"))
23151 (defun org-agenda-tree-to-indirect-buffer ()
23152 "Show the subtree corresponding to the current entry in an indirect buffer.
23153 This calls the command `org-tree-to-indirect-buffer' from the original
23154 Org-mode buffer.
23155 With numerical prefix arg ARG, go up to this level and then take that tree.
23156 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
23157 dedicated frame)."
23158 (interactive)
23159 (org-agenda-check-no-diary)
23160 (let* ((marker (or (get-text-property (point) 'org-marker)
23161 (org-agenda-error)))
23162 (buffer (marker-buffer marker))
23163 (pos (marker-position marker)))
23164 (with-current-buffer buffer
23165 (save-excursion
23166 (goto-char pos)
23167 (call-interactively 'org-tree-to-indirect-buffer)))))
23169 (defvar org-last-heading-marker (make-marker)
23170 "Marker pointing to the headline that last changed its TODO state
23171 by a remote command from the agenda.")
23173 (defun org-agenda-todo-nextset ()
23174 "Switch TODO entry to next sequence."
23175 (interactive)
23176 (org-agenda-todo 'nextset))
23178 (defun org-agenda-todo-previousset ()
23179 "Switch TODO entry to previous sequence."
23180 (interactive)
23181 (org-agenda-todo 'previousset))
23183 (defun org-agenda-todo (&optional arg)
23184 "Cycle TODO state of line at point, also in Org-mode file.
23185 This changes the line at point, all other lines in the agenda referring to
23186 the same tree node, and the headline of the tree node in the Org-mode file."
23187 (interactive "P")
23188 (org-agenda-check-no-diary)
23189 (let* ((col (current-column))
23190 (marker (or (get-text-property (point) 'org-marker)
23191 (org-agenda-error)))
23192 (buffer (marker-buffer marker))
23193 (pos (marker-position marker))
23194 (hdmarker (get-text-property (point) 'org-hd-marker))
23195 (inhibit-read-only t)
23196 newhead)
23197 (org-with-remote-undo buffer
23198 (with-current-buffer buffer
23199 (widen)
23200 (goto-char pos)
23201 (org-show-context 'agenda)
23202 (save-excursion
23203 (and (outline-next-heading)
23204 (org-flag-heading nil))) ; show the next heading
23205 (org-todo arg)
23206 (and (bolp) (forward-char 1))
23207 (setq newhead (org-get-heading))
23208 (save-excursion
23209 (org-back-to-heading)
23210 (move-marker org-last-heading-marker (point))))
23211 (beginning-of-line 1)
23212 (save-excursion
23213 (org-agenda-change-all-lines newhead hdmarker 'fixface))
23214 (move-to-column col))))
23216 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
23217 "Change all lines in the agenda buffer which match HDMARKER.
23218 The new content of the line will be NEWHEAD (as modified by
23219 `org-format-agenda-item'). HDMARKER is checked with
23220 `equal' against all `org-hd-marker' text properties in the file.
23221 If FIXFACE is non-nil, the face of each item is modified acording to
23222 the new TODO state."
23223 (let* ((inhibit-read-only t)
23224 props m pl undone-face done-face finish new dotime cat tags)
23225 (save-excursion
23226 (goto-char (point-max))
23227 (beginning-of-line 1)
23228 (while (not finish)
23229 (setq finish (bobp))
23230 (when (and (setq m (get-text-property (point) 'org-hd-marker))
23231 (equal m hdmarker))
23232 (setq props (text-properties-at (point))
23233 dotime (get-text-property (point) 'dotime)
23234 cat (get-text-property (point) 'org-category)
23235 tags (get-text-property (point) 'tags)
23236 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
23237 pl (get-text-property (point) 'prefix-length)
23238 undone-face (get-text-property (point) 'undone-face)
23239 done-face (get-text-property (point) 'done-face))
23240 (move-to-column pl)
23241 (cond
23242 ((equal new "")
23243 (beginning-of-line 1)
23244 (and (looking-at ".*\n?") (replace-match "")))
23245 ((looking-at ".*")
23246 (replace-match new t t)
23247 (beginning-of-line 1)
23248 (add-text-properties (point-at-bol) (point-at-eol) props)
23249 (when fixface
23250 (add-text-properties
23251 (point-at-bol) (point-at-eol)
23252 (list 'face
23253 (if org-last-todo-state-is-todo
23254 undone-face done-face))))
23255 (org-agenda-highlight-todo 'line)
23256 (beginning-of-line 1))
23257 (t (error "Line update did not work"))))
23258 (beginning-of-line 0)))
23259 (org-finalize-agenda)))
23261 (defun org-agenda-align-tags (&optional line)
23262 "Align all tags in agenda items to `org-agenda-tags-column'."
23263 (let ((inhibit-read-only t) l c)
23264 (save-excursion
23265 (goto-char (if line (point-at-bol) (point-min)))
23266 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
23267 (if line (point-at-eol) nil) t)
23268 (add-text-properties
23269 (match-beginning 2) (match-end 2)
23270 (list 'face (delq nil (list 'org-tag (get-text-property
23271 (match-beginning 2) 'face)))))
23272 (setq l (- (match-end 2) (match-beginning 2))
23273 c (if (< org-agenda-tags-column 0)
23274 (- (abs org-agenda-tags-column) l)
23275 org-agenda-tags-column))
23276 (delete-region (match-beginning 1) (match-end 1))
23277 (goto-char (match-beginning 1))
23278 (insert (org-add-props
23279 (make-string (max 1 (- c (current-column))) ?\ )
23280 (text-properties-at (point))))))))
23282 (defun org-agenda-priority-up ()
23283 "Increase the priority of line at point, also in Org-mode file."
23284 (interactive)
23285 (org-agenda-priority 'up))
23287 (defun org-agenda-priority-down ()
23288 "Decrease the priority of line at point, also in Org-mode file."
23289 (interactive)
23290 (org-agenda-priority 'down))
23292 (defun org-agenda-priority (&optional force-direction)
23293 "Set the priority of line at point, also in Org-mode file.
23294 This changes the line at point, all other lines in the agenda referring to
23295 the same tree node, and the headline of the tree node in the Org-mode file."
23296 (interactive)
23297 (org-agenda-check-no-diary)
23298 (let* ((marker (or (get-text-property (point) 'org-marker)
23299 (org-agenda-error)))
23300 (hdmarker (get-text-property (point) 'org-hd-marker))
23301 (buffer (marker-buffer hdmarker))
23302 (pos (marker-position hdmarker))
23303 (inhibit-read-only t)
23304 newhead)
23305 (org-with-remote-undo buffer
23306 (with-current-buffer buffer
23307 (widen)
23308 (goto-char pos)
23309 (org-show-context 'agenda)
23310 (save-excursion
23311 (and (outline-next-heading)
23312 (org-flag-heading nil))) ; show the next heading
23313 (funcall 'org-priority force-direction)
23314 (end-of-line 1)
23315 (setq newhead (org-get-heading)))
23316 (org-agenda-change-all-lines newhead hdmarker)
23317 (beginning-of-line 1))))
23319 (defun org-get-tags-at (&optional pos)
23320 "Get a list of all headline tags applicable at POS.
23321 POS defaults to point. If tags are inherited, the list contains
23322 the targets in the same sequence as the headlines appear, i.e.
23323 the tags of the current headline come last."
23324 (interactive)
23325 (let (tags lastpos)
23326 (save-excursion
23327 (save-restriction
23328 (widen)
23329 (goto-char (or pos (point)))
23330 (save-match-data
23331 (condition-case nil
23332 (progn
23333 (org-back-to-heading t)
23334 (while (not (equal lastpos (point)))
23335 (setq lastpos (point))
23336 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
23337 (setq tags (append (org-split-string
23338 (org-match-string-no-properties 1) ":")
23339 tags)))
23340 (or org-use-tag-inheritance (error ""))
23341 (org-up-heading-all 1)))
23342 (error nil))))
23343 tags)))
23345 ;; FIXME: should fix the tags property of the agenda line.
23346 (defun org-agenda-set-tags ()
23347 "Set tags for the current headline."
23348 (interactive)
23349 (org-agenda-check-no-diary)
23350 (if (and (org-region-active-p) (interactive-p))
23351 (call-interactively 'org-change-tag-in-region)
23352 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23353 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23354 (org-agenda-error)))
23355 (buffer (marker-buffer hdmarker))
23356 (pos (marker-position hdmarker))
23357 (inhibit-read-only t)
23358 newhead)
23359 (org-with-remote-undo buffer
23360 (with-current-buffer buffer
23361 (widen)
23362 (goto-char pos)
23363 (save-excursion
23364 (org-show-context 'agenda))
23365 (save-excursion
23366 (and (outline-next-heading)
23367 (org-flag-heading nil))) ; show the next heading
23368 (goto-char pos)
23369 (call-interactively 'org-set-tags)
23370 (end-of-line 1)
23371 (setq newhead (org-get-heading)))
23372 (org-agenda-change-all-lines newhead hdmarker)
23373 (beginning-of-line 1)))))
23375 (defun org-agenda-toggle-archive-tag ()
23376 "Toggle the archive tag for the current entry."
23377 (interactive)
23378 (org-agenda-check-no-diary)
23379 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23380 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23381 (org-agenda-error)))
23382 (buffer (marker-buffer hdmarker))
23383 (pos (marker-position hdmarker))
23384 (inhibit-read-only t)
23385 newhead)
23386 (org-with-remote-undo buffer
23387 (with-current-buffer buffer
23388 (widen)
23389 (goto-char pos)
23390 (org-show-context 'agenda)
23391 (save-excursion
23392 (and (outline-next-heading)
23393 (org-flag-heading nil))) ; show the next heading
23394 (call-interactively 'org-toggle-archive-tag)
23395 (end-of-line 1)
23396 (setq newhead (org-get-heading)))
23397 (org-agenda-change-all-lines newhead hdmarker)
23398 (beginning-of-line 1))))
23400 (defun org-agenda-date-later (arg &optional what)
23401 "Change the date of this item to one day later."
23402 (interactive "p")
23403 (org-agenda-check-type t 'agenda 'timeline)
23404 (org-agenda-check-no-diary)
23405 (let* ((marker (or (get-text-property (point) 'org-marker)
23406 (org-agenda-error)))
23407 (buffer (marker-buffer marker))
23408 (pos (marker-position marker)))
23409 (org-with-remote-undo buffer
23410 (with-current-buffer buffer
23411 (widen)
23412 (goto-char pos)
23413 (if (not (org-at-timestamp-p))
23414 (error "Cannot find time stamp"))
23415 (org-timestamp-change arg (or what 'day)))
23416 (org-agenda-show-new-time marker org-last-changed-timestamp))
23417 (message "Time stamp changed to %s" org-last-changed-timestamp)))
23419 (defun org-agenda-date-earlier (arg &optional what)
23420 "Change the date of this item to one day earlier."
23421 (interactive "p")
23422 (org-agenda-date-later (- arg) what))
23424 (defun org-agenda-show-new-time (marker stamp &optional prefix)
23425 "Show new date stamp via text properties."
23426 ;; We use text properties to make this undoable
23427 (let ((inhibit-read-only t))
23428 (setq stamp (concat " " prefix " => " stamp))
23429 (save-excursion
23430 (goto-char (point-max))
23431 (while (not (bobp))
23432 (when (equal marker (get-text-property (point) 'org-marker))
23433 (move-to-column (- (window-width) (length stamp)) t)
23434 (if (featurep 'xemacs)
23435 ;; Use `duplicable' property to trigger undo recording
23436 (let ((ex (make-extent nil nil))
23437 (gl (make-glyph stamp)))
23438 (set-glyph-face gl 'secondary-selection)
23439 (set-extent-properties
23440 ex (list 'invisible t 'end-glyph gl 'duplicable t))
23441 (insert-extent ex (1- (point)) (point-at-eol)))
23442 (add-text-properties
23443 (1- (point)) (point-at-eol)
23444 (list 'display (org-add-props stamp nil
23445 'face 'secondary-selection))))
23446 (beginning-of-line 1))
23447 (beginning-of-line 0)))))
23449 (defun org-agenda-date-prompt (arg)
23450 "Change the date of this item. Date is prompted for, with default today.
23451 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23452 be used to request time specification in the time stamp."
23453 (interactive "P")
23454 (org-agenda-check-type t 'agenda 'timeline)
23455 (org-agenda-check-no-diary)
23456 (let* ((marker (or (get-text-property (point) 'org-marker)
23457 (org-agenda-error)))
23458 (buffer (marker-buffer marker))
23459 (pos (marker-position marker)))
23460 (org-with-remote-undo buffer
23461 (with-current-buffer buffer
23462 (widen)
23463 (goto-char pos)
23464 (if (not (org-at-timestamp-p))
23465 (error "Cannot find time stamp"))
23466 (org-time-stamp arg)
23467 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23469 (defun org-agenda-schedule (arg)
23470 "Schedule the item at point."
23471 (interactive "P")
23472 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23473 (org-agenda-check-no-diary)
23474 (let* ((marker (or (get-text-property (point) 'org-marker)
23475 (org-agenda-error)))
23476 (type (marker-insertion-type marker))
23477 (buffer (marker-buffer marker))
23478 (pos (marker-position marker))
23479 (org-insert-labeled-timestamps-at-point nil)
23481 (when type (message "%s" type) (sit-for 3))
23482 (set-marker-insertion-type marker t)
23483 (org-with-remote-undo buffer
23484 (with-current-buffer buffer
23485 (widen)
23486 (goto-char pos)
23487 (setq ts (org-schedule arg)))
23488 (org-agenda-show-new-time marker ts "S"))
23489 (message "Item scheduled for %s" ts)))
23491 (defun org-agenda-deadline (arg)
23492 "Schedule the item at point."
23493 (interactive "P")
23494 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23495 (org-agenda-check-no-diary)
23496 (let* ((marker (or (get-text-property (point) 'org-marker)
23497 (org-agenda-error)))
23498 (buffer (marker-buffer marker))
23499 (pos (marker-position marker))
23500 (org-insert-labeled-timestamps-at-point nil)
23502 (org-with-remote-undo buffer
23503 (with-current-buffer buffer
23504 (widen)
23505 (goto-char pos)
23506 (setq ts (org-deadline arg)))
23507 (org-agenda-show-new-time marker ts "S"))
23508 (message "Deadline for this item set to %s" ts)))
23510 (defun org-get-heading (&optional no-tags)
23511 "Return the heading of the current entry, without the stars."
23512 (save-excursion
23513 (org-back-to-heading t)
23514 (if (looking-at
23515 (if no-tags
23516 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23517 "\\*+[ \t]+\\([^\r\n]*\\)"))
23518 (match-string 1) "")))
23520 (defun org-agenda-clock-in (&optional arg)
23521 "Start the clock on the currently selected item."
23522 (interactive "P")
23523 (org-agenda-check-no-diary)
23524 (let* ((marker (or (get-text-property (point) 'org-marker)
23525 (org-agenda-error)))
23526 (pos (marker-position marker)))
23527 (org-with-remote-undo (marker-buffer marker)
23528 (with-current-buffer (marker-buffer marker)
23529 (widen)
23530 (goto-char pos)
23531 (org-clock-in)))))
23533 (defun org-agenda-clock-out (&optional arg)
23534 "Stop the currently running clock."
23535 (interactive "P")
23536 (unless (marker-buffer org-clock-marker)
23537 (error "No running clock"))
23538 (org-with-remote-undo (marker-buffer org-clock-marker)
23539 (org-clock-out)))
23541 (defun org-agenda-clock-cancel (&optional arg)
23542 "Cancel the currently running clock."
23543 (interactive "P")
23544 (unless (marker-buffer org-clock-marker)
23545 (error "No running clock"))
23546 (org-with-remote-undo (marker-buffer org-clock-marker)
23547 (org-clock-cancel)))
23549 (defun org-agenda-diary-entry ()
23550 "Make a diary entry, like the `i' command from the calendar.
23551 All the standard commands work: block, weekly etc."
23552 (interactive)
23553 (org-agenda-check-type t 'agenda 'timeline)
23554 (require 'diary-lib)
23555 (let* ((char (progn
23556 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23557 (read-char-exclusive)))
23558 (cmd (cdr (assoc char
23559 '((?d . insert-diary-entry)
23560 (?w . insert-weekly-diary-entry)
23561 (?m . insert-monthly-diary-entry)
23562 (?y . insert-yearly-diary-entry)
23563 (?a . insert-anniversary-diary-entry)
23564 (?b . insert-block-diary-entry)
23565 (?c . insert-cyclic-diary-entry)))))
23566 (oldf (symbol-function 'calendar-cursor-to-date))
23567 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23568 (point (point))
23569 (mark (or (mark t) (point))))
23570 (unless cmd
23571 (error "No command associated with <%c>" char))
23572 (unless (and (get-text-property point 'day)
23573 (or (not (equal ?b char))
23574 (get-text-property mark 'day)))
23575 (error "Don't know which date to use for diary entry"))
23576 ;; We implement this by hacking the `calendar-cursor-to-date' function
23577 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23578 (let ((calendar-mark-ring
23579 (list (calendar-gregorian-from-absolute
23580 (or (get-text-property mark 'day)
23581 (get-text-property point 'day))))))
23582 (unwind-protect
23583 (progn
23584 (fset 'calendar-cursor-to-date
23585 (lambda (&optional error)
23586 (calendar-gregorian-from-absolute
23587 (get-text-property point 'day))))
23588 (call-interactively cmd))
23589 (fset 'calendar-cursor-to-date oldf)))))
23592 (defun org-agenda-execute-calendar-command (cmd)
23593 "Execute a calendar command from the agenda, with the date associated to
23594 the cursor position."
23595 (org-agenda-check-type t 'agenda 'timeline)
23596 (require 'diary-lib)
23597 (unless (get-text-property (point) 'day)
23598 (error "Don't know which date to use for calendar command"))
23599 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23600 (point (point))
23601 (date (calendar-gregorian-from-absolute
23602 (get-text-property point 'day)))
23603 ;; the following 3 vars are needed in the calendar
23604 (displayed-day (extract-calendar-day date))
23605 (displayed-month (extract-calendar-month date))
23606 (displayed-year (extract-calendar-year date)))
23607 (unwind-protect
23608 (progn
23609 (fset 'calendar-cursor-to-date
23610 (lambda (&optional error)
23611 (calendar-gregorian-from-absolute
23612 (get-text-property point 'day))))
23613 (call-interactively cmd))
23614 (fset 'calendar-cursor-to-date oldf))))
23616 (defun org-agenda-phases-of-moon ()
23617 "Display the phases of the moon for the 3 months around the cursor date."
23618 (interactive)
23619 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23621 (defun org-agenda-holidays ()
23622 "Display the holidays for the 3 months around the cursor date."
23623 (interactive)
23624 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23626 (defun org-agenda-sunrise-sunset (arg)
23627 "Display sunrise and sunset for the cursor date.
23628 Latitude and longitude can be specified with the variables
23629 `calendar-latitude' and `calendar-longitude'. When called with prefix
23630 argument, latitude and longitude will be prompted for."
23631 (interactive "P")
23632 (let ((calendar-longitude (if arg nil calendar-longitude))
23633 (calendar-latitude (if arg nil calendar-latitude))
23634 (calendar-location-name
23635 (if arg "the given coordinates" calendar-location-name)))
23636 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23638 (defun org-agenda-goto-calendar ()
23639 "Open the Emacs calendar with the date at the cursor."
23640 (interactive)
23641 (org-agenda-check-type t 'agenda 'timeline)
23642 (let* ((day (or (get-text-property (point) 'day)
23643 (error "Don't know which date to open in calendar")))
23644 (date (calendar-gregorian-from-absolute day))
23645 (calendar-move-hook nil)
23646 (view-calendar-holidays-initially nil)
23647 (view-diary-entries-initially nil))
23648 (calendar)
23649 (calendar-goto-date date)))
23651 (defun org-calendar-goto-agenda ()
23652 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23653 This is a command that has to be installed in `calendar-mode-map'."
23654 (interactive)
23655 (org-agenda-list nil (calendar-absolute-from-gregorian
23656 (calendar-cursor-to-date))
23657 nil))
23659 (defun org-agenda-convert-date ()
23660 (interactive)
23661 (org-agenda-check-type t 'agenda 'timeline)
23662 (let ((day (get-text-property (point) 'day))
23663 date s)
23664 (unless day
23665 (error "Don't know which date to convert"))
23666 (setq date (calendar-gregorian-from-absolute day))
23667 (setq s (concat
23668 "Gregorian: " (calendar-date-string date) "\n"
23669 "ISO: " (calendar-iso-date-string date) "\n"
23670 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23671 "Julian: " (calendar-julian-date-string date) "\n"
23672 "Astron. JD: " (calendar-astro-date-string date)
23673 " (Julian date number at noon UTC)\n"
23674 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23675 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23676 "French: " (calendar-french-date-string date) "\n"
23677 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23678 "Mayan: " (calendar-mayan-date-string date) "\n"
23679 "Coptic: " (calendar-coptic-date-string date) "\n"
23680 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23681 "Persian: " (calendar-persian-date-string date) "\n"
23682 "Chinese: " (calendar-chinese-date-string date) "\n"))
23683 (with-output-to-temp-buffer "*Dates*"
23684 (princ s))
23685 (if (fboundp 'fit-window-to-buffer)
23686 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23689 ;;;; Embedded LaTeX
23691 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23692 "Keymap for the minor `org-cdlatex-mode'.")
23694 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23695 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23696 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23697 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23698 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23700 (defvar org-cdlatex-texmathp-advice-is-done nil
23701 "Flag remembering if we have applied the advice to texmathp already.")
23703 (define-minor-mode org-cdlatex-mode
23704 "Toggle the minor `org-cdlatex-mode'.
23705 This mode supports entering LaTeX environment and math in LaTeX fragments
23706 in Org-mode.
23707 \\{org-cdlatex-mode-map}"
23708 nil " OCDL" nil
23709 (when org-cdlatex-mode (require 'cdlatex))
23710 (unless org-cdlatex-texmathp-advice-is-done
23711 (setq org-cdlatex-texmathp-advice-is-done t)
23712 (defadvice texmathp (around org-math-always-on activate)
23713 "Always return t in org-mode buffers.
23714 This is because we want to insert math symbols without dollars even outside
23715 the LaTeX math segments. If Orgmode thinks that point is actually inside
23716 en embedded LaTeX fragement, let texmathp do its job.
23717 \\[org-cdlatex-mode-map]"
23718 (interactive)
23719 (let (p)
23720 (cond
23721 ((not (org-mode-p)) ad-do-it)
23722 ((eq this-command 'cdlatex-math-symbol)
23723 (setq ad-return-value t
23724 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23726 (let ((p (org-inside-LaTeX-fragment-p)))
23727 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23728 (setq ad-return-value t
23729 texmathp-why '("Org-mode embedded math" . 0))
23730 (if p ad-do-it)))))))))
23732 (defun turn-on-org-cdlatex ()
23733 "Unconditionally turn on `org-cdlatex-mode'."
23734 (org-cdlatex-mode 1))
23736 (defun org-inside-LaTeX-fragment-p ()
23737 "Test if point is inside a LaTeX fragment.
23738 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23739 sequence appearing also before point.
23740 Even though the matchers for math are configurable, this function assumes
23741 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23742 delimiters are skipped when they have been removed by customization.
23743 The return value is nil, or a cons cell with the delimiter and
23744 and the position of this delimiter.
23746 This function does a reasonably good job, but can locally be fooled by
23747 for example currency specifications. For example it will assume being in
23748 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23749 fragments that are properly closed, but during editing, we have to live
23750 with the uncertainty caused by missing closing delimiters. This function
23751 looks only before point, not after."
23752 (catch 'exit
23753 (let ((pos (point))
23754 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23755 (lim (progn
23756 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23757 (point)))
23758 dd-on str (start 0) m re)
23759 (goto-char pos)
23760 (when dodollar
23761 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23762 re (nth 1 (assoc "$" org-latex-regexps)))
23763 (while (string-match re str start)
23764 (cond
23765 ((= (match-end 0) (length str))
23766 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23767 ((= (match-end 0) (- (length str) 5))
23768 (throw 'exit nil))
23769 (t (setq start (match-end 0))))))
23770 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23771 (goto-char pos)
23772 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23773 (and (match-beginning 2) (throw 'exit nil))
23774 ;; count $$
23775 (while (re-search-backward "\\$\\$" lim t)
23776 (setq dd-on (not dd-on)))
23777 (goto-char pos)
23778 (if dd-on (cons "$$" m))))))
23781 (defun org-try-cdlatex-tab ()
23782 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23783 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23784 - inside a LaTeX fragment, or
23785 - after the first word in a line, where an abbreviation expansion could
23786 insert a LaTeX environment."
23787 (when org-cdlatex-mode
23788 (cond
23789 ((save-excursion
23790 (skip-chars-backward "a-zA-Z0-9*")
23791 (skip-chars-backward " \t")
23792 (bolp))
23793 (cdlatex-tab) t)
23794 ((org-inside-LaTeX-fragment-p)
23795 (cdlatex-tab) t)
23796 (t nil))))
23798 (defun org-cdlatex-underscore-caret (&optional arg)
23799 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23800 Revert to the normal definition outside of these fragments."
23801 (interactive "P")
23802 (if (org-inside-LaTeX-fragment-p)
23803 (call-interactively 'cdlatex-sub-superscript)
23804 (let (org-cdlatex-mode)
23805 (call-interactively (key-binding (vector last-input-event))))))
23807 (defun org-cdlatex-math-modify (&optional arg)
23808 "Execute `cdlatex-math-modify' in LaTeX fragments.
23809 Revert to the normal definition outside of these fragments."
23810 (interactive "P")
23811 (if (org-inside-LaTeX-fragment-p)
23812 (call-interactively 'cdlatex-math-modify)
23813 (let (org-cdlatex-mode)
23814 (call-interactively (key-binding (vector last-input-event))))))
23816 (defvar org-latex-fragment-image-overlays nil
23817 "List of overlays carrying the images of latex fragments.")
23818 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23820 (defun org-remove-latex-fragment-image-overlays ()
23821 "Remove all overlays with LaTeX fragment images in current buffer."
23822 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23823 (setq org-latex-fragment-image-overlays nil))
23825 (defun org-preview-latex-fragment (&optional subtree)
23826 "Preview the LaTeX fragment at point, or all locally or globally.
23827 If the cursor is in a LaTeX fragment, create the image and overlay
23828 it over the source code. If there is no fragment at point, display
23829 all fragments in the current text, from one headline to the next. With
23830 prefix SUBTREE, display all fragments in the current subtree. With a
23831 double prefix `C-u C-u', or when the cursor is before the first headline,
23832 display all fragments in the buffer.
23833 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23834 (interactive "P")
23835 (org-remove-latex-fragment-image-overlays)
23836 (save-excursion
23837 (save-restriction
23838 (let (beg end at msg)
23839 (cond
23840 ((or (equal subtree '(16))
23841 (not (save-excursion
23842 (re-search-backward (concat "^" outline-regexp) nil t))))
23843 (setq beg (point-min) end (point-max)
23844 msg "Creating images for buffer...%s"))
23845 ((equal subtree '(4))
23846 (org-back-to-heading)
23847 (setq beg (point) end (org-end-of-subtree t)
23848 msg "Creating images for subtree...%s"))
23850 (if (setq at (org-inside-LaTeX-fragment-p))
23851 (goto-char (max (point-min) (- (cdr at) 2)))
23852 (org-back-to-heading))
23853 (setq beg (point) end (progn (outline-next-heading) (point))
23854 msg (if at "Creating image...%s"
23855 "Creating images for entry...%s"))))
23856 (message msg "")
23857 (narrow-to-region beg end)
23858 (goto-char beg)
23859 (org-format-latex
23860 (concat "ltxpng/" (file-name-sans-extension
23861 (file-name-nondirectory
23862 buffer-file-name)))
23863 default-directory 'overlays msg at 'forbuffer)
23864 (message msg "done. Use `C-c C-c' to remove images.")))))
23866 (defvar org-latex-regexps
23867 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23868 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23869 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23870 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23871 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23872 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23873 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23874 "Regular expressions for matching embedded LaTeX.")
23876 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23877 "Replace LaTeX fragments with links to an image, and produce images."
23878 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23879 (let* ((prefixnodir (file-name-nondirectory prefix))
23880 (absprefix (expand-file-name prefix dir))
23881 (todir (file-name-directory absprefix))
23882 (opt org-format-latex-options)
23883 (matchers (plist-get opt :matchers))
23884 (re-list org-latex-regexps)
23885 (cnt 0) txt link beg end re e checkdir
23886 m n block linkfile movefile ov)
23887 ;; Check if there are old images files with this prefix, and remove them
23888 (when (file-directory-p todir)
23889 (mapc 'delete-file
23890 (directory-files
23891 todir 'full
23892 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23893 ;; Check the different regular expressions
23894 (while (setq e (pop re-list))
23895 (setq m (car e) re (nth 1 e) n (nth 2 e)
23896 block (if (nth 3 e) "\n\n" ""))
23897 (when (member m matchers)
23898 (goto-char (point-min))
23899 (while (re-search-forward re nil t)
23900 (when (or (not at) (equal (cdr at) (match-beginning n)))
23901 (setq txt (match-string n)
23902 beg (match-beginning n) end (match-end n)
23903 cnt (1+ cnt)
23904 linkfile (format "%s_%04d.png" prefix cnt)
23905 movefile (format "%s_%04d.png" absprefix cnt)
23906 link (concat block "[[file:" linkfile "]]" block))
23907 (if msg (message msg cnt))
23908 (goto-char beg)
23909 (unless checkdir ; make sure the directory exists
23910 (setq checkdir t)
23911 (or (file-directory-p todir) (make-directory todir)))
23912 (org-create-formula-image
23913 txt movefile opt forbuffer)
23914 (if overlays
23915 (progn
23916 (setq ov (org-make-overlay beg end))
23917 (if (featurep 'xemacs)
23918 (progn
23919 (org-overlay-put ov 'invisible t)
23920 (org-overlay-put
23921 ov 'end-glyph
23922 (make-glyph (vector 'png :file movefile))))
23923 (org-overlay-put
23924 ov 'display
23925 (list 'image :type 'png :file movefile :ascent 'center)))
23926 (push ov org-latex-fragment-image-overlays)
23927 (goto-char end))
23928 (delete-region beg end)
23929 (insert link))))))))
23931 ;; This function borrows from Ganesh Swami's latex2png.el
23932 (defun org-create-formula-image (string tofile options buffer)
23933 (let* ((tmpdir (if (featurep 'xemacs)
23934 (temp-directory)
23935 temporary-file-directory))
23936 (texfilebase (make-temp-name
23937 (expand-file-name "orgtex" tmpdir)))
23938 (texfile (concat texfilebase ".tex"))
23939 (dvifile (concat texfilebase ".dvi"))
23940 (pngfile (concat texfilebase ".png"))
23941 (fnh (face-attribute 'default :height nil))
23942 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23943 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23944 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23945 "Black"))
23946 (bg (or (plist-get options (if buffer :background :html-background))
23947 "Transparent")))
23948 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23949 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23950 (with-temp-file texfile
23951 (insert org-format-latex-header
23952 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23953 (let ((dir default-directory))
23954 (condition-case nil
23955 (progn
23956 (cd tmpdir)
23957 (call-process "latex" nil nil nil texfile))
23958 (error nil))
23959 (cd dir))
23960 (if (not (file-exists-p dvifile))
23961 (progn (message "Failed to create dvi file from %s" texfile) nil)
23962 (call-process "dvipng" nil nil nil
23963 "-E" "-fg" fg "-bg" bg
23964 "-D" dpi
23965 ;;"-x" scale "-y" scale
23966 "-T" "tight"
23967 "-o" pngfile
23968 dvifile)
23969 (if (not (file-exists-p pngfile))
23970 (progn (message "Failed to create png file from %s" texfile) nil)
23971 ;; Use the requested file name and clean up
23972 (copy-file pngfile tofile 'replace)
23973 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23974 (delete-file (concat texfilebase e)))
23975 pngfile))))
23977 (defun org-dvipng-color (attr)
23978 "Return an rgb color specification for dvipng."
23979 (apply 'format "rgb %s %s %s"
23980 (mapcar 'org-normalize-color
23981 (color-values (face-attribute 'default attr nil)))))
23983 (defun org-normalize-color (value)
23984 "Return string to be used as color value for an RGB component."
23985 (format "%g" (/ value 65535.0)))
23987 ;;;; Exporting
23989 ;;; Variables, constants, and parameter plists
23991 (defconst org-level-max 20)
23993 (defvar org-export-html-preamble nil
23994 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23995 (defvar org-export-html-postamble nil
23996 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23997 (defvar org-export-html-auto-preamble t
23998 "Should default preamble be inserted? Set by publishing functions.")
23999 (defvar org-export-html-auto-postamble t
24000 "Should default postamble be inserted? Set by publishing functions.")
24001 (defvar org-current-export-file nil) ; dynamically scoped parameter
24002 (defvar org-current-export-dir nil) ; dynamically scoped parameter
24005 (defconst org-export-plist-vars
24006 '((:language . org-export-default-language)
24007 (:customtime . org-display-custom-times)
24008 (:headline-levels . org-export-headline-levels)
24009 (:section-numbers . org-export-with-section-numbers)
24010 (:table-of-contents . org-export-with-toc)
24011 (:preserve-breaks . org-export-preserve-breaks)
24012 (:archived-trees . org-export-with-archived-trees)
24013 (:emphasize . org-export-with-emphasize)
24014 (:sub-superscript . org-export-with-sub-superscripts)
24015 (:special-strings . org-export-with-special-strings)
24016 (:footnotes . org-export-with-footnotes)
24017 (:drawers . org-export-with-drawers)
24018 (:tags . org-export-with-tags)
24019 (:TeX-macros . org-export-with-TeX-macros)
24020 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
24021 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
24022 (:fixed-width . org-export-with-fixed-width)
24023 (:timestamps . org-export-with-timestamps)
24024 (:author-info . org-export-author-info)
24025 (:time-stamp-file . org-export-time-stamp-file)
24026 (:tables . org-export-with-tables)
24027 (:table-auto-headline . org-export-highlight-first-table-line)
24028 (:style . org-export-html-style)
24029 (:agenda-style . org-agenda-export-html-style)
24030 (:convert-org-links . org-export-html-link-org-files-as-html)
24031 (:inline-images . org-export-html-inline-images)
24032 (:html-extension . org-export-html-extension)
24033 (:html-table-tag . org-export-html-table-tag)
24034 (:expand-quoted-html . org-export-html-expand)
24035 (:timestamp . org-export-html-with-timestamp)
24036 (:publishing-directory . org-export-publishing-directory)
24037 (:preamble . org-export-html-preamble)
24038 (:postamble . org-export-html-postamble)
24039 (:auto-preamble . org-export-html-auto-preamble)
24040 (:auto-postamble . org-export-html-auto-postamble)
24041 (:author . user-full-name)
24042 (:email . user-mail-address)))
24044 (defun org-default-export-plist ()
24045 "Return the property list with default settings for the export variables."
24046 (let ((l org-export-plist-vars) rtn e)
24047 (while (setq e (pop l))
24048 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
24049 rtn))
24051 (defun org-infile-export-plist ()
24052 "Return the property list with file-local settings for export."
24053 (save-excursion
24054 (save-restriction
24055 (widen)
24056 (goto-char 0)
24057 (let ((re (org-make-options-regexp
24058 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
24059 p key val text options)
24060 (while (re-search-forward re nil t)
24061 (setq key (org-match-string-no-properties 1)
24062 val (org-match-string-no-properties 2))
24063 (cond
24064 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
24065 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
24066 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
24067 ((string-equal key "DATE") (setq p (plist-put p :date val)))
24068 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
24069 ((string-equal key "TEXT")
24070 (setq text (if text (concat text "\n" val) val)))
24071 ((string-equal key "OPTIONS") (setq options val))))
24072 (setq p (plist-put p :text text))
24073 (when options
24074 (let ((op '(("H" . :headline-levels)
24075 ("num" . :section-numbers)
24076 ("toc" . :table-of-contents)
24077 ("\\n" . :preserve-breaks)
24078 ("@" . :expand-quoted-html)
24079 (":" . :fixed-width)
24080 ("|" . :tables)
24081 ("^" . :sub-superscript)
24082 ("-" . :special-strings)
24083 ("f" . :footnotes)
24084 ("d" . :drawers)
24085 ("tags" . :tags)
24086 ("*" . :emphasize)
24087 ("TeX" . :TeX-macros)
24088 ("LaTeX" . :LaTeX-fragments)
24089 ("skip" . :skip-before-1st-heading)
24090 ("author" . :author-info)
24091 ("timestamp" . :time-stamp-file)))
24093 (while (setq o (pop op))
24094 (if (string-match (concat (regexp-quote (car o))
24095 ":\\([^ \t\n\r;,.]*\\)")
24096 options)
24097 (setq p (plist-put p (cdr o)
24098 (car (read-from-string
24099 (match-string 1 options)))))))))
24100 p))))
24102 (defun org-export-directory (type plist)
24103 (let* ((val (plist-get plist :publishing-directory))
24104 (dir (if (listp val)
24105 (or (cdr (assoc type val)) ".")
24106 val)))
24107 dir))
24109 (defun org-skip-comments (lines)
24110 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
24111 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
24112 (re2 "^\\(\\*+\\)[ \t\n\r]")
24113 (case-fold-search nil)
24114 rtn line level)
24115 (while (setq line (pop lines))
24116 (cond
24117 ((and (string-match re1 line)
24118 (setq level (- (match-end 1) (match-beginning 1))))
24119 ;; Beginning of a COMMENT subtree. Skip it.
24120 (while (and (setq line (pop lines))
24121 (or (not (string-match re2 line))
24122 (> (- (match-end 1) (match-beginning 1)) level))))
24123 (setq lines (cons line lines)))
24124 ((string-match "^#" line)
24125 ;; an ordinary comment line
24127 ((and org-export-table-remove-special-lines
24128 (string-match "^[ \t]*|" line)
24129 (or (string-match "^[ \t]*| *[!_^] *|" line)
24130 (and (string-match "| *<[0-9]+> *|" line)
24131 (not (string-match "| *[^ <|]" line)))))
24132 ;; a special table line that should be removed
24134 (t (setq rtn (cons line rtn)))))
24135 (nreverse rtn)))
24137 (defun org-export (&optional arg)
24138 (interactive)
24139 (let ((help "[t] insert the export option template
24140 \[v] limit export to visible part of outline tree
24142 \[a] export as ASCII
24144 \[h] export as HTML
24145 \[H] export as HTML to temporary buffer
24146 \[R] export region as HTML
24147 \[b] export as HTML and browse immediately
24148 \[x] export as XOXO
24150 \[l] export as LaTeX
24151 \[L] export as LaTeX to temporary buffer
24153 \[i] export current file as iCalendar file
24154 \[I] export all agenda files as iCalendar files
24155 \[c] export agenda files into combined iCalendar file
24157 \[F] publish current file
24158 \[P] publish current project
24159 \[X] publish... (project will be prompted for)
24160 \[A] publish all projects")
24161 (cmds
24162 '((?t . org-insert-export-options-template)
24163 (?v . org-export-visible)
24164 (?a . org-export-as-ascii)
24165 (?h . org-export-as-html)
24166 (?b . org-export-as-html-and-open)
24167 (?H . org-export-as-html-to-buffer)
24168 (?R . org-export-region-as-html)
24169 (?x . org-export-as-xoxo)
24170 (?l . org-export-as-latex)
24171 (?L . org-export-as-latex-to-buffer)
24172 (?i . org-export-icalendar-this-file)
24173 (?I . org-export-icalendar-all-agenda-files)
24174 (?c . org-export-icalendar-combine-agenda-files)
24175 (?F . org-publish-current-file)
24176 (?P . org-publish-current-project)
24177 (?X . org-publish)
24178 (?A . org-publish-all)))
24179 r1 r2 ass)
24180 (save-window-excursion
24181 (delete-other-windows)
24182 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
24183 (princ help))
24184 (message "Select command: ")
24185 (setq r1 (read-char-exclusive)))
24186 (setq r2 (if (< r1 27) (+ r1 96) r1))
24187 (if (setq ass (assq r2 cmds))
24188 (call-interactively (cdr ass))
24189 (error "No command associated with key %c" r1))))
24191 (defconst org-html-entities
24192 '(("nbsp")
24193 ("iexcl")
24194 ("cent")
24195 ("pound")
24196 ("curren")
24197 ("yen")
24198 ("brvbar")
24199 ("vert" . "&#124;")
24200 ("sect")
24201 ("uml")
24202 ("copy")
24203 ("ordf")
24204 ("laquo")
24205 ("not")
24206 ("shy")
24207 ("reg")
24208 ("macr")
24209 ("deg")
24210 ("plusmn")
24211 ("sup2")
24212 ("sup3")
24213 ("acute")
24214 ("micro")
24215 ("para")
24216 ("middot")
24217 ("odot"."o")
24218 ("star"."*")
24219 ("cedil")
24220 ("sup1")
24221 ("ordm")
24222 ("raquo")
24223 ("frac14")
24224 ("frac12")
24225 ("frac34")
24226 ("iquest")
24227 ("Agrave")
24228 ("Aacute")
24229 ("Acirc")
24230 ("Atilde")
24231 ("Auml")
24232 ("Aring") ("AA"."&Aring;")
24233 ("AElig")
24234 ("Ccedil")
24235 ("Egrave")
24236 ("Eacute")
24237 ("Ecirc")
24238 ("Euml")
24239 ("Igrave")
24240 ("Iacute")
24241 ("Icirc")
24242 ("Iuml")
24243 ("ETH")
24244 ("Ntilde")
24245 ("Ograve")
24246 ("Oacute")
24247 ("Ocirc")
24248 ("Otilde")
24249 ("Ouml")
24250 ("times")
24251 ("Oslash")
24252 ("Ugrave")
24253 ("Uacute")
24254 ("Ucirc")
24255 ("Uuml")
24256 ("Yacute")
24257 ("THORN")
24258 ("szlig")
24259 ("agrave")
24260 ("aacute")
24261 ("acirc")
24262 ("atilde")
24263 ("auml")
24264 ("aring")
24265 ("aelig")
24266 ("ccedil")
24267 ("egrave")
24268 ("eacute")
24269 ("ecirc")
24270 ("euml")
24271 ("igrave")
24272 ("iacute")
24273 ("icirc")
24274 ("iuml")
24275 ("eth")
24276 ("ntilde")
24277 ("ograve")
24278 ("oacute")
24279 ("ocirc")
24280 ("otilde")
24281 ("ouml")
24282 ("divide")
24283 ("oslash")
24284 ("ugrave")
24285 ("uacute")
24286 ("ucirc")
24287 ("uuml")
24288 ("yacute")
24289 ("thorn")
24290 ("yuml")
24291 ("fnof")
24292 ("Alpha")
24293 ("Beta")
24294 ("Gamma")
24295 ("Delta")
24296 ("Epsilon")
24297 ("Zeta")
24298 ("Eta")
24299 ("Theta")
24300 ("Iota")
24301 ("Kappa")
24302 ("Lambda")
24303 ("Mu")
24304 ("Nu")
24305 ("Xi")
24306 ("Omicron")
24307 ("Pi")
24308 ("Rho")
24309 ("Sigma")
24310 ("Tau")
24311 ("Upsilon")
24312 ("Phi")
24313 ("Chi")
24314 ("Psi")
24315 ("Omega")
24316 ("alpha")
24317 ("beta")
24318 ("gamma")
24319 ("delta")
24320 ("epsilon")
24321 ("varepsilon"."&epsilon;")
24322 ("zeta")
24323 ("eta")
24324 ("theta")
24325 ("iota")
24326 ("kappa")
24327 ("lambda")
24328 ("mu")
24329 ("nu")
24330 ("xi")
24331 ("omicron")
24332 ("pi")
24333 ("rho")
24334 ("sigmaf") ("varsigma"."&sigmaf;")
24335 ("sigma")
24336 ("tau")
24337 ("upsilon")
24338 ("phi")
24339 ("chi")
24340 ("psi")
24341 ("omega")
24342 ("thetasym") ("vartheta"."&thetasym;")
24343 ("upsih")
24344 ("piv")
24345 ("bull") ("bullet"."&bull;")
24346 ("hellip") ("dots"."&hellip;")
24347 ("prime")
24348 ("Prime")
24349 ("oline")
24350 ("frasl")
24351 ("weierp")
24352 ("image")
24353 ("real")
24354 ("trade")
24355 ("alefsym")
24356 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
24357 ("uarr") ("uparrow"."&uarr;")
24358 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
24359 ("darr")("downarrow"."&darr;")
24360 ("harr") ("leftrightarrow"."&harr;")
24361 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
24362 ("lArr") ("Leftarrow"."&lArr;")
24363 ("uArr") ("Uparrow"."&uArr;")
24364 ("rArr") ("Rightarrow"."&rArr;")
24365 ("dArr") ("Downarrow"."&dArr;")
24366 ("hArr") ("Leftrightarrow"."&hArr;")
24367 ("forall")
24368 ("part") ("partial"."&part;")
24369 ("exist") ("exists"."&exist;")
24370 ("empty") ("emptyset"."&empty;")
24371 ("nabla")
24372 ("isin") ("in"."&isin;")
24373 ("notin")
24374 ("ni")
24375 ("prod")
24376 ("sum")
24377 ("minus")
24378 ("lowast") ("ast"."&lowast;")
24379 ("radic")
24380 ("prop") ("proptp"."&prop;")
24381 ("infin") ("infty"."&infin;")
24382 ("ang") ("angle"."&ang;")
24383 ("and") ("wedge"."&and;")
24384 ("or") ("vee"."&or;")
24385 ("cap")
24386 ("cup")
24387 ("int")
24388 ("there4")
24389 ("sim")
24390 ("cong") ("simeq"."&cong;")
24391 ("asymp")("approx"."&asymp;")
24392 ("ne") ("neq"."&ne;")
24393 ("equiv")
24394 ("le")
24395 ("ge")
24396 ("sub") ("subset"."&sub;")
24397 ("sup") ("supset"."&sup;")
24398 ("nsub")
24399 ("sube")
24400 ("supe")
24401 ("oplus")
24402 ("otimes")
24403 ("perp")
24404 ("sdot") ("cdot"."&sdot;")
24405 ("lceil")
24406 ("rceil")
24407 ("lfloor")
24408 ("rfloor")
24409 ("lang")
24410 ("rang")
24411 ("loz") ("Diamond"."&loz;")
24412 ("spades") ("spadesuit"."&spades;")
24413 ("clubs") ("clubsuit"."&clubs;")
24414 ("hearts") ("diamondsuit"."&hearts;")
24415 ("diams") ("diamondsuit"."&diams;")
24416 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
24417 ("quot")
24418 ("amp")
24419 ("lt")
24420 ("gt")
24421 ("OElig")
24422 ("oelig")
24423 ("Scaron")
24424 ("scaron")
24425 ("Yuml")
24426 ("circ")
24427 ("tilde")
24428 ("ensp")
24429 ("emsp")
24430 ("thinsp")
24431 ("zwnj")
24432 ("zwj")
24433 ("lrm")
24434 ("rlm")
24435 ("ndash")
24436 ("mdash")
24437 ("lsquo")
24438 ("rsquo")
24439 ("sbquo")
24440 ("ldquo")
24441 ("rdquo")
24442 ("bdquo")
24443 ("dagger")
24444 ("Dagger")
24445 ("permil")
24446 ("lsaquo")
24447 ("rsaquo")
24448 ("euro")
24450 ("arccos"."arccos")
24451 ("arcsin"."arcsin")
24452 ("arctan"."arctan")
24453 ("arg"."arg")
24454 ("cos"."cos")
24455 ("cosh"."cosh")
24456 ("cot"."cot")
24457 ("coth"."coth")
24458 ("csc"."csc")
24459 ("deg"."deg")
24460 ("det"."det")
24461 ("dim"."dim")
24462 ("exp"."exp")
24463 ("gcd"."gcd")
24464 ("hom"."hom")
24465 ("inf"."inf")
24466 ("ker"."ker")
24467 ("lg"."lg")
24468 ("lim"."lim")
24469 ("liminf"."liminf")
24470 ("limsup"."limsup")
24471 ("ln"."ln")
24472 ("log"."log")
24473 ("max"."max")
24474 ("min"."min")
24475 ("Pr"."Pr")
24476 ("sec"."sec")
24477 ("sin"."sin")
24478 ("sinh"."sinh")
24479 ("sup"."sup")
24480 ("tan"."tan")
24481 ("tanh"."tanh")
24483 "Entities for TeX->HTML translation.
24484 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24485 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24486 In that case, \"\\ent\" will be translated to \"&other;\".
24487 The list contains HTML entities for Latin-1, Greek and other symbols.
24488 It is supplemented by a number of commonly used TeX macros with appropriate
24489 translations. There is currently no way for users to extend this.")
24491 ;;; General functions for all backends
24493 (defun org-cleaned-string-for-export (string &rest parameters)
24494 "Cleanup a buffer STRING so that links can be created safely."
24495 (interactive)
24496 (let* ((re-radio (and org-target-link-regexp
24497 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24498 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24499 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24500 (re-archive (concat ":" org-archive-tag ":"))
24501 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24502 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24503 (htmlp (plist-get parameters :for-html))
24504 (asciip (plist-get parameters :for-ascii))
24505 (latexp (plist-get parameters :for-LaTeX))
24506 (commentsp (plist-get parameters :comments))
24507 (archived-trees (plist-get parameters :archived-trees))
24508 (inhibit-read-only t)
24509 (drawers org-drawers)
24510 (exp-drawers (plist-get parameters :drawers))
24511 (outline-regexp "\\*+ ")
24512 a b xx
24513 rtn p)
24514 (with-current-buffer (get-buffer-create " org-mode-tmp")
24515 (erase-buffer)
24516 (insert string)
24517 ;; Remove license-to-kill stuff
24518 (while (setq p (text-property-any (point-min) (point-max)
24519 :org-license-to-kill t))
24520 (delete-region p (next-single-property-change p :org-license-to-kill)))
24522 (let ((org-inhibit-startup t)) (org-mode))
24523 (untabify (point-min) (point-max))
24525 ;; Get rid of drawers
24526 (unless (eq t exp-drawers)
24527 (goto-char (point-min))
24528 (let ((re (concat "^[ \t]*:\\("
24529 (mapconcat
24530 'identity
24531 (org-delete-all exp-drawers
24532 (copy-sequence drawers))
24533 "\\|")
24534 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24535 (while (re-search-forward re nil t)
24536 (replace-match ""))))
24538 ;; Get the correct stuff before the first headline
24539 (when (plist-get parameters :skip-before-1st-heading)
24540 (goto-char (point-min))
24541 (when (re-search-forward "^\\*+[ \t]" nil t)
24542 (delete-region (point-min) (match-beginning 0))
24543 (goto-char (point-min))
24544 (insert "\n")))
24545 (when (plist-get parameters :add-text)
24546 (goto-char (point-min))
24547 (insert (plist-get parameters :add-text) "\n"))
24549 ;; Get rid of archived trees
24550 (when (not (eq archived-trees t))
24551 (goto-char (point-min))
24552 (while (re-search-forward re-archive nil t)
24553 (if (not (org-on-heading-p t))
24554 (org-end-of-subtree t)
24555 (beginning-of-line 1)
24556 (setq a (if archived-trees
24557 (1+ (point-at-eol)) (point))
24558 b (org-end-of-subtree t))
24559 (if (> b a) (delete-region a b)))))
24561 ;; Find targets in comments and move them out of comments,
24562 ;; but mark them as targets that should be invisible
24563 (goto-char (point-min))
24564 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24565 (replace-match "\\1(INVISIBLE)"))
24567 ;; Protect backend specific stuff, throw away the others.
24568 (let ((formatters
24569 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24570 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24571 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24572 fmt)
24573 (goto-char (point-min))
24574 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24575 (goto-char (match-end 0))
24576 (while (not (looking-at "#\\+END_EXAMPLE"))
24577 (insert ": ")
24578 (beginning-of-line 2)))
24579 (goto-char (point-min))
24580 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24581 (add-text-properties (match-beginning 0) (match-end 0)
24582 '(org-protected t)))
24583 (while formatters
24584 (setq fmt (pop formatters))
24585 (when (car fmt)
24586 (goto-char (point-min))
24587 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24588 ":[ \t]*\\(.*\\)") nil t)
24589 (replace-match "\\1" t)
24590 (add-text-properties
24591 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24592 '(org-protected t))))
24593 (goto-char (point-min))
24594 (while (re-search-forward
24595 (concat "^#\\+"
24596 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24597 (cadddr fmt) "\\>.*\n?") nil t)
24598 (if (car fmt)
24599 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24600 '(org-protected t))
24601 (delete-region (match-beginning 0) (match-end 0))))))
24603 ;; Protect quoted subtrees
24604 (goto-char (point-min))
24605 (while (re-search-forward re-quote nil t)
24606 (goto-char (match-beginning 0))
24607 (end-of-line 1)
24608 (add-text-properties (point) (org-end-of-subtree t)
24609 '(org-protected t)))
24611 ;; Protect verbatim elements
24612 (goto-char (point-min))
24613 (while (re-search-forward org-verbatim-re nil t)
24614 (add-text-properties (match-beginning 4) (match-end 4)
24615 '(org-protected t))
24616 (goto-char (1+ (match-end 4))))
24618 ;; Remove subtrees that are commented
24619 (goto-char (point-min))
24620 (while (re-search-forward re-commented nil t)
24621 (goto-char (match-beginning 0))
24622 (delete-region (point) (org-end-of-subtree t)))
24624 ;; Remove special table lines
24625 (when org-export-table-remove-special-lines
24626 (goto-char (point-min))
24627 (while (re-search-forward "^[ \t]*|" nil t)
24628 (beginning-of-line 1)
24629 (if (or (looking-at "[ \t]*| *[!_^] *|")
24630 (and (looking-at ".*?| *<[0-9]+> *|")
24631 (not (looking-at ".*?| *[^ <|]"))))
24632 (delete-region (max (point-min) (1- (point-at-bol)))
24633 (point-at-eol))
24634 (end-of-line 1))))
24636 ;; Specific LaTeX stuff
24637 (when latexp
24638 (require 'org-export-latex nil)
24639 (org-export-latex-cleaned-string))
24641 (when asciip
24642 (org-export-ascii-clean-string))
24644 ;; Specific HTML stuff
24645 (when htmlp
24646 ;; Convert LaTeX fragments to images
24647 (when (plist-get parameters :LaTeX-fragments)
24648 (org-format-latex
24649 (concat "ltxpng/" (file-name-sans-extension
24650 (file-name-nondirectory
24651 org-current-export-file)))
24652 org-current-export-dir nil "Creating LaTeX image %s"))
24653 (message "Exporting..."))
24655 ;; Remove or replace comments
24656 (goto-char (point-min))
24657 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24658 (if commentsp
24659 (progn (add-text-properties
24660 (match-beginning 0) (match-end 0) '(org-protected t))
24661 (replace-match (format commentsp (match-string 1)) t t))
24662 (replace-match "")))
24664 ;; Find matches for radio targets and turn them into internal links
24665 (goto-char (point-min))
24666 (when re-radio
24667 (while (re-search-forward re-radio nil t)
24668 (org-if-unprotected
24669 (replace-match "\\1[[\\2]]"))))
24671 ;; Find all links that contain a newline and put them into a single line
24672 (goto-char (point-min))
24673 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24674 (org-if-unprotected
24675 (replace-match "\\1 \\3")
24676 (goto-char (match-beginning 0))))
24679 ;; Normalize links: Convert angle and plain links into bracket links
24680 ;; Expand link abbreviations
24681 (goto-char (point-min))
24682 (while (re-search-forward re-plain-link nil t)
24683 (goto-char (1- (match-end 0)))
24684 (org-if-unprotected
24685 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24686 ":" (match-string 3) "]]")))
24687 ;; added 'org-link face to links
24688 (put-text-property 0 (length s) 'face 'org-link s)
24689 (replace-match s t t))))
24690 (goto-char (point-min))
24691 (while (re-search-forward re-angle-link nil t)
24692 (goto-char (1- (match-end 0)))
24693 (org-if-unprotected
24694 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24695 ":" (match-string 3) "]]")))
24696 (put-text-property 0 (length s) 'face 'org-link s)
24697 (replace-match s t t))))
24698 (goto-char (point-min))
24699 (while (re-search-forward org-bracket-link-regexp nil t)
24700 (org-if-unprotected
24701 (let* ((s (concat "[[" (setq xx (save-match-data
24702 (org-link-expand-abbrev (match-string 1))))
24704 (if (match-end 3)
24705 (match-string 2)
24706 (concat "[" xx "]"))
24707 "]")))
24708 (put-text-property 0 (length s) 'face 'org-link s)
24709 (replace-match s t t))))
24711 ;; Find multiline emphasis and put them into single line
24712 (when (plist-get parameters :emph-multiline)
24713 (goto-char (point-min))
24714 (while (re-search-forward org-emph-re nil t)
24715 (if (not (= (char-after (match-beginning 3))
24716 (char-after (match-beginning 4))))
24717 (org-if-unprotected
24718 (subst-char-in-region (match-beginning 0) (match-end 0)
24719 ?\n ?\ t)
24720 (goto-char (1- (match-end 0))))
24721 (goto-char (1+ (match-beginning 0))))))
24723 (setq rtn (buffer-string)))
24724 (kill-buffer " org-mode-tmp")
24725 rtn))
24727 (defun org-export-grab-title-from-buffer ()
24728 "Get a title for the current document, from looking at the buffer."
24729 (let ((inhibit-read-only t))
24730 (save-excursion
24731 (goto-char (point-min))
24732 (let ((end (save-excursion (outline-next-heading) (point))))
24733 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24734 ;; Mark the line so that it will not be exported as normal text.
24735 (org-unmodified
24736 (add-text-properties (match-beginning 0) (match-end 0)
24737 (list :org-license-to-kill t)))
24738 ;; Return the title string
24739 (org-trim (match-string 0)))))))
24741 (defun org-export-get-title-from-subtree ()
24742 "Return subtree title and exclude it from export."
24743 (let (title (m (mark)))
24744 (save-excursion
24745 (goto-char (region-beginning))
24746 (when (and (org-at-heading-p)
24747 (>= (org-end-of-subtree t t) (region-end)))
24748 ;; This is a subtree, we take the title from the first heading
24749 (goto-char (region-beginning))
24750 (looking-at org-todo-line-regexp)
24751 (setq title (match-string 3))
24752 (org-unmodified
24753 (add-text-properties (point) (1+ (point-at-eol))
24754 (list :org-license-to-kill t)))))
24755 title))
24757 (defun org-solidify-link-text (s &optional alist)
24758 "Take link text and make a safe target out of it."
24759 (save-match-data
24760 (let* ((rtn
24761 (mapconcat
24762 'identity
24763 (org-split-string s "[ \t\r\n]+") "--"))
24764 (a (assoc rtn alist)))
24765 (or (cdr a) rtn))))
24767 (defun org-get-min-level (lines)
24768 "Get the minimum level in LINES."
24769 (let ((re "^\\(\\*+\\) ") l min)
24770 (catch 'exit
24771 (while (setq l (pop lines))
24772 (if (string-match re l)
24773 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24774 1)))
24776 ;; Variable holding the vector with section numbers
24777 (defvar org-section-numbers (make-vector org-level-max 0))
24779 (defun org-init-section-numbers ()
24780 "Initialize the vector for the section numbers."
24781 (let* ((level -1)
24782 (numbers (nreverse (org-split-string "" "\\.")))
24783 (depth (1- (length org-section-numbers)))
24784 (i depth) number-string)
24785 (while (>= i 0)
24786 (if (> i level)
24787 (aset org-section-numbers i 0)
24788 (setq number-string (or (car numbers) "0"))
24789 (if (string-match "\\`[A-Z]\\'" number-string)
24790 (aset org-section-numbers i
24791 (- (string-to-char number-string) ?A -1))
24792 (aset org-section-numbers i (string-to-number number-string)))
24793 (pop numbers))
24794 (setq i (1- i)))))
24796 (defun org-section-number (&optional level)
24797 "Return a string with the current section number.
24798 When LEVEL is non-nil, increase section numbers on that level."
24799 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24800 (when level
24801 (when (> level -1)
24802 (aset org-section-numbers
24803 level (1+ (aref org-section-numbers level))))
24804 (setq idx (1+ level))
24805 (while (<= idx depth)
24806 (if (not (= idx 1))
24807 (aset org-section-numbers idx 0))
24808 (setq idx (1+ idx))))
24809 (setq idx 0)
24810 (while (<= idx depth)
24811 (setq n (aref org-section-numbers idx))
24812 (setq string (concat string (if (not (string= string "")) "." "")
24813 (int-to-string n)))
24814 (setq idx (1+ idx)))
24815 (save-match-data
24816 (if (string-match "\\`\\([@0]\\.\\)+" string)
24817 (setq string (replace-match "" t nil string)))
24818 (if (string-match "\\(\\.0\\)+\\'" string)
24819 (setq string (replace-match "" t nil string))))
24820 string))
24822 ;;; ASCII export
24824 (defvar org-last-level nil) ; dynamically scoped variable
24825 (defvar org-min-level nil) ; dynamically scoped variable
24826 (defvar org-levels-open nil) ; dynamically scoped parameter
24827 (defvar org-ascii-current-indentation nil) ; For communication
24829 (defun org-export-as-ascii (arg)
24830 "Export the outline as a pretty ASCII file.
24831 If there is an active region, export only the region.
24832 The prefix ARG specifies how many levels of the outline should become
24833 underlined headlines. The default is 3."
24834 (interactive "P")
24835 (setq-default org-todo-line-regexp org-todo-line-regexp)
24836 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24837 (org-infile-export-plist)))
24838 (region-p (org-region-active-p))
24839 (subtree-p
24840 (when region-p
24841 (save-excursion
24842 (goto-char (region-beginning))
24843 (and (org-at-heading-p)
24844 (>= (org-end-of-subtree t t) (region-end))))))
24845 (custom-times org-display-custom-times)
24846 (org-ascii-current-indentation '(0 . 0))
24847 (level 0) line txt
24848 (umax nil)
24849 (umax-toc nil)
24850 (case-fold-search nil)
24851 (filename (concat (file-name-as-directory
24852 (org-export-directory :ascii opt-plist))
24853 (file-name-sans-extension
24854 (or (and subtree-p
24855 (org-entry-get (region-beginning)
24856 "EXPORT_FILE_NAME" t))
24857 (file-name-nondirectory buffer-file-name)))
24858 ".txt"))
24859 (filename (if (equal (file-truename filename)
24860 (file-truename buffer-file-name))
24861 (concat filename ".txt")
24862 filename))
24863 (buffer (find-file-noselect filename))
24864 (org-levels-open (make-vector org-level-max nil))
24865 (odd org-odd-levels-only)
24866 (date (plist-get opt-plist :date))
24867 (author (plist-get opt-plist :author))
24868 (title (or (and subtree-p (org-export-get-title-from-subtree))
24869 (plist-get opt-plist :title)
24870 (and (not
24871 (plist-get opt-plist :skip-before-1st-heading))
24872 (org-export-grab-title-from-buffer))
24873 (file-name-sans-extension
24874 (file-name-nondirectory buffer-file-name))))
24875 (email (plist-get opt-plist :email))
24876 (language (plist-get opt-plist :language))
24877 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24878 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24879 (todo nil)
24880 (lang-words nil)
24881 (region
24882 (buffer-substring
24883 (if (org-region-active-p) (region-beginning) (point-min))
24884 (if (org-region-active-p) (region-end) (point-max))))
24885 (lines (org-split-string
24886 (org-cleaned-string-for-export
24887 region
24888 :for-ascii t
24889 :skip-before-1st-heading
24890 (plist-get opt-plist :skip-before-1st-heading)
24891 :drawers (plist-get opt-plist :drawers)
24892 :verbatim-multiline t
24893 :archived-trees
24894 (plist-get opt-plist :archived-trees)
24895 :add-text (plist-get opt-plist :text))
24896 "\n"))
24897 thetoc have-headings first-heading-pos
24898 table-open table-buffer)
24900 (let ((inhibit-read-only t))
24901 (org-unmodified
24902 (remove-text-properties (point-min) (point-max)
24903 '(:org-license-to-kill t))))
24905 (setq org-min-level (org-get-min-level lines))
24906 (setq org-last-level org-min-level)
24907 (org-init-section-numbers)
24909 (find-file-noselect filename)
24911 (setq lang-words (or (assoc language org-export-language-setup)
24912 (assoc "en" org-export-language-setup)))
24913 (switch-to-buffer-other-window buffer)
24914 (erase-buffer)
24915 (fundamental-mode)
24916 ;; create local variables for all options, to make sure all called
24917 ;; functions get the correct information
24918 (mapc (lambda (x)
24919 (set (make-local-variable (cdr x))
24920 (plist-get opt-plist (car x))))
24921 org-export-plist-vars)
24922 (org-set-local 'org-odd-levels-only odd)
24923 (setq umax (if arg (prefix-numeric-value arg)
24924 org-export-headline-levels))
24925 (setq umax-toc (if (integerp org-export-with-toc)
24926 (min org-export-with-toc umax)
24927 umax))
24929 ;; File header
24930 (if title (org-insert-centered title ?=))
24931 (insert "\n")
24932 (if (and (or author email)
24933 org-export-author-info)
24934 (insert (concat (nth 1 lang-words) ": " (or author "")
24935 (if email (concat " <" email ">") "")
24936 "\n")))
24938 (cond
24939 ((and date (string-match "%" date))
24940 (setq date (format-time-string date (current-time))))
24941 (date)
24942 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24944 (if (and date org-export-time-stamp-file)
24945 (insert (concat (nth 2 lang-words) ": " date"\n")))
24947 (insert "\n\n")
24949 (if org-export-with-toc
24950 (progn
24951 (push (concat (nth 3 lang-words) "\n") thetoc)
24952 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24953 (mapc '(lambda (line)
24954 (if (string-match org-todo-line-regexp
24955 line)
24956 ;; This is a headline
24957 (progn
24958 (setq have-headings t)
24959 (setq level (- (match-end 1) (match-beginning 1))
24960 level (org-tr-level level)
24961 txt (match-string 3 line)
24962 todo
24963 (or (and org-export-mark-todo-in-toc
24964 (match-beginning 2)
24965 (not (member (match-string 2 line)
24966 org-done-keywords)))
24967 ; TODO, not DONE
24968 (and org-export-mark-todo-in-toc
24969 (= level umax-toc)
24970 (org-search-todo-below
24971 line lines level))))
24972 (setq txt (org-html-expand-for-ascii txt))
24974 (while (string-match org-bracket-link-regexp txt)
24975 (setq txt
24976 (replace-match
24977 (match-string (if (match-end 2) 3 1) txt)
24978 t t txt)))
24980 (if (and (memq org-export-with-tags '(not-in-toc nil))
24981 (string-match
24982 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24983 txt))
24984 (setq txt (replace-match "" t t txt)))
24985 (if (string-match quote-re0 txt)
24986 (setq txt (replace-match "" t t txt)))
24988 (if org-export-with-section-numbers
24989 (setq txt (concat (org-section-number level)
24990 " " txt)))
24991 (if (<= level umax-toc)
24992 (progn
24993 (push
24994 (concat
24995 (make-string
24996 (* (max 0 (- level org-min-level)) 4) ?\ )
24997 (format (if todo "%s (*)\n" "%s\n") txt))
24998 thetoc)
24999 (setq org-last-level level))
25000 ))))
25001 lines)
25002 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25004 (org-init-section-numbers)
25005 (while (setq line (pop lines))
25006 ;; Remove the quoted HTML tags.
25007 (setq line (org-html-expand-for-ascii line))
25008 ;; Remove targets
25009 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
25010 (setq line (replace-match "" t t line)))
25011 ;; Replace internal links
25012 (while (string-match org-bracket-link-regexp line)
25013 (setq line (replace-match
25014 (if (match-end 3) "[\\3]" "[\\1]")
25015 t nil line)))
25016 (when custom-times
25017 (setq line (org-translate-time line)))
25018 (cond
25019 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25020 ;; a Headline
25021 (setq first-heading-pos (or first-heading-pos (point)))
25022 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25023 txt (match-string 2 line))
25024 (org-ascii-level-start level txt umax lines))
25026 ((and org-export-with-tables
25027 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25028 (if (not table-open)
25029 ;; New table starts
25030 (setq table-open t table-buffer nil))
25031 ;; Accumulate lines
25032 (setq table-buffer (cons line table-buffer))
25033 (when (or (not lines)
25034 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25035 (car lines))))
25036 (setq table-open nil
25037 table-buffer (nreverse table-buffer))
25038 (insert (mapconcat
25039 (lambda (x)
25040 (org-fix-indentation x org-ascii-current-indentation))
25041 (org-format-table-ascii table-buffer)
25042 "\n") "\n")))
25044 (setq line (org-fix-indentation line org-ascii-current-indentation))
25045 (if (and org-export-with-fixed-width
25046 (string-match "^\\([ \t]*\\)\\(:\\)" line))
25047 (setq line (replace-match "\\1" nil nil line)))
25048 (insert line "\n"))))
25050 (normal-mode)
25052 ;; insert the table of contents
25053 (when thetoc
25054 (goto-char (point-min))
25055 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
25056 (progn
25057 (goto-char (match-beginning 0))
25058 (replace-match ""))
25059 (goto-char first-heading-pos))
25060 (mapc 'insert thetoc)
25061 (or (looking-at "[ \t]*\n[ \t]*\n")
25062 (insert "\n\n")))
25064 ;; Convert whitespace place holders
25065 (goto-char (point-min))
25066 (let (beg end)
25067 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25068 (setq end (next-single-property-change beg 'org-whitespace))
25069 (goto-char beg)
25070 (delete-region beg end)
25071 (insert (make-string (- end beg) ?\ ))))
25073 (save-buffer)
25074 ;; remove display and invisible chars
25075 (let (beg end)
25076 (goto-char (point-min))
25077 (while (setq beg (next-single-property-change (point) 'display))
25078 (setq end (next-single-property-change beg 'display))
25079 (delete-region beg end)
25080 (goto-char beg)
25081 (insert "=>"))
25082 (goto-char (point-min))
25083 (while (setq beg (next-single-property-change (point) 'org-cwidth))
25084 (setq end (next-single-property-change beg 'org-cwidth))
25085 (delete-region beg end)
25086 (goto-char beg)))
25087 (goto-char (point-min))))
25089 (defun org-export-ascii-clean-string ()
25090 "Do extra work for ASCII export"
25091 (goto-char (point-min))
25092 (while (re-search-forward org-verbatim-re nil t)
25093 (goto-char (match-end 2))
25094 (backward-delete-char 1) (insert "'")
25095 (goto-char (match-beginning 2))
25096 (delete-char 1) (insert "`")
25097 (goto-char (match-end 2))))
25099 (defun org-search-todo-below (line lines level)
25100 "Search the subtree below LINE for any TODO entries."
25101 (let ((rest (cdr (memq line lines)))
25102 (re org-todo-line-regexp)
25103 line lv todo)
25104 (catch 'exit
25105 (while (setq line (pop rest))
25106 (if (string-match re line)
25107 (progn
25108 (setq lv (- (match-end 1) (match-beginning 1))
25109 todo (and (match-beginning 2)
25110 (not (member (match-string 2 line)
25111 org-done-keywords))))
25112 ; TODO, not DONE
25113 (if (<= lv level) (throw 'exit nil))
25114 (if todo (throw 'exit t))))))))
25116 (defun org-html-expand-for-ascii (line)
25117 "Handle quoted HTML for ASCII export."
25118 (if org-export-html-expand
25119 (while (string-match "@<[^<>\n]*>" line)
25120 ;; We just remove the tags for now.
25121 (setq line (replace-match "" nil nil line))))
25122 line)
25124 (defun org-insert-centered (s &optional underline)
25125 "Insert the string S centered and underline it with character UNDERLINE."
25126 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
25127 (insert (make-string ind ?\ ) s "\n")
25128 (if underline
25129 (insert (make-string ind ?\ )
25130 (make-string (string-width s) underline)
25131 "\n"))))
25133 (defun org-ascii-level-start (level title umax &optional lines)
25134 "Insert a new level in ASCII export."
25135 (let (char (n (- level umax 1)) (ind 0))
25136 (if (> level umax)
25137 (progn
25138 (insert (make-string (* 2 n) ?\ )
25139 (char-to-string (nth (% n (length org-export-ascii-bullets))
25140 org-export-ascii-bullets))
25141 " " title "\n")
25142 ;; find the indentation of the next non-empty line
25143 (catch 'stop
25144 (while lines
25145 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
25146 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
25147 (throw 'stop (setq ind (org-get-indentation (car lines)))))
25148 (pop lines)))
25149 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
25150 (if (or (not (equal (char-before) ?\n))
25151 (not (equal (char-before (1- (point))) ?\n)))
25152 (insert "\n"))
25153 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
25154 (unless org-export-with-tags
25155 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25156 (setq title (replace-match "" t t title))))
25157 (if org-export-with-section-numbers
25158 (setq title (concat (org-section-number level) " " title)))
25159 (insert title "\n" (make-string (string-width title) char) "\n")
25160 (setq org-ascii-current-indentation '(0 . 0)))))
25162 (defun org-export-visible (type arg)
25163 "Create a copy of the visible part of the current buffer, and export it.
25164 The copy is created in a temporary buffer and removed after use.
25165 TYPE is the final key (as a string) that also select the export command in
25166 the `C-c C-e' export dispatcher.
25167 As a special case, if the you type SPC at the prompt, the temporary
25168 org-mode file will not be removed but presented to you so that you can
25169 continue to use it. The prefix arg ARG is passed through to the exporting
25170 command."
25171 (interactive
25172 (list (progn
25173 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
25174 (read-char-exclusive))
25175 current-prefix-arg))
25176 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
25177 (error "Invalid export key"))
25178 (let* ((binding (cdr (assoc type
25179 '((?a . org-export-as-ascii)
25180 (?\C-a . org-export-as-ascii)
25181 (?b . org-export-as-html-and-open)
25182 (?\C-b . org-export-as-html-and-open)
25183 (?h . org-export-as-html)
25184 (?H . org-export-as-html-to-buffer)
25185 (?R . org-export-region-as-html)
25186 (?x . org-export-as-xoxo)))))
25187 (keepp (equal type ?\ ))
25188 (file buffer-file-name)
25189 (buffer (get-buffer-create "*Org Export Visible*"))
25190 s e)
25191 ;; Need to hack the drawers here.
25192 (save-excursion
25193 (goto-char (point-min))
25194 (while (re-search-forward org-drawer-regexp nil t)
25195 (goto-char (match-beginning 1))
25196 (or (org-invisible-p) (org-flag-drawer nil))))
25197 (with-current-buffer buffer (erase-buffer))
25198 (save-excursion
25199 (setq s (goto-char (point-min)))
25200 (while (not (= (point) (point-max)))
25201 (goto-char (org-find-invisible))
25202 (append-to-buffer buffer s (point))
25203 (setq s (goto-char (org-find-visible))))
25204 (org-cycle-hide-drawers 'all)
25205 (goto-char (point-min))
25206 (unless keepp
25207 ;; Copy all comment lines to the end, to make sure #+ settings are
25208 ;; still available for the second export step. Kind of a hack, but
25209 ;; does do the trick.
25210 (if (looking-at "#[^\r\n]*")
25211 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
25212 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
25213 (append-to-buffer buffer (1+ (match-beginning 0))
25214 (min (point-max) (1+ (match-end 0))))))
25215 (set-buffer buffer)
25216 (let ((buffer-file-name file)
25217 (org-inhibit-startup t))
25218 (org-mode)
25219 (show-all)
25220 (unless keepp (funcall binding arg))))
25221 (if (not keepp)
25222 (kill-buffer buffer)
25223 (switch-to-buffer-other-window buffer)
25224 (goto-char (point-min)))))
25226 (defun org-find-visible ()
25227 (let ((s (point)))
25228 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25229 (get-char-property s 'invisible)))
25231 (defun org-find-invisible ()
25232 (let ((s (point)))
25233 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25234 (not (get-char-property s 'invisible))))
25237 ;;; HTML export
25239 (defun org-get-current-options ()
25240 "Return a string with current options as keyword options.
25241 Does include HTML export options as well as TODO and CATEGORY stuff."
25242 (format
25243 "#+TITLE: %s
25244 #+AUTHOR: %s
25245 #+EMAIL: %s
25246 #+LANGUAGE: %s
25247 #+TEXT: Some descriptive text to be emitted. Several lines OK.
25248 #+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
25249 #+CATEGORY: %s
25250 #+SEQ_TODO: %s
25251 #+TYP_TODO: %s
25252 #+PRIORITIES: %c %c %c
25253 #+DRAWERS: %s
25254 #+STARTUP: %s %s %s %s %s
25255 #+TAGS: %s
25256 #+ARCHIVE: %s
25257 #+LINK: %s
25259 (buffer-name) (user-full-name) user-mail-address org-export-default-language
25260 org-export-headline-levels
25261 org-export-with-section-numbers
25262 org-export-with-toc
25263 org-export-preserve-breaks
25264 org-export-html-expand
25265 org-export-with-fixed-width
25266 org-export-with-tables
25267 org-export-with-sub-superscripts
25268 org-export-with-special-strings
25269 org-export-with-footnotes
25270 org-export-with-emphasize
25271 org-export-with-TeX-macros
25272 org-export-with-LaTeX-fragments
25273 org-export-skip-text-before-1st-heading
25274 org-export-with-drawers
25275 org-export-with-tags
25276 (file-name-nondirectory buffer-file-name)
25277 "TODO FEEDBACK VERIFY DONE"
25278 "Me Jason Marie DONE"
25279 org-highest-priority org-lowest-priority org-default-priority
25280 (mapconcat 'identity org-drawers " ")
25281 (cdr (assoc org-startup-folded
25282 '((nil . "showall") (t . "overview") (content . "content"))))
25283 (if org-odd-levels-only "odd" "oddeven")
25284 (if org-hide-leading-stars "hidestars" "showstars")
25285 (if org-startup-align-all-tables "align" "noalign")
25286 (cond ((eq org-log-done t) "logdone")
25287 ((equal org-log-done 'note) "lognotedone")
25288 ((not org-log-done) "nologdone"))
25289 (or (mapconcat (lambda (x)
25290 (cond
25291 ((equal '(:startgroup) x) "{")
25292 ((equal '(:endgroup) x) "}")
25293 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
25294 (t (car x))))
25295 (or org-tag-alist (org-get-buffer-tags)) " ") "")
25296 org-archive-location
25297 "org file:~/org/%s.org"
25300 (defun org-insert-export-options-template ()
25301 "Insert into the buffer a template with information for exporting."
25302 (interactive)
25303 (if (not (bolp)) (newline))
25304 (let ((s (org-get-current-options)))
25305 (and (string-match "#\\+CATEGORY" s)
25306 (setq s (substring s 0 (match-beginning 0))))
25307 (insert s)))
25309 (defun org-toggle-fixed-width-section (arg)
25310 "Toggle the fixed-width export.
25311 If there is no active region, the QUOTE keyword at the current headline is
25312 inserted or removed. When present, it causes the text between this headline
25313 and the next to be exported as fixed-width text, and unmodified.
25314 If there is an active region, this command adds or removes a colon as the
25315 first character of this line. If the first character of a line is a colon,
25316 this line is also exported in fixed-width font."
25317 (interactive "P")
25318 (let* ((cc 0)
25319 (regionp (org-region-active-p))
25320 (beg (if regionp (region-beginning) (point)))
25321 (end (if regionp (region-end)))
25322 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
25323 (case-fold-search nil)
25324 (re "[ \t]*\\(:\\)")
25325 off)
25326 (if regionp
25327 (save-excursion
25328 (goto-char beg)
25329 (setq cc (current-column))
25330 (beginning-of-line 1)
25331 (setq off (looking-at re))
25332 (while (> nlines 0)
25333 (setq nlines (1- nlines))
25334 (beginning-of-line 1)
25335 (cond
25336 (arg
25337 (move-to-column cc t)
25338 (insert ":\n")
25339 (forward-line -1))
25340 ((and off (looking-at re))
25341 (replace-match "" t t nil 1))
25342 ((not off) (move-to-column cc t) (insert ":")))
25343 (forward-line 1)))
25344 (save-excursion
25345 (org-back-to-heading)
25346 (if (looking-at (concat outline-regexp
25347 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
25348 (replace-match "" t t nil 1)
25349 (if (looking-at outline-regexp)
25350 (progn
25351 (goto-char (match-end 0))
25352 (insert org-quote-string " "))))))))
25354 (defun org-export-as-html-and-open (arg)
25355 "Export the outline as HTML and immediately open it with a browser.
25356 If there is an active region, export only the region.
25357 The prefix ARG specifies how many levels of the outline should become
25358 headlines. The default is 3. Lower levels will become bulleted lists."
25359 (interactive "P")
25360 (org-export-as-html arg 'hidden)
25361 (org-open-file buffer-file-name))
25363 (defun org-export-as-html-batch ()
25364 "Call `org-export-as-html', may be used in batch processing as
25365 emacs --batch
25366 --load=$HOME/lib/emacs/org.el
25367 --eval \"(setq org-export-headline-levels 2)\"
25368 --visit=MyFile --funcall org-export-as-html-batch"
25369 (org-export-as-html org-export-headline-levels 'hidden))
25371 (defun org-export-as-html-to-buffer (arg)
25372 "Call `org-exort-as-html` with output to a temporary buffer.
25373 No file is created. The prefix ARG is passed through to `org-export-as-html'."
25374 (interactive "P")
25375 (org-export-as-html arg nil nil "*Org HTML Export*")
25376 (switch-to-buffer-other-window "*Org HTML Export*"))
25378 (defun org-replace-region-by-html (beg end)
25379 "Assume the current region has org-mode syntax, and convert it to HTML.
25380 This can be used in any buffer. For example, you could write an
25381 itemized list in org-mode syntax in an HTML buffer and then use this
25382 command to convert it."
25383 (interactive "r")
25384 (let (reg html buf pop-up-frames)
25385 (save-window-excursion
25386 (if (org-mode-p)
25387 (setq html (org-export-region-as-html
25388 beg end t 'string))
25389 (setq reg (buffer-substring beg end)
25390 buf (get-buffer-create "*Org tmp*"))
25391 (with-current-buffer buf
25392 (erase-buffer)
25393 (insert reg)
25394 (org-mode)
25395 (setq html (org-export-region-as-html
25396 (point-min) (point-max) t 'string)))
25397 (kill-buffer buf)))
25398 (delete-region beg end)
25399 (insert html)))
25401 (defun org-export-region-as-html (beg end &optional body-only buffer)
25402 "Convert region from BEG to END in org-mode buffer to HTML.
25403 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
25404 contents, and only produce the region of converted text, useful for
25405 cut-and-paste operations.
25406 If BUFFER is a buffer or a string, use/create that buffer as a target
25407 of the converted HTML. If BUFFER is the symbol `string', return the
25408 produced HTML as a string and leave not buffer behind. For example,
25409 a Lisp program could call this function in the following way:
25411 (setq html (org-export-region-as-html beg end t 'string))
25413 When called interactively, the output buffer is selected, and shown
25414 in a window. A non-interactive call will only retunr the buffer."
25415 (interactive "r\nP")
25416 (when (interactive-p)
25417 (setq buffer "*Org HTML Export*"))
25418 (let ((transient-mark-mode t) (zmacs-regions t)
25419 rtn)
25420 (goto-char end)
25421 (set-mark (point)) ;; to activate the region
25422 (goto-char beg)
25423 (setq rtn (org-export-as-html
25424 nil nil nil
25425 buffer body-only))
25426 (if (fboundp 'deactivate-mark) (deactivate-mark))
25427 (if (and (interactive-p) (bufferp rtn))
25428 (switch-to-buffer-other-window rtn)
25429 rtn)))
25431 (defvar html-table-tag nil) ; dynamically scoped into this.
25432 (defun org-export-as-html (arg &optional hidden ext-plist
25433 to-buffer body-only pub-dir)
25434 "Export the outline as a pretty HTML file.
25435 If there is an active region, export only the region. The prefix
25436 ARG specifies how many levels of the outline should become
25437 headlines. The default is 3. Lower levels will become bulleted
25438 lists. When HIDDEN is non-nil, don't display the HTML buffer.
25439 EXT-PLIST is a property list with external parameters overriding
25440 org-mode's default settings, but still inferior to file-local
25441 settings. When TO-BUFFER is non-nil, create a buffer with that
25442 name and export to that buffer. If TO-BUFFER is the symbol
25443 `string', don't leave any buffer behind but just return the
25444 resulting HTML as a string. When BODY-ONLY is set, don't produce
25445 the file header and footer, simply return the content of
25446 <body>...</body>, without even the body tags themselves. When
25447 PUB-DIR is set, use this as the publishing directory."
25448 (interactive "P")
25450 ;; Make sure we have a file name when we need it.
25451 (when (and (not (or to-buffer body-only))
25452 (not buffer-file-name))
25453 (if (buffer-base-buffer)
25454 (org-set-local 'buffer-file-name
25455 (with-current-buffer (buffer-base-buffer)
25456 buffer-file-name))
25457 (error "Need a file name to be able to export.")))
25459 (message "Exporting...")
25460 (setq-default org-todo-line-regexp org-todo-line-regexp)
25461 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25462 (setq-default org-done-keywords org-done-keywords)
25463 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25464 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25465 ext-plist
25466 (org-infile-export-plist)))
25468 (style (plist-get opt-plist :style))
25469 (html-extension (plist-get opt-plist :html-extension))
25470 (link-validate (plist-get opt-plist :link-validation-function))
25471 valid thetoc have-headings first-heading-pos
25472 (odd org-odd-levels-only)
25473 (region-p (org-region-active-p))
25474 (subtree-p
25475 (when region-p
25476 (save-excursion
25477 (goto-char (region-beginning))
25478 (and (org-at-heading-p)
25479 (>= (org-end-of-subtree t t) (region-end))))))
25480 ;; The following two are dynamically scoped into other
25481 ;; routines below.
25482 (org-current-export-dir
25483 (or pub-dir (org-export-directory :html opt-plist)))
25484 (org-current-export-file buffer-file-name)
25485 (level 0) (line "") (origline "") txt todo
25486 (umax nil)
25487 (umax-toc nil)
25488 (filename (if to-buffer nil
25489 (expand-file-name
25490 (concat
25491 (file-name-sans-extension
25492 (or (and subtree-p
25493 (org-entry-get (region-beginning)
25494 "EXPORT_FILE_NAME" t))
25495 (file-name-nondirectory buffer-file-name)))
25496 "." html-extension)
25497 (file-name-as-directory
25498 (or pub-dir (org-export-directory :html opt-plist))))))
25499 (current-dir (if buffer-file-name
25500 (file-name-directory buffer-file-name)
25501 default-directory))
25502 (buffer (if to-buffer
25503 (cond
25504 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25505 (t (get-buffer-create to-buffer)))
25506 (find-file-noselect filename)))
25507 (org-levels-open (make-vector org-level-max nil))
25508 (date (plist-get opt-plist :date))
25509 (author (plist-get opt-plist :author))
25510 (title (or (and subtree-p (org-export-get-title-from-subtree))
25511 (plist-get opt-plist :title)
25512 (and (not
25513 (plist-get opt-plist :skip-before-1st-heading))
25514 (org-export-grab-title-from-buffer))
25515 (and buffer-file-name
25516 (file-name-sans-extension
25517 (file-name-nondirectory buffer-file-name)))
25518 "UNTITLED"))
25519 (html-table-tag (plist-get opt-plist :html-table-tag))
25520 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25521 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25522 (inquote nil)
25523 (infixed nil)
25524 (in-local-list nil)
25525 (local-list-num nil)
25526 (local-list-indent nil)
25527 (llt org-plain-list-ordered-item-terminator)
25528 (email (plist-get opt-plist :email))
25529 (language (plist-get opt-plist :language))
25530 (lang-words nil)
25531 (target-alist nil) tg
25532 (head-count 0) cnt
25533 (start 0)
25534 (coding-system (and (boundp 'buffer-file-coding-system)
25535 buffer-file-coding-system))
25536 (coding-system-for-write (or org-export-html-coding-system
25537 coding-system))
25538 (save-buffer-coding-system (or org-export-html-coding-system
25539 coding-system))
25540 (charset (and coding-system-for-write
25541 (fboundp 'coding-system-get)
25542 (coding-system-get coding-system-for-write
25543 'mime-charset)))
25544 (region
25545 (buffer-substring
25546 (if region-p (region-beginning) (point-min))
25547 (if region-p (region-end) (point-max))))
25548 (lines
25549 (org-split-string
25550 (org-cleaned-string-for-export
25551 region
25552 :emph-multiline t
25553 :for-html t
25554 :skip-before-1st-heading
25555 (plist-get opt-plist :skip-before-1st-heading)
25556 :drawers (plist-get opt-plist :drawers)
25557 :archived-trees
25558 (plist-get opt-plist :archived-trees)
25559 :add-text
25560 (plist-get opt-plist :text)
25561 :LaTeX-fragments
25562 (plist-get opt-plist :LaTeX-fragments))
25563 "[\r\n]"))
25564 table-open type
25565 table-buffer table-orig-buffer
25566 ind start-is-num starter didclose
25567 rpl path desc descp desc1 desc2 link
25570 (let ((inhibit-read-only t))
25571 (org-unmodified
25572 (remove-text-properties (point-min) (point-max)
25573 '(:org-license-to-kill t))))
25575 (message "Exporting...")
25577 (setq org-min-level (org-get-min-level lines))
25578 (setq org-last-level org-min-level)
25579 (org-init-section-numbers)
25581 (cond
25582 ((and date (string-match "%" date))
25583 (setq date (format-time-string date (current-time))))
25584 (date)
25585 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25587 ;; Get the language-dependent settings
25588 (setq lang-words (or (assoc language org-export-language-setup)
25589 (assoc "en" org-export-language-setup)))
25591 ;; Switch to the output buffer
25592 (set-buffer buffer)
25593 (let ((inhibit-read-only t)) (erase-buffer))
25594 (fundamental-mode)
25596 (and (fboundp 'set-buffer-file-coding-system)
25597 (set-buffer-file-coding-system coding-system-for-write))
25599 (let ((case-fold-search nil)
25600 (org-odd-levels-only odd))
25601 ;; create local variables for all options, to make sure all called
25602 ;; functions get the correct information
25603 (mapc (lambda (x)
25604 (set (make-local-variable (cdr x))
25605 (plist-get opt-plist (car x))))
25606 org-export-plist-vars)
25607 (setq umax (if arg (prefix-numeric-value arg)
25608 org-export-headline-levels))
25609 (setq umax-toc (if (integerp org-export-with-toc)
25610 (min org-export-with-toc umax)
25611 umax))
25612 (unless body-only
25613 ;; File header
25614 (insert (format
25615 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25616 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25617 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25618 lang=\"%s\" xml:lang=\"%s\">
25619 <head>
25620 <title>%s</title>
25621 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25622 <meta name=\"generator\" content=\"Org-mode\"/>
25623 <meta name=\"generated\" content=\"%s\"/>
25624 <meta name=\"author\" content=\"%s\"/>
25626 </head><body>
25628 language language (org-html-expand title)
25629 (or charset "iso-8859-1") date author style))
25631 (insert (or (plist-get opt-plist :preamble) ""))
25633 (when (plist-get opt-plist :auto-preamble)
25634 (if title (insert (format org-export-html-title-format
25635 (org-html-expand title))))))
25637 (if (and org-export-with-toc (not body-only))
25638 (progn
25639 (push (format "<h%d>%s</h%d>\n"
25640 org-export-html-toplevel-hlevel
25641 (nth 3 lang-words)
25642 org-export-html-toplevel-hlevel)
25643 thetoc)
25644 (push "<ul>\n<li>" thetoc)
25645 (setq lines
25646 (mapcar '(lambda (line)
25647 (if (string-match org-todo-line-regexp line)
25648 ;; This is a headline
25649 (progn
25650 (setq have-headings t)
25651 (setq level (- (match-end 1) (match-beginning 1))
25652 level (org-tr-level level)
25653 txt (save-match-data
25654 (org-html-expand
25655 (org-export-cleanup-toc-line
25656 (match-string 3 line))))
25657 todo
25658 (or (and org-export-mark-todo-in-toc
25659 (match-beginning 2)
25660 (not (member (match-string 2 line)
25661 org-done-keywords)))
25662 ; TODO, not DONE
25663 (and org-export-mark-todo-in-toc
25664 (= level umax-toc)
25665 (org-search-todo-below
25666 line lines level))))
25667 (if (string-match
25668 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25669 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25670 (if (string-match quote-re0 txt)
25671 (setq txt (replace-match "" t t txt)))
25672 (if org-export-with-section-numbers
25673 (setq txt (concat (org-section-number level)
25674 " " txt)))
25675 (if (<= level (max umax umax-toc))
25676 (setq head-count (+ head-count 1)))
25677 (if (<= level umax-toc)
25678 (progn
25679 (if (> level org-last-level)
25680 (progn
25681 (setq cnt (- level org-last-level))
25682 (while (>= (setq cnt (1- cnt)) 0)
25683 (push "\n<ul>\n<li>" thetoc))
25684 (push "\n" thetoc)))
25685 (if (< level org-last-level)
25686 (progn
25687 (setq cnt (- org-last-level level))
25688 (while (>= (setq cnt (1- cnt)) 0)
25689 (push "</li>\n</ul>" thetoc))
25690 (push "\n" thetoc)))
25691 ;; Check for targets
25692 (while (string-match org-target-regexp line)
25693 (setq tg (match-string 1 line)
25694 line (replace-match
25695 (concat "@<span class=\"target\">" tg "@</span> ")
25696 t t line))
25697 (push (cons (org-solidify-link-text tg)
25698 (format "sec-%d" head-count))
25699 target-alist))
25700 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25701 (setq txt (replace-match "" t t txt)))
25702 (push
25703 (format
25704 (if todo
25705 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25706 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25707 head-count txt) thetoc)
25709 (setq org-last-level level))
25711 line)
25712 lines))
25713 (while (> org-last-level (1- org-min-level))
25714 (setq org-last-level (1- org-last-level))
25715 (push "</li>\n</ul>\n" thetoc))
25716 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25718 (setq head-count 0)
25719 (org-init-section-numbers)
25721 (while (setq line (pop lines) origline line)
25722 (catch 'nextline
25724 ;; end of quote section?
25725 (when (and inquote (string-match "^\\*+ " line))
25726 (insert "</pre>\n")
25727 (setq inquote nil))
25728 ;; inside a quote section?
25729 (when inquote
25730 (insert (org-html-protect line) "\n")
25731 (throw 'nextline nil))
25733 ;; verbatim lines
25734 (when (and org-export-with-fixed-width
25735 (string-match "^[ \t]*:\\(.*\\)" line))
25736 (when (not infixed)
25737 (setq infixed t)
25738 (insert "<pre>\n"))
25739 (insert (org-html-protect (match-string 1 line)) "\n")
25740 (when (and lines
25741 (not (string-match "^[ \t]*\\(:.*\\)"
25742 (car lines))))
25743 (setq infixed nil)
25744 (insert "</pre>\n"))
25745 (throw 'nextline nil))
25747 ;; Protected HTML
25748 (when (get-text-property 0 'org-protected line)
25749 (let (par)
25750 (when (re-search-backward
25751 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25752 (setq par (match-string 1))
25753 (replace-match "\\2\n"))
25754 (insert line "\n")
25755 (while (and lines
25756 (or (= (length (car lines)) 0)
25757 (get-text-property 0 'org-protected (car lines))))
25758 (insert (pop lines) "\n"))
25759 (and par (insert "<p>\n")))
25760 (throw 'nextline nil))
25762 ;; Horizontal line
25763 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25764 (insert "\n<hr/>\n")
25765 (throw 'nextline nil))
25767 ;; make targets to anchors
25768 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25769 (cond
25770 ((match-end 2)
25771 (setq line (replace-match
25772 (concat "@<a name=\""
25773 (org-solidify-link-text (match-string 1 line))
25774 "\">\\nbsp@</a>")
25775 t t line)))
25776 ((and org-export-with-toc (equal (string-to-char line) ?*))
25777 (setq line (replace-match
25778 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25779 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25780 t t line)))
25782 (setq line (replace-match
25783 (concat "@<a name=\""
25784 (org-solidify-link-text (match-string 1 line))
25785 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25786 t t line)))))
25788 (setq line (org-html-handle-time-stamps line))
25790 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25791 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25792 ;; Also handle sub_superscripts and checkboxes
25793 (or (string-match org-table-hline-regexp line)
25794 (setq line (org-html-expand line)))
25796 ;; Format the links
25797 (setq start 0)
25798 (while (string-match org-bracket-link-analytic-regexp line start)
25799 (setq start (match-beginning 0))
25800 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25801 (setq path (match-string 3 line))
25802 (setq desc1 (if (match-end 5) (match-string 5 line))
25803 desc2 (if (match-end 2) (concat type ":" path) path)
25804 descp (and desc1 (not (equal desc1 desc2)))
25805 desc (or desc1 desc2))
25806 ;; Make an image out of the description if that is so wanted
25807 (when (and descp (org-file-image-p desc))
25808 (save-match-data
25809 (if (string-match "^file:" desc)
25810 (setq desc (substring desc (match-end 0)))))
25811 (setq desc (concat "<img src=\"" desc "\"/>")))
25812 ;; FIXME: do we need to unescape here somewhere?
25813 (cond
25814 ((equal type "internal")
25815 (setq rpl
25816 (concat
25817 "<a href=\"#"
25818 (org-solidify-link-text
25819 (save-match-data (org-link-unescape path)) target-alist)
25820 "\">" desc "</a>")))
25821 ((member type '("http" "https"))
25822 ;; standard URL, just check if we need to inline an image
25823 (if (and (or (eq t org-export-html-inline-images)
25824 (and org-export-html-inline-images (not descp)))
25825 (org-file-image-p path))
25826 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25827 (setq link (concat type ":" path))
25828 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25829 ((member type '("ftp" "mailto" "news"))
25830 ;; standard URL
25831 (setq link (concat type ":" path))
25832 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25833 ((string= type "file")
25834 ;; FILE link
25835 (let* ((filename path)
25836 (abs-p (file-name-absolute-p filename))
25837 thefile file-is-image-p search)
25838 (save-match-data
25839 (if (string-match "::\\(.*\\)" filename)
25840 (setq search (match-string 1 filename)
25841 filename (replace-match "" t nil filename)))
25842 (setq valid
25843 (if (functionp link-validate)
25844 (funcall link-validate filename current-dir)
25846 (setq file-is-image-p (org-file-image-p filename))
25847 (setq thefile (if abs-p (expand-file-name filename) filename))
25848 (when (and org-export-html-link-org-files-as-html
25849 (string-match "\\.org$" thefile))
25850 (setq thefile (concat (substring thefile 0
25851 (match-beginning 0))
25852 "." html-extension))
25853 (if (and search
25854 ;; make sure this is can be used as target search
25855 (not (string-match "^[0-9]*$" search))
25856 (not (string-match "^\\*" search))
25857 (not (string-match "^/.*/$" search)))
25858 (setq thefile (concat thefile "#"
25859 (org-solidify-link-text
25860 (org-link-unescape search)))))
25861 (when (string-match "^file:" desc)
25862 (setq desc (replace-match "" t t desc))
25863 (if (string-match "\\.org$" desc)
25864 (setq desc (replace-match "" t t desc))))))
25865 (setq rpl (if (and file-is-image-p
25866 (or (eq t org-export-html-inline-images)
25867 (and org-export-html-inline-images
25868 (not descp))))
25869 (concat "<img src=\"" thefile "\"/>")
25870 (concat "<a href=\"" thefile "\">" desc "</a>")))
25871 (if (not valid) (setq rpl desc))))
25872 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25873 (setq rpl (concat "<i>&lt;" type ":"
25874 (save-match-data (org-link-unescape path))
25875 "&gt;</i>"))))
25876 (setq line (replace-match rpl t t line)
25877 start (+ start (length rpl))))
25879 ;; TODO items
25880 (if (and (string-match org-todo-line-regexp line)
25881 (match-beginning 2))
25883 (setq line
25884 (concat (substring line 0 (match-beginning 2))
25885 "<span class=\""
25886 (if (member (match-string 2 line)
25887 org-done-keywords)
25888 "done" "todo")
25889 "\">" (match-string 2 line)
25890 "</span>" (substring line (match-end 2)))))
25892 ;; Does this contain a reference to a footnote?
25893 (when org-export-with-footnotes
25894 (setq start 0)
25895 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25896 (if (get-text-property (match-beginning 2) 'org-protected line)
25897 (setq start (match-end 2))
25898 (let ((n (match-string 2 line)))
25899 (setq line
25900 (replace-match
25901 (format
25902 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25903 (match-string 1 line) n n n)
25904 t t line))))))
25906 (cond
25907 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25908 ;; This is a headline
25909 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25910 txt (match-string 2 line))
25911 (if (string-match quote-re0 txt)
25912 (setq txt (replace-match "" t t txt)))
25913 (if (<= level (max umax umax-toc))
25914 (setq head-count (+ head-count 1)))
25915 (when in-local-list
25916 ;; Close any local lists before inserting a new header line
25917 (while local-list-num
25918 (org-close-li)
25919 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25920 (pop local-list-num))
25921 (setq local-list-indent nil
25922 in-local-list nil))
25923 (setq first-heading-pos (or first-heading-pos (point)))
25924 (org-html-level-start level txt umax
25925 (and org-export-with-toc (<= level umax))
25926 head-count)
25927 ;; QUOTES
25928 (when (string-match quote-re line)
25929 (insert "<pre>")
25930 (setq inquote t)))
25932 ((and org-export-with-tables
25933 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25934 (if (not table-open)
25935 ;; New table starts
25936 (setq table-open t table-buffer nil table-orig-buffer nil))
25937 ;; Accumulate lines
25938 (setq table-buffer (cons line table-buffer)
25939 table-orig-buffer (cons origline table-orig-buffer))
25940 (when (or (not lines)
25941 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25942 (car lines))))
25943 (setq table-open nil
25944 table-buffer (nreverse table-buffer)
25945 table-orig-buffer (nreverse table-orig-buffer))
25946 (org-close-par-maybe)
25947 (insert (org-format-table-html table-buffer table-orig-buffer))))
25949 ;; Normal lines
25950 (when (string-match
25951 (cond
25952 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25953 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25954 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25955 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25956 line)
25957 (setq ind (org-get-string-indentation line)
25958 start-is-num (match-beginning 4)
25959 starter (if (match-beginning 2)
25960 (substring (match-string 2 line) 0 -1))
25961 line (substring line (match-beginning 5)))
25962 (unless (string-match "[^ \t]" line)
25963 ;; empty line. Pretend indentation is large.
25964 (setq ind (if org-empty-line-terminates-plain-lists
25966 (1+ (or (car local-list-indent) 1)))))
25967 (setq didclose nil)
25968 (while (and in-local-list
25969 (or (and (= ind (car local-list-indent))
25970 (not starter))
25971 (< ind (car local-list-indent))))
25972 (setq didclose t)
25973 (org-close-li)
25974 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25975 (pop local-list-num) (pop local-list-indent)
25976 (setq in-local-list local-list-indent))
25977 (cond
25978 ((and starter
25979 (or (not in-local-list)
25980 (> ind (car local-list-indent))))
25981 ;; Start new (level of) list
25982 (org-close-par-maybe)
25983 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25984 (push start-is-num local-list-num)
25985 (push ind local-list-indent)
25986 (setq in-local-list t))
25987 (starter
25988 ;; continue current list
25989 (org-close-li)
25990 (insert "<li>\n"))
25991 (didclose
25992 ;; we did close a list, normal text follows: need <p>
25993 (org-open-par)))
25994 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25995 (setq line
25996 (replace-match
25997 (if (equal (match-string 1 line) "X")
25998 "<b>[X]</b>"
25999 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
26000 t t line))))
26002 ;; Empty lines start a new paragraph. If hand-formatted lists
26003 ;; are not fully interpreted, lines starting with "-", "+", "*"
26004 ;; also start a new paragraph.
26005 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
26007 ;; Is this the start of a footnote?
26008 (when org-export-with-footnotes
26009 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
26010 (org-close-par-maybe)
26011 (let ((n (match-string 1 line)))
26012 (setq line (replace-match
26013 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
26015 ;; Check if the line break needs to be conserved
26016 (cond
26017 ((string-match "\\\\\\\\[ \t]*$" line)
26018 (setq line (replace-match "<br/>" t t line)))
26019 (org-export-preserve-breaks
26020 (setq line (concat line "<br/>"))))
26022 (insert line "\n")))))
26024 ;; Properly close all local lists and other lists
26025 (when inquote (insert "</pre>\n"))
26026 (when in-local-list
26027 ;; Close any local lists before inserting a new header line
26028 (while local-list-num
26029 (org-close-li)
26030 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
26031 (pop local-list-num))
26032 (setq local-list-indent nil
26033 in-local-list nil))
26034 (org-html-level-start 1 nil umax
26035 (and org-export-with-toc (<= level umax))
26036 head-count)
26038 (unless body-only
26039 (when (plist-get opt-plist :auto-postamble)
26040 (insert "<div id=\"postamble\">")
26041 (when (and org-export-author-info author)
26042 (insert "<p class=\"author\"> "
26043 (nth 1 lang-words) ": " author "\n")
26044 (when email
26045 (if (listp (split-string email ",+ *"))
26046 (mapc (lambda(e)
26047 (insert "<a href=\"mailto:" e "\">&lt;"
26048 e "&gt;</a>\n"))
26049 (split-string email ",+ *"))
26050 (insert "<a href=\"mailto:" email "\">&lt;"
26051 email "&gt;</a>\n")))
26052 (insert "</p>\n"))
26053 (when (and date org-export-time-stamp-file)
26054 (insert "<p class=\"date\"> "
26055 (nth 2 lang-words) ": "
26056 date "</p>\n"))
26057 (insert "</div>"))
26059 (if org-export-html-with-timestamp
26060 (insert org-export-html-html-helper-timestamp))
26061 (insert (or (plist-get opt-plist :postamble) ""))
26062 (insert "</body>\n</html>\n"))
26064 (normal-mode)
26065 (if (eq major-mode default-major-mode) (html-mode))
26067 ;; insert the table of contents
26068 (goto-char (point-min))
26069 (when thetoc
26070 (if (or (re-search-forward
26071 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
26072 (re-search-forward
26073 "\\[TABLE-OF-CONTENTS\\]" nil t))
26074 (progn
26075 (goto-char (match-beginning 0))
26076 (replace-match ""))
26077 (goto-char first-heading-pos)
26078 (when (looking-at "\\s-*</p>")
26079 (goto-char (match-end 0))
26080 (insert "\n")))
26081 (insert "<div id=\"table-of-contents\">\n")
26082 (mapc 'insert thetoc)
26083 (insert "</div>\n"))
26084 ;; remove empty paragraphs and lists
26085 (goto-char (point-min))
26086 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
26087 (replace-match ""))
26088 (goto-char (point-min))
26089 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
26090 (replace-match ""))
26091 (goto-char (point-min))
26092 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
26093 (replace-match ""))
26094 ;; Convert whitespace place holders
26095 (goto-char (point-min))
26096 (let (beg end n)
26097 (while (setq beg (next-single-property-change (point) 'org-whitespace))
26098 (setq n (get-text-property beg 'org-whitespace)
26099 end (next-single-property-change beg 'org-whitespace))
26100 (goto-char beg)
26101 (delete-region beg end)
26102 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
26103 (make-string n ?x)))))
26104 (or to-buffer (save-buffer))
26105 (goto-char (point-min))
26106 (message "Exporting... done")
26107 (if (eq to-buffer 'string)
26108 (prog1 (buffer-substring (point-min) (point-max))
26109 (kill-buffer (current-buffer)))
26110 (current-buffer)))))
26112 (defvar org-table-colgroup-info nil)
26113 (defun org-format-table-ascii (lines)
26114 "Format a table for ascii export."
26115 (if (stringp lines)
26116 (setq lines (org-split-string lines "\n")))
26117 (if (not (string-match "^[ \t]*|" (car lines)))
26118 ;; Table made by table.el - test for spanning
26119 lines
26121 ;; A normal org table
26122 ;; Get rid of hlines at beginning and end
26123 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26124 (setq lines (nreverse lines))
26125 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26126 (setq lines (nreverse lines))
26127 (when org-export-table-remove-special-lines
26128 ;; Check if the table has a marking column. If yes remove the
26129 ;; column and the special lines
26130 (setq lines (org-table-clean-before-export lines)))
26131 ;; Get rid of the vertical lines except for grouping
26132 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
26133 rtn line vl1 start)
26134 (while (setq line (pop lines))
26135 (if (string-match org-table-hline-regexp line)
26136 (and (string-match "|\\(.*\\)|" line)
26137 (setq line (replace-match " \\1" t nil line)))
26138 (setq start 0 vl1 vl)
26139 (while (string-match "|" line start)
26140 (setq start (match-end 0))
26141 (or (pop vl1) (setq line (replace-match " " t t line)))))
26142 (push line rtn))
26143 (nreverse rtn))))
26145 (defun org-colgroup-info-to-vline-list (info)
26146 (let (vl new last)
26147 (while info
26148 (setq last new new (pop info))
26149 (if (or (memq last '(:end :startend))
26150 (memq new '(:start :startend)))
26151 (push t vl)
26152 (push nil vl)))
26153 (setq vl (nreverse vl))
26154 (and vl (setcar vl nil))
26155 vl))
26157 (defun org-format-table-html (lines olines)
26158 "Find out which HTML converter to use and return the HTML code."
26159 (if (stringp lines)
26160 (setq lines (org-split-string lines "\n")))
26161 (if (string-match "^[ \t]*|" (car lines))
26162 ;; A normal org table
26163 (org-format-org-table-html lines)
26164 ;; Table made by table.el - test for spanning
26165 (let* ((hlines (delq nil (mapcar
26166 (lambda (x)
26167 (if (string-match "^[ \t]*\\+-" x) x
26168 nil))
26169 lines)))
26170 (first (car hlines))
26171 (ll (and (string-match "\\S-+" first)
26172 (match-string 0 first)))
26173 (re (concat "^[ \t]*" (regexp-quote ll)))
26174 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
26175 hlines))))
26176 (if (and (not spanning)
26177 (not org-export-prefer-native-exporter-for-tables))
26178 ;; We can use my own converter with HTML conversions
26179 (org-format-table-table-html lines)
26180 ;; Need to use the code generator in table.el, with the original text.
26181 (org-format-table-table-html-using-table-generate-source olines)))))
26183 (defun org-format-org-table-html (lines &optional splice)
26184 "Format a table into HTML."
26185 ;; Get rid of hlines at beginning and end
26186 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26187 (setq lines (nreverse lines))
26188 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26189 (setq lines (nreverse lines))
26190 (when org-export-table-remove-special-lines
26191 ;; Check if the table has a marking column. If yes remove the
26192 ;; column and the special lines
26193 (setq lines (org-table-clean-before-export lines)))
26195 (let ((head (and org-export-highlight-first-table-line
26196 (delq nil (mapcar
26197 (lambda (x) (string-match "^[ \t]*|-" x))
26198 (cdr lines)))))
26199 (nlines 0) fnum i
26200 tbopen line fields html gr colgropen)
26201 (if splice (setq head nil))
26202 (unless splice (push (if head "<thead>" "<tbody>") html))
26203 (setq tbopen t)
26204 (while (setq line (pop lines))
26205 (catch 'next-line
26206 (if (string-match "^[ \t]*|-" line)
26207 (progn
26208 (unless splice
26209 (push (if head "</thead>" "</tbody>") html)
26210 (if lines (push "<tbody>" html) (setq tbopen nil)))
26211 (setq head nil) ;; head ends here, first time around
26212 ;; ignore this line
26213 (throw 'next-line t)))
26214 ;; Break the line into fields
26215 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26216 (unless fnum (setq fnum (make-vector (length fields) 0)))
26217 (setq nlines (1+ nlines) i -1)
26218 (push (concat "<tr>"
26219 (mapconcat
26220 (lambda (x)
26221 (setq i (1+ i))
26222 (if (and (< i nlines)
26223 (string-match org-table-number-regexp x))
26224 (incf (aref fnum i)))
26225 (if head
26226 (concat (car org-export-table-header-tags) x
26227 (cdr org-export-table-header-tags))
26228 (concat (car org-export-table-data-tags) x
26229 (cdr org-export-table-data-tags))))
26230 fields "")
26231 "</tr>")
26232 html)))
26233 (unless splice (if tbopen (push "</tbody>" html)))
26234 (unless splice (push "</table>\n" html))
26235 (setq html (nreverse html))
26236 (unless splice
26237 ;; Put in col tags with the alignment (unfortuntely often ignored...)
26238 (push (mapconcat
26239 (lambda (x)
26240 (setq gr (pop org-table-colgroup-info))
26241 (format "%s<col align=\"%s\"></col>%s"
26242 (if (memq gr '(:start :startend))
26243 (prog1
26244 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
26245 (setq colgropen t))
26247 (if (> (/ (float x) nlines) org-table-number-fraction)
26248 "right" "left")
26249 (if (memq gr '(:end :startend))
26250 (progn (setq colgropen nil) "</colgroup>")
26251 "")))
26252 fnum "")
26253 html)
26254 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
26255 (push html-table-tag html))
26256 (concat (mapconcat 'identity html "\n") "\n")))
26258 (defun org-table-clean-before-export (lines)
26259 "Check if the table has a marking column.
26260 If yes remove the column and the special lines."
26261 (setq org-table-colgroup-info nil)
26262 (if (memq nil
26263 (mapcar
26264 (lambda (x) (or (string-match "^[ \t]*|-" x)
26265 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
26266 lines))
26267 (progn
26268 (setq org-table-clean-did-remove-column nil)
26269 (delq nil
26270 (mapcar
26271 (lambda (x)
26272 (cond
26273 ((string-match "^[ \t]*| */ *|" x)
26274 (setq org-table-colgroup-info
26275 (mapcar (lambda (x)
26276 (cond ((member x '("<" "&lt;")) :start)
26277 ((member x '(">" "&gt;")) :end)
26278 ((member x '("<>" "&lt;&gt;")) :startend)
26279 (t nil)))
26280 (org-split-string x "[ \t]*|[ \t]*")))
26281 nil)
26282 (t x)))
26283 lines)))
26284 (setq org-table-clean-did-remove-column t)
26285 (delq nil
26286 (mapcar
26287 (lambda (x)
26288 (cond
26289 ((string-match "^[ \t]*| */ *|" x)
26290 (setq org-table-colgroup-info
26291 (mapcar (lambda (x)
26292 (cond ((member x '("<" "&lt;")) :start)
26293 ((member x '(">" "&gt;")) :end)
26294 ((member x '("<>" "&lt;&gt;")) :startend)
26295 (t nil)))
26296 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
26297 nil)
26298 ((string-match "^[ \t]*| *[!_^/] *|" x)
26299 nil) ; ignore this line
26300 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
26301 (string-match "^\\([ \t]*\\)|[^|]*|" x))
26302 ;; remove the first column
26303 (replace-match "\\1|" t nil x))))
26304 lines))))
26306 (defun org-format-table-table-html (lines)
26307 "Format a table generated by table.el into HTML.
26308 This conversion does *not* use `table-generate-source' from table.el.
26309 This has the advantage that Org-mode's HTML conversions can be used.
26310 But it has the disadvantage, that no cell- or row-spanning is allowed."
26311 (let (line field-buffer
26312 (head org-export-highlight-first-table-line)
26313 fields html empty)
26314 (setq html (concat html-table-tag "\n"))
26315 (while (setq line (pop lines))
26316 (setq empty "&nbsp;")
26317 (catch 'next-line
26318 (if (string-match "^[ \t]*\\+-" line)
26319 (progn
26320 (if field-buffer
26321 (progn
26322 (setq
26323 html
26324 (concat
26325 html
26326 "<tr>"
26327 (mapconcat
26328 (lambda (x)
26329 (if (equal x "") (setq x empty))
26330 (if head
26331 (concat (car org-export-table-header-tags) x
26332 (cdr org-export-table-header-tags))
26333 (concat (car org-export-table-data-tags) x
26334 (cdr org-export-table-data-tags))))
26335 field-buffer "\n")
26336 "</tr>\n"))
26337 (setq head nil)
26338 (setq field-buffer nil)))
26339 ;; Ignore this line
26340 (throw 'next-line t)))
26341 ;; Break the line into fields and store the fields
26342 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26343 (if field-buffer
26344 (setq field-buffer (mapcar
26345 (lambda (x)
26346 (concat x "<br/>" (pop fields)))
26347 field-buffer))
26348 (setq field-buffer fields))))
26349 (setq html (concat html "</table>\n"))
26350 html))
26352 (defun org-format-table-table-html-using-table-generate-source (lines)
26353 "Format a table into html, using `table-generate-source' from table.el.
26354 This has the advantage that cell- or row-spanning is allowed.
26355 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
26356 (require 'table)
26357 (with-current-buffer (get-buffer-create " org-tmp1 ")
26358 (erase-buffer)
26359 (insert (mapconcat 'identity lines "\n"))
26360 (goto-char (point-min))
26361 (if (not (re-search-forward "|[^+]" nil t))
26362 (error "Error processing table"))
26363 (table-recognize-table)
26364 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
26365 (table-generate-source 'html " org-tmp2 ")
26366 (set-buffer " org-tmp2 ")
26367 (buffer-substring (point-min) (point-max))))
26369 (defun org-html-handle-time-stamps (s)
26370 "Format time stamps in string S, or remove them."
26371 (catch 'exit
26372 (let (r b)
26373 (while (string-match org-maybe-keyword-time-regexp s)
26374 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
26375 ;; never export CLOCK
26376 (throw 'exit ""))
26377 (or b (setq b (substring s 0 (match-beginning 0))))
26378 (if (not org-export-with-timestamps)
26379 (setq r (concat r (substring s 0 (match-beginning 0)))
26380 s (substring s (match-end 0)))
26381 (setq r (concat
26382 r (substring s 0 (match-beginning 0))
26383 (if (match-end 1)
26384 (format "@<span class=\"timestamp-kwd\">%s @</span>"
26385 (match-string 1 s)))
26386 (format " @<span class=\"timestamp\">%s@</span>"
26387 (substring
26388 (org-translate-time (match-string 3 s)) 1 -1)))
26389 s (substring s (match-end 0)))))
26390 ;; Line break if line started and ended with time stamp stuff
26391 (if (not r)
26393 (setq r (concat r s))
26394 (unless (string-match "\\S-" (concat b s))
26395 (setq r (concat r "@<br/>")))
26396 r))))
26398 (defun org-html-protect (s)
26399 ;; convert & to &amp;, < to &lt; and > to &gt;
26400 (let ((start 0))
26401 (while (string-match "&" s start)
26402 (setq s (replace-match "&amp;" t t s)
26403 start (1+ (match-beginning 0))))
26404 (while (string-match "<" s)
26405 (setq s (replace-match "&lt;" t t s)))
26406 (while (string-match ">" s)
26407 (setq s (replace-match "&gt;" t t s))))
26410 (defun org-export-cleanup-toc-line (s)
26411 "Remove tags and time staps from lines going into the toc."
26412 (when (memq org-export-with-tags '(not-in-toc nil))
26413 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
26414 (setq s (replace-match "" t t s))))
26415 (when org-export-remove-timestamps-from-toc
26416 (while (string-match org-maybe-keyword-time-regexp s)
26417 (setq s (replace-match "" t t s))))
26418 (while (string-match org-bracket-link-regexp s)
26419 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
26420 t t s)))
26423 (defun org-html-expand (string)
26424 "Prepare STRING for HTML export. Applies all active conversions.
26425 If there are links in the string, don't modify these."
26426 (let* ((re (concat org-bracket-link-regexp "\\|"
26427 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
26428 m s l res)
26429 (while (setq m (string-match re string))
26430 (setq s (substring string 0 m)
26431 l (match-string 0 string)
26432 string (substring string (match-end 0)))
26433 (push (org-html-do-expand s) res)
26434 (push l res))
26435 (push (org-html-do-expand string) res)
26436 (apply 'concat (nreverse res))))
26438 (defun org-html-do-expand (s)
26439 "Apply all active conversions to translate special ASCII to HTML."
26440 (setq s (org-html-protect s))
26441 (if org-export-html-expand
26442 (let ((start 0))
26443 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
26444 (setq s (replace-match "<\\1>" t nil s)))))
26445 (if org-export-with-emphasize
26446 (setq s (org-export-html-convert-emphasize s)))
26447 (if org-export-with-special-strings
26448 (setq s (org-export-html-convert-special-strings s)))
26449 (if org-export-with-sub-superscripts
26450 (setq s (org-export-html-convert-sub-super s)))
26451 (if org-export-with-TeX-macros
26452 (let ((start 0) wd ass)
26453 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26454 (if (get-text-property (match-beginning 0) 'org-protected s)
26455 (setq start (match-end 0))
26456 (setq wd (match-string 1 s))
26457 (if (setq ass (assoc wd org-html-entities))
26458 (setq s (replace-match (or (cdr ass)
26459 (concat "&" (car ass) ";"))
26460 t t s))
26461 (setq start (+ start (length wd))))))))
26464 (defun org-create-multibrace-regexp (left right n)
26465 "Create a regular expression which will match a balanced sexp.
26466 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26467 as single character strings.
26468 The regexp returned will match the entire expression including the
26469 delimiters. It will also define a single group which contains the
26470 match except for the outermost delimiters. The maximum depth of
26471 stacked delimiters is N. Escaping delimiters is not possible."
26472 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26473 (or "\\|")
26474 (re nothing)
26475 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26476 (while (> n 1)
26477 (setq n (1- n)
26478 re (concat re or next)
26479 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26480 (concat left "\\(" re "\\)" right)))
26482 (defvar org-match-substring-regexp
26483 (concat
26484 "\\([^\\]\\)\\([_^]\\)\\("
26485 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26486 "\\|"
26487 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26488 "\\|"
26489 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26490 "The regular expression matching a sub- or superscript.")
26492 (defvar org-match-substring-with-braces-regexp
26493 (concat
26494 "\\([^\\]\\)\\([_^]\\)\\("
26495 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26496 "\\)")
26497 "The regular expression matching a sub- or superscript, forcing braces.")
26499 (defconst org-export-html-special-string-regexps
26500 '(("\\\\-" . "&shy;")
26501 ("---\\([^-]\\)" . "&mdash;\\1")
26502 ("--\\([^-]\\)" . "&ndash;\\1")
26503 ("\\.\\.\\." . "&hellip;"))
26504 "Regular expressions for special string conversion.")
26506 (defun org-export-html-convert-special-strings (string)
26507 "Convert special characters in STRING to HTML."
26508 (let ((all org-export-html-special-string-regexps)
26509 e a re rpl start)
26510 (while (setq a (pop all))
26511 (setq re (car a) rpl (cdr a) start 0)
26512 (while (string-match re string start)
26513 (if (get-text-property (match-beginning 0) 'org-protected string)
26514 (setq start (match-end 0))
26515 (setq string (replace-match rpl t nil string)))))
26516 string))
26518 (defun org-export-html-convert-sub-super (string)
26519 "Convert sub- and superscripts in STRING to HTML."
26520 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26521 (while (string-match org-match-substring-regexp string s)
26522 (cond
26523 ((and requireb (match-end 8)) (setq s (match-end 2)))
26524 ((get-text-property (match-beginning 2) 'org-protected string)
26525 (setq s (match-end 2)))
26527 (setq s (match-end 1)
26528 key (if (string= (match-string 2 string) "_") "sub" "sup")
26529 c (or (match-string 8 string)
26530 (match-string 6 string)
26531 (match-string 5 string))
26532 string (replace-match
26533 (concat (match-string 1 string)
26534 "<" key ">" c "</" key ">")
26535 t t string)))))
26536 (while (string-match "\\\\\\([_^]\\)" string)
26537 (setq string (replace-match (match-string 1 string) t t string)))
26538 string))
26540 (defun org-export-html-convert-emphasize (string)
26541 "Apply emphasis."
26542 (let ((s 0) rpl)
26543 (while (string-match org-emph-re string s)
26544 (if (not (equal
26545 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26546 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26547 (setq s (match-beginning 0)
26549 (concat
26550 (match-string 1 string)
26551 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26552 (match-string 4 string)
26553 (nth 3 (assoc (match-string 3 string)
26554 org-emphasis-alist))
26555 (match-string 5 string))
26556 string (replace-match rpl t t string)
26557 s (+ s (- (length rpl) 2)))
26558 (setq s (1+ s))))
26559 string))
26561 (defvar org-par-open nil)
26562 (defun org-open-par ()
26563 "Insert <p>, but first close previous paragraph if any."
26564 (org-close-par-maybe)
26565 (insert "\n<p>")
26566 (setq org-par-open t))
26567 (defun org-close-par-maybe ()
26568 "Close paragraph if there is one open."
26569 (when org-par-open
26570 (insert "</p>")
26571 (setq org-par-open nil)))
26572 (defun org-close-li ()
26573 "Close <li> if necessary."
26574 (org-close-par-maybe)
26575 (insert "</li>\n"))
26577 (defvar body-only) ; dynamically scoped into this.
26578 (defun org-html-level-start (level title umax with-toc head-count)
26579 "Insert a new level in HTML export.
26580 When TITLE is nil, just close all open levels."
26581 (org-close-par-maybe)
26582 (let ((l org-level-max))
26583 (while (>= l level)
26584 (if (aref org-levels-open (1- l))
26585 (progn
26586 (org-html-level-close l umax)
26587 (aset org-levels-open (1- l) nil)))
26588 (setq l (1- l)))
26589 (when title
26590 ;; If title is nil, this means this function is called to close
26591 ;; all levels, so the rest is done only if title is given
26592 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26593 (setq title (replace-match
26594 (if org-export-with-tags
26595 (save-match-data
26596 (concat
26597 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26598 (mapconcat 'identity (org-split-string
26599 (match-string 1 title) ":")
26600 "&nbsp;")
26601 "</span>"))
26603 t t title)))
26604 (if (> level umax)
26605 (progn
26606 (if (aref org-levels-open (1- level))
26607 (progn
26608 (org-close-li)
26609 (insert "<li>" title "<br/>\n"))
26610 (aset org-levels-open (1- level) t)
26611 (org-close-par-maybe)
26612 (insert "<ul>\n<li>" title "<br/>\n")))
26613 (aset org-levels-open (1- level) t)
26614 (if (and org-export-with-section-numbers (not body-only))
26615 (setq title (concat (org-section-number level) " " title)))
26616 (setq level (+ level org-export-html-toplevel-hlevel -1))
26617 (if with-toc
26618 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26619 level level head-count title level))
26620 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26621 (org-open-par)))))
26623 (defun org-html-level-close (level max-outline-level)
26624 "Terminate one level in HTML export."
26625 (if (<= level max-outline-level)
26626 (insert "</div>\n")
26627 (org-close-li)
26628 (insert "</ul>\n")))
26630 ;;; iCalendar export
26632 ;;;###autoload
26633 (defun org-export-icalendar-this-file ()
26634 "Export current file as an iCalendar file.
26635 The iCalendar file will be located in the same directory as the Org-mode
26636 file, but with extension `.ics'."
26637 (interactive)
26638 (org-export-icalendar nil buffer-file-name))
26640 ;;;###autoload
26641 (defun org-export-icalendar-all-agenda-files ()
26642 "Export all files in `org-agenda-files' to iCalendar .ics files.
26643 Each iCalendar file will be located in the same directory as the Org-mode
26644 file, but with extension `.ics'."
26645 (interactive)
26646 (apply 'org-export-icalendar nil (org-agenda-files t)))
26648 ;;;###autoload
26649 (defun org-export-icalendar-combine-agenda-files ()
26650 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26651 The file is stored under the name `org-combined-agenda-icalendar-file'."
26652 (interactive)
26653 (apply 'org-export-icalendar t (org-agenda-files t)))
26655 (defun org-export-icalendar (combine &rest files)
26656 "Create iCalendar files for all elements of FILES.
26657 If COMBINE is non-nil, combine all calendar entries into a single large
26658 file and store it under the name `org-combined-agenda-icalendar-file'."
26659 (save-excursion
26660 (org-prepare-agenda-buffers files)
26661 (let* ((dir (org-export-directory
26662 :ical (list :publishing-directory
26663 org-export-publishing-directory)))
26664 file ical-file ical-buffer category started org-agenda-new-buffers)
26666 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26667 (when combine
26668 (setq ical-file
26669 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26670 org-combined-agenda-icalendar-file
26671 (expand-file-name org-combined-agenda-icalendar-file dir))
26672 ical-buffer (org-get-agenda-file-buffer ical-file))
26673 (set-buffer ical-buffer) (erase-buffer))
26674 (while (setq file (pop files))
26675 (catch 'nextfile
26676 (org-check-agenda-file file)
26677 (set-buffer (org-get-agenda-file-buffer file))
26678 (unless combine
26679 (setq ical-file (concat (file-name-as-directory dir)
26680 (file-name-sans-extension
26681 (file-name-nondirectory buffer-file-name))
26682 ".ics"))
26683 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26684 (with-current-buffer ical-buffer (erase-buffer)))
26685 (setq category (or org-category
26686 (file-name-sans-extension
26687 (file-name-nondirectory buffer-file-name))))
26688 (if (symbolp category) (setq category (symbol-name category)))
26689 (let ((standard-output ical-buffer))
26690 (if combine
26691 (and (not started) (setq started t)
26692 (org-start-icalendar-file org-icalendar-combined-name))
26693 (org-start-icalendar-file category))
26694 (org-print-icalendar-entries combine)
26695 (when (or (and combine (not files)) (not combine))
26696 (org-finish-icalendar-file)
26697 (set-buffer ical-buffer)
26698 (save-buffer)
26699 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26700 (org-release-buffers org-agenda-new-buffers))))
26702 (defvar org-after-save-iCalendar-file-hook nil
26703 "Hook run after an iCalendar file has been saved.
26704 The iCalendar buffer is still current when this hook is run.
26705 A good way to use this is to tell a desktop calenndar application to re-read
26706 the iCalendar file.")
26708 (defun org-print-icalendar-entries (&optional combine)
26709 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26710 When COMBINE is non nil, add the category to each line."
26711 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26712 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26713 (dts (org-ical-ts-to-string
26714 (format-time-string (cdr org-time-stamp-formats) (current-time))
26715 "DTSTART"))
26716 hd ts ts2 state status (inc t) pos b sexp rrule
26717 scheduledp deadlinep tmp pri category entry location summary desc
26718 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26719 (org-refresh-category-properties)
26720 (save-excursion
26721 (goto-char (point-min))
26722 (while (re-search-forward re1 nil t)
26723 (catch :skip
26724 (org-agenda-skip)
26725 (setq pos (match-beginning 0)
26726 ts (match-string 0)
26727 inc t
26728 hd (org-get-heading)
26729 summary (org-icalendar-cleanup-string
26730 (org-entry-get nil "SUMMARY"))
26731 desc (org-icalendar-cleanup-string
26732 (or (org-entry-get nil "DESCRIPTION")
26733 (and org-icalendar-include-body (org-get-entry)))
26734 t org-icalendar-include-body)
26735 location (org-icalendar-cleanup-string
26736 (org-entry-get nil "LOCATION"))
26737 category (org-get-category))
26738 (if (looking-at re2)
26739 (progn
26740 (goto-char (match-end 0))
26741 (setq ts2 (match-string 1) inc nil))
26742 (setq tmp (buffer-substring (max (point-min)
26743 (- pos org-ds-keyword-length))
26744 pos)
26745 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26746 (progn
26747 (setq inc nil)
26748 (replace-match "\\1" t nil ts))
26750 deadlinep (string-match org-deadline-regexp tmp)
26751 scheduledp (string-match org-scheduled-regexp tmp)
26752 ;; donep (org-entry-is-done-p)
26754 (if (or (string-match org-tr-regexp hd)
26755 (string-match org-ts-regexp hd))
26756 (setq hd (replace-match "" t t hd)))
26757 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26758 (setq rrule
26759 (concat "\nRRULE:FREQ="
26760 (cdr (assoc
26761 (match-string 2 ts)
26762 '(("d" . "DAILY")("w" . "WEEKLY")
26763 ("m" . "MONTHLY")("y" . "YEARLY"))))
26764 ";INTERVAL=" (match-string 1 ts)))
26765 (setq rrule ""))
26766 (setq summary (or summary hd))
26767 (if (string-match org-bracket-link-regexp summary)
26768 (setq summary
26769 (replace-match (if (match-end 3)
26770 (match-string 3 summary)
26771 (match-string 1 summary))
26772 t t summary)))
26773 (if deadlinep (setq summary (concat "DL: " summary)))
26774 (if scheduledp (setq summary (concat "S: " summary)))
26775 (if (string-match "\\`<%%" ts)
26776 (with-current-buffer sexp-buffer
26777 (insert (substring ts 1 -1) " " summary "\n"))
26778 (princ (format "BEGIN:VEVENT
26780 %s%s
26781 SUMMARY:%s%s%s
26782 CATEGORIES:%s
26783 END:VEVENT\n"
26784 (org-ical-ts-to-string ts "DTSTART")
26785 (org-ical-ts-to-string ts2 "DTEND" inc)
26786 rrule summary
26787 (if (and desc (string-match "\\S-" desc))
26788 (concat "\nDESCRIPTION: " desc) "")
26789 (if (and location (string-match "\\S-" location))
26790 (concat "\nLOCATION: " location) "")
26791 category)))))
26793 (when (and org-icalendar-include-sexps
26794 (condition-case nil (require 'icalendar) (error nil))
26795 (fboundp 'icalendar-export-region))
26796 ;; Get all the literal sexps
26797 (goto-char (point-min))
26798 (while (re-search-forward "^&?%%(" nil t)
26799 (catch :skip
26800 (org-agenda-skip)
26801 (setq b (match-beginning 0))
26802 (goto-char (1- (match-end 0)))
26803 (forward-sexp 1)
26804 (end-of-line 1)
26805 (setq sexp (buffer-substring b (point)))
26806 (with-current-buffer sexp-buffer
26807 (insert sexp "\n"))
26808 (princ (org-diary-to-ical-string sexp-buffer)))))
26810 (when org-icalendar-include-todo
26811 (goto-char (point-min))
26812 (while (re-search-forward org-todo-line-regexp nil t)
26813 (catch :skip
26814 (org-agenda-skip)
26815 (setq state (match-string 2))
26816 (setq status (if (member state org-done-keywords)
26817 "COMPLETED" "NEEDS-ACTION"))
26818 (when (and state
26819 (or (not (member state org-done-keywords))
26820 (eq org-icalendar-include-todo 'all))
26821 (not (member org-archive-tag (org-get-tags-at)))
26823 (setq hd (match-string 3)
26824 summary (org-icalendar-cleanup-string
26825 (org-entry-get nil "SUMMARY"))
26826 desc (org-icalendar-cleanup-string
26827 (or (org-entry-get nil "DESCRIPTION")
26828 (and org-icalendar-include-body (org-get-entry)))
26829 t org-icalendar-include-body)
26830 location (org-icalendar-cleanup-string
26831 (org-entry-get nil "LOCATION")))
26832 (if (string-match org-bracket-link-regexp hd)
26833 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26834 (match-string 1 hd))
26835 t t hd)))
26836 (if (string-match org-priority-regexp hd)
26837 (setq pri (string-to-char (match-string 2 hd))
26838 hd (concat (substring hd 0 (match-beginning 1))
26839 (substring hd (match-end 1))))
26840 (setq pri org-default-priority))
26841 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26842 (- org-lowest-priority org-highest-priority))))))
26844 (princ (format "BEGIN:VTODO
26846 SUMMARY:%s%s%s
26847 CATEGORIES:%s
26848 SEQUENCE:1
26849 PRIORITY:%d
26850 STATUS:%s
26851 END:VTODO\n"
26853 (or summary hd)
26854 (if (and location (string-match "\\S-" location))
26855 (concat "\nLOCATION: " location) "")
26856 (if (and desc (string-match "\\S-" desc))
26857 (concat "\nDESCRIPTION: " desc) "")
26858 category pri status)))))))))
26860 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26861 "Take out stuff and quote what needs to be quoted.
26862 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26863 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26864 characters."
26865 (if (not s)
26867 (when is-body
26868 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26869 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26870 (while (string-match re s) (setq s (replace-match "" t t s)))
26871 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26872 (let ((start 0))
26873 (while (string-match "\\([,;\\]\\)" s start)
26874 (setq start (+ (match-beginning 0) 2)
26875 s (replace-match "\\\\\\1" nil nil s))))
26876 (when is-body
26877 (while (string-match "[ \t]*\n[ \t]*" s)
26878 (setq s (replace-match "\\n" t t s))))
26879 (setq s (org-trim s))
26880 (if is-body
26881 (if maxlength
26882 (if (and (numberp maxlength)
26883 (> (length s) maxlength))
26884 (setq s (substring s 0 maxlength)))))
26887 (defun org-get-entry ()
26888 "Clean-up description string."
26889 (save-excursion
26890 (org-back-to-heading t)
26891 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26893 (defun org-start-icalendar-file (name)
26894 "Start an iCalendar file by inserting the header."
26895 (let ((user user-full-name)
26896 (name (or name "unknown"))
26897 (timezone (cadr (current-time-zone))))
26898 (princ
26899 (format "BEGIN:VCALENDAR
26900 VERSION:2.0
26901 X-WR-CALNAME:%s
26902 PRODID:-//%s//Emacs with Org-mode//EN
26903 X-WR-TIMEZONE:%s
26904 CALSCALE:GREGORIAN\n" name user timezone))))
26906 (defun org-finish-icalendar-file ()
26907 "Finish an iCalendar file by inserting the END statement."
26908 (princ "END:VCALENDAR\n"))
26910 (defun org-ical-ts-to-string (s keyword &optional inc)
26911 "Take a time string S and convert it to iCalendar format.
26912 KEYWORD is added in front, to make a complete line like DTSTART....
26913 When INC is non-nil, increase the hour by two (if time string contains
26914 a time), or the day by one (if it does not contain a time)."
26915 (let ((t1 (org-parse-time-string s 'nodefault))
26916 t2 fmt have-time time)
26917 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26918 (setq t2 t1 have-time t)
26919 (setq t2 (org-parse-time-string s)))
26920 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26921 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26922 (when inc
26923 (if have-time
26924 (if org-agenda-default-appointment-duration
26925 (setq mi (+ org-agenda-default-appointment-duration mi))
26926 (setq h (+ 2 h)))
26927 (setq d (1+ d))))
26928 (setq time (encode-time s mi h d m y)))
26929 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26930 (concat keyword (format-time-string fmt time))))
26932 ;;; XOXO export
26934 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26935 (with-current-buffer buffer
26936 (apply 'insert output)))
26937 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26939 (defun org-export-as-xoxo (&optional buffer)
26940 "Export the org buffer as XOXO.
26941 The XOXO buffer is named *xoxo-<source buffer name>*"
26942 (interactive (list (current-buffer)))
26943 ;; A quickie abstraction
26945 ;; Output everything as XOXO
26946 (with-current-buffer (get-buffer buffer)
26947 (let* ((pos (point))
26948 (opt-plist (org-combine-plists (org-default-export-plist)
26949 (org-infile-export-plist)))
26950 (filename (concat (file-name-as-directory
26951 (org-export-directory :xoxo opt-plist))
26952 (file-name-sans-extension
26953 (file-name-nondirectory buffer-file-name))
26954 ".html"))
26955 (out (find-file-noselect filename))
26956 (last-level 1)
26957 (hanging-li nil))
26958 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26959 ;; Check the output buffer is empty.
26960 (with-current-buffer out (erase-buffer))
26961 ;; Kick off the output
26962 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26963 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26964 (let* ((hd (match-string-no-properties 1))
26965 (level (length hd))
26966 (text (concat
26967 (match-string-no-properties 2)
26968 (save-excursion
26969 (goto-char (match-end 0))
26970 (let ((str ""))
26971 (catch 'loop
26972 (while 't
26973 (forward-line)
26974 (if (looking-at "^[ \t]\\(.*\\)")
26975 (setq str (concat str (match-string-no-properties 1)))
26976 (throw 'loop str)))))))))
26978 ;; Handle level rendering
26979 (cond
26980 ((> level last-level)
26981 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26983 ((< level last-level)
26984 (dotimes (- (- last-level level) 1)
26985 (if hanging-li
26986 (org-export-as-xoxo-insert-into out "</li>\n"))
26987 (org-export-as-xoxo-insert-into out "</ol>\n"))
26988 (when hanging-li
26989 (org-export-as-xoxo-insert-into out "</li>\n")
26990 (setq hanging-li nil)))
26992 ((equal level last-level)
26993 (if hanging-li
26994 (org-export-as-xoxo-insert-into out "</li>\n")))
26997 (setq last-level level)
26999 ;; And output the new li
27000 (setq hanging-li 't)
27001 (if (equal ?+ (elt text 0))
27002 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
27003 (org-export-as-xoxo-insert-into out "<li>" text))))
27005 ;; Finally finish off the ol
27006 (dotimes (- last-level 1)
27007 (if hanging-li
27008 (org-export-as-xoxo-insert-into out "</li>\n"))
27009 (org-export-as-xoxo-insert-into out "</ol>\n"))
27011 (goto-char pos)
27012 ;; Finish the buffer off and clean it up.
27013 (switch-to-buffer-other-window out)
27014 (indent-region (point-min) (point-max) nil)
27015 (save-buffer)
27016 (goto-char (point-min))
27020 ;;;; Key bindings
27022 ;; Make `C-c C-x' a prefix key
27023 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
27025 ;; TAB key with modifiers
27026 (org-defkey org-mode-map "\C-i" 'org-cycle)
27027 (org-defkey org-mode-map [(tab)] 'org-cycle)
27028 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
27029 (org-defkey org-mode-map [(meta tab)] 'org-complete)
27030 (org-defkey org-mode-map "\M-\t" 'org-complete)
27031 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
27032 ;; The following line is necessary under Suse GNU/Linux
27033 (unless (featurep 'xemacs)
27034 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
27035 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
27036 (define-key org-mode-map [backtab] 'org-shifttab)
27038 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
27039 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
27040 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
27042 ;; Cursor keys with modifiers
27043 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
27044 (org-defkey org-mode-map [(meta right)] 'org-metaright)
27045 (org-defkey org-mode-map [(meta up)] 'org-metaup)
27046 (org-defkey org-mode-map [(meta down)] 'org-metadown)
27048 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
27049 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
27050 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
27051 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
27053 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
27054 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
27055 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
27056 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
27058 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
27059 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
27061 ;;; Extra keys for tty access.
27062 ;; We only set them when really needed because otherwise the
27063 ;; menus don't show the simple keys
27065 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
27066 (not window-system))
27067 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
27068 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
27069 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
27070 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
27071 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
27072 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
27073 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
27074 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
27075 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
27076 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
27077 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
27078 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
27079 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
27080 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
27081 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
27082 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
27083 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
27084 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
27085 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
27086 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
27087 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
27088 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
27090 ;; All the other keys
27092 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
27093 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
27094 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
27095 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
27096 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
27097 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
27098 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
27099 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
27100 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
27101 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
27102 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
27103 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
27104 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
27105 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
27106 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
27107 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
27108 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
27109 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
27110 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
27111 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
27112 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
27113 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
27114 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
27115 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
27116 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
27117 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
27118 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
27119 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
27120 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
27121 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
27122 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
27123 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
27124 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
27125 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
27126 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
27127 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
27128 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
27129 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
27130 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
27131 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
27132 (org-defkey org-mode-map "\C-c^" 'org-sort)
27133 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
27134 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
27135 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
27136 (org-defkey org-mode-map "\C-m" 'org-return)
27137 (org-defkey org-mode-map "\C-j" 'org-return-indent)
27138 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
27139 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
27140 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
27141 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
27142 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
27143 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
27144 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
27145 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
27146 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
27147 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
27148 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
27149 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
27150 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
27151 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
27152 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
27154 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
27155 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
27156 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
27157 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
27159 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
27160 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
27161 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
27162 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
27163 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
27164 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
27165 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
27166 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
27167 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
27168 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
27169 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
27170 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
27172 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
27174 (when (featurep 'xemacs)
27175 (org-defkey org-mode-map 'button3 'popup-mode-menu))
27177 (defsubst org-table-p () (org-at-table-p))
27179 (defun org-self-insert-command (N)
27180 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
27181 If the cursor is in a table looking at whitespace, the whitespace is
27182 overwritten, and the table is not marked as requiring realignment."
27183 (interactive "p")
27184 (if (and (org-table-p)
27185 (progn
27186 ;; check if we blank the field, and if that triggers align
27187 (and org-table-auto-blank-field
27188 (member last-command
27189 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
27190 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
27191 ;; got extra space, this field does not determine column width
27192 (let (org-table-may-need-update) (org-table-blank-field))
27193 ;; no extra space, this field may determine column width
27194 (org-table-blank-field)))
27196 (eq N 1)
27197 (looking-at "[^|\n]* |"))
27198 (let (org-table-may-need-update)
27199 (goto-char (1- (match-end 0)))
27200 (delete-backward-char 1)
27201 (goto-char (match-beginning 0))
27202 (self-insert-command N))
27203 (setq org-table-may-need-update t)
27204 (self-insert-command N)
27205 (org-fix-tags-on-the-fly)))
27207 (defun org-fix-tags-on-the-fly ()
27208 (when (and (equal (char-after (point-at-bol)) ?*)
27209 (org-on-heading-p))
27210 (org-align-tags-here org-tags-column)))
27212 (defun org-delete-backward-char (N)
27213 "Like `delete-backward-char', insert whitespace at field end in tables.
27214 When deleting backwards, in tables this function will insert whitespace in
27215 front of the next \"|\" separator, to keep the table aligned. The table will
27216 still be marked for re-alignment if the field did fill the entire column,
27217 because, in this case the deletion might narrow the column."
27218 (interactive "p")
27219 (if (and (org-table-p)
27220 (eq N 1)
27221 (string-match "|" (buffer-substring (point-at-bol) (point)))
27222 (looking-at ".*?|"))
27223 (let ((pos (point))
27224 (noalign (looking-at "[^|\n\r]* |"))
27225 (c org-table-may-need-update))
27226 (backward-delete-char N)
27227 (skip-chars-forward "^|")
27228 (insert " ")
27229 (goto-char (1- pos))
27230 ;; noalign: if there were two spaces at the end, this field
27231 ;; does not determine the width of the column.
27232 (if noalign (setq org-table-may-need-update c)))
27233 (backward-delete-char N)
27234 (org-fix-tags-on-the-fly)))
27236 (defun org-delete-char (N)
27237 "Like `delete-char', but insert whitespace at field end in tables.
27238 When deleting characters, in tables this function will insert whitespace in
27239 front of the next \"|\" separator, to keep the table aligned. The table will
27240 still be marked for re-alignment if the field did fill the entire column,
27241 because, in this case the deletion might narrow the column."
27242 (interactive "p")
27243 (if (and (org-table-p)
27244 (not (bolp))
27245 (not (= (char-after) ?|))
27246 (eq N 1))
27247 (if (looking-at ".*?|")
27248 (let ((pos (point))
27249 (noalign (looking-at "[^|\n\r]* |"))
27250 (c org-table-may-need-update))
27251 (replace-match (concat
27252 (substring (match-string 0) 1 -1)
27253 " |"))
27254 (goto-char pos)
27255 ;; noalign: if there were two spaces at the end, this field
27256 ;; does not determine the width of the column.
27257 (if noalign (setq org-table-may-need-update c)))
27258 (delete-char N))
27259 (delete-char N)
27260 (org-fix-tags-on-the-fly)))
27262 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
27263 (put 'org-self-insert-command 'delete-selection t)
27264 (put 'orgtbl-self-insert-command 'delete-selection t)
27265 (put 'org-delete-char 'delete-selection 'supersede)
27266 (put 'org-delete-backward-char 'delete-selection 'supersede)
27268 ;; Make `flyspell-mode' delay after some commands
27269 (put 'org-self-insert-command 'flyspell-delayed t)
27270 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
27271 (put 'org-delete-char 'flyspell-delayed t)
27272 (put 'org-delete-backward-char 'flyspell-delayed t)
27274 ;; Make pabbrev-mode expand after org-mode commands
27275 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
27276 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
27278 ;; How to do this: Measure non-white length of current string
27279 ;; If equal to column width, we should realign.
27281 (defun org-remap (map &rest commands)
27282 "In MAP, remap the functions given in COMMANDS.
27283 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
27284 (let (new old)
27285 (while commands
27286 (setq old (pop commands) new (pop commands))
27287 (if (fboundp 'command-remapping)
27288 (org-defkey map (vector 'remap old) new)
27289 (substitute-key-definition old new map global-map)))))
27291 (when (eq org-enable-table-editor 'optimized)
27292 ;; If the user wants maximum table support, we need to hijack
27293 ;; some standard editing functions
27294 (org-remap org-mode-map
27295 'self-insert-command 'org-self-insert-command
27296 'delete-char 'org-delete-char
27297 'delete-backward-char 'org-delete-backward-char)
27298 (org-defkey org-mode-map "|" 'org-force-self-insert))
27300 (defun org-shiftcursor-error ()
27301 "Throw an error because Shift-Cursor command was applied in wrong context."
27302 (error "This command is active in special context like tables, headlines or timestamps"))
27304 (defun org-shifttab (&optional arg)
27305 "Global visibility cycling or move to previous table field.
27306 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
27307 on context.
27308 See the individual commands for more information."
27309 (interactive "P")
27310 (cond
27311 ((org-at-table-p) (call-interactively 'org-table-previous-field))
27312 (arg (message "Content view to level: ")
27313 (org-content (prefix-numeric-value arg))
27314 (setq org-cycle-global-status 'overview))
27315 (t (call-interactively 'org-global-cycle))))
27317 (defun org-shiftmetaleft ()
27318 "Promote subtree or delete table column.
27319 Calls `org-promote-subtree', `org-outdent-item',
27320 or `org-table-delete-column', depending on context.
27321 See the individual commands for more information."
27322 (interactive)
27323 (cond
27324 ((org-at-table-p) (call-interactively 'org-table-delete-column))
27325 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
27326 ((org-at-item-p) (call-interactively 'org-outdent-item))
27327 (t (org-shiftcursor-error))))
27329 (defun org-shiftmetaright ()
27330 "Demote subtree or insert table column.
27331 Calls `org-demote-subtree', `org-indent-item',
27332 or `org-table-insert-column', depending on context.
27333 See the individual commands for more information."
27334 (interactive)
27335 (cond
27336 ((org-at-table-p) (call-interactively 'org-table-insert-column))
27337 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
27338 ((org-at-item-p) (call-interactively 'org-indent-item))
27339 (t (org-shiftcursor-error))))
27341 (defun org-shiftmetaup (&optional arg)
27342 "Move subtree up or kill table row.
27343 Calls `org-move-subtree-up' or `org-table-kill-row' or
27344 `org-move-item-up' depending on context. See the individual commands
27345 for more information."
27346 (interactive "P")
27347 (cond
27348 ((org-at-table-p) (call-interactively 'org-table-kill-row))
27349 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27350 ((org-at-item-p) (call-interactively 'org-move-item-up))
27351 (t (org-shiftcursor-error))))
27352 (defun org-shiftmetadown (&optional arg)
27353 "Move subtree down or insert table row.
27354 Calls `org-move-subtree-down' or `org-table-insert-row' or
27355 `org-move-item-down', depending on context. See the individual
27356 commands for more information."
27357 (interactive "P")
27358 (cond
27359 ((org-at-table-p) (call-interactively 'org-table-insert-row))
27360 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27361 ((org-at-item-p) (call-interactively 'org-move-item-down))
27362 (t (org-shiftcursor-error))))
27364 (defun org-metaleft (&optional arg)
27365 "Promote heading or move table column to left.
27366 Calls `org-do-promote' or `org-table-move-column', depending on context.
27367 With no specific context, calls the Emacs default `backward-word'.
27368 See the individual commands for more information."
27369 (interactive "P")
27370 (cond
27371 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
27372 ((or (org-on-heading-p) (org-region-active-p))
27373 (call-interactively 'org-do-promote))
27374 ((org-at-item-p) (call-interactively 'org-outdent-item))
27375 (t (call-interactively 'backward-word))))
27377 (defun org-metaright (&optional arg)
27378 "Demote subtree or move table column to right.
27379 Calls `org-do-demote' or `org-table-move-column', depending on context.
27380 With no specific context, calls the Emacs default `forward-word'.
27381 See the individual commands for more information."
27382 (interactive "P")
27383 (cond
27384 ((org-at-table-p) (call-interactively 'org-table-move-column))
27385 ((or (org-on-heading-p) (org-region-active-p))
27386 (call-interactively 'org-do-demote))
27387 ((org-at-item-p) (call-interactively 'org-indent-item))
27388 (t (call-interactively 'forward-word))))
27390 (defun org-metaup (&optional arg)
27391 "Move subtree up or move table row up.
27392 Calls `org-move-subtree-up' or `org-table-move-row' or
27393 `org-move-item-up', depending on context. See the individual commands
27394 for more information."
27395 (interactive "P")
27396 (cond
27397 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
27398 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27399 ((org-at-item-p) (call-interactively 'org-move-item-up))
27400 (t (transpose-lines 1) (beginning-of-line -1))))
27402 (defun org-metadown (&optional arg)
27403 "Move subtree down or move table row down.
27404 Calls `org-move-subtree-down' or `org-table-move-row' or
27405 `org-move-item-down', depending on context. See the individual
27406 commands for more information."
27407 (interactive "P")
27408 (cond
27409 ((org-at-table-p) (call-interactively 'org-table-move-row))
27410 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27411 ((org-at-item-p) (call-interactively 'org-move-item-down))
27412 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
27414 (defun org-shiftup (&optional arg)
27415 "Increase item in timestamp or increase priority of current headline.
27416 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
27417 depending on context. See the individual commands for more information."
27418 (interactive "P")
27419 (cond
27420 ((org-at-timestamp-p t)
27421 (call-interactively (if org-edit-timestamp-down-means-later
27422 'org-timestamp-down 'org-timestamp-up)))
27423 ((org-on-heading-p) (call-interactively 'org-priority-up))
27424 ((org-at-item-p) (call-interactively 'org-previous-item))
27425 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
27427 (defun org-shiftdown (&optional arg)
27428 "Decrease item in timestamp or decrease priority of current headline.
27429 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
27430 depending on context. See the individual commands for more information."
27431 (interactive "P")
27432 (cond
27433 ((org-at-timestamp-p t)
27434 (call-interactively (if org-edit-timestamp-down-means-later
27435 'org-timestamp-up 'org-timestamp-down)))
27436 ((org-on-heading-p) (call-interactively 'org-priority-down))
27437 (t (call-interactively 'org-next-item))))
27439 (defun org-shiftright ()
27440 "Next TODO keyword or timestamp one day later, depending on context."
27441 (interactive)
27442 (cond
27443 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
27444 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
27445 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
27446 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
27447 (t (org-shiftcursor-error))))
27449 (defun org-shiftleft ()
27450 "Previous TODO keyword or timestamp one day earlier, depending on context."
27451 (interactive)
27452 (cond
27453 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27454 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27455 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27456 ((org-at-property-p)
27457 (call-interactively 'org-property-previous-allowed-value))
27458 (t (org-shiftcursor-error))))
27460 (defun org-shiftcontrolright ()
27461 "Switch to next TODO set."
27462 (interactive)
27463 (cond
27464 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27465 (t (org-shiftcursor-error))))
27467 (defun org-shiftcontrolleft ()
27468 "Switch to previous TODO set."
27469 (interactive)
27470 (cond
27471 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27472 (t (org-shiftcursor-error))))
27474 (defun org-ctrl-c-ret ()
27475 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27476 (interactive)
27477 (cond
27478 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27479 (t (call-interactively 'org-insert-heading))))
27481 (defun org-copy-special ()
27482 "Copy region in table or copy current subtree.
27483 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27484 See the individual commands for more information."
27485 (interactive)
27486 (call-interactively
27487 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27489 (defun org-cut-special ()
27490 "Cut region in table or cut current subtree.
27491 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27492 See the individual commands for more information."
27493 (interactive)
27494 (call-interactively
27495 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27497 (defun org-paste-special (arg)
27498 "Paste rectangular region into table, or past subtree relative to level.
27499 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27500 See the individual commands for more information."
27501 (interactive "P")
27502 (if (org-at-table-p)
27503 (org-table-paste-rectangle)
27504 (org-paste-subtree arg)))
27506 (defun org-ctrl-c-ctrl-c (&optional arg)
27507 "Set tags in headline, or update according to changed information at point.
27509 This command does many different things, depending on context:
27511 - If the cursor is in a headline, prompt for tags and insert them
27512 into the current line, aligned to `org-tags-column'. When called
27513 with prefix arg, realign all tags in the current buffer.
27515 - If the cursor is in one of the special #+KEYWORD lines, this
27516 triggers scanning the buffer for these lines and updating the
27517 information.
27519 - If the cursor is inside a table, realign the table. This command
27520 works even if the automatic table editor has been turned off.
27522 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27523 the entire table.
27525 - If the cursor is a the beginning of a dynamic block, update it.
27527 - If the cursor is inside a table created by the table.el package,
27528 activate that table.
27530 - If the current buffer is a remember buffer, close note and file it.
27531 with a prefix argument, file it without further interaction to the default
27532 location.
27534 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27535 links in this buffer.
27537 - If the cursor is on a numbered item in a plain list, renumber the
27538 ordered list.
27540 - If the cursor is on a checkbox, toggle it."
27541 (interactive "P")
27542 (let ((org-enable-table-editor t))
27543 (cond
27544 ((or org-clock-overlays
27545 org-occur-highlights
27546 org-latex-fragment-image-overlays)
27547 (org-remove-clock-overlays)
27548 (org-remove-occur-highlights)
27549 (org-remove-latex-fragment-image-overlays)
27550 (message "Temporary highlights/overlays removed from current buffer"))
27551 ((and (local-variable-p 'org-finish-function (current-buffer))
27552 (fboundp org-finish-function))
27553 (funcall org-finish-function))
27554 ((org-at-property-p)
27555 (call-interactively 'org-property-action))
27556 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27557 ((org-on-heading-p) (call-interactively 'org-set-tags))
27558 ((org-at-table.el-p)
27559 (require 'table)
27560 (beginning-of-line 1)
27561 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27562 (call-interactively 'table-recognize-table))
27563 ((org-at-table-p)
27564 (org-table-maybe-eval-formula)
27565 (if arg
27566 (call-interactively 'org-table-recalculate)
27567 (org-table-maybe-recalculate-line))
27568 (call-interactively 'org-table-align))
27569 ((org-at-item-checkbox-p)
27570 (call-interactively 'org-toggle-checkbox))
27571 ((org-at-item-p)
27572 (call-interactively 'org-maybe-renumber-ordered-list))
27573 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27574 ;; Dynamic block
27575 (beginning-of-line 1)
27576 (org-update-dblock))
27577 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27578 (cond
27579 ((equal (match-string 1) "TBLFM")
27580 ;; Recalculate the table before this line
27581 (save-excursion
27582 (beginning-of-line 1)
27583 (skip-chars-backward " \r\n\t")
27584 (if (org-at-table-p)
27585 (org-call-with-arg 'org-table-recalculate t))))
27587 (call-interactively 'org-mode-restart))))
27588 (t (error "C-c C-c can do nothing useful at this location.")))))
27590 (defun org-mode-restart ()
27591 "Restart Org-mode, to scan again for special lines.
27592 Also updates the keyword regular expressions."
27593 (interactive)
27594 (let ((org-inhibit-startup t)) (org-mode))
27595 (message "Org-mode restarted to refresh keyword and special line setup"))
27597 (defun org-kill-note-or-show-branches ()
27598 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27599 (interactive)
27600 (if (not org-finish-function)
27601 (call-interactively 'show-branches)
27602 (let ((org-note-abort t))
27603 (funcall org-finish-function))))
27605 (defun org-return (&optional indent)
27606 "Goto next table row or insert a newline.
27607 Calls `org-table-next-row' or `newline', depending on context.
27608 See the individual commands for more information."
27609 (interactive)
27610 (cond
27611 ((bobp) (if indent (newline-and-indent) (newline)))
27612 ((and (org-at-heading-p)
27613 (looking-at
27614 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27615 (org-show-entry)
27616 (end-of-line 1)
27617 (newline))
27618 ((org-at-table-p)
27619 (org-table-justify-field-maybe)
27620 (call-interactively 'org-table-next-row))
27621 (t (if indent (newline-and-indent) (newline)))))
27623 (defun org-return-indent ()
27624 "Goto next table row or insert a newline and indent.
27625 Calls `org-table-next-row' or `newline-and-indent', depending on
27626 context. See the individual commands for more information."
27627 (interactive)
27628 (org-return t))
27630 (defun org-ctrl-c-star ()
27631 "Compute table, or change heading status of lines.
27632 Calls `org-table-recalculate' or `org-toggle-region-headlines',
27633 depending on context. This will also turn a plain list item or a normal
27634 line into a subheading."
27635 (interactive)
27636 (cond
27637 ((org-at-table-p)
27638 (call-interactively 'org-table-recalculate))
27639 ((org-region-active-p)
27640 ;; Convert all lines in region to list items
27641 (call-interactively 'org-toggle-region-headings))
27642 ((org-on-heading-p)
27643 (org-toggle-region-headings (point-at-bol)
27644 (min (1+ (point-at-eol)) (point-max))))
27645 ((org-at-item-p)
27646 ;; Convert to heading
27647 ;; FIXME: not yet implemented
27649 (t (org-toggle-region-headings (point-at-bol)
27650 (min (1+ (point-at-eol)) (point-max))))))
27652 (defun org-ctrl-c-minus ()
27653 "Insert separator line in table or modify bullet status of line.
27654 Also turns a plain line or a region of lines into list items.
27655 Calls `org-table-insert-hline', `org-toggle-region-items', or
27656 `org-cycle-list-bullet', depending on context."
27657 (interactive)
27658 (cond
27659 ((org-at-table-p)
27660 (call-interactively 'org-table-insert-hline))
27661 ((org-on-heading-p)
27662 ;; Convert to item
27663 (save-excursion
27664 (beginning-of-line 1)
27665 (if (looking-at "\\*+ ")
27666 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
27667 ((org-region-active-p)
27668 ;; Convert all lines in region to list items
27669 (call-interactively 'org-toggle-region-items))
27670 ((org-in-item-p)
27671 (call-interactively 'org-cycle-list-bullet))
27672 (t (org-toggle-region-items (point-at-bol)
27673 (min (1+ (point-at-eol)) (point-max))))))
27675 (defun org-toggle-region-items (beg end)
27676 "Convert all lines in region to list items.
27677 If the first line is already an item, convert all list items in the region
27678 to normal lines."
27679 (interactive "r")
27680 (let (l2 l)
27681 (save-excursion
27682 (goto-char end)
27683 (setq l2 (org-current-line))
27684 (goto-char beg)
27685 (beginning-of-line 1)
27686 (setq l (1- (org-current-line)))
27687 (if (org-at-item-p)
27688 ;; We already have items, de-itemize
27689 (while (< (setq l (1+ l)) l2)
27690 (when (org-at-item-p)
27691 (goto-char (match-beginning 2))
27692 (delete-region (match-beginning 2) (match-end 2))
27693 (and (looking-at "[ \t]+") (replace-match "")))
27694 (beginning-of-line 2))
27695 (while (< (setq l (1+ l)) l2)
27696 (unless (org-at-item-p)
27697 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27698 (replace-match "\\1- \\2")))
27699 (beginning-of-line 2))))))
27701 (defun org-toggle-region-headings (beg end)
27702 "Convert all lines in region to list items.
27703 If the first line is already an item, convert all list items in the region
27704 to normal lines."
27705 (interactive "r")
27706 (let (l2 l)
27707 (save-excursion
27708 (goto-char end)
27709 (setq l2 (org-current-line))
27710 (goto-char beg)
27711 (beginning-of-line 1)
27712 (setq l (1- (org-current-line)))
27713 (if (org-on-heading-p)
27714 ;; We already have headlines, de-star them
27715 (while (< (setq l (1+ l)) l2)
27716 (when (org-on-heading-p t)
27717 (and (looking-at outline-regexp) (replace-match "")))
27718 (beginning-of-line 2))
27719 (let* ((stars (save-excursion
27720 (re-search-backward org-complex-heading-regexp nil t)
27721 (or (match-string 1) "*")))
27722 (add-stars (if org-odd-levels-only "**" "*"))
27723 (rpl (concat stars add-stars " \\2")))
27724 (while (< (setq l (1+ l)) l2)
27725 (unless (org-on-heading-p)
27726 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27727 (replace-match rpl)))
27728 (beginning-of-line 2)))))))
27730 (defun org-meta-return (&optional arg)
27731 "Insert a new heading or wrap a region in a table.
27732 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27733 See the individual commands for more information."
27734 (interactive "P")
27735 (cond
27736 ((org-at-table-p)
27737 (call-interactively 'org-table-wrap-region))
27738 (t (call-interactively 'org-insert-heading))))
27740 ;;; Menu entries
27742 ;; Define the Org-mode menus
27743 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27744 '("Tbl"
27745 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27746 ["Next Field" org-cycle (org-at-table-p)]
27747 ["Previous Field" org-shifttab (org-at-table-p)]
27748 ["Next Row" org-return (org-at-table-p)]
27749 "--"
27750 ["Blank Field" org-table-blank-field (org-at-table-p)]
27751 ["Edit Field" org-table-edit-field (org-at-table-p)]
27752 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27753 "--"
27754 ("Column"
27755 ["Move Column Left" org-metaleft (org-at-table-p)]
27756 ["Move Column Right" org-metaright (org-at-table-p)]
27757 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27758 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27759 ("Row"
27760 ["Move Row Up" org-metaup (org-at-table-p)]
27761 ["Move Row Down" org-metadown (org-at-table-p)]
27762 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27763 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27764 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27765 "--"
27766 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27767 ("Rectangle"
27768 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27769 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27770 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27771 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27772 "--"
27773 ("Calculate"
27774 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27775 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27776 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27777 "--"
27778 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27779 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27780 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27781 "--"
27782 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27783 "--"
27784 ["Sum Column/Rectangle" org-table-sum
27785 (or (org-at-table-p) (org-region-active-p))]
27786 ["Which Column?" org-table-current-column (org-at-table-p)])
27787 ["Debug Formulas"
27788 org-table-toggle-formula-debugger
27789 :style toggle :selected org-table-formula-debug]
27790 ["Show Col/Row Numbers"
27791 org-table-toggle-coordinate-overlays
27792 :style toggle :selected org-table-overlay-coordinates]
27793 "--"
27794 ["Create" org-table-create (and (not (org-at-table-p))
27795 org-enable-table-editor)]
27796 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27797 ["Import from File" org-table-import (not (org-at-table-p))]
27798 ["Export to File" org-table-export (org-at-table-p)]
27799 "--"
27800 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27802 (easy-menu-define org-org-menu org-mode-map "Org menu"
27803 '("Org"
27804 ("Show/Hide"
27805 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27806 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27807 ["Sparse Tree" org-occur t]
27808 ["Reveal Context" org-reveal t]
27809 ["Show All" show-all t]
27810 "--"
27811 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27812 "--"
27813 ["New Heading" org-insert-heading t]
27814 ("Navigate Headings"
27815 ["Up" outline-up-heading t]
27816 ["Next" outline-next-visible-heading t]
27817 ["Previous" outline-previous-visible-heading t]
27818 ["Next Same Level" outline-forward-same-level t]
27819 ["Previous Same Level" outline-backward-same-level t]
27820 "--"
27821 ["Jump" org-goto t])
27822 ("Edit Structure"
27823 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27824 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27825 "--"
27826 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27827 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27828 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27829 "--"
27830 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27831 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27832 ["Demote Heading" org-metaright (not (org-at-table-p))]
27833 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27834 "--"
27835 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27836 "--"
27837 ["Convert to odd levels" org-convert-to-odd-levels t]
27838 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27839 ("Editing"
27840 ["Emphasis..." org-emphasize t])
27841 ("Archive"
27842 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27843 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27844 ; :active t :keys "C-u C-c C-x C-a"]
27845 ["Sparse trees open ARCHIVE trees"
27846 (setq org-sparse-tree-open-archived-trees
27847 (not org-sparse-tree-open-archived-trees))
27848 :style toggle :selected org-sparse-tree-open-archived-trees]
27849 ["Cycling opens ARCHIVE trees"
27850 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27851 :style toggle :selected org-cycle-open-archived-trees]
27852 ["Agenda includes ARCHIVE trees"
27853 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27854 :style toggle :selected (not org-agenda-skip-archived-trees)]
27855 "--"
27856 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27857 ; ["Check and Move Children" (org-archive-subtree '(4))
27858 ; :active t :keys "C-u C-c C-x C-s"]
27860 "--"
27861 ("TODO Lists"
27862 ["TODO/DONE/-" org-todo t]
27863 ("Select keyword"
27864 ["Next keyword" org-shiftright (org-on-heading-p)]
27865 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27866 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27867 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27868 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27869 ["Show TODO Tree" org-show-todo-tree t]
27870 ["Global TODO list" org-todo-list t]
27871 "--"
27872 ["Set Priority" org-priority t]
27873 ["Priority Up" org-shiftup t]
27874 ["Priority Down" org-shiftdown t])
27875 ("TAGS and Properties"
27876 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27877 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27878 "--"
27879 ["Set property" 'org-set-property t]
27880 ["Column view of properties" org-columns t]
27881 ["Insert Column View DBlock" org-insert-columns-dblock t])
27882 ("Dates and Scheduling"
27883 ["Timestamp" org-time-stamp t]
27884 ["Timestamp (inactive)" org-time-stamp-inactive t]
27885 ("Change Date"
27886 ["1 Day Later" org-shiftright t]
27887 ["1 Day Earlier" org-shiftleft t]
27888 ["1 ... Later" org-shiftup t]
27889 ["1 ... Earlier" org-shiftdown t])
27890 ["Compute Time Range" org-evaluate-time-range t]
27891 ["Schedule Item" org-schedule t]
27892 ["Deadline" org-deadline t]
27893 "--"
27894 ["Custom time format" org-toggle-time-stamp-overlays
27895 :style radio :selected org-display-custom-times]
27896 "--"
27897 ["Goto Calendar" org-goto-calendar t]
27898 ["Date from Calendar" org-date-from-calendar t])
27899 ("Logging work"
27900 ["Clock in" org-clock-in t]
27901 ["Clock out" org-clock-out t]
27902 ["Clock cancel" org-clock-cancel t]
27903 ["Goto running clock" org-clock-goto t]
27904 ["Display times" org-clock-display t]
27905 ["Create clock table" org-clock-report t]
27906 "--"
27907 ["Record DONE time"
27908 (progn (setq org-log-done (not org-log-done))
27909 (message "Switching to %s will %s record a timestamp"
27910 (car org-done-keywords)
27911 (if org-log-done "automatically" "not")))
27912 :style toggle :selected org-log-done])
27913 "--"
27914 ["Agenda Command..." org-agenda t]
27915 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27916 ("File List for Agenda")
27917 ("Special views current file"
27918 ["TODO Tree" org-show-todo-tree t]
27919 ["Check Deadlines" org-check-deadlines t]
27920 ["Timeline" org-timeline t]
27921 ["Tags Tree" org-tags-sparse-tree t])
27922 "--"
27923 ("Hyperlinks"
27924 ["Store Link (Global)" org-store-link t]
27925 ["Insert Link" org-insert-link t]
27926 ["Follow Link" org-open-at-point t]
27927 "--"
27928 ["Next link" org-next-link t]
27929 ["Previous link" org-previous-link t]
27930 "--"
27931 ["Descriptive Links"
27932 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27933 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27934 ["Literal Links"
27935 (progn
27936 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27937 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27938 "--"
27939 ["Export/Publish..." org-export t]
27940 ("LaTeX"
27941 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27942 :selected org-cdlatex-mode]
27943 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27944 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27945 ["Modify math symbol" org-cdlatex-math-modify
27946 (org-inside-LaTeX-fragment-p)]
27947 ["Export LaTeX fragments as images"
27948 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27949 :style toggle :selected org-export-with-LaTeX-fragments])
27950 "--"
27951 ("Documentation"
27952 ["Show Version" org-version t]
27953 ["Info Documentation" org-info t])
27954 ("Customize"
27955 ["Browse Org Group" org-customize t]
27956 "--"
27957 ["Expand This Menu" org-create-customize-menu
27958 (fboundp 'customize-menu-create)])
27959 "--"
27960 ["Refresh setup" org-mode-restart t]
27963 (defun org-info (&optional node)
27964 "Read documentation for Org-mode in the info system.
27965 With optional NODE, go directly to that node."
27966 (interactive)
27967 (info (format "(org)%s" (or node ""))))
27969 (defun org-install-agenda-files-menu ()
27970 (let ((bl (buffer-list)))
27971 (save-excursion
27972 (while bl
27973 (set-buffer (pop bl))
27974 (if (org-mode-p) (setq bl nil)))
27975 (when (org-mode-p)
27976 (easy-menu-change
27977 '("Org") "File List for Agenda"
27978 (append
27979 (list
27980 ["Edit File List" (org-edit-agenda-file-list) t]
27981 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27982 ["Remove Current File from List" org-remove-file t]
27983 ["Cycle through agenda files" org-cycle-agenda-files t]
27984 ["Occur in all agenda files" org-occur-in-agenda-files t]
27985 "--")
27986 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27988 ;;;; Documentation
27990 (defun org-customize ()
27991 "Call the customize function with org as argument."
27992 (interactive)
27993 (customize-browse 'org))
27995 (defun org-create-customize-menu ()
27996 "Create a full customization menu for Org-mode, insert it into the menu."
27997 (interactive)
27998 (if (fboundp 'customize-menu-create)
27999 (progn
28000 (easy-menu-change
28001 '("Org") "Customize"
28002 `(["Browse Org group" org-customize t]
28003 "--"
28004 ,(customize-menu-create 'org)
28005 ["Set" Custom-set t]
28006 ["Save" Custom-save t]
28007 ["Reset to Current" Custom-reset-current t]
28008 ["Reset to Saved" Custom-reset-saved t]
28009 ["Reset to Standard Settings" Custom-reset-standard t]))
28010 (message "\"Org\"-menu now contains full customization menu"))
28011 (error "Cannot expand menu (outdated version of cus-edit.el)")))
28013 ;;;; Miscellaneous stuff
28016 ;;; Generally useful functions
28018 (defun org-context ()
28019 "Return a list of contexts of the current cursor position.
28020 If several contexts apply, all are returned.
28021 Each context entry is a list with a symbol naming the context, and
28022 two positions indicating start and end of the context. Possible
28023 contexts are:
28025 :headline anywhere in a headline
28026 :headline-stars on the leading stars in a headline
28027 :todo-keyword on a TODO keyword (including DONE) in a headline
28028 :tags on the TAGS in a headline
28029 :priority on the priority cookie in a headline
28030 :item on the first line of a plain list item
28031 :item-bullet on the bullet/number of a plain list item
28032 :checkbox on the checkbox in a plain list item
28033 :table in an org-mode table
28034 :table-special on a special filed in a table
28035 :table-table in a table.el table
28036 :link on a hyperlink
28037 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
28038 :target on a <<target>>
28039 :radio-target on a <<<radio-target>>>
28040 :latex-fragment on a LaTeX fragment
28041 :latex-preview on a LaTeX fragment with overlayed preview image
28043 This function expects the position to be visible because it uses font-lock
28044 faces as a help to recognize the following contexts: :table-special, :link,
28045 and :keyword."
28046 (let* ((f (get-text-property (point) 'face))
28047 (faces (if (listp f) f (list f)))
28048 (p (point)) clist o)
28049 ;; First the large context
28050 (cond
28051 ((org-on-heading-p t)
28052 (push (list :headline (point-at-bol) (point-at-eol)) clist)
28053 (when (progn
28054 (beginning-of-line 1)
28055 (looking-at org-todo-line-tags-regexp))
28056 (push (org-point-in-group p 1 :headline-stars) clist)
28057 (push (org-point-in-group p 2 :todo-keyword) clist)
28058 (push (org-point-in-group p 4 :tags) clist))
28059 (goto-char p)
28060 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
28061 (if (looking-at "\\[#[A-Z0-9]\\]")
28062 (push (org-point-in-group p 0 :priority) clist)))
28064 ((org-at-item-p)
28065 (push (org-point-in-group p 2 :item-bullet) clist)
28066 (push (list :item (point-at-bol)
28067 (save-excursion (org-end-of-item) (point)))
28068 clist)
28069 (and (org-at-item-checkbox-p)
28070 (push (org-point-in-group p 0 :checkbox) clist)))
28072 ((org-at-table-p)
28073 (push (list :table (org-table-begin) (org-table-end)) clist)
28074 (if (memq 'org-formula faces)
28075 (push (list :table-special
28076 (previous-single-property-change p 'face)
28077 (next-single-property-change p 'face)) clist)))
28078 ((org-at-table-p 'any)
28079 (push (list :table-table) clist)))
28080 (goto-char p)
28082 ;; Now the small context
28083 (cond
28084 ((org-at-timestamp-p)
28085 (push (org-point-in-group p 0 :timestamp) clist))
28086 ((memq 'org-link faces)
28087 (push (list :link
28088 (previous-single-property-change p 'face)
28089 (next-single-property-change p 'face)) clist))
28090 ((memq 'org-special-keyword faces)
28091 (push (list :keyword
28092 (previous-single-property-change p 'face)
28093 (next-single-property-change p 'face)) clist))
28094 ((org-on-target-p)
28095 (push (org-point-in-group p 0 :target) clist)
28096 (goto-char (1- (match-beginning 0)))
28097 (if (looking-at org-radio-target-regexp)
28098 (push (org-point-in-group p 0 :radio-target) clist))
28099 (goto-char p))
28100 ((setq o (car (delq nil
28101 (mapcar
28102 (lambda (x)
28103 (if (memq x org-latex-fragment-image-overlays) x))
28104 (org-overlays-at (point))))))
28105 (push (list :latex-fragment
28106 (org-overlay-start o) (org-overlay-end o)) clist)
28107 (push (list :latex-preview
28108 (org-overlay-start o) (org-overlay-end o)) clist))
28109 ((org-inside-LaTeX-fragment-p)
28110 ;; FIXME: positions wrong.
28111 (push (list :latex-fragment (point) (point)) clist)))
28113 (setq clist (nreverse (delq nil clist)))
28114 clist))
28116 ;; FIXME: Compare with at-regexp-p Do we need both?
28117 (defun org-in-regexp (re &optional nlines visually)
28118 "Check if point is inside a match of regexp.
28119 Normally only the current line is checked, but you can include NLINES extra
28120 lines both before and after point into the search.
28121 If VISUALLY is set, require that the cursor is not after the match but
28122 really on, so that the block visually is on the match."
28123 (catch 'exit
28124 (let ((pos (point))
28125 (eol (point-at-eol (+ 1 (or nlines 0))))
28126 (inc (if visually 1 0)))
28127 (save-excursion
28128 (beginning-of-line (- 1 (or nlines 0)))
28129 (while (re-search-forward re eol t)
28130 (if (and (<= (match-beginning 0) pos)
28131 (>= (+ inc (match-end 0)) pos))
28132 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
28134 (defun org-at-regexp-p (regexp)
28135 "Is point inside a match of REGEXP in the current line?"
28136 (catch 'exit
28137 (save-excursion
28138 (let ((pos (point)) (end (point-at-eol)))
28139 (beginning-of-line 1)
28140 (while (re-search-forward regexp end t)
28141 (if (and (<= (match-beginning 0) pos)
28142 (>= (match-end 0) pos))
28143 (throw 'exit t)))
28144 nil))))
28146 (defun org-occur-in-agenda-files (regexp &optional nlines)
28147 "Call `multi-occur' with buffers for all agenda files."
28148 (interactive "sOrg-files matching: \np")
28149 (let* ((files (org-agenda-files))
28150 (tnames (mapcar 'file-truename files))
28151 (extra org-agenda-text-search-extra-files)
28153 (while (setq f (pop extra))
28154 (unless (member (file-truename f) tnames)
28155 (add-to-list 'files f 'append)
28156 (add-to-list 'tnames (file-truename f) 'append)))
28157 (multi-occur
28158 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
28159 regexp)))
28161 (if (boundp 'occur-mode-find-occurrence-hook)
28162 ;; Emacs 23
28163 (add-hook 'occur-mode-find-occurrence-hook
28164 (lambda ()
28165 (when (org-mode-p)
28166 (org-reveal))))
28167 ;; Emacs 22
28168 (defadvice occur-mode-goto-occurrence
28169 (after org-occur-reveal activate)
28170 (and (org-mode-p) (org-reveal)))
28171 (defadvice occur-mode-goto-occurrence-other-window
28172 (after org-occur-reveal activate)
28173 (and (org-mode-p) (org-reveal)))
28174 (defadvice occur-mode-display-occurrence
28175 (after org-occur-reveal activate)
28176 (when (org-mode-p)
28177 (let ((pos (occur-mode-find-occurrence)))
28178 (with-current-buffer (marker-buffer pos)
28179 (save-excursion
28180 (goto-char pos)
28181 (org-reveal)))))))
28183 (defun org-uniquify (list)
28184 "Remove duplicate elements from LIST."
28185 (let (res)
28186 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
28187 res))
28189 (defun org-delete-all (elts list)
28190 "Remove all elements in ELTS from LIST."
28191 (while elts
28192 (setq list (delete (pop elts) list)))
28193 list)
28195 (defun org-back-over-empty-lines ()
28196 "Move backwards over witespace, to the beginning of the first empty line.
28197 Returns the number o empty lines passed."
28198 (let ((pos (point)))
28199 (skip-chars-backward " \t\n\r")
28200 (beginning-of-line 2)
28201 (goto-char (min (point) pos))
28202 (count-lines (point) pos)))
28204 (defun org-skip-whitespace ()
28205 (skip-chars-forward " \t\n\r"))
28207 (defun org-point-in-group (point group &optional context)
28208 "Check if POINT is in match-group GROUP.
28209 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
28210 match. If the match group does ot exist or point is not inside it,
28211 return nil."
28212 (and (match-beginning group)
28213 (>= point (match-beginning group))
28214 (<= point (match-end group))
28215 (if context
28216 (list context (match-beginning group) (match-end group))
28217 t)))
28219 (defun org-switch-to-buffer-other-window (&rest args)
28220 "Switch to buffer in a second window on the current frame.
28221 In particular, do not allow pop-up frames."
28222 (let (pop-up-frames special-display-buffer-names special-display-regexps
28223 special-display-function)
28224 (apply 'switch-to-buffer-other-window args)))
28226 (defun org-combine-plists (&rest plists)
28227 "Create a single property list from all plists in PLISTS.
28228 The process starts by copying the first list, and then setting properties
28229 from the other lists. Settings in the last list are the most significant
28230 ones and overrule settings in the other lists."
28231 (let ((rtn (copy-sequence (pop plists)))
28232 p v ls)
28233 (while plists
28234 (setq ls (pop plists))
28235 (while ls
28236 (setq p (pop ls) v (pop ls))
28237 (setq rtn (plist-put rtn p v))))
28238 rtn))
28240 (defun org-move-line-down (arg)
28241 "Move the current line down. With prefix argument, move it past ARG lines."
28242 (interactive "p")
28243 (let ((col (current-column))
28244 beg end pos)
28245 (beginning-of-line 1) (setq beg (point))
28246 (beginning-of-line 2) (setq end (point))
28247 (beginning-of-line (+ 1 arg))
28248 (setq pos (move-marker (make-marker) (point)))
28249 (insert (delete-and-extract-region beg end))
28250 (goto-char pos)
28251 (move-to-column col)))
28253 (defun org-move-line-up (arg)
28254 "Move the current line up. With prefix argument, move it past ARG lines."
28255 (interactive "p")
28256 (let ((col (current-column))
28257 beg end pos)
28258 (beginning-of-line 1) (setq beg (point))
28259 (beginning-of-line 2) (setq end (point))
28260 (beginning-of-line (- arg))
28261 (setq pos (move-marker (make-marker) (point)))
28262 (insert (delete-and-extract-region beg end))
28263 (goto-char pos)
28264 (move-to-column col)))
28266 (defun org-replace-escapes (string table)
28267 "Replace %-escapes in STRING with values in TABLE.
28268 TABLE is an association list with keys like \"%a\" and string values.
28269 The sequences in STRING may contain normal field width and padding information,
28270 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
28271 so values can contain further %-escapes if they are define later in TABLE."
28272 (let ((case-fold-search nil)
28273 e re rpl)
28274 (while (setq e (pop table))
28275 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
28276 (while (string-match re string)
28277 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
28278 (cdr e)))
28279 (setq string (replace-match rpl t t string))))
28280 string))
28283 (defun org-sublist (list start end)
28284 "Return a section of LIST, from START to END.
28285 Counting starts at 1."
28286 (let (rtn (c start))
28287 (setq list (nthcdr (1- start) list))
28288 (while (and list (<= c end))
28289 (push (pop list) rtn)
28290 (setq c (1+ c)))
28291 (nreverse rtn)))
28293 (defun org-find-base-buffer-visiting (file)
28294 "Like `find-buffer-visiting' but alway return the base buffer and
28295 not an indirect buffer"
28296 (let ((buf (find-buffer-visiting file)))
28297 (if buf
28298 (or (buffer-base-buffer buf) buf)
28299 nil)))
28301 (defun org-image-file-name-regexp ()
28302 "Return regexp matching the file names of images."
28303 (if (fboundp 'image-file-name-regexp)
28304 (image-file-name-regexp)
28305 (let ((image-file-name-extensions
28306 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
28307 "xbm" "xpm" "pbm" "pgm" "ppm")))
28308 (concat "\\."
28309 (regexp-opt (nconc (mapcar 'upcase
28310 image-file-name-extensions)
28311 image-file-name-extensions)
28313 "\\'"))))
28315 (defun org-file-image-p (file)
28316 "Return non-nil if FILE is an image."
28317 (save-match-data
28318 (string-match (org-image-file-name-regexp) file)))
28320 ;;; Paragraph filling stuff.
28321 ;; We want this to be just right, so use the full arsenal.
28323 (defun org-indent-line-function ()
28324 "Indent line like previous, but further if previous was headline or item."
28325 (interactive)
28326 (let* ((pos (point))
28327 (itemp (org-at-item-p))
28328 column bpos bcol tpos tcol bullet btype bullet-type)
28329 ;; Find the previous relevant line
28330 (beginning-of-line 1)
28331 (cond
28332 ((looking-at "#") (setq column 0))
28333 ((looking-at "\\*+ ") (setq column 0))
28335 (beginning-of-line 0)
28336 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
28337 (beginning-of-line 0))
28338 (cond
28339 ((looking-at "\\*+[ \t]+")
28340 (goto-char (match-end 0))
28341 (setq column (current-column)))
28342 ((org-in-item-p)
28343 (org-beginning-of-item)
28344 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28345 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
28346 (setq bpos (match-beginning 1) tpos (match-end 0)
28347 bcol (progn (goto-char bpos) (current-column))
28348 tcol (progn (goto-char tpos) (current-column))
28349 bullet (match-string 1)
28350 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
28351 (if (not itemp)
28352 (setq column tcol)
28353 (goto-char pos)
28354 (beginning-of-line 1)
28355 (if (looking-at "\\S-")
28356 (progn
28357 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28358 (setq bullet (match-string 1)
28359 btype (if (string-match "[0-9]" bullet) "n" bullet))
28360 (setq column (if (equal btype bullet-type) bcol tcol)))
28361 (setq column (org-get-indentation)))))
28362 (t (setq column (org-get-indentation))))))
28363 (goto-char pos)
28364 (if (<= (current-column) (current-indentation))
28365 (indent-line-to column)
28366 (save-excursion (indent-line-to column)))
28367 (setq column (current-column))
28368 (beginning-of-line 1)
28369 (if (looking-at
28370 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
28371 (replace-match (concat "\\1" (format org-property-format
28372 (match-string 2) (match-string 3)))
28373 t nil))
28374 (move-to-column column)))
28376 (defun org-set-autofill-regexps ()
28377 (interactive)
28378 ;; In the paragraph separator we include headlines, because filling
28379 ;; text in a line directly attached to a headline would otherwise
28380 ;; fill the headline as well.
28381 (org-set-local 'comment-start-skip "^#+[ \t]*")
28382 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
28383 ;; The paragraph starter includes hand-formatted lists.
28384 (org-set-local 'paragraph-start
28385 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
28386 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
28387 ;; But only if the user has not turned off tables or fixed-width regions
28388 (org-set-local
28389 'auto-fill-inhibit-regexp
28390 (concat "\\*+ \\|#\\+"
28391 "\\|[ \t]*" org-keyword-time-regexp
28392 (if (or org-enable-table-editor org-enable-fixed-width-editor)
28393 (concat
28394 "\\|[ \t]*["
28395 (if org-enable-table-editor "|" "")
28396 (if org-enable-fixed-width-editor ":" "")
28397 "]"))))
28398 ;; We use our own fill-paragraph function, to make sure that tables
28399 ;; and fixed-width regions are not wrapped. That function will pass
28400 ;; through to `fill-paragraph' when appropriate.
28401 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
28402 ; Adaptive filling: To get full control, first make sure that
28403 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
28404 (org-set-local 'adaptive-fill-regexp "\000")
28405 (org-set-local 'adaptive-fill-function
28406 'org-adaptive-fill-function)
28407 (org-set-local
28408 'align-mode-rules-list
28409 '((org-in-buffer-settings
28410 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
28411 (modes . '(org-mode))))))
28413 (defun org-fill-paragraph (&optional justify)
28414 "Re-align a table, pass through to fill-paragraph if no table."
28415 (let ((table-p (org-at-table-p))
28416 (table.el-p (org-at-table.el-p)))
28417 (cond ((and (equal (char-after (point-at-bol)) ?*)
28418 (save-excursion (goto-char (point-at-bol))
28419 (looking-at outline-regexp)))
28420 t) ; skip headlines
28421 (table.el-p t) ; skip table.el tables
28422 (table-p (org-table-align) t) ; align org-mode tables
28423 (t nil)))) ; call paragraph-fill
28425 ;; For reference, this is the default value of adaptive-fill-regexp
28426 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
28428 (defun org-adaptive-fill-function ()
28429 "Return a fill prefix for org-mode files.
28430 In particular, this makes sure hanging paragraphs for hand-formatted lists
28431 work correctly."
28432 (cond ((looking-at "#[ \t]+")
28433 (match-string 0))
28434 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
28435 (save-excursion
28436 (goto-char (match-end 0))
28437 (make-string (current-column) ?\ )))
28438 (t nil)))
28440 ;;;; Functions extending outline functionality
28443 (defun org-beginning-of-line (&optional arg)
28444 "Go to the beginning of the current line. If that is invisible, continue
28445 to a visible line beginning. This makes the function of C-a more intuitive.
28446 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28447 first attempt, and only move to after the tags when the cursor is already
28448 beyond the end of the headline."
28449 (interactive "P")
28450 (let ((pos (point)))
28451 (beginning-of-line 1)
28452 (if (bobp)
28454 (backward-char 1)
28455 (if (org-invisible-p)
28456 (while (and (not (bobp)) (org-invisible-p))
28457 (backward-char 1)
28458 (beginning-of-line 1))
28459 (forward-char 1)))
28460 (when org-special-ctrl-a/e
28461 (cond
28462 ((and (looking-at org-todo-line-regexp)
28463 (= (char-after (match-end 1)) ?\ ))
28464 (goto-char
28465 (if (eq org-special-ctrl-a/e t)
28466 (cond ((> pos (match-beginning 3)) (match-beginning 3))
28467 ((= pos (point)) (match-beginning 3))
28468 (t (point)))
28469 (cond ((> pos (point)) (point))
28470 ((not (eq last-command this-command)) (point))
28471 (t (match-beginning 3))))))
28472 ((org-at-item-p)
28473 (goto-char
28474 (if (eq org-special-ctrl-a/e t)
28475 (cond ((> pos (match-end 4)) (match-end 4))
28476 ((= pos (point)) (match-end 4))
28477 (t (point)))
28478 (cond ((> pos (point)) (point))
28479 ((not (eq last-command this-command)) (point))
28480 (t (match-end 4))))))))))
28482 (defun org-end-of-line (&optional arg)
28483 "Go to the end of the line.
28484 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28485 first attempt, and only move to after the tags when the cursor is already
28486 beyond the end of the headline."
28487 (interactive "P")
28488 (if (or (not org-special-ctrl-a/e)
28489 (not (org-on-heading-p)))
28490 (end-of-line arg)
28491 (let ((pos (point)))
28492 (beginning-of-line 1)
28493 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
28494 (if (eq org-special-ctrl-a/e t)
28495 (if (or (< pos (match-beginning 1))
28496 (= pos (match-end 0)))
28497 (goto-char (match-beginning 1))
28498 (goto-char (match-end 0)))
28499 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
28500 (goto-char (match-end 0))
28501 (goto-char (match-beginning 1))))
28502 (end-of-line arg)))))
28504 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
28505 (define-key org-mode-map "\C-e" 'org-end-of-line)
28507 (defun org-kill-line (&optional arg)
28508 "Kill line, to tags or end of line."
28509 (interactive "P")
28510 (cond
28511 ((or (not org-special-ctrl-k)
28512 (bolp)
28513 (not (org-on-heading-p)))
28514 (call-interactively 'kill-line))
28515 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
28516 (kill-region (point) (match-beginning 1))
28517 (org-set-tags nil t))
28518 (t (kill-region (point) (point-at-eol)))))
28520 (define-key org-mode-map "\C-k" 'org-kill-line)
28522 (defun org-invisible-p ()
28523 "Check if point is at a character currently not visible."
28524 ;; Early versions of noutline don't have `outline-invisible-p'.
28525 (if (fboundp 'outline-invisible-p)
28526 (outline-invisible-p)
28527 (get-char-property (point) 'invisible)))
28529 (defun org-invisible-p2 ()
28530 "Check if point is at a character currently not visible."
28531 (save-excursion
28532 (if (and (eolp) (not (bobp))) (backward-char 1))
28533 ;; Early versions of noutline don't have `outline-invisible-p'.
28534 (if (fboundp 'outline-invisible-p)
28535 (outline-invisible-p)
28536 (get-char-property (point) 'invisible))))
28538 (defalias 'org-back-to-heading 'outline-back-to-heading)
28539 (defalias 'org-on-heading-p 'outline-on-heading-p)
28540 (defalias 'org-at-heading-p 'outline-on-heading-p)
28541 (defun org-at-heading-or-item-p ()
28542 (or (org-on-heading-p) (org-at-item-p)))
28544 (defun org-on-target-p ()
28545 (or (org-in-regexp org-radio-target-regexp)
28546 (org-in-regexp org-target-regexp)))
28548 (defun org-up-heading-all (arg)
28549 "Move to the heading line of which the present line is a subheading.
28550 This function considers both visible and invisible heading lines.
28551 With argument, move up ARG levels."
28552 (if (fboundp 'outline-up-heading-all)
28553 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28554 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28556 (defun org-up-heading-safe ()
28557 "Move to the heading line of which the present line is a subheading.
28558 This version will not throw an error. It will return the level of the
28559 headline found, or nil if no higher level is found."
28560 (let ((pos (point)) start-level level
28561 (re (concat "^" outline-regexp)))
28562 (catch 'exit
28563 (outline-back-to-heading t)
28564 (setq start-level (funcall outline-level))
28565 (if (equal start-level 1) (throw 'exit nil))
28566 (while (re-search-backward re nil t)
28567 (setq level (funcall outline-level))
28568 (if (< level start-level) (throw 'exit level)))
28569 nil)))
28571 (defun org-first-sibling-p ()
28572 "Is this heading the first child of its parents?"
28573 (interactive)
28574 (let ((re (concat "^" outline-regexp))
28575 level l)
28576 (unless (org-at-heading-p t)
28577 (error "Not at a heading"))
28578 (setq level (funcall outline-level))
28579 (save-excursion
28580 (if (not (re-search-backward re nil t))
28582 (setq l (funcall outline-level))
28583 (< l level)))))
28585 (defun org-goto-sibling (&optional previous)
28586 "Goto the next sibling, even if it is invisible.
28587 When PREVIOUS is set, go to the previous sibling instead. Returns t
28588 when a sibling was found. When none is found, return nil and don't
28589 move point."
28590 (let ((fun (if previous 're-search-backward 're-search-forward))
28591 (pos (point))
28592 (re (concat "^" outline-regexp))
28593 level l)
28594 (when (condition-case nil (org-back-to-heading t) (error nil))
28595 (setq level (funcall outline-level))
28596 (catch 'exit
28597 (or previous (forward-char 1))
28598 (while (funcall fun re nil t)
28599 (setq l (funcall outline-level))
28600 (when (< l level) (goto-char pos) (throw 'exit nil))
28601 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28602 (goto-char pos)
28603 nil))))
28605 (defun org-show-siblings ()
28606 "Show all siblings of the current headline."
28607 (save-excursion
28608 (while (org-goto-sibling) (org-flag-heading nil)))
28609 (save-excursion
28610 (while (org-goto-sibling 'previous)
28611 (org-flag-heading nil))))
28613 (defun org-show-hidden-entry ()
28614 "Show an entry where even the heading is hidden."
28615 (save-excursion
28616 (org-show-entry)))
28618 (defun org-flag-heading (flag &optional entry)
28619 "Flag the current heading. FLAG non-nil means make invisible.
28620 When ENTRY is non-nil, show the entire entry."
28621 (save-excursion
28622 (org-back-to-heading t)
28623 ;; Check if we should show the entire entry
28624 (if entry
28625 (progn
28626 (org-show-entry)
28627 (save-excursion
28628 (and (outline-next-heading)
28629 (org-flag-heading nil))))
28630 (outline-flag-region (max (point-min) (1- (point)))
28631 (save-excursion (outline-end-of-heading) (point))
28632 flag))))
28634 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28635 ;; This is an exact copy of the original function, but it uses
28636 ;; `org-back-to-heading', to make it work also in invisible
28637 ;; trees. And is uses an invisible-OK argument.
28638 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28639 (org-back-to-heading invisible-OK)
28640 (let ((first t)
28641 (level (funcall outline-level)))
28642 (while (and (not (eobp))
28643 (or first (> (funcall outline-level) level)))
28644 (setq first nil)
28645 (outline-next-heading))
28646 (unless to-heading
28647 (if (memq (preceding-char) '(?\n ?\^M))
28648 (progn
28649 ;; Go to end of line before heading
28650 (forward-char -1)
28651 (if (memq (preceding-char) '(?\n ?\^M))
28652 ;; leave blank line before heading
28653 (forward-char -1))))))
28654 (point))
28656 (defun org-show-subtree ()
28657 "Show everything after this heading at deeper levels."
28658 (outline-flag-region
28659 (point)
28660 (save-excursion
28661 (outline-end-of-subtree) (outline-next-heading) (point))
28662 nil))
28664 (defun org-show-entry ()
28665 "Show the body directly following this heading.
28666 Show the heading too, if it is currently invisible."
28667 (interactive)
28668 (save-excursion
28669 (condition-case nil
28670 (progn
28671 (org-back-to-heading t)
28672 (outline-flag-region
28673 (max (point-min) (1- (point)))
28674 (save-excursion
28675 (re-search-forward
28676 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28677 (or (match-beginning 1) (point-max)))
28678 nil))
28679 (error nil))))
28681 (defun org-make-options-regexp (kwds)
28682 "Make a regular expression for keyword lines."
28683 (concat
28685 "#?[ \t]*\\+\\("
28686 (mapconcat 'regexp-quote kwds "\\|")
28687 "\\):[ \t]*"
28688 "\\(.+\\)"))
28690 ;; Make isearch reveal the necessary context
28691 (defun org-isearch-end ()
28692 "Reveal context after isearch exits."
28693 (when isearch-success ; only if search was successful
28694 (if (featurep 'xemacs)
28695 ;; Under XEmacs, the hook is run in the correct place,
28696 ;; we directly show the context.
28697 (org-show-context 'isearch)
28698 ;; In Emacs the hook runs *before* restoring the overlays.
28699 ;; So we have to use a one-time post-command-hook to do this.
28700 ;; (Emacs 22 has a special variable, see function `org-mode')
28701 (unless (and (boundp 'isearch-mode-end-hook-quit)
28702 isearch-mode-end-hook-quit)
28703 ;; Only when the isearch was not quitted.
28704 (org-add-hook 'post-command-hook 'org-isearch-post-command
28705 'append 'local)))))
28707 (defun org-isearch-post-command ()
28708 "Remove self from hook, and show context."
28709 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28710 (org-show-context 'isearch))
28713 ;;;; Integration with and fixes for other packages
28715 ;;; Imenu support
28717 (defvar org-imenu-markers nil
28718 "All markers currently used by Imenu.")
28719 (make-variable-buffer-local 'org-imenu-markers)
28721 (defun org-imenu-new-marker (&optional pos)
28722 "Return a new marker for use by Imenu, and remember the marker."
28723 (let ((m (make-marker)))
28724 (move-marker m (or pos (point)))
28725 (push m org-imenu-markers)
28728 (defun org-imenu-get-tree ()
28729 "Produce the index for Imenu."
28730 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28731 (setq org-imenu-markers nil)
28732 (let* ((n org-imenu-depth)
28733 (re (concat "^" outline-regexp))
28734 (subs (make-vector (1+ n) nil))
28735 (last-level 0)
28736 m tree level head)
28737 (save-excursion
28738 (save-restriction
28739 (widen)
28740 (goto-char (point-max))
28741 (while (re-search-backward re nil t)
28742 (setq level (org-reduced-level (funcall outline-level)))
28743 (when (<= level n)
28744 (looking-at org-complex-heading-regexp)
28745 (setq head (org-match-string-no-properties 4)
28746 m (org-imenu-new-marker))
28747 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28748 (if (>= level last-level)
28749 (push (cons head m) (aref subs level))
28750 (push (cons head (aref subs (1+ level))) (aref subs level))
28751 (loop for i from (1+ level) to n do (aset subs i nil)))
28752 (setq last-level level)))))
28753 (aref subs 1)))
28755 (eval-after-load "imenu"
28756 '(progn
28757 (add-hook 'imenu-after-jump-hook
28758 (lambda () (org-show-context 'org-goto)))))
28760 ;; Speedbar support
28762 (defun org-speedbar-set-agenda-restriction ()
28763 "Restrict future agenda commands to the location at point in speedbar.
28764 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28765 (interactive)
28766 (let (p m tp np dir txt w)
28767 (cond
28768 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28769 'org-imenu t))
28770 (setq m (get-text-property p 'org-imenu-marker))
28771 (save-excursion
28772 (save-restriction
28773 (set-buffer (marker-buffer m))
28774 (goto-char m)
28775 (org-agenda-set-restriction-lock 'subtree))))
28776 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28777 'speedbar-function 'speedbar-find-file))
28778 (setq tp (previous-single-property-change
28779 (1+ p) 'speedbar-function)
28780 np (next-single-property-change
28781 tp 'speedbar-function)
28782 dir (speedbar-line-directory)
28783 txt (buffer-substring-no-properties (or tp (point-min))
28784 (or np (point-max))))
28785 (save-excursion
28786 (save-restriction
28787 (set-buffer (find-file-noselect
28788 (let ((default-directory dir))
28789 (expand-file-name txt))))
28790 (unless (org-mode-p)
28791 (error "Cannot restrict to non-Org-mode file"))
28792 (org-agenda-set-restriction-lock 'file))))
28793 (t (error "Don't know how to restrict Org-mode's agenda")))
28794 (org-move-overlay org-speedbar-restriction-lock-overlay
28795 (point-at-bol) (point-at-eol))
28796 (setq current-prefix-arg nil)
28797 (org-agenda-maybe-redo)))
28799 (eval-after-load "speedbar"
28800 '(progn
28801 (speedbar-add-supported-extension ".org")
28802 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28803 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28804 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28805 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28806 (add-hook 'speedbar-visiting-tag-hook
28807 (lambda () (org-show-context 'org-goto)))))
28810 ;;; Fixes and Hacks
28812 ;; Make flyspell not check words in links, to not mess up our keymap
28813 (defun org-mode-flyspell-verify ()
28814 "Don't let flyspell put overlays at active buttons."
28815 (not (get-text-property (point) 'keymap)))
28817 ;; Make `bookmark-jump' show the jump location if it was hidden.
28818 (eval-after-load "bookmark"
28819 '(if (boundp 'bookmark-after-jump-hook)
28820 ;; We can use the hook
28821 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28822 ;; Hook not available, use advice
28823 (defadvice bookmark-jump (after org-make-visible activate)
28824 "Make the position visible."
28825 (org-bookmark-jump-unhide))))
28827 (defun org-bookmark-jump-unhide ()
28828 "Unhide the current position, to show the bookmark location."
28829 (and (org-mode-p)
28830 (or (org-invisible-p)
28831 (save-excursion (goto-char (max (point-min) (1- (point))))
28832 (org-invisible-p)))
28833 (org-show-context 'bookmark-jump)))
28835 ;; Make session.el ignore our circular variable
28836 (eval-after-load "session"
28837 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28839 ;;;; Experimental code
28841 (defun org-closed-in-range ()
28842 "Sparse tree of items closed in a certain time range.
28843 Still experimental, may disappear in the future."
28844 (interactive)
28845 ;; Get the time interval from the user.
28846 (let* ((time1 (time-to-seconds
28847 (org-read-date nil 'to-time nil "Starting date: ")))
28848 (time2 (time-to-seconds
28849 (org-read-date nil 'to-time nil "End date:")))
28850 ;; callback function
28851 (callback (lambda ()
28852 (let ((time
28853 (time-to-seconds
28854 (apply 'encode-time
28855 (org-parse-time-string
28856 (match-string 1))))))
28857 ;; check if time in interval
28858 (and (>= time time1) (<= time time2))))))
28859 ;; make tree, check each match with the callback
28860 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28862 ;;;; Finish up
28864 (provide 'org)
28866 (run-hooks 'org-load-hook)
28868 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28869 ;;; org.el ends here