Changing timestamps granularly.
[org-mode/org-tableheadings.git] / org.el
blob99e69f2fc15c5f63e55881c68e6ea6cb4fcdbd0c
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 '(org-load-default-extensions)
155 "Hook that is run after org.el has been loaded.
156 This happens also after `org' has been provided, so
157 requiring something in this hook that does a (require 'org) is ok."
158 :group 'org
159 :type 'hook)
161 (defcustom org-default-extensions '(org-irc)
162 "Extensions that should always be loaded together with org.el.
163 If the description starts with <A>, this means the extension
164 will be autoloaded when needed, preloading is not necessary."
165 :group 'org
166 :type
167 '(set :greedy t
168 (const :tag " Mouse support (org-mouse.el)" org-mouse)
169 (const :tag "<A> Publishing (org-publish.el)" org-publish)
170 (const :tag "<A> LaTeX export (org-export-latex.el)" org-export-latex)
171 (const :tag " IRC/ERC links (org-irc.el)" org-irc)
172 (const :tag " Apple Mail message links under OS X (org-mac-message.el)" org-mac-message)))
174 (defun org-load-default-extensions ()
175 "Load all extensions listed in `org-default-extensions'."
176 (mapc (lambda (ext)
177 (condition-case nil (require ext)
178 (error (message "Problems while trying to load feature `%s'" ext))))
179 org-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-tab-follows-link nil
1250 "Non-nil means, on links TAB will follow the link.
1251 Needs to be set before org.el is loaded."
1252 :group 'org-link-follow
1253 :type 'boolean)
1255 (defcustom org-return-follows-link nil
1256 "Non-nil means, on links RET will follow the link.
1257 Needs to be set before org.el is loaded."
1258 :group 'org-link-follow
1259 :type 'boolean)
1261 (defcustom org-mouse-1-follows-link
1262 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1263 "Non-nil means, mouse-1 on a link will follow the link.
1264 A longer mouse click will still set point. Does not work on XEmacs.
1265 Needs to be set before org.el is loaded."
1266 :group 'org-link-follow
1267 :type 'boolean)
1269 (defcustom org-mark-ring-length 4
1270 "Number of different positions to be recorded in the ring
1271 Changing this requires a restart of Emacs to work correctly."
1272 :group 'org-link-follow
1273 :type 'interger)
1275 (defcustom org-link-frame-setup
1276 '((vm . vm-visit-folder-other-frame)
1277 (gnus . gnus-other-frame)
1278 (file . find-file-other-window))
1279 "Setup the frame configuration for following links.
1280 When following a link with Emacs, it may often be useful to display
1281 this link in another window or frame. This variable can be used to
1282 set this up for the different types of links.
1283 For VM, use any of
1284 `vm-visit-folder'
1285 `vm-visit-folder-other-frame'
1286 For Gnus, use any of
1287 `gnus'
1288 `gnus-other-frame'
1289 For FILE, use any of
1290 `find-file'
1291 `find-file-other-window'
1292 `find-file-other-frame'
1293 For the calendar, use the variable `calendar-setup'.
1294 For BBDB, it is currently only possible to display the matches in
1295 another window."
1296 :group 'org-link-follow
1297 :type '(list
1298 (cons (const vm)
1299 (choice
1300 (const vm-visit-folder)
1301 (const vm-visit-folder-other-window)
1302 (const vm-visit-folder-other-frame)))
1303 (cons (const gnus)
1304 (choice
1305 (const gnus)
1306 (const gnus-other-frame)))
1307 (cons (const file)
1308 (choice
1309 (const find-file)
1310 (const find-file-other-window)
1311 (const find-file-other-frame)))))
1313 (defcustom org-display-internal-link-with-indirect-buffer nil
1314 "Non-nil means, use indirect buffer to display infile links.
1315 Activating internal links (from one location in a file to another location
1316 in the same file) normally just jumps to the location. When the link is
1317 activated with a C-u prefix (or with mouse-3), the link is displayed in
1318 another window. When this option is set, the other window actually displays
1319 an indirect buffer clone of the current buffer, to avoid any visibility
1320 changes to the current buffer."
1321 :group 'org-link-follow
1322 :type 'boolean)
1324 (defcustom org-open-non-existing-files nil
1325 "Non-nil means, `org-open-file' will open non-existing files.
1326 When nil, an error will be generated."
1327 :group 'org-link-follow
1328 :type 'boolean)
1330 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1331 "Function and arguments to call for following mailto links.
1332 This is a list with the first element being a lisp function, and the
1333 remaining elements being arguments to the function. In string arguments,
1334 %a will be replaced by the address, and %s will be replaced by the subject
1335 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1336 :group 'org-link-follow
1337 :type '(choice
1338 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1339 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1340 (const :tag "message-mail" (message-mail "%a" "%s"))
1341 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1343 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1344 "Non-nil means, ask for confirmation before executing shell links.
1345 Shell links can be dangerous: just think about a link
1347 [[shell:rm -rf ~/*][Google Search]]
1349 This link would show up in your Org-mode document as \"Google Search\",
1350 but really it would remove your entire home directory.
1351 Therefore we advise against setting this variable to nil.
1352 Just change it to `y-or-n-p' of you want to confirm with a
1353 single keystroke rather than having to type \"yes\"."
1354 :group 'org-link-follow
1355 :type '(choice
1356 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1357 (const :tag "with y-or-n (faster)" y-or-n-p)
1358 (const :tag "no confirmation (dangerous)" nil)))
1360 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1361 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1362 Elisp links can be dangerous: just think about a link
1364 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1366 This link would show up in your Org-mode document as \"Google Search\",
1367 but really it would remove your entire home directory.
1368 Therefore we advise against setting this variable to nil.
1369 Just change it to `y-or-n-p' of you want to confirm with a
1370 single keystroke rather than having to type \"yes\"."
1371 :group 'org-link-follow
1372 :type '(choice
1373 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1374 (const :tag "with y-or-n (faster)" y-or-n-p)
1375 (const :tag "no confirmation (dangerous)" nil)))
1377 (defconst org-file-apps-defaults-gnu
1378 '((remote . emacs)
1379 (t . mailcap))
1380 "Default file applications on a UNIX or GNU/Linux system.
1381 See `org-file-apps'.")
1383 (defconst org-file-apps-defaults-macosx
1384 '((remote . emacs)
1385 (t . "open %s")
1386 ("ps" . "gv %s")
1387 ("ps.gz" . "gv %s")
1388 ("eps" . "gv %s")
1389 ("eps.gz" . "gv %s")
1390 ("dvi" . "xdvi %s")
1391 ("fig" . "xfig %s"))
1392 "Default file applications on a MacOS X system.
1393 The system \"open\" is known as a default, but we use X11 applications
1394 for some files for which the OS does not have a good default.
1395 See `org-file-apps'.")
1397 (defconst org-file-apps-defaults-windowsnt
1398 (list
1399 '(remote . emacs)
1400 (cons t
1401 (list (if (featurep 'xemacs)
1402 'mswindows-shell-execute
1403 'w32-shell-execute)
1404 "open" 'file)))
1405 "Default file applications on a Windows NT system.
1406 The system \"open\" is used for most files.
1407 See `org-file-apps'.")
1409 (defcustom org-file-apps
1411 ("txt" . emacs)
1412 ("tex" . emacs)
1413 ("ltx" . emacs)
1414 ("org" . emacs)
1415 ("el" . emacs)
1416 ("bib" . emacs)
1418 "External applications for opening `file:path' items in a document.
1419 Org-mode uses system defaults for different file types, but
1420 you can use this variable to set the application for a given file
1421 extension. The entries in this list are cons cells where the car identifies
1422 files and the cdr the corresponding command. Possible values for the
1423 file identifier are
1424 \"ext\" A string identifying an extension
1425 `directory' Matches a directory
1426 `remote' Matches a remote file, accessible through tramp or efs.
1427 Remote files most likely should be visited through Emacs
1428 because external applications cannot handle such paths.
1429 t Default for all remaining files
1431 Possible values for the command are:
1432 `emacs' The file will be visited by the current Emacs process.
1433 `default' Use the default application for this file type.
1434 string A command to be executed by a shell; %s will be replaced
1435 by the path to the file.
1436 sexp A Lisp form which will be evaluated. The file path will
1437 be available in the Lisp variable `file'.
1438 For more examples, see the system specific constants
1439 `org-file-apps-defaults-macosx'
1440 `org-file-apps-defaults-windowsnt'
1441 `org-file-apps-defaults-gnu'."
1442 :group 'org-link-follow
1443 :type '(repeat
1444 (cons (choice :value ""
1445 (string :tag "Extension")
1446 (const :tag "Default for unrecognized files" t)
1447 (const :tag "Remote file" remote)
1448 (const :tag "Links to a directory" directory))
1449 (choice :value ""
1450 (const :tag "Visit with Emacs" emacs)
1451 (const :tag "Use system default" default)
1452 (string :tag "Command")
1453 (sexp :tag "Lisp form")))))
1455 (defcustom org-mhe-search-all-folders nil
1456 "Non-nil means, that the search for the mh-message will be extended to
1457 all folders if the message cannot be found in the folder given in the link.
1458 Searching all folders is very efficient with one of the search engines
1459 supported by MH-E, but will be slow with pick."
1460 :group 'org-link-follow
1461 :type 'boolean)
1463 (defgroup org-remember nil
1464 "Options concerning interaction with remember.el."
1465 :tag "Org Remember"
1466 :group 'org)
1468 (defcustom org-directory "~/org"
1469 "Directory with org files.
1470 This directory will be used as default to prompt for org files.
1471 Used by the hooks for remember.el."
1472 :group 'org-remember
1473 :type 'directory)
1475 (defcustom org-default-notes-file "~/.notes"
1476 "Default target for storing notes.
1477 Used by the hooks for remember.el. This can be a string, or nil to mean
1478 the value of `remember-data-file'.
1479 You can set this on a per-template basis with the variable
1480 `org-remember-templates'."
1481 :group 'org-remember
1482 :type '(choice
1483 (const :tag "Default from remember-data-file" nil)
1484 file))
1486 (defcustom org-remember-store-without-prompt t
1487 "Non-nil means, `C-c C-c' stores remember note without further promts.
1488 In this case, you need `C-u C-c C-c' to get the prompts for
1489 note file and headline.
1490 When this variable is nil, `C-c C-c' give you the prompts, and
1491 `C-u C-c C-c' trigger the fasttrack."
1492 :group 'org-remember
1493 :type 'boolean)
1495 (defcustom org-remember-interactive-interface 'refile
1496 "The interface to be used for interactive filing of remember notes.
1497 This is only used when the interactive mode for selecting a filing
1498 location is used (see the variable `org-remember-store-without-prompt').
1499 Allowed vaues are:
1500 outline The interface shows an outline of the relevant file
1501 and the correct heading is found by moving through
1502 the outline or by searching with incremental search.
1503 outline-path-completion Headlines in the current buffer are offered via
1504 completion.
1505 refile Use the refile interface, and offer headlines,
1506 possibly from different buffers."
1507 :group 'org-remember
1508 :type '(choice
1509 (const :tag "Refile" refile)
1510 (const :tag "Outline" outline)
1511 (const :tag "Outline-path-completion" outline-path-completion)))
1513 (defcustom org-goto-interface 'outline
1514 "The default interface to be used for `org-goto'.
1515 Allowed vaues are:
1516 outline The interface shows an outline of the relevant file
1517 and the correct heading is found by moving through
1518 the outline or by searching with incremental search.
1519 outline-path-completion Headlines in the current buffer are offered via
1520 completion."
1521 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1522 :type '(choice
1523 (const :tag "Outline" outline)
1524 (const :tag "Outline-path-completion" outline-path-completion)))
1526 (defcustom org-remember-default-headline ""
1527 "The headline that should be the default location in the notes file.
1528 When filing remember notes, the cursor will start at that position.
1529 You can set this on a per-template basis with the variable
1530 `org-remember-templates'."
1531 :group 'org-remember
1532 :type 'string)
1534 (defcustom org-remember-templates nil
1535 "Templates for the creation of remember buffers.
1536 When nil, just let remember make the buffer.
1537 When not nil, this is a list of 5-element lists. In each entry, the first
1538 element is the name of the template, which should be a single short word.
1539 The second element is a character, a unique key to select this template.
1540 The third element is the template. The fourth element is optional and can
1541 specify a destination file for remember items created with this template.
1542 The default file is given by `org-default-notes-file'. An optional fifth
1543 element can specify the headline in that file that should be offered
1544 first when the user is asked to file the entry. The default headline is
1545 given in the variable `org-remember-default-headline'.
1547 The template specifies the structure of the remember buffer. It should have
1548 a first line starting with a star, to act as the org-mode headline.
1549 Furthermore, the following %-escapes will be replaced with content:
1551 %^{prompt} Prompt the user for a string and replace this sequence with it.
1552 A default value and a completion table ca be specified like this:
1553 %^{prompt|default|completion2|completion3|...}
1554 %t time stamp, date only
1555 %T time stamp with date and time
1556 %u, %U like the above, but inactive time stamps
1557 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1558 You may define a prompt like %^{Please specify birthday}t
1559 %n user name (taken from `user-full-name')
1560 %a annotation, normally the link created with org-store-link
1561 %i initial content, the region active. If %i is indented,
1562 the entire inserted text will be indented as well.
1563 %c content of the clipboard, or current kill ring head
1564 %^g prompt for tags, with completion on tags in target file
1565 %^G prompt for tags, with completion all tags in all agenda files
1566 %:keyword specific information for certain link types, see below
1567 %[pathname] insert the contents of the file given by `pathname'
1568 %(sexp) evaluate elisp `(sexp)' and replace with the result
1569 %! Store this note immediately after filling the template
1571 %? After completing the template, position cursor here.
1573 Apart from these general escapes, you can access information specific to the
1574 link type that is created. For example, calling `remember' in emails or gnus
1575 will record the author and the subject of the message, which you can access
1576 with %:author and %:subject, respectively. Here is a complete list of what
1577 is recorded for each link type.
1579 Link type | Available information
1580 -------------------+------------------------------------------------------
1581 bbdb | %:type %:name %:company
1582 vm, wl, mh, rmail | %:type %:subject %:message-id
1583 | %:from %:fromname %:fromaddress
1584 | %:to %:toname %:toaddress
1585 | %:fromto (either \"to NAME\" or \"from NAME\")
1586 gnus | %:group, for messages also all email fields
1587 w3, w3m | %:type %:url
1588 info | %:type %:file %:node
1589 calendar | %:type %:date"
1590 :group 'org-remember
1591 :get (lambda (var) ; Make sure all entries have 5 elements
1592 (mapcar (lambda (x)
1593 (if (not (stringp (car x))) (setq x (cons "" x)))
1594 (cond ((= (length x) 4) (append x '("")))
1595 ((= (length x) 3) (append x '("" "")))
1596 (t x)))
1597 (default-value var)))
1598 :type '(repeat
1599 :tag "enabled"
1600 (list :value ("" ?a "\n" nil nil)
1601 (string :tag "Name")
1602 (character :tag "Selection Key")
1603 (string :tag "Template")
1604 (choice
1605 (file :tag "Destination file")
1606 (const :tag "Prompt for file" nil))
1607 (choice
1608 (string :tag "Destination headline")
1609 (const :tag "Selection interface for heading")))))
1611 (defcustom org-reverse-note-order nil
1612 "Non-nil means, store new notes at the beginning of a file or entry.
1613 When nil, new notes will be filed to the end of a file or entry.
1614 This can also be a list with cons cells of regular expressions that
1615 are matched against file names, and values."
1616 :group 'org-remember
1617 :type '(choice
1618 (const :tag "Reverse always" t)
1619 (const :tag "Reverse never" nil)
1620 (repeat :tag "By file name regexp"
1621 (cons regexp boolean))))
1623 (defcustom org-refile-targets nil
1624 "Targets for refiling entries with \\[org-refile].
1625 This is list of cons cells. Each cell contains:
1626 - a specification of the files to be considered, either a list of files,
1627 or a symbol whose function or value fields will be used to retrieve
1628 a file name or a list of file names. Nil means, refile to a different
1629 heading in the current buffer.
1630 - A specification of how to find candidate refile targets. This may be
1631 any of
1632 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1633 This tag has to be present in all target headlines, inheritance will
1634 not be considered.
1635 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1636 todo keyword.
1637 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1638 headlines that are refiling targets.
1639 - a cons cell (:level . N). Any headline of level N is considered a target.
1640 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1641 ;; FIXME: what if there are a var and func with same name???
1642 :group 'org-remember
1643 :type '(repeat
1644 (cons
1645 (choice :value org-agenda-files
1646 (const :tag "All agenda files" org-agenda-files)
1647 (const :tag "Current buffer" nil)
1648 (function) (variable) (file))
1649 (choice :tag "Identify target headline by"
1650 (cons :tag "Specific tag" (const :tag) (string))
1651 (cons :tag "TODO keyword" (const :todo) (string))
1652 (cons :tag "Regular expression" (const :regexp) (regexp))
1653 (cons :tag "Level number" (const :level) (integer))
1654 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1656 (defcustom org-refile-use-outline-path nil
1657 "Non-nil means, provide refile targets as paths.
1658 So a level 3 headline will be available as level1/level2/level3.
1659 When the value is `file', also include the file name (without directory)
1660 into the path. When `full-file-path', include the full file path."
1661 :group 'org-remember
1662 :type '(choice
1663 (const :tag "Not" nil)
1664 (const :tag "Yes" t)
1665 (const :tag "Start with file name" file)
1666 (const :tag "Start with full file path" full-file-path)))
1668 (defgroup org-todo nil
1669 "Options concerning TODO items in Org-mode."
1670 :tag "Org TODO"
1671 :group 'org)
1673 (defgroup org-progress nil
1674 "Options concerning Progress logging in Org-mode."
1675 :tag "Org Progress"
1676 :group 'org-time)
1678 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1679 "List of TODO entry keyword sequences and their interpretation.
1680 \\<org-mode-map>This is a list of sequences.
1682 Each sequence starts with a symbol, either `sequence' or `type',
1683 indicating if the keywords should be interpreted as a sequence of
1684 action steps, or as different types of TODO items. The first
1685 keywords are states requiring action - these states will select a headline
1686 for inclusion into the global TODO list Org-mode produces. If one of
1687 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1688 signify that no further action is necessary. If \"|\" is not found,
1689 the last keyword is treated as the only DONE state of the sequence.
1691 The command \\[org-todo] cycles an entry through these states, and one
1692 additional state where no keyword is present. For details about this
1693 cycling, see the manual.
1695 TODO keywords and interpretation can also be set on a per-file basis with
1696 the special #+SEQ_TODO and #+TYP_TODO lines.
1698 Each keyword can optionally specify a character for fast state selection
1699 \(in combination with the variable `org-use-fast-todo-selection')
1700 and specifiers for state change logging, using the same syntax
1701 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1702 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1703 indicates to record a time stamp each time this state is selected.
1704 \"WAIT(w@)\" says that the user should in addition be prompted for a
1705 note, and \"WAIT(w@/@)\" says that a note should be taken both when
1706 entering and when leaving this state.
1708 For backward compatibility, this variable may also be just a list
1709 of keywords - in this case the interptetation (sequence or type) will be
1710 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1711 :group 'org-todo
1712 :group 'org-keywords
1713 :type '(choice
1714 (repeat :tag "Old syntax, just keywords"
1715 (string :tag "Keyword"))
1716 (repeat :tag "New syntax"
1717 (cons
1718 (choice
1719 :tag "Interpretation"
1720 (const :tag "Sequence (cycling hits every state)" sequence)
1721 (const :tag "Type (cycling directly to DONE)" type))
1722 (repeat
1723 (string :tag "Keyword"))))))
1725 (defvar org-todo-keywords-1 nil
1726 "All TODO and DONE keywords active in a buffer.")
1727 (make-variable-buffer-local 'org-todo-keywords-1)
1728 (defvar org-todo-keywords-for-agenda nil)
1729 (defvar org-done-keywords-for-agenda nil)
1730 (defvar org-not-done-keywords nil)
1731 (make-variable-buffer-local 'org-not-done-keywords)
1732 (defvar org-done-keywords nil)
1733 (make-variable-buffer-local 'org-done-keywords)
1734 (defvar org-todo-heads nil)
1735 (make-variable-buffer-local 'org-todo-heads)
1736 (defvar org-todo-sets nil)
1737 (make-variable-buffer-local 'org-todo-sets)
1738 (defvar org-todo-log-states nil)
1739 (make-variable-buffer-local 'org-todo-log-states)
1740 (defvar org-todo-kwd-alist nil)
1741 (make-variable-buffer-local 'org-todo-kwd-alist)
1742 (defvar org-todo-key-alist nil)
1743 (make-variable-buffer-local 'org-todo-key-alist)
1744 (defvar org-todo-key-trigger nil)
1745 (make-variable-buffer-local 'org-todo-key-trigger)
1747 (defcustom org-todo-interpretation 'sequence
1748 "Controls how TODO keywords are interpreted.
1749 This variable is in principle obsolete and is only used for
1750 backward compatibility, if the interpretation of todo keywords is
1751 not given already in `org-todo-keywords'. See that variable for
1752 more information."
1753 :group 'org-todo
1754 :group 'org-keywords
1755 :type '(choice (const sequence)
1756 (const type)))
1758 (defcustom org-use-fast-todo-selection 'prefix
1759 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1760 This variable describes if and under what circumstances the cycling
1761 mechanism for TODO keywords will be replaced by a single-key, direct
1762 selection scheme.
1764 When nil, fast selection is never used.
1766 When the symbol `prefix', it will be used when `org-todo' is called with
1767 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1768 in an agenda buffer.
1770 When t, fast selection is used by default. In this case, the prefix
1771 argument forces cycling instead.
1773 In all cases, the special interface is only used if access keys have actually
1774 been assigned by the user, i.e. if keywords in the configuration are followed
1775 by a letter in parenthesis, like TODO(t)."
1776 :group 'org-todo
1777 :type '(choice
1778 (const :tag "Never" nil)
1779 (const :tag "By default" t)
1780 (const :tag "Only with C-u C-c C-t" prefix)))
1782 (defcustom org-after-todo-state-change-hook nil
1783 "Hook which is run after the state of a TODO item was changed.
1784 The new state (a string with a TODO keyword, or nil) is available in the
1785 Lisp variable `state'."
1786 :group 'org-todo
1787 :type 'hook)
1789 (defcustom org-log-done nil
1790 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1791 When equal to the list (done), also prompt for a closing note.
1792 This can also be configured on a per-file basis by adding one of
1793 the following lines anywhere in the buffer:
1795 #+STARTUP: logdone
1796 #+STARTUP: lognotedone
1797 #+STARTUP: nologdone"
1798 :group 'org-todo
1799 :group 'org-progress
1800 :type '(choice
1801 (const :tag "No logging" nil)
1802 (const :tag "Record CLOSED timestamp" time)
1803 (const :tag "Record CLOSED timestamp with closing note." note)))
1805 ;; Normalize old uses of org-log-done.
1806 (cond
1807 ((eq org-log-done t) (setq org-log-done 'time))
1808 ((and (listp org-log-done) (memq 'done org-log-done))
1809 (setq org-log-done 'note)))
1811 ;; FIXME: document
1812 (defcustom org-log-note-clock-out nil
1813 "Non-nil means, recored a note when clocking out of an item.
1814 This can also be configured on a per-file basis by adding one of
1815 the following lines anywhere in the buffer:
1817 #+STARTUP: lognoteclock-out
1818 #+STARTUP: nolognoteclock-out"
1819 :group 'org-todo
1820 :group 'org-progress
1821 :type 'boolean)
1823 (defcustom org-log-done-with-time t
1824 "Non-nil means, the CLOSED time stamp will contain date and time.
1825 When nil, only the date will be recorded."
1826 :group 'org-progress
1827 :type 'boolean)
1829 (defcustom org-log-note-headings
1830 '((done . "CLOSING NOTE %t")
1831 (state . "State %-12s %t")
1832 (clock-out . ""))
1833 "Headings for notes added when clocking out or closing TODO items.
1834 The value is an alist, with the car being a symbol indicating the note
1835 context, and the cdr is the heading to be used. The heading may also be the
1836 empty string.
1837 %t in the heading will be replaced by a time stamp.
1838 %s will be replaced by the new TODO state, in double quotes.
1839 %u will be replaced by the user name.
1840 %U will be replaced by the full user name."
1841 :group 'org-todo
1842 :group 'org-progress
1843 :type '(list :greedy t
1844 (cons (const :tag "Heading when closing an item" done) string)
1845 (cons (const :tag
1846 "Heading when changing todo state (todo sequence only)"
1847 state) string)
1848 (cons (const :tag "Heading when clocking out" clock-out) string)))
1850 (defcustom org-log-states-order-reversed t
1851 "Non-nil means, the latest state change note will be directly after heading.
1852 When nil, the notes will be orderer according to time."
1853 :group 'org-todo
1854 :group 'org-progress
1855 :type 'boolean)
1857 (defcustom org-log-repeat 'time
1858 "Non-nil means, record moving through the DONE state when triggering repeat.
1859 An auto-repeating tasks is immediately switched back to TODO when marked
1860 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1861 the TODO keyword definition, or recording a cloing note by setting
1862 `org-log-done', there will be no record of the task moving trhough DONE.
1863 This variable forces taking a note anyway. Possible values are:
1865 nil Don't force a record
1866 time Record a time stamp
1867 note Record a note
1869 This option can also be set with on a per-file-basis with
1871 #+STARTUP: logrepeat
1872 #+STARTUP: lognoterepeat
1873 #+STARTUP: nologrepeat
1875 You can have local logging settings for a subtree by setting the LOGGING
1876 property to one or more of these keywords."
1877 :group 'org-todo
1878 :group 'org-progress
1879 :type '(choice
1880 (const :tag "Don't force a record" nil)
1881 (const :tag "Force recording the DONE state" time)
1882 (const :tag "Force recording a note with the DONE state" note)))
1884 (defcustom org-clock-into-drawer 2
1885 "Should clocking info be wrapped into a drawer?
1886 When t, clocking info will always be inserted into a :CLOCK: drawer.
1887 If necessary, the drawer will be created.
1888 When nil, the drawer will not be created, but used when present.
1889 When an integer and the number of clocking entries in an item
1890 reaches or exceeds this number, a drawer will be created."
1891 :group 'org-todo
1892 :group 'org-progress
1893 :type '(choice
1894 (const :tag "Always" t)
1895 (const :tag "Only when drawer exists" nil)
1896 (integer :tag "When at least N clock entries")))
1898 (defcustom org-clock-out-when-done t
1899 "When t, the clock will be stopped when the relevant entry is marked DONE.
1900 Nil means, clock will keep running until stopped explicitly with
1901 `C-c C-x C-o', or until the clock is started in a different item."
1902 :group 'org-progress
1903 :type 'boolean)
1905 (defcustom org-clock-in-switch-to-state nil
1906 "Set task to a special todo state while clocking it.
1907 The value should be the state to which the entry should be switched."
1908 :group 'org-progress
1909 :group 'org-todo
1910 :type '(choice
1911 (const :tag "Don't force a state" nil)
1912 (string :tag "State")))
1914 (defgroup org-priorities nil
1915 "Priorities in Org-mode."
1916 :tag "Org Priorities"
1917 :group 'org-todo)
1919 (defcustom org-highest-priority ?A
1920 "The highest priority of TODO items. A character like ?A, ?B etc.
1921 Must have a smaller ASCII number than `org-lowest-priority'."
1922 :group 'org-priorities
1923 :type 'character)
1925 (defcustom org-lowest-priority ?C
1926 "The lowest priority of TODO items. A character like ?A, ?B etc.
1927 Must have a larger ASCII number than `org-highest-priority'."
1928 :group 'org-priorities
1929 :type 'character)
1931 (defcustom org-default-priority ?B
1932 "The default priority of TODO items.
1933 This is the priority an item get if no explicit priority is given."
1934 :group 'org-priorities
1935 :type 'character)
1937 (defcustom org-priority-start-cycle-with-default t
1938 "Non-nil means, start with default priority when starting to cycle.
1939 When this is nil, the first step in the cycle will be (depending on the
1940 command used) one higher or lower that the default priority."
1941 :group 'org-priorities
1942 :type 'boolean)
1944 (defgroup org-time nil
1945 "Options concerning time stamps and deadlines in Org-mode."
1946 :tag "Org Time"
1947 :group 'org)
1949 (defcustom org-insert-labeled-timestamps-at-point nil
1950 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1951 When nil, these labeled time stamps are forces into the second line of an
1952 entry, just after the headline. When scheduling from the global TODO list,
1953 the time stamp will always be forced into the second line."
1954 :group 'org-time
1955 :type 'boolean)
1957 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1958 "Formats for `format-time-string' which are used for time stamps.
1959 It is not recommended to change this constant.")
1961 (defcustom org-time-stamp-rounding-minutes '(0 5)
1962 "Number of minutes to round time stamps to.
1963 These are two values, the first applies when first creating a time stamp.
1964 The second applies when changing it with the commands `S-up' and `S-down'.
1965 When changing the time stamp, this means that it will change in steps
1966 of N minues, as given by the second value.
1968 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1969 numbers should be factors of 60, so for example 5, 10, 15.
1971 When this is larger than 1, you can still force an exact time-stamp by using
1972 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1973 and by using a prefix arg to `S-up/down' to specify the exact number
1974 of minutes to shift."
1975 :group 'org-time
1976 :type '(list
1977 (integer :tag "when inserting times")
1978 (integer :tag "when modifying times")))
1980 (defcustom org-display-custom-times nil
1981 "Non-nil means, overlay custom formats over all time stamps.
1982 The formats are defined through the variable `org-time-stamp-custom-formats'.
1983 To turn this on on a per-file basis, insert anywhere in the file:
1984 #+STARTUP: customtime"
1985 :group 'org-time
1986 :set 'set-default
1987 :type 'sexp)
1988 (make-variable-buffer-local 'org-display-custom-times)
1990 (defcustom org-time-stamp-custom-formats
1991 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1992 "Custom formats for time stamps. See `format-time-string' for the syntax.
1993 These are overlayed over the default ISO format if the variable
1994 `org-display-custom-times' is set. Time like %H:%M should be at the
1995 end of the second format."
1996 :group 'org-time
1997 :type 'sexp)
1999 (defun org-time-stamp-format (&optional long inactive)
2000 "Get the right format for a time string."
2001 (let ((f (if long (cdr org-time-stamp-formats)
2002 (car org-time-stamp-formats))))
2003 (if inactive
2004 (concat "[" (substring f 1 -1) "]")
2005 f)))
2007 (defcustom org-read-date-prefer-future t
2008 "Non-nil means, assume future for incomplete date input from user.
2009 This affects the following situations:
2010 1. The user gives a day, but no month.
2011 For example, if today is the 15th, and you enter \"3\", Org-mode will
2012 read this as the third of *next* month. However, if you enter \"17\",
2013 it will be considered as *this* month.
2014 2. The user gives a month but not a year.
2015 For example, if it is april and you enter \"feb 2\", this will be read
2016 as feb 2, *next* year. \"May 5\", however, will be this year.
2018 When this option is nil, the current month and year will always be used
2019 as defaults."
2020 :group 'org-time
2021 :type 'boolean)
2023 (defcustom org-read-date-display-live t
2024 "Non-nil means, display current interpretation of date prompt live.
2025 This display will be in an overlay, in the minibuffer."
2026 :group 'org-time
2027 :type 'boolean)
2029 (defcustom org-read-date-popup-calendar t
2030 "Non-nil means, pop up a calendar when prompting for a date.
2031 In the calendar, the date can be selected with mouse-1. However, the
2032 minibuffer will also be active, and you can simply enter the date as well.
2033 When nil, only the minibuffer will be available."
2034 :group 'org-time
2035 :type 'boolean)
2036 (if (fboundp 'defvaralias)
2037 (defvaralias 'org-popup-calendar-for-date-prompt
2038 'org-read-date-popup-calendar))
2040 (defcustom org-extend-today-until 0
2041 "The hour when your day really ends.
2042 This has influence for the following applications:
2043 - When switching the agenda to \"today\". It it is still earlier than
2044 the time given here, the day recognized as TODAY is actually yesterday.
2045 - When a date is read from the user and it is still before the time given
2046 here, the current date and time will be assumed to be yesterday, 23:59.
2048 FIXME:
2049 IMPORTANT: This is still a very experimental feature, it may disappear
2050 again or it may be extended to mean more things."
2051 :group 'org-time
2052 :type 'number)
2054 (defcustom org-edit-timestamp-down-means-later nil
2055 "Non-nil means, S-down will increase the time in a time stamp.
2056 When nil, S-up will increase."
2057 :group 'org-time
2058 :type 'boolean)
2060 (defcustom org-calendar-follow-timestamp-change t
2061 "Non-nil means, make the calendar window follow timestamp changes.
2062 When a timestamp is modified and the calendar window is visible, it will be
2063 moved to the new date."
2064 :group 'org-time
2065 :type 'boolean)
2067 (defcustom org-clock-heading-function nil
2068 "When non-nil, should be a function to create `org-clock-heading'.
2069 This is the string shown in the mode line when a clock is running.
2070 The function is called with point at the beginning of the headline."
2071 :group 'org-time ; FIXME: Should we have a separate group????
2072 :type 'function)
2074 (defgroup org-tags nil
2075 "Options concerning tags in Org-mode."
2076 :tag "Org Tags"
2077 :group 'org)
2079 (defcustom org-tag-alist nil
2080 "List of tags allowed in Org-mode files.
2081 When this list is nil, Org-mode will base TAG input on what is already in the
2082 buffer.
2083 The value of this variable is an alist, the car of each entry must be a
2084 keyword as a string, the cdr may be a character that is used to select
2085 that tag through the fast-tag-selection interface.
2086 See the manual for details."
2087 :group 'org-tags
2088 :type '(repeat
2089 (choice
2090 (cons (string :tag "Tag name")
2091 (character :tag "Access char"))
2092 (const :tag "Start radio group" (:startgroup))
2093 (const :tag "End radio group" (:endgroup)))))
2095 (defcustom org-use-fast-tag-selection 'auto
2096 "Non-nil means, use fast tag selection scheme.
2097 This is a special interface to select and deselect tags with single keys.
2098 When nil, fast selection is never used.
2099 When the symbol `auto', fast selection is used if and only if selection
2100 characters for tags have been configured, either through the variable
2101 `org-tag-alist' or through a #+TAGS line in the buffer.
2102 When t, fast selection is always used and selection keys are assigned
2103 automatically if necessary."
2104 :group 'org-tags
2105 :type '(choice
2106 (const :tag "Always" t)
2107 (const :tag "Never" nil)
2108 (const :tag "When selection characters are configured" 'auto)))
2110 (defcustom org-fast-tag-selection-single-key nil
2111 "Non-nil means, fast tag selection exits after first change.
2112 When nil, you have to press RET to exit it.
2113 During fast tag selection, you can toggle this flag with `C-c'.
2114 This variable can also have the value `expert'. In this case, the window
2115 displaying the tags menu is not even shown, until you press C-c again."
2116 :group 'org-tags
2117 :type '(choice
2118 (const :tag "No" nil)
2119 (const :tag "Yes" t)
2120 (const :tag "Expert" expert)))
2122 (defvar org-fast-tag-selection-include-todo nil
2123 "Non-nil means, fast tags selection interface will also offer TODO states.
2124 This is an undocumented feature, you should not rely on it.")
2126 (defcustom org-tags-column -80
2127 "The column to which tags should be indented in a headline.
2128 If this number is positive, it specifies the column. If it is negative,
2129 it means that the tags should be flushright to that column. For example,
2130 -80 works well for a normal 80 character screen."
2131 :group 'org-tags
2132 :type 'integer)
2134 (defcustom org-auto-align-tags t
2135 "Non-nil means, realign tags after pro/demotion of TODO state change.
2136 These operations change the length of a headline and therefore shift
2137 the tags around. With this options turned on, after each such operation
2138 the tags are again aligned to `org-tags-column'."
2139 :group 'org-tags
2140 :type 'boolean)
2142 (defcustom org-use-tag-inheritance t
2143 "Non-nil means, tags in levels apply also for sublevels.
2144 When nil, only the tags directly given in a specific line apply there.
2145 If you turn off this option, you very likely want to turn on the
2146 companion option `org-tags-match-list-sublevels'."
2147 :group 'org-tags
2148 :type 'boolean)
2150 (defcustom org-tags-match-list-sublevels nil
2151 "Non-nil means list also sublevels of headlines matching tag search.
2152 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2153 the sublevels of a headline matching a tag search often also match
2154 the same search. Listing all of them can create very long lists.
2155 Setting this variable to nil causes subtrees of a match to be skipped.
2156 This option is off by default, because inheritance in on. If you turn
2157 inheritance off, you very likely want to turn this option on.
2159 As a special case, if the tag search is restricted to TODO items, the
2160 value of this variable is ignored and sublevels are always checked, to
2161 make sure all corresponding TODO items find their way into the list."
2162 :group 'org-tags
2163 :type 'boolean)
2165 (defvar org-tags-history nil
2166 "History of minibuffer reads for tags.")
2167 (defvar org-last-tags-completion-table nil
2168 "The last used completion table for tags.")
2169 (defvar org-after-tags-change-hook nil
2170 "Hook that is run after the tags in a line have changed.")
2172 (defgroup org-properties nil
2173 "Options concerning properties in Org-mode."
2174 :tag "Org Properties"
2175 :group 'org)
2177 (defcustom org-property-format "%-10s %s"
2178 "How property key/value pairs should be formatted by `indent-line'.
2179 When `indent-line' hits a property definition, it will format the line
2180 according to this format, mainly to make sure that the values are
2181 lined-up with respect to each other."
2182 :group 'org-properties
2183 :type 'string)
2185 (defcustom org-use-property-inheritance nil
2186 "Non-nil means, properties apply also for sublevels.
2187 This setting is only relevant during property searches, not when querying
2188 an entry with `org-entry-get'. To retrieve a property with inheritance,
2189 you need to call `org-entry-get' with the inheritance flag.
2190 Turning this on can cause significant overhead when doing a search, so
2191 this is turned off by default.
2192 When nil, only the properties directly given in the current entry count.
2193 The value may also be a list of properties that shouldhave inheritance.
2195 However, note that some special properties use inheritance under special
2196 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2197 and the properties ending in \"_ALL\" when they are used as descriptor
2198 for valid values of a property."
2199 :group 'org-properties
2200 :type '(choice
2201 (const :tag "Not" nil)
2202 (const :tag "Always" nil)
2203 (repeat :tag "Specific properties" (string :tag "Property"))))
2205 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2206 "The default column format, if no other format has been defined.
2207 This variable can be set on the per-file basis by inserting a line
2209 #+COLUMNS: %25ITEM ....."
2210 :group 'org-properties
2211 :type 'string)
2213 (defcustom org-global-properties nil
2214 "List of property/value pairs that can be inherited by any entry.
2215 You can set buffer-local values for this by adding lines like
2217 #+PROPERTY: NAME VALUE"
2218 :group 'org-properties
2219 :type '(repeat
2220 (cons (string :tag "Property")
2221 (string :tag "Value"))))
2223 (defvar org-local-properties nil
2224 "List of property/value pairs that can be inherited by any entry.
2225 Valid for the current buffer.
2226 This variable is populated from #+PROPERTY lines.")
2228 (defgroup org-agenda nil
2229 "Options concerning agenda views in Org-mode."
2230 :tag "Org Agenda"
2231 :group 'org)
2233 (defvar org-category nil
2234 "Variable used by org files to set a category for agenda display.
2235 Such files should use a file variable to set it, for example
2237 # -*- mode: org; org-category: \"ELisp\"
2239 or contain a special line
2241 #+CATEGORY: ELisp
2243 If the file does not specify a category, then file's base name
2244 is used instead.")
2245 (make-variable-buffer-local 'org-category)
2247 (defcustom org-agenda-files nil
2248 "The files to be used for agenda display.
2249 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2250 \\[org-remove-file]. You can also use customize to edit the list.
2252 If an entry is a directory, all files in that directory that are matched by
2253 `org-agenda-file-regexp' will be part of the file list.
2255 If the value of the variable is not a list but a single file name, then
2256 the list of agenda files is actually stored and maintained in that file, one
2257 agenda file per line."
2258 :group 'org-agenda
2259 :type '(choice
2260 (repeat :tag "List of files and directories" file)
2261 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2263 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2264 "Regular expression to match files for `org-agenda-files'.
2265 If any element in the list in that variable contains a directory instead
2266 of a normal file, all files in that directory that are matched by this
2267 regular expression will be included."
2268 :group 'org-agenda
2269 :type 'regexp)
2271 (defcustom org-agenda-skip-unavailable-files nil
2272 "t means to just skip non-reachable files in `org-agenda-files'.
2273 Nil means to remove them, after a query, from the list."
2274 :group 'org-agenda
2275 :type 'boolean)
2277 (defcustom org-agenda-text-search-extra-files nil
2278 "List of extra files to be searched by text search commands.
2279 These files will be search in addition to the agenda files bu the
2280 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2281 Note that these files will only be searched for text search commands,
2282 not for the other agenda views like todo lists, tag earches or the weekly
2283 agenda. This variable is intended to list notes and possibly archive files
2284 that should also be searched by these two commands."
2285 :group 'org-agenda
2286 :type '(repeat file))
2288 (if (fboundp 'defvaralias)
2289 (defvaralias 'org-agenda-multi-occur-extra-files
2290 'org-agenda-text-search-extra-files))
2292 (defcustom org-agenda-confirm-kill 1
2293 "When set, remote killing from the agenda buffer needs confirmation.
2294 When t, a confirmation is always needed. When a number N, confirmation is
2295 only needed when the text to be killed contains more than N non-white lines."
2296 :group 'org-agenda
2297 :type '(choice
2298 (const :tag "Never" nil)
2299 (const :tag "Always" t)
2300 (number :tag "When more than N lines")))
2302 (defcustom org-calendar-to-agenda-key [?c]
2303 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2304 The command `org-calendar-goto-agenda' will be bound to this key. The
2305 default is the character `c' because then `c' can be used to switch back and
2306 forth between agenda and calendar."
2307 :group 'org-agenda
2308 :type 'sexp)
2310 (defcustom org-agenda-compact-blocks nil
2311 "Non-nil means, make the block agenda more compact.
2312 This is done by leaving out unnecessary lines."
2313 :group 'org-agenda
2314 :type nil)
2316 (defgroup org-agenda-export nil
2317 "Options concerning exporting agenda views in Org-mode."
2318 :tag "Org Agenda Export"
2319 :group 'org-agenda)
2321 (defcustom org-agenda-with-colors t
2322 "Non-nil means, use colors in agenda views."
2323 :group 'org-agenda-export
2324 :type 'boolean)
2326 (defcustom org-agenda-exporter-settings nil
2327 "Alist of variable/value pairs that should be active during agenda export.
2328 This is a good place to set uptions for ps-print and for htmlize."
2329 :group 'org-agenda-export
2330 :type '(repeat
2331 (list
2332 (variable)
2333 (sexp :tag "Value"))))
2335 (defcustom org-agenda-export-html-style ""
2336 "The style specification for exported HTML Agenda files.
2337 If this variable contains a string, it will replace the default <style>
2338 section as produced by `htmlize'.
2339 Since there are different ways of setting style information, this variable
2340 needs to contain the full HTML structure to provide a style, including the
2341 surrounding HTML tags. The style specifications should include definitions
2342 the fonts used by the agenda, here is an example:
2344 <style type=\"text/css\">
2345 p { font-weight: normal; color: gray; }
2346 .org-agenda-structure {
2347 font-size: 110%;
2348 color: #003399;
2349 font-weight: 600;
2351 .org-todo {
2352 color: #cc6666;Week-agenda:
2353 font-weight: bold;
2355 .org-done {
2356 color: #339933;
2358 .title { text-align: center; }
2359 .todo, .deadline { color: red; }
2360 .done { color: green; }
2361 </style>
2363 or, if you want to keep the style in a file,
2365 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2367 As the value of this option simply gets inserted into the HTML <head> header,
2368 you can \"misuse\" it to also add other text to the header. However,
2369 <style>...</style> is required, if not present the variable will be ignored."
2370 :group 'org-agenda-export
2371 :group 'org-export-html
2372 :type 'string)
2374 (defgroup org-agenda-custom-commands nil
2375 "Options concerning agenda views in Org-mode."
2376 :tag "Org Agenda Custom Commands"
2377 :group 'org-agenda)
2379 (defcustom org-agenda-custom-commands nil
2380 "Custom commands for the agenda.
2381 These commands will be offered on the splash screen displayed by the
2382 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2384 (key desc type match options files)
2386 key The key (one or more characters as a string) to be associated
2387 with the command.
2388 desc A description of the commend, when omitted or nil, a default
2389 description is built using MATCH.
2390 type The command type, any of the following symbols:
2391 agenda The daily/weekly agenda.
2392 todo Entries with a specific TODO keyword, in all agenda files.
2393 search Entries containing search words entry or headline.
2394 tags Tags/Property/TODO match in all agenda files.
2395 tags-todo Tags/P/T match in all agenda files, TODO entries only.
2396 todo-tree Sparse tree of specific TODO keyword in *current* file.
2397 tags-tree Sparse tree with all tags matches in *current* file.
2398 occur-tree Occur sparse tree for *current* file.
2399 ... A user-defined function.
2400 match What to search for:
2401 - a single keyword for TODO keyword searches
2402 - a tags match expression for tags searches
2403 - a regular expression for occur searches
2404 options A list of option settings, similar to that in a let form, so like
2405 this: ((opt1 val1) (opt2 val2) ...)
2406 files A list of files file to write the produced agenda buffer to
2407 with the command `org-store-agenda-views'.
2408 If a file name ends in \".html\", an HTML version of the buffer
2409 is written out. If it ends in \".ps\", a postscript version is
2410 produced. Otherwide, only the plain text is written to the file.
2412 You can also define a set of commands, to create a composite agenda buffer.
2413 In this case, an entry looks like this:
2415 (key desc (cmd1 cmd2 ...) general-options file)
2417 where
2419 desc A description string to be displayed in the dispatcher menu.
2420 cmd An agenda command, similar to the above. However, tree commands
2421 are no allowed, but instead you can get agenda and global todo list.
2422 So valid commands for a set are:
2423 (agenda)
2424 (alltodo)
2425 (stuck)
2426 (todo \"match\" options files)
2427 (search \"match\" options files)
2428 (tags \"match\" options files)
2429 (tags-todo \"match\" options files)
2431 Each command can carry a list of options, and another set of options can be
2432 given for the whole set of commands. Individual command options take
2433 precedence over the general options.
2435 When using several characters as key to a command, the first characters
2436 are prefix commands. For the dispatcher to display useful information, you
2437 should provide a description for the prefix, like
2439 (setq org-agenda-custom-commands
2440 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2441 (\"hl\" tags \"+HOME+Lisa\")
2442 (\"hp\" tags \"+HOME+Peter\")
2443 (\"hk\" tags \"+HOME+Kim\")))"
2444 :group 'org-agenda-custom-commands
2445 :type '(repeat
2446 (choice :value ("a" "" tags "" nil)
2447 (list :tag "Single command"
2448 (string :tag "Access Key(s) ")
2449 (option (string :tag "Description"))
2450 (choice
2451 (const :tag "Agenda" agenda)
2452 (const :tag "TODO list" alltodo)
2453 (const :tag "Search words" search)
2454 (const :tag "Stuck projects" stuck)
2455 (const :tag "Tags search (all agenda files)" tags)
2456 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2457 (const :tag "TODO keyword search (all agenda files)" todo)
2458 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2459 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2460 (const :tag "Occur tree (current buffer)" occur-tree)
2461 (sexp :tag "Other, user-defined function"))
2462 (string :tag "Match")
2463 (repeat :tag "Local options"
2464 (list (variable :tag "Option") (sexp :tag "Value")))
2465 (option (repeat :tag "Export" (file :tag "Export to"))))
2466 (list :tag "Command series, all agenda files"
2467 (string :tag "Access Key(s)")
2468 (string :tag "Description ")
2469 (repeat
2470 (choice
2471 (const :tag "Agenda" (agenda))
2472 (const :tag "TODO list" (alltodo))
2473 (list :tag "Search words"
2474 (const :format "" search)
2475 (string :tag "Match")
2476 (repeat :tag "Local options"
2477 (list (variable :tag "Option")
2478 (sexp :tag "Value"))))
2479 (const :tag "Stuck projects" (stuck))
2480 (list :tag "Tags search"
2481 (const :format "" tags)
2482 (string :tag "Match")
2483 (repeat :tag "Local options"
2484 (list (variable :tag "Option")
2485 (sexp :tag "Value"))))
2487 (list :tag "Tags search, TODO entries only"
2488 (const :format "" tags-todo)
2489 (string :tag "Match")
2490 (repeat :tag "Local options"
2491 (list (variable :tag "Option")
2492 (sexp :tag "Value"))))
2494 (list :tag "TODO keyword search"
2495 (const :format "" todo)
2496 (string :tag "Match")
2497 (repeat :tag "Local options"
2498 (list (variable :tag "Option")
2499 (sexp :tag "Value"))))
2501 (list :tag "Other, user-defined function"
2502 (symbol :tag "function")
2503 (string :tag "Match")
2504 (repeat :tag "Local options"
2505 (list (variable :tag "Option")
2506 (sexp :tag "Value"))))))
2508 (repeat :tag "General options"
2509 (list (variable :tag "Option")
2510 (sexp :tag "Value")))
2511 (option (repeat :tag "Export" (file :tag "Export to"))))
2512 (cons :tag "Prefix key documentation"
2513 (string :tag "Access Key(s)")
2514 (string :tag "Description ")))))
2516 (defcustom org-agenda-query-register ?o
2517 "The register holding the current query string.
2518 The prupose of this is that if you construct a query string interactively,
2519 you can then use it to define a custom command."
2520 :group 'org-agenda-custom-commands
2521 :type 'character)
2523 (defcustom org-stuck-projects
2524 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2525 "How to identify stuck projects.
2526 This is a list of four items:
2527 1. A tags/todo matcher string that is used to identify a project.
2528 The entire tree below a headline matched by this is considered one project.
2529 2. A list of TODO keywords identifying non-stuck projects.
2530 If the project subtree contains any headline with one of these todo
2531 keywords, the project is considered to be not stuck. If you specify
2532 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2533 3. A list of tags identifying non-stuck projects.
2534 If the project subtree contains any headline with one of these tags,
2535 the project is considered to be not stuck. If you specify \"*\" as
2536 a tag, any tag will mark the project unstuck.
2537 4. An arbitrary regular expression matching non-stuck projects.
2539 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2540 or `C-c a #' to produce the list."
2541 :group 'org-agenda-custom-commands
2542 :type '(list
2543 (string :tag "Tags/TODO match to identify a project")
2544 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2545 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2546 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2549 (defgroup org-agenda-skip nil
2550 "Options concerning skipping parts of agenda files."
2551 :tag "Org Agenda Skip"
2552 :group 'org-agenda)
2554 (defcustom org-agenda-todo-list-sublevels t
2555 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2556 When nil, the sublevels of a TODO entry are not checked, resulting in
2557 potentially much shorter TODO lists."
2558 :group 'org-agenda-skip
2559 :group 'org-todo
2560 :type 'boolean)
2562 (defcustom org-agenda-todo-ignore-with-date nil
2563 "Non-nil means, don't show entries with a date in the global todo list.
2564 You can use this if you prefer to mark mere appointments with a TODO keyword,
2565 but don't want them to show up in the TODO list.
2566 When this is set, it also covers deadlines and scheduled items, the settings
2567 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2568 will be ignored."
2569 :group 'org-agenda-skip
2570 :group 'org-todo
2571 :type 'boolean)
2573 (defcustom org-agenda-todo-ignore-scheduled nil
2574 "Non-nil means, don't show scheduled entries in the global todo list.
2575 The idea behind this is that by scheduling it, you have already taken care
2576 of this item.
2577 See also `org-agenda-todo-ignore-with-date'."
2578 :group 'org-agenda-skip
2579 :group 'org-todo
2580 :type 'boolean)
2582 (defcustom org-agenda-todo-ignore-deadlines nil
2583 "Non-nil means, don't show near deadline entries in the global todo list.
2584 Near means closer than `org-deadline-warning-days' days.
2585 The idea behind this is that such items will appear in the agenda anyway.
2586 See also `org-agenda-todo-ignore-with-date'."
2587 :group 'org-agenda-skip
2588 :group 'org-todo
2589 :type 'boolean)
2591 (defcustom org-agenda-skip-scheduled-if-done nil
2592 "Non-nil means don't show scheduled items in agenda when they are done.
2593 This is relevant for the daily/weekly agenda, not for the TODO list. And
2594 it applies only to the actual date of the scheduling. Warnings about
2595 an item with a past scheduling dates are always turned off when the item
2596 is DONE."
2597 :group 'org-agenda-skip
2598 :type 'boolean)
2600 (defcustom org-agenda-skip-deadline-if-done nil
2601 "Non-nil means don't show deadines when the corresponding item is done.
2602 When nil, the deadline is still shown and should give you a happy feeling.
2603 This is relevant for the daily/weekly agenda. And it applied only to the
2604 actualy date of the deadline. Warnings about approching and past-due
2605 deadlines are always turned off when the item is DONE."
2606 :group 'org-agenda-skip
2607 :type 'boolean)
2609 (defcustom org-agenda-skip-timestamp-if-done nil
2610 "Non-nil means don't select item by timestamp or -range if it is DONE."
2611 :group 'org-agenda-skip
2612 :type 'boolean)
2614 (defcustom org-timeline-show-empty-dates 3
2615 "Non-nil means, `org-timeline' also shows dates without an entry.
2616 When nil, only the days which actually have entries are shown.
2617 When t, all days between the first and the last date are shown.
2618 When an integer, show also empty dates, but if there is a gap of more than
2619 N days, just insert a special line indicating the size of the gap."
2620 :group 'org-agenda-skip
2621 :type '(choice
2622 (const :tag "None" nil)
2623 (const :tag "All" t)
2624 (number :tag "at most")))
2627 (defgroup org-agenda-startup nil
2628 "Options concerning initial settings in the Agenda in Org Mode."
2629 :tag "Org Agenda Startup"
2630 :group 'org-agenda)
2632 (defcustom org-finalize-agenda-hook nil
2633 "Hook run just before displaying an agenda buffer."
2634 :group 'org-agenda-startup
2635 :type 'hook)
2637 (defcustom org-agenda-mouse-1-follows-link nil
2638 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2639 A longer mouse click will still set point. Does not work on XEmacs.
2640 Needs to be set before org.el is loaded."
2641 :group 'org-agenda-startup
2642 :type 'boolean)
2644 (defcustom org-agenda-start-with-follow-mode nil
2645 "The initial value of follow-mode in a newly created agenda window."
2646 :group 'org-agenda-startup
2647 :type 'boolean)
2649 (defgroup org-agenda-windows nil
2650 "Options concerning the windows used by the Agenda in Org Mode."
2651 :tag "Org Agenda Windows"
2652 :group 'org-agenda)
2654 (defcustom org-agenda-window-setup 'reorganize-frame
2655 "How the agenda buffer should be displayed.
2656 Possible values for this option are:
2658 current-window Show agenda in the current window, keeping all other windows.
2659 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2660 other-window Use `switch-to-buffer-other-window' to display agenda.
2661 reorganize-frame Show only two windows on the current frame, the current
2662 window and the agenda.
2663 See also the variable `org-agenda-restore-windows-after-quit'."
2664 :group 'org-agenda-windows
2665 :type '(choice
2666 (const current-window)
2667 (const other-frame)
2668 (const other-window)
2669 (const reorganize-frame)))
2671 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2672 "The min and max height of the agenda window as a fraction of frame height.
2673 The value of the variable is a cons cell with two numbers between 0 and 1.
2674 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2675 :group 'org-agenda-windows
2676 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2678 (defcustom org-agenda-restore-windows-after-quit nil
2679 "Non-nil means, restore window configuration open exiting agenda.
2680 Before the window configuration is changed for displaying the agenda,
2681 the current status is recorded. When the agenda is exited with
2682 `q' or `x' and this option is set, the old state is restored. If
2683 `org-agenda-window-setup' is `other-frame', the value of this
2684 option will be ignored.."
2685 :group 'org-agenda-windows
2686 :type 'boolean)
2688 (defcustom org-indirect-buffer-display 'other-window
2689 "How should indirect tree buffers be displayed?
2690 This applies to indirect buffers created with the commands
2691 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2692 Valid values are:
2693 current-window Display in the current window
2694 other-window Just display in another window.
2695 dedicated-frame Create one new frame, and re-use it each time.
2696 new-frame Make a new frame each time. Note that in this case
2697 previously-made indirect buffers are kept, and you need to
2698 kill these buffers yourself."
2699 :group 'org-structure
2700 :group 'org-agenda-windows
2701 :type '(choice
2702 (const :tag "In current window" current-window)
2703 (const :tag "In current frame, other window" other-window)
2704 (const :tag "Each time a new frame" new-frame)
2705 (const :tag "One dedicated frame" dedicated-frame)))
2707 (defgroup org-agenda-daily/weekly nil
2708 "Options concerning the daily/weekly agenda."
2709 :tag "Org Agenda Daily/Weekly"
2710 :group 'org-agenda)
2712 (defcustom org-agenda-ndays 7
2713 "Number of days to include in overview display.
2714 Should be 1 or 7."
2715 :group 'org-agenda-daily/weekly
2716 :type 'number)
2718 (defcustom org-agenda-start-on-weekday 1
2719 "Non-nil means, start the overview always on the specified weekday.
2720 0 denotes Sunday, 1 denotes Monday etc.
2721 When nil, always start on the current day."
2722 :group 'org-agenda-daily/weekly
2723 :type '(choice (const :tag "Today" nil)
2724 (number :tag "Weekday No.")))
2726 (defcustom org-agenda-show-all-dates t
2727 "Non-nil means, `org-agenda' shows every day in the selected range.
2728 When nil, only the days which actually have entries are shown."
2729 :group 'org-agenda-daily/weekly
2730 :type 'boolean)
2732 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2733 "Format string for displaying dates in the agenda.
2734 Used by the daily/weekly agenda and by the timeline. This should be
2735 a format string understood by `format-time-string', or a function returning
2736 the formatted date as a string. The function must take a single argument,
2737 a calendar-style date list like (month day year)."
2738 :group 'org-agenda-daily/weekly
2739 :type '(choice
2740 (string :tag "Format string")
2741 (function :tag "Function")))
2743 (defun org-agenda-format-date-aligned (date)
2744 "Format a date string for display in the daily/weekly agenda, or timeline.
2745 This function makes sure that dates are aligned for easy reading."
2746 (format "%-9s %2d %s %4d"
2747 (calendar-day-name date)
2748 (extract-calendar-day date)
2749 (calendar-month-name (extract-calendar-month date))
2750 (extract-calendar-year date)))
2752 (defcustom org-agenda-include-diary nil
2753 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2754 :group 'org-agenda-daily/weekly
2755 :type 'boolean)
2757 (defcustom org-agenda-include-all-todo nil
2758 "Set means weekly/daily agenda will always contain all TODO entries.
2759 The TODO entries will be listed at the top of the agenda, before
2760 the entries for specific days."
2761 :group 'org-agenda-daily/weekly
2762 :type 'boolean)
2764 (defcustom org-agenda-repeating-timestamp-show-all t
2765 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2766 When nil, only one occurence is shown, either today or the
2767 nearest into the future."
2768 :group 'org-agenda-daily/weekly
2769 :type 'boolean)
2771 (defcustom org-deadline-warning-days 14
2772 "No. of days before expiration during which a deadline becomes active.
2773 This variable governs the display in sparse trees and in the agenda.
2774 When 0 or negative, it means use this number (the absolute value of it)
2775 even if a deadline has a different individual lead time specified."
2776 :group 'org-time
2777 :group 'org-agenda-daily/weekly
2778 :type 'number)
2780 (defcustom org-scheduled-past-days 10000
2781 "No. of days to continue listing scheduled items that are not marked DONE.
2782 When an item is scheduled on a date, it shows up in the agenda on this
2783 day and will be listed until it is marked done for the number of days
2784 given here."
2785 :group 'org-agenda-daily/weekly
2786 :type 'number)
2788 (defgroup org-agenda-time-grid nil
2789 "Options concerning the time grid in the Org-mode Agenda."
2790 :tag "Org Agenda Time Grid"
2791 :group 'org-agenda)
2793 (defcustom org-agenda-use-time-grid t
2794 "Non-nil means, show a time grid in the agenda schedule.
2795 A time grid is a set of lines for specific times (like every two hours between
2796 8:00 and 20:00). The items scheduled for a day at specific times are
2797 sorted in between these lines.
2798 For details about when the grid will be shown, and what it will look like, see
2799 the variable `org-agenda-time-grid'."
2800 :group 'org-agenda-time-grid
2801 :type 'boolean)
2803 (defcustom org-agenda-time-grid
2804 '((daily today require-timed)
2805 "----------------"
2806 (800 1000 1200 1400 1600 1800 2000))
2808 "The settings for time grid for agenda display.
2809 This is a list of three items. The first item is again a list. It contains
2810 symbols specifying conditions when the grid should be displayed:
2812 daily if the agenda shows a single day
2813 weekly if the agenda shows an entire week
2814 today show grid on current date, independent of daily/weekly display
2815 require-timed show grid only if at least one item has a time specification
2817 The second item is a string which will be places behing the grid time.
2819 The third item is a list of integers, indicating the times that should have
2820 a grid line."
2821 :group 'org-agenda-time-grid
2822 :type
2823 '(list
2824 (set :greedy t :tag "Grid Display Options"
2825 (const :tag "Show grid in single day agenda display" daily)
2826 (const :tag "Show grid in weekly agenda display" weekly)
2827 (const :tag "Always show grid for today" today)
2828 (const :tag "Show grid only if any timed entries are present"
2829 require-timed)
2830 (const :tag "Skip grid times already present in an entry"
2831 remove-match))
2832 (string :tag "Grid String")
2833 (repeat :tag "Grid Times" (integer :tag "Time"))))
2835 (defgroup org-agenda-sorting nil
2836 "Options concerning sorting in the Org-mode Agenda."
2837 :tag "Org Agenda Sorting"
2838 :group 'org-agenda)
2840 (defconst org-sorting-choice
2841 '(choice
2842 (const time-up) (const time-down)
2843 (const category-keep) (const category-up) (const category-down)
2844 (const tag-down) (const tag-up)
2845 (const priority-up) (const priority-down))
2846 "Sorting choices.")
2848 (defcustom org-agenda-sorting-strategy
2849 '((agenda time-up category-keep priority-down)
2850 (todo category-keep priority-down)
2851 (tags category-keep priority-down)
2852 (search category-keep))
2853 "Sorting structure for the agenda items of a single day.
2854 This is a list of symbols which will be used in sequence to determine
2855 if an entry should be listed before another entry. The following
2856 symbols are recognized:
2858 time-up Put entries with time-of-day indications first, early first
2859 time-down Put entries with time-of-day indications first, late first
2860 category-keep Keep the default order of categories, corresponding to the
2861 sequence in `org-agenda-files'.
2862 category-up Sort alphabetically by category, A-Z.
2863 category-down Sort alphabetically by category, Z-A.
2864 tag-up Sort alphabetically by last tag, A-Z.
2865 tag-down Sort alphabetically by last tag, Z-A.
2866 priority-up Sort numerically by priority, high priority last.
2867 priority-down Sort numerically by priority, high priority first.
2869 The different possibilities will be tried in sequence, and testing stops
2870 if one comparison returns a \"not-equal\". For example, the default
2871 '(time-up category-keep priority-down)
2872 means: Pull out all entries having a specified time of day and sort them,
2873 in order to make a time schedule for the current day the first thing in the
2874 agenda listing for the day. Of the entries without a time indication, keep
2875 the grouped in categories, don't sort the categories, but keep them in
2876 the sequence given in `org-agenda-files'. Within each category sort by
2877 priority.
2879 Leaving out `category-keep' would mean that items will be sorted across
2880 categories by priority.
2882 Instead of a single list, this can also be a set of list for specific
2883 contents, with a context symbol in the car of the list, any of
2884 `agenda', `todo', `tags' for the corresponding agenda views."
2885 :group 'org-agenda-sorting
2886 :type `(choice
2887 (repeat :tag "General" ,org-sorting-choice)
2888 (list :tag "Individually"
2889 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2890 (repeat ,org-sorting-choice))
2891 (cons (const :tag "Strategy for TODO lists" todo)
2892 (repeat ,org-sorting-choice))
2893 (cons (const :tag "Strategy for Tags matches" tags)
2894 (repeat ,org-sorting-choice)))))
2896 (defcustom org-sort-agenda-notime-is-late t
2897 "Non-nil means, items without time are considered late.
2898 This is only relevant for sorting. When t, items which have no explicit
2899 time like 15:30 will be considered as 99:01, i.e. later than any items which
2900 do have a time. When nil, the default time is before 0:00. You can use this
2901 option to decide if the schedule for today should come before or after timeless
2902 agenda entries."
2903 :group 'org-agenda-sorting
2904 :type 'boolean)
2906 (defgroup org-agenda-line-format nil
2907 "Options concerning the entry prefix in the Org-mode agenda display."
2908 :tag "Org Agenda Line Format"
2909 :group 'org-agenda)
2911 (defcustom org-agenda-prefix-format
2912 '((agenda . " %-12:c%?-12t% s")
2913 (timeline . " % s")
2914 (todo . " %-12:c")
2915 (tags . " %-12:c")
2916 (search . " %-12:c"))
2917 "Format specifications for the prefix of items in the agenda views.
2918 An alist with four entries, for the different agenda types. The keys to the
2919 sublists are `agenda', `timeline', `todo', and `tags'. The values
2920 are format strings.
2921 This format works similar to a printf format, with the following meaning:
2923 %c the category of the item, \"Diary\" for entries from the diary, or
2924 as given by the CATEGORY keyword or derived from the file name.
2925 %T the *last* tag of the item. Last because inherited tags come
2926 first in the list.
2927 %t the time-of-day specification if one applies to the entry, in the
2928 format HH:MM
2929 %s Scheduling/Deadline information, a short string
2931 All specifiers work basically like the standard `%s' of printf, but may
2932 contain two additional characters: A question mark just after the `%' and
2933 a whitespace/punctuation character just before the final letter.
2935 If the first character after `%' is a question mark, the entire field
2936 will only be included if the corresponding value applies to the
2937 current entry. This is useful for fields which should have fixed
2938 width when present, but zero width when absent. For example,
2939 \"%?-12t\" will result in a 12 character time field if a time of the
2940 day is specified, but will completely disappear in entries which do
2941 not contain a time.
2943 If there is punctuation or whitespace character just before the final
2944 format letter, this character will be appended to the field value if
2945 the value is not empty. For example, the format \"%-12:c\" leads to
2946 \"Diary: \" if the category is \"Diary\". If the category were be
2947 empty, no additional colon would be interted.
2949 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2950 - Indent the line with two space characters
2951 - Give the category in a 12 chars wide field, padded with whitespace on
2952 the right (because of `-'). Append a colon if there is a category
2953 (because of `:').
2954 - If there is a time-of-day, put it into a 12 chars wide field. If no
2955 time, don't put in an empty field, just skip it (because of '?').
2956 - Finally, put the scheduling information and append a whitespace.
2958 As another example, if you don't want the time-of-day of entries in
2959 the prefix, you could use:
2961 (setq org-agenda-prefix-format \" %-11:c% s\")
2963 See also the variables `org-agenda-remove-times-when-in-prefix' and
2964 `org-agenda-remove-tags'."
2965 :type '(choice
2966 (string :tag "General format")
2967 (list :greedy t :tag "View dependent"
2968 (cons (const agenda) (string :tag "Format"))
2969 (cons (const timeline) (string :tag "Format"))
2970 (cons (const todo) (string :tag "Format"))
2971 (cons (const tags) (string :tag "Format"))
2972 (cons (const search) (string :tag "Format"))))
2973 :group 'org-agenda-line-format)
2975 (defvar org-prefix-format-compiled nil
2976 "The compiled version of the most recently used prefix format.
2977 See the variable `org-agenda-prefix-format'.")
2979 (defcustom org-agenda-todo-keyword-format "%-1s"
2980 "Format for the TODO keyword in agenda lines.
2981 Set this to something like \"%-12s\" if you want all TODO keywords
2982 to occupy a fixed space in the agenda display."
2983 :group 'org-agenda-line-format
2984 :type 'string)
2986 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2987 "Text preceeding scheduled items in the agenda view.
2988 This is a list with two strings. The first applies when the item is
2989 scheduled on the current day. The second applies when it has been scheduled
2990 previously, it may contain a %d to capture how many days ago the item was
2991 scheduled."
2992 :group 'org-agenda-line-format
2993 :type '(list
2994 (string :tag "Scheduled today ")
2995 (string :tag "Scheduled previously")))
2997 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2998 "Text preceeding deadline items in the agenda view.
2999 This is a list with two strings. The first applies when the item has its
3000 deadline on the current day. The second applies when it is in the past or
3001 in the future, it may contain %d to capture how many days away the deadline
3002 is (was)."
3003 :group 'org-agenda-line-format
3004 :type '(list
3005 (string :tag "Deadline today ")
3006 (string :tag "Deadline relative")))
3008 (defcustom org-agenda-remove-times-when-in-prefix t
3009 "Non-nil means, remove duplicate time specifications in agenda items.
3010 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
3011 time-of-day specification in a headline or diary entry is extracted and
3012 placed into the prefix. If this option is non-nil, the original specification
3013 \(a timestamp or -range, or just a plain time(range) specification like
3014 11:30-4pm) will be removed for agenda display. This makes the agenda less
3015 cluttered.
3016 The option can be t or nil. It may also be the symbol `beg', indicating
3017 that the time should only be removed what it is located at the beginning of
3018 the headline/diary entry."
3019 :group 'org-agenda-line-format
3020 :type '(choice
3021 (const :tag "Always" t)
3022 (const :tag "Never" nil)
3023 (const :tag "When at beginning of entry" beg)))
3026 (defcustom org-agenda-default-appointment-duration nil
3027 "Default duration for appointments that only have a starting time.
3028 When nil, no duration is specified in such cases.
3029 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
3030 :group 'org-agenda-line-format
3031 :type '(choice
3032 (integer :tag "Minutes")
3033 (const :tag "No default duration")))
3036 (defcustom org-agenda-remove-tags nil
3037 "Non-nil means, remove the tags from the headline copy in the agenda.
3038 When this is the symbol `prefix', only remove tags when
3039 `org-agenda-prefix-format' contains a `%T' specifier."
3040 :group 'org-agenda-line-format
3041 :type '(choice
3042 (const :tag "Always" t)
3043 (const :tag "Never" nil)
3044 (const :tag "When prefix format contains %T" prefix)))
3046 (if (fboundp 'defvaralias)
3047 (defvaralias 'org-agenda-remove-tags-when-in-prefix
3048 'org-agenda-remove-tags))
3050 (defcustom org-agenda-tags-column -80
3051 "Shift tags in agenda items to this column.
3052 If this number is positive, it specifies the column. If it is negative,
3053 it means that the tags should be flushright to that column. For example,
3054 -80 works well for a normal 80 character screen."
3055 :group 'org-agenda-line-format
3056 :type 'integer)
3058 (if (fboundp 'defvaralias)
3059 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
3061 (defcustom org-agenda-fontify-priorities t
3062 "Non-nil means, highlight low and high priorities in agenda.
3063 When t, the highest priority entries are bold, lowest priority italic.
3064 This may also be an association list of priority faces. The face may be
3065 a names face, or a list like `(:background \"Red\")'."
3066 :group 'org-agenda-line-format
3067 :type '(choice
3068 (const :tag "Never" nil)
3069 (const :tag "Defaults" t)
3070 (repeat :tag "Specify"
3071 (list (character :tag "Priority" :value ?A)
3072 (sexp :tag "face")))))
3074 (defgroup org-latex nil
3075 "Options for embedding LaTeX code into Org-mode"
3076 :tag "Org LaTeX"
3077 :group 'org)
3079 (defcustom org-format-latex-options
3080 '(:foreground default :background default :scale 1.0
3081 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3082 :matchers ("begin" "$" "$$" "\\(" "\\["))
3083 "Options for creating images from LaTeX fragments.
3084 This is a property list with the following properties:
3085 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
3086 `default' means use the forground of the default face.
3087 :background the background color, or \"Transparent\".
3088 `default' means use the background of the default face.
3089 :scale a scaling factor for the size of the images
3090 :html-foreground, :html-background, :html-scale
3091 The same numbers for HTML export.
3092 :matchers a list indicating which matchers should be used to
3093 find LaTeX fragments. Valid members of this list are:
3094 \"begin\" find environments
3095 \"$\" find math expressions surrounded by $...$
3096 \"$$\" find math expressions surrounded by $$....$$
3097 \"\\(\" find math expressions surrounded by \\(...\\)
3098 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3099 :group 'org-latex
3100 :type 'plist)
3102 (defcustom org-format-latex-header "\\documentclass{article}
3103 \\usepackage{fullpage} % do not remove
3104 \\usepackage{amssymb}
3105 \\usepackage[usenames]{color}
3106 \\usepackage{amsmath}
3107 \\usepackage{latexsym}
3108 \\usepackage[mathscr]{eucal}
3109 \\pagestyle{empty} % do not remove"
3110 "The document header used for processing LaTeX fragments."
3111 :group 'org-latex
3112 :type 'string)
3114 (defgroup org-export nil
3115 "Options for exporting org-listings."
3116 :tag "Org Export"
3117 :group 'org)
3119 (defgroup org-export-general nil
3120 "General options for exporting Org-mode files."
3121 :tag "Org Export General"
3122 :group 'org-export)
3124 ;; FIXME
3125 (defvar org-export-publishing-directory nil)
3127 (defcustom org-export-with-special-strings t
3128 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3129 When this option is turned on, these strings will be exported as:
3131 Org HTML LaTeX
3132 -----+----------+--------
3133 \\- &shy; \\-
3134 -- &ndash; --
3135 --- &mdash; ---
3136 ... &hellip; \ldots
3138 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3139 :group 'org-export-translation
3140 :type 'boolean)
3142 (defcustom org-export-language-setup
3143 '(("en" "Author" "Date" "Table of Contents")
3144 ("cs" "Autor" "Datum" "Obsah")
3145 ("da" "Ophavsmand" "Dato" "Indhold")
3146 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3147 ("es" "Autor" "Fecha" "\xcdndice")
3148 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3149 ("it" "Autore" "Data" "Indice")
3150 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3151 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3152 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3153 "Terms used in export text, translated to different languages.
3154 Use the variable `org-export-default-language' to set the language,
3155 or use the +OPTION lines for a per-file setting."
3156 :group 'org-export-general
3157 :type '(repeat
3158 (list
3159 (string :tag "HTML language tag")
3160 (string :tag "Author")
3161 (string :tag "Date")
3162 (string :tag "Table of Contents"))))
3164 (defcustom org-export-default-language "en"
3165 "The default language of HTML export, as a string.
3166 This should have an association in `org-export-language-setup'."
3167 :group 'org-export-general
3168 :type 'string)
3170 (defcustom org-export-skip-text-before-1st-heading t
3171 "Non-nil means, skip all text before the first headline when exporting.
3172 When nil, that text is exported as well."
3173 :group 'org-export-general
3174 :type 'boolean)
3176 (defcustom org-export-headline-levels 3
3177 "The last level which is still exported as a headline.
3178 Inferior levels will produce itemize lists when exported.
3179 Note that a numeric prefix argument to an exporter function overrides
3180 this setting.
3182 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3183 :group 'org-export-general
3184 :type 'number)
3186 (defcustom org-export-with-section-numbers t
3187 "Non-nil means, add section numbers to headlines when exporting.
3189 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3190 :group 'org-export-general
3191 :type 'boolean)
3193 (defcustom org-export-with-toc t
3194 "Non-nil means, create a table of contents in exported files.
3195 The TOC contains headlines with levels up to`org-export-headline-levels'.
3196 When an integer, include levels up to N in the toc, this may then be
3197 different from `org-export-headline-levels', but it will not be allowed
3198 to be larger than the number of headline levels.
3199 When nil, no table of contents is made.
3201 Headlines which contain any TODO items will be marked with \"(*)\" in
3202 ASCII export, and with red color in HTML output, if the option
3203 `org-export-mark-todo-in-toc' is set.
3205 In HTML output, the TOC will be clickable.
3207 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3208 or \"toc:3\"."
3209 :group 'org-export-general
3210 :type '(choice
3211 (const :tag "No Table of Contents" nil)
3212 (const :tag "Full Table of Contents" t)
3213 (integer :tag "TOC to level")))
3215 (defcustom org-export-mark-todo-in-toc nil
3216 "Non-nil means, mark TOC lines that contain any open TODO items."
3217 :group 'org-export-general
3218 :type 'boolean)
3220 (defcustom org-export-preserve-breaks nil
3221 "Non-nil means, preserve all line breaks when exporting.
3222 Normally, in HTML output paragraphs will be reformatted. In ASCII
3223 export, line breaks will always be preserved, regardless of this variable.
3225 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3226 :group 'org-export-general
3227 :type 'boolean)
3229 (defcustom org-export-with-archived-trees 'headline
3230 "Whether subtrees with the ARCHIVE tag should be exported.
3231 This can have three different values
3232 nil Do not export, pretend this tree is not present
3233 t Do export the entire tree
3234 headline Only export the headline, but skip the tree below it."
3235 :group 'org-export-general
3236 :group 'org-archive
3237 :type '(choice
3238 (const :tag "not at all" nil)
3239 (const :tag "headline only" 'headline)
3240 (const :tag "entirely" t)))
3242 (defcustom org-export-author-info t
3243 "Non-nil means, insert author name and email into the exported file.
3245 This option can also be set with the +OPTIONS line,
3246 e.g. \"author-info:nil\"."
3247 :group 'org-export-general
3248 :type 'boolean)
3250 (defcustom org-export-time-stamp-file t
3251 "Non-nil means, insert a time stamp into the exported file.
3252 The time stamp shows when the file was created.
3254 This option can also be set with the +OPTIONS line,
3255 e.g. \"timestamp:nil\"."
3256 :group 'org-export-general
3257 :type 'boolean)
3259 (defcustom org-export-with-timestamps t
3260 "If nil, do not export time stamps and associated keywords."
3261 :group 'org-export-general
3262 :type 'boolean)
3264 (defcustom org-export-remove-timestamps-from-toc t
3265 "If nil, remove timestamps from the table of contents entries."
3266 :group 'org-export-general
3267 :type 'boolean)
3269 (defcustom org-export-with-tags 'not-in-toc
3270 "If nil, do not export tags, just remove them from headlines.
3271 If this is the symbol `not-in-toc', tags will be removed from table of
3272 contents entries, but still be shown in the headlines of the document.
3274 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3275 :group 'org-export-general
3276 :type '(choice
3277 (const :tag "Off" nil)
3278 (const :tag "Not in TOC" not-in-toc)
3279 (const :tag "On" t)))
3281 (defcustom org-export-with-drawers nil
3282 "Non-nil means, export with drawers like the property drawer.
3283 When t, all drawers are exported. This may also be a list of
3284 drawer names to export."
3285 :group 'org-export-general
3286 :type '(choice
3287 (const :tag "All drawers" t)
3288 (const :tag "None" nil)
3289 (repeat :tag "Selected drawers"
3290 (string :tag "Drawer name"))))
3292 (defgroup org-export-translation nil
3293 "Options for translating special ascii sequences for the export backends."
3294 :tag "Org Export Translation"
3295 :group 'org-export)
3297 (defcustom org-export-with-emphasize t
3298 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3299 If the export target supports emphasizing text, the word will be
3300 typeset in bold, italic, or underlined, respectively. Works only for
3301 single words, but you can say: I *really* *mean* *this*.
3302 Not all export backends support this.
3304 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3305 :group 'org-export-translation
3306 :type 'boolean)
3308 (defcustom org-export-with-footnotes t
3309 "If nil, export [1] as a footnote marker.
3310 Lines starting with [1] will be formatted as footnotes.
3312 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3313 :group 'org-export-translation
3314 :type 'boolean)
3316 (defcustom org-export-with-sub-superscripts t
3317 "Non-nil means, interpret \"_\" and \"^\" for export.
3318 When this option is turned on, you can use TeX-like syntax for sub- and
3319 superscripts. Several characters after \"_\" or \"^\" will be
3320 considered as a single item - so grouping with {} is normally not
3321 needed. For example, the following things will be parsed as single
3322 sub- or superscripts.
3324 10^24 or 10^tau several digits will be considered 1 item.
3325 10^-12 or 10^-tau a leading sign with digits or a word
3326 x^2-y^3 will be read as x^2 - y^3, because items are
3327 terminated by almost any nonword/nondigit char.
3328 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3330 Still, ambiguity is possible - so when in doubt use {} to enclose the
3331 sub/superscript. If you set this variable to the symbol `{}',
3332 the braces are *required* in order to trigger interpretations as
3333 sub/superscript. This can be helpful in documents that need \"_\"
3334 frequently in plain text.
3336 Not all export backends support this, but HTML does.
3338 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3339 :group 'org-export-translation
3340 :type '(choice
3341 (const :tag "Always interpret" t)
3342 (const :tag "Only with braces" {})
3343 (const :tag "Never interpret" nil)))
3345 (defcustom org-export-with-special-strings t
3346 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3347 When this option is turned on, these strings will be exported as:
3349 \\- : &shy;
3350 -- : &ndash;
3351 --- : &mdash;
3353 Not all export backends support this, but HTML does.
3355 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3356 :group 'org-export-translation
3357 :type 'boolean)
3359 (defcustom org-export-with-TeX-macros t
3360 "Non-nil means, interpret simple TeX-like macros when exporting.
3361 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3362 No only real TeX macros will work here, but the standard HTML entities
3363 for math can be used as macro names as well. For a list of supported
3364 names in HTML export, see the constant `org-html-entities'.
3365 Not all export backends support this.
3367 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3368 :group 'org-export-translation
3369 :group 'org-export-latex
3370 :type 'boolean)
3372 (defcustom org-export-with-LaTeX-fragments nil
3373 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3374 When set, the exporter will find LaTeX environments if the \\begin line is
3375 the first non-white thing on a line. It will also find the math delimiters
3376 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3377 display math.
3379 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3380 :group 'org-export-translation
3381 :group 'org-export-latex
3382 :type 'boolean)
3384 (defcustom org-export-with-fixed-width t
3385 "Non-nil means, lines starting with \":\" will be in fixed width font.
3386 This can be used to have pre-formatted text, fragments of code etc. For
3387 example:
3388 : ;; Some Lisp examples
3389 : (while (defc cnt)
3390 : (ding))
3391 will be looking just like this in also HTML. See also the QUOTE keyword.
3392 Not all export backends support this.
3394 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3395 :group 'org-export-translation
3396 :type 'boolean)
3398 (defcustom org-match-sexp-depth 3
3399 "Number of stacked braces for sub/superscript matching.
3400 This has to be set before loading org.el to be effective."
3401 :group 'org-export-translation
3402 :type 'integer)
3404 (defgroup org-export-tables nil
3405 "Options for exporting tables in Org-mode."
3406 :tag "Org Export Tables"
3407 :group 'org-export)
3409 (defcustom org-export-with-tables t
3410 "If non-nil, lines starting with \"|\" define a table.
3411 For example:
3413 | Name | Address | Birthday |
3414 |-------------+----------+-----------|
3415 | Arthur Dent | England | 29.2.2100 |
3417 Not all export backends support this.
3419 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3420 :group 'org-export-tables
3421 :type 'boolean)
3423 (defcustom org-export-highlight-first-table-line t
3424 "Non-nil means, highlight the first table line.
3425 In HTML export, this means use <th> instead of <td>.
3426 In tables created with table.el, this applies to the first table line.
3427 In Org-mode tables, all lines before the first horizontal separator
3428 line will be formatted with <th> tags."
3429 :group 'org-export-tables
3430 :type 'boolean)
3432 (defcustom org-export-table-remove-special-lines t
3433 "Remove special lines and marking characters in calculating tables.
3434 This removes the special marking character column from tables that are set
3435 up for spreadsheet calculations. It also removes the entire lines
3436 marked with `!', `_', or `^'. The lines with `$' are kept, because
3437 the values of constants may be useful to have."
3438 :group 'org-export-tables
3439 :type 'boolean)
3441 (defcustom org-export-prefer-native-exporter-for-tables nil
3442 "Non-nil means, always export tables created with table.el natively.
3443 Natively means, use the HTML code generator in table.el.
3444 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3445 the table does not use row- or column-spanning). This has the
3446 advantage, that the automatic HTML conversions for math symbols and
3447 sub/superscripts can be applied. Org-mode's HTML generator is also
3448 much faster."
3449 :group 'org-export-tables
3450 :type 'boolean)
3452 (defgroup org-export-ascii nil
3453 "Options specific for ASCII export of Org-mode files."
3454 :tag "Org Export ASCII"
3455 :group 'org-export)
3457 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3458 "Characters for underlining headings in ASCII export.
3459 In the given sequence, these characters will be used for level 1, 2, ..."
3460 :group 'org-export-ascii
3461 :type '(repeat character))
3463 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3464 "Bullet characters for headlines converted to lists in ASCII export.
3465 The first character is used for the first lest level generated in this
3466 way, and so on. If there are more levels than characters given here,
3467 the list will be repeated.
3468 Note that plain lists will keep the same bullets as the have in the
3469 Org-mode file."
3470 :group 'org-export-ascii
3471 :type '(repeat character))
3473 (defgroup org-export-xml nil
3474 "Options specific for XML export of Org-mode files."
3475 :tag "Org Export XML"
3476 :group 'org-export)
3478 (defgroup org-export-html nil
3479 "Options specific for HTML export of Org-mode files."
3480 :tag "Org Export HTML"
3481 :group 'org-export)
3483 (defcustom org-export-html-coding-system nil
3485 :group 'org-export-html
3486 :type 'coding-system)
3488 (defcustom org-export-html-extension "html"
3489 "The extension for exported HTML files."
3490 :group 'org-export-html
3491 :type 'string)
3493 (defcustom org-export-html-style
3494 "<style type=\"text/css\">
3495 html {
3496 font-family: Times, serif;
3497 font-size: 12pt;
3499 .title { text-align: center; }
3500 .todo { color: red; }
3501 .done { color: green; }
3502 .timestamp { color: grey }
3503 .timestamp-kwd { color: CadetBlue }
3504 .tag { background-color:lightblue; font-weight:normal }
3505 .target { background-color: lavender; }
3506 pre {
3507 border: 1pt solid #AEBDCC;
3508 background-color: #F3F5F7;
3509 padding: 5pt;
3510 font-family: courier, monospace;
3512 table { border-collapse: collapse; }
3513 td, th {
3514 vertical-align: top;
3515 <!--border: 1pt solid #ADB9CC;-->
3517 </style>"
3518 "The default style specification for exported HTML files.
3519 Since there are different ways of setting style information, this variable
3520 needs to contain the full HTML structure to provide a style, including the
3521 surrounding HTML tags. The style specifications should include definitions
3522 for new classes todo, done, title, and deadline. For example, legal values
3523 would be:
3525 <style type=\"text/css\">
3526 p { font-weight: normal; color: gray; }
3527 h1 { color: black; }
3528 .title { text-align: center; }
3529 .todo, .deadline { color: red; }
3530 .done { color: green; }
3531 </style>
3533 or, if you want to keep the style in a file,
3535 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3537 As the value of this option simply gets inserted into the HTML <head> header,
3538 you can \"misuse\" it to add arbitrary text to the header."
3539 :group 'org-export-html
3540 :type 'string)
3543 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3544 "Format for typesetting the document title in HTML export."
3545 :group 'org-export-html
3546 :type 'string)
3548 (defcustom org-export-html-toplevel-hlevel 2
3549 "The <H> level for level 1 headings in HTML export."
3550 :group 'org-export-html
3551 :type 'string)
3553 (defcustom org-export-html-link-org-files-as-html t
3554 "Non-nil means, make file links to `file.org' point to `file.html'.
3555 When org-mode is exporting an org-mode file to HTML, links to
3556 non-html files are directly put into a href tag in HTML.
3557 However, links to other Org-mode files (recognized by the
3558 extension `.org.) should become links to the corresponding html
3559 file, assuming that the linked org-mode file will also be
3560 converted to HTML.
3561 When nil, the links still point to the plain `.org' file."
3562 :group 'org-export-html
3563 :type 'boolean)
3565 (defcustom org-export-html-inline-images 'maybe
3566 "Non-nil means, inline images into exported HTML pages.
3567 This is done using an <img> tag. When nil, an anchor with href is used to
3568 link to the image. If this option is `maybe', then images in links with
3569 an empty description will be inlined, while images with a description will
3570 be linked only."
3571 :group 'org-export-html
3572 :type '(choice (const :tag "Never" nil)
3573 (const :tag "Always" t)
3574 (const :tag "When there is no description" maybe)))
3576 ;; FIXME: rename
3577 (defcustom org-export-html-expand t
3578 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3579 When nil, these tags will be exported as plain text and therefore
3580 not be interpreted by a browser.
3582 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3583 :group 'org-export-html
3584 :type 'boolean)
3586 (defcustom org-export-html-table-tag
3587 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3588 "The HTML tag that is used to start a table.
3589 This must be a <table> tag, but you may change the options like
3590 borders and spacing."
3591 :group 'org-export-html
3592 :type 'string)
3594 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3595 "The opening tag for table header fields.
3596 This is customizable so that alignment options can be specified."
3597 :group 'org-export-tables
3598 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3600 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3601 "The opening tag for table data fields.
3602 This is customizable so that alignment options can be specified."
3603 :group 'org-export-tables
3604 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3606 (defcustom org-export-html-with-timestamp nil
3607 "If non-nil, write `org-export-html-html-helper-timestamp'
3608 into the exported HTML text. Otherwise, the buffer will just be saved
3609 to a file."
3610 :group 'org-export-html
3611 :type 'boolean)
3613 (defcustom org-export-html-html-helper-timestamp
3614 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3615 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3616 :group 'org-export-html
3617 :type 'string)
3619 (defgroup org-export-icalendar nil
3620 "Options specific for iCalendar export of Org-mode files."
3621 :tag "Org Export iCalendar"
3622 :group 'org-export)
3624 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3625 "The file name for the iCalendar file covering all agenda files.
3626 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3627 The file name should be absolute, the file will be overwritten without warning."
3628 :group 'org-export-icalendar
3629 :type 'file)
3631 (defcustom org-icalendar-include-todo nil
3632 "Non-nil means, export to iCalendar files should also cover TODO items."
3633 :group 'org-export-icalendar
3634 :type '(choice
3635 (const :tag "None" nil)
3636 (const :tag "Unfinished" t)
3637 (const :tag "All" all)))
3639 (defcustom org-icalendar-include-sexps t
3640 "Non-nil means, export to iCalendar files should also cover sexp entries.
3641 These are entries like in the diary, but directly in an Org-mode file."
3642 :group 'org-export-icalendar
3643 :type 'boolean)
3645 (defcustom org-icalendar-include-body 100
3646 "Amount of text below headline to be included in iCalendar export.
3647 This is a number of characters that should maximally be included.
3648 Properties, scheduling and clocking lines will always be removed.
3649 The text will be inserted into the DESCRIPTION field."
3650 :group 'org-export-icalendar
3651 :type '(choice
3652 (const :tag "Nothing" nil)
3653 (const :tag "Everything" t)
3654 (integer :tag "Max characters")))
3656 (defcustom org-icalendar-combined-name "OrgMode"
3657 "Calendar name for the combined iCalendar representing all agenda files."
3658 :group 'org-export-icalendar
3659 :type 'string)
3661 (defgroup org-font-lock nil
3662 "Font-lock settings for highlighting in Org-mode."
3663 :tag "Org Font Lock"
3664 :group 'org)
3666 (defcustom org-level-color-stars-only nil
3667 "Non-nil means fontify only the stars in each headline.
3668 When nil, the entire headline is fontified.
3669 Changing it requires restart of `font-lock-mode' to become effective
3670 also in regions already fontified."
3671 :group 'org-font-lock
3672 :type 'boolean)
3674 (defcustom org-hide-leading-stars nil
3675 "Non-nil means, hide the first N-1 stars in a headline.
3676 This works by using the face `org-hide' for these stars. This
3677 face is white for a light background, and black for a dark
3678 background. You may have to customize the face `org-hide' to
3679 make this work.
3680 Changing it requires restart of `font-lock-mode' to become effective
3681 also in regions already fontified.
3682 You may also set this on a per-file basis by adding one of the following
3683 lines to the buffer:
3685 #+STARTUP: hidestars
3686 #+STARTUP: showstars"
3687 :group 'org-font-lock
3688 :type 'boolean)
3690 (defcustom org-fontify-done-headline nil
3691 "Non-nil means, change the face of a headline if it is marked DONE.
3692 Normally, only the TODO/DONE keyword indicates the state of a headline.
3693 When this is non-nil, the headline after the keyword is set to the
3694 `org-headline-done' as an additional indication."
3695 :group 'org-font-lock
3696 :type 'boolean)
3698 (defcustom org-fontify-emphasized-text t
3699 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3700 Changing this variable requires a restart of Emacs to take effect."
3701 :group 'org-font-lock
3702 :type 'boolean)
3704 (defcustom org-highlight-latex-fragments-and-specials nil
3705 "Non-nil means, fontify what is treated specially by the exporters."
3706 :group 'org-font-lock
3707 :type 'boolean)
3709 (defcustom org-hide-emphasis-markers nil
3710 "Non-nil mean font-lock should hide the emphasis marker characters."
3711 :group 'org-font-lock
3712 :type 'boolean)
3714 (defvar org-emph-re nil
3715 "Regular expression for matching emphasis.")
3716 (defvar org-verbatim-re nil
3717 "Regular expression for matching verbatim text.")
3718 (defvar org-emphasis-regexp-components) ; defined just below
3719 (defvar org-emphasis-alist) ; defined just below
3720 (defun org-set-emph-re (var val)
3721 "Set variable and compute the emphasis regular expression."
3722 (set var val)
3723 (when (and (boundp 'org-emphasis-alist)
3724 (boundp 'org-emphasis-regexp-components)
3725 org-emphasis-alist org-emphasis-regexp-components)
3726 (let* ((e org-emphasis-regexp-components)
3727 (pre (car e))
3728 (post (nth 1 e))
3729 (border (nth 2 e))
3730 (body (nth 3 e))
3731 (nl (nth 4 e))
3732 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3733 (body1 (concat body "*?"))
3734 (markers (mapconcat 'car org-emphasis-alist ""))
3735 (vmarkers (mapconcat
3736 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3737 org-emphasis-alist "")))
3738 ;; make sure special characters appear at the right position in the class
3739 (if (string-match "\\^" markers)
3740 (setq markers (concat (replace-match "" t t markers) "^")))
3741 (if (string-match "-" markers)
3742 (setq markers (concat (replace-match "" t t markers) "-")))
3743 (if (string-match "\\^" vmarkers)
3744 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3745 (if (string-match "-" vmarkers)
3746 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3747 (if (> nl 0)
3748 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3749 (int-to-string nl) "\\}")))
3750 ;; Make the regexp
3751 (setq org-emph-re
3752 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3753 "\\("
3754 "\\([" markers "]\\)"
3755 "\\("
3756 "[^" border "]\\|"
3757 "[^" border (if (and nil stacked) markers) "]"
3758 body1
3759 "[^" border (if (and nil stacked) markers) "]"
3760 "\\)"
3761 "\\3\\)"
3762 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3763 (setq org-verbatim-re
3764 (concat "\\([" pre "]\\|^\\)"
3765 "\\("
3766 "\\([" vmarkers "]\\)"
3767 "\\("
3768 "[^" border "]\\|"
3769 "[^" border "]"
3770 body1
3771 "[^" border "]"
3772 "\\)"
3773 "\\3\\)"
3774 "\\([" post "]\\|$\\)")))))
3776 (defcustom org-emphasis-regexp-components
3777 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3778 "Components used to build the regular expression for emphasis.
3779 This is a list with 6 entries. Terminology: In an emphasis string
3780 like \" *strong word* \", we call the initial space PREMATCH, the final
3781 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3782 and \"trong wor\" is the body. The different components in this variable
3783 specify what is allowed/forbidden in each part:
3785 pre Chars allowed as prematch. Beginning of line will be allowed too.
3786 post Chars allowed as postmatch. End of line will be allowed too.
3787 border The chars *forbidden* as border characters.
3788 body-regexp A regexp like \".\" to match a body character. Don't use
3789 non-shy groups here, and don't allow newline here.
3790 newline The maximum number of newlines allowed in an emphasis exp.
3792 Use customize to modify this, or restart Emacs after changing it."
3793 :group 'org-font-lock
3794 :set 'org-set-emph-re
3795 :type '(list
3796 (sexp :tag "Allowed chars in pre ")
3797 (sexp :tag "Allowed chars in post ")
3798 (sexp :tag "Forbidden chars in border ")
3799 (sexp :tag "Regexp for body ")
3800 (integer :tag "number of newlines allowed")
3801 (option (boolean :tag "Stacking (DISABLED) "))))
3803 (defcustom org-emphasis-alist
3804 '(("*" bold "<b>" "</b>")
3805 ("/" italic "<i>" "</i>")
3806 ("_" underline "<u>" "</u>")
3807 ("=" org-code "<code>" "</code>" verbatim)
3808 ("~" org-verbatim "" "" verbatim)
3809 ("+" (:strike-through t) "<del>" "</del>")
3811 "Special syntax for emphasized text.
3812 Text starting and ending with a special character will be emphasized, for
3813 example *bold*, _underlined_ and /italic/. This variable sets the marker
3814 characters, the face to be used by font-lock for highlighting in Org-mode
3815 Emacs buffers, and the HTML tags to be used for this.
3816 Use customize to modify this, or restart Emacs after changing it."
3817 :group 'org-font-lock
3818 :set 'org-set-emph-re
3819 :type '(repeat
3820 (list
3821 (string :tag "Marker character")
3822 (choice
3823 (face :tag "Font-lock-face")
3824 (plist :tag "Face property list"))
3825 (string :tag "HTML start tag")
3826 (string :tag "HTML end tag")
3827 (option (const verbatim)))))
3829 ;;; The faces
3831 (defgroup org-faces nil
3832 "Faces in Org-mode."
3833 :tag "Org Faces"
3834 :group 'org-font-lock)
3836 (defun org-compatible-face (inherits specs)
3837 "Make a compatible face specification.
3838 If INHERITS is an existing face and if the Emacs version supports it,
3839 just inherit the face. If not, use SPECS to define the face.
3840 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3841 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3842 to the top of the list. The `min-colors' attribute will be removed from
3843 any other entries, and any resulting duplicates will be removed entirely."
3844 (cond
3845 ((and inherits (facep inherits)
3846 (not (featurep 'xemacs)) (> emacs-major-version 22))
3847 ;; In Emacs 23, we use inheritance where possible.
3848 ;; We only do this in Emacs 23, because only there the outline
3849 ;; faces have been changed to the original org-mode-level-faces.
3850 (list (list t :inherit inherits)))
3851 ((or (featurep 'xemacs) (< emacs-major-version 22))
3852 ;; These do not understand the `min-colors' attribute.
3853 (let (r e a)
3854 (while (setq e (pop specs))
3855 (cond
3856 ((memq (car e) '(t default)) (push e r))
3857 ((setq a (member '(min-colors 8) (car e)))
3858 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3859 (cdr e)))))
3860 ((setq a (assq 'min-colors (car e)))
3861 (setq e (cons (delq a (car e)) (cdr e)))
3862 (or (assoc (car e) r) (push e r)))
3863 (t (or (assoc (car e) r) (push e r)))))
3864 (nreverse r)))
3865 (t specs)))
3866 (put 'org-compatible-face 'lisp-indent-function 1)
3868 (defface org-hide
3869 '((((background light)) (:foreground "white"))
3870 (((background dark)) (:foreground "black")))
3871 "Face used to hide leading stars in headlines.
3872 The forground color of this face should be equal to the background
3873 color of the frame."
3874 :group 'org-faces)
3876 (defface org-level-1 ;; font-lock-function-name-face
3877 (org-compatible-face 'outline-1
3878 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3879 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3880 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3881 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3882 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3883 (t (:bold t))))
3884 "Face used for level 1 headlines."
3885 :group 'org-faces)
3887 (defface org-level-2 ;; font-lock-variable-name-face
3888 (org-compatible-face 'outline-2
3889 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3890 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3891 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3892 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3893 (t (:bold t))))
3894 "Face used for level 2 headlines."
3895 :group 'org-faces)
3897 (defface org-level-3 ;; font-lock-keyword-face
3898 (org-compatible-face 'outline-3
3899 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3900 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3901 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3902 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3903 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3904 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3905 (t (:bold t))))
3906 "Face used for level 3 headlines."
3907 :group 'org-faces)
3909 (defface org-level-4 ;; font-lock-comment-face
3910 (org-compatible-face 'outline-4
3911 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3912 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3913 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3914 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3915 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3916 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3917 (t (:bold t))))
3918 "Face used for level 4 headlines."
3919 :group 'org-faces)
3921 (defface org-level-5 ;; font-lock-type-face
3922 (org-compatible-face 'outline-5
3923 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3924 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3925 (((class color) (min-colors 8)) (:foreground "green"))))
3926 "Face used for level 5 headlines."
3927 :group 'org-faces)
3929 (defface org-level-6 ;; font-lock-constant-face
3930 (org-compatible-face 'outline-6
3931 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3932 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3933 (((class color) (min-colors 8)) (:foreground "magenta"))))
3934 "Face used for level 6 headlines."
3935 :group 'org-faces)
3937 (defface org-level-7 ;; font-lock-builtin-face
3938 (org-compatible-face 'outline-7
3939 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3940 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3941 (((class color) (min-colors 8)) (:foreground "blue"))))
3942 "Face used for level 7 headlines."
3943 :group 'org-faces)
3945 (defface org-level-8 ;; font-lock-string-face
3946 (org-compatible-face 'outline-8
3947 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3948 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3949 (((class color) (min-colors 8)) (:foreground "green"))))
3950 "Face used for level 8 headlines."
3951 :group 'org-faces)
3953 (defface org-special-keyword ;; font-lock-string-face
3954 (org-compatible-face nil
3955 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3956 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3957 (t (:italic t))))
3958 "Face used for special keywords."
3959 :group 'org-faces)
3961 (defface org-drawer ;; font-lock-function-name-face
3962 (org-compatible-face nil
3963 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3964 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3965 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3966 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3967 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3968 (t (:bold t))))
3969 "Face used for drawers."
3970 :group 'org-faces)
3972 (defface org-property-value nil
3973 "Face used for the value of a property."
3974 :group 'org-faces)
3976 (defface org-column
3977 (org-compatible-face nil
3978 '((((class color) (min-colors 16) (background light))
3979 (:background "grey90"))
3980 (((class color) (min-colors 16) (background dark))
3981 (:background "grey30"))
3982 (((class color) (min-colors 8))
3983 (:background "cyan" :foreground "black"))
3984 (t (:inverse-video t))))
3985 "Face for column display of entry properties."
3986 :group 'org-faces)
3988 (when (fboundp 'set-face-attribute)
3989 ;; Make sure that a fixed-width face is used when we have a column table.
3990 (set-face-attribute 'org-column nil
3991 :height (face-attribute 'default :height)
3992 :family (face-attribute 'default :family)))
3994 (defface org-warning
3995 (org-compatible-face 'font-lock-warning-face
3996 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3997 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3998 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3999 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4000 (t (:bold t))))
4001 "Face for deadlines and TODO keywords."
4002 :group 'org-faces)
4004 (defface org-archived ; similar to shadow
4005 (org-compatible-face 'shadow
4006 '((((class color grayscale) (min-colors 88) (background light))
4007 (:foreground "grey50"))
4008 (((class color grayscale) (min-colors 88) (background dark))
4009 (:foreground "grey70"))
4010 (((class color) (min-colors 8) (background light))
4011 (:foreground "green"))
4012 (((class color) (min-colors 8) (background dark))
4013 (:foreground "yellow"))))
4014 "Face for headline with the ARCHIVE tag."
4015 :group 'org-faces)
4017 (defface org-link
4018 '((((class color) (background light)) (:foreground "Purple" :underline t))
4019 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4020 (t (:underline t)))
4021 "Face for links."
4022 :group 'org-faces)
4024 (defface org-ellipsis
4025 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
4026 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
4027 (t (:strike-through t)))
4028 "Face for the ellipsis in folded text."
4029 :group 'org-faces)
4031 (defface org-target
4032 '((((class color) (background light)) (:underline t))
4033 (((class color) (background dark)) (:underline t))
4034 (t (:underline t)))
4035 "Face for links."
4036 :group 'org-faces)
4038 (defface org-date
4039 '((((class color) (background light)) (:foreground "Purple" :underline t))
4040 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4041 (t (:underline t)))
4042 "Face for links."
4043 :group 'org-faces)
4045 (defface org-sexp-date
4046 '((((class color) (background light)) (:foreground "Purple"))
4047 (((class color) (background dark)) (:foreground "Cyan"))
4048 (t (:underline t)))
4049 "Face for links."
4050 :group 'org-faces)
4052 (defface org-tag
4053 '((t (:bold t)))
4054 "Face for tags."
4055 :group 'org-faces)
4057 (defface org-todo ; font-lock-warning-face
4058 (org-compatible-face nil
4059 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4060 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4061 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4062 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4063 (t (:inverse-video t :bold t))))
4064 "Face for TODO keywords."
4065 :group 'org-faces)
4067 (defface org-done ;; font-lock-type-face
4068 (org-compatible-face nil
4069 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
4070 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
4071 (((class color) (min-colors 8)) (:foreground "green"))
4072 (t (:bold t))))
4073 "Face used for todo keywords that indicate DONE items."
4074 :group 'org-faces)
4076 (defface org-headline-done ;; font-lock-string-face
4077 (org-compatible-face nil
4078 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4079 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4080 (((class color) (min-colors 8) (background light)) (:bold nil))))
4081 "Face used to indicate that a headline is DONE.
4082 This face is only used if `org-fontify-done-headline' is set. If applies
4083 to the part of the headline after the DONE keyword."
4084 :group 'org-faces)
4086 (defcustom org-todo-keyword-faces nil
4087 "Faces for specific TODO keywords.
4088 This is a list of cons cells, with TODO keywords in the car
4089 and faces in the cdr. The face can be a symbol, or a property
4090 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
4091 :group 'org-faces
4092 :group 'org-todo
4093 :type '(repeat
4094 (cons
4095 (string :tag "keyword")
4096 (sexp :tag "face"))))
4098 (defface org-table ;; font-lock-function-name-face
4099 (org-compatible-face nil
4100 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4101 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4102 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4103 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4104 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4105 (((class color) (min-colors 8) (background dark)))))
4106 "Face used for tables."
4107 :group 'org-faces)
4109 (defface org-formula
4110 (org-compatible-face nil
4111 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4112 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4113 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4114 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4115 (t (:bold t :italic t))))
4116 "Face for formulas."
4117 :group 'org-faces)
4119 (defface org-code
4120 (org-compatible-face nil
4121 '((((class color grayscale) (min-colors 88) (background light))
4122 (:foreground "grey50"))
4123 (((class color grayscale) (min-colors 88) (background dark))
4124 (:foreground "grey70"))
4125 (((class color) (min-colors 8) (background light))
4126 (:foreground "green"))
4127 (((class color) (min-colors 8) (background dark))
4128 (:foreground "yellow"))))
4129 "Face for fixed-with text like code snippets."
4130 :group 'org-faces
4131 :version "22.1")
4133 (defface org-verbatim
4134 (org-compatible-face nil
4135 '((((class color grayscale) (min-colors 88) (background light))
4136 (:foreground "grey50" :underline t))
4137 (((class color grayscale) (min-colors 88) (background dark))
4138 (:foreground "grey70" :underline t))
4139 (((class color) (min-colors 8) (background light))
4140 (:foreground "green" :underline t))
4141 (((class color) (min-colors 8) (background dark))
4142 (:foreground "yellow" :underline t))))
4143 "Face for fixed-with text like code snippets."
4144 :group 'org-faces
4145 :version "22.1")
4147 (defface org-agenda-structure ;; font-lock-function-name-face
4148 (org-compatible-face nil
4149 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4150 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4151 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4152 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4153 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4154 (t (:bold t))))
4155 "Face used in agenda for captions and dates."
4156 :group 'org-faces)
4158 (defface org-scheduled-today
4159 (org-compatible-face nil
4160 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4161 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4162 (((class color) (min-colors 8)) (:foreground "green"))
4163 (t (:bold t :italic t))))
4164 "Face for items scheduled for a certain day."
4165 :group 'org-faces)
4167 (defface org-scheduled-previously
4168 (org-compatible-face nil
4169 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4170 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4171 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4172 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4173 (t (:bold t))))
4174 "Face for items scheduled previously, and not yet done."
4175 :group 'org-faces)
4177 (defface org-upcoming-deadline
4178 (org-compatible-face nil
4179 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4180 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4181 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4182 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4183 (t (:bold t))))
4184 "Face for items scheduled previously, and not yet done."
4185 :group 'org-faces)
4187 (defcustom org-agenda-deadline-faces
4188 '((1.0 . org-warning)
4189 (0.5 . org-upcoming-deadline)
4190 (0.0 . default))
4191 "Faces for showing deadlines in the agenda.
4192 This is a list of cons cells. The cdr of each cell is a face to be used,
4193 and it can also just be like '(:foreground \"yellow\").
4194 Each car is a fraction of the head-warning time that must have passed for
4195 this the face in the cdr to be used for display. The numbers must be
4196 given in descending order. The head-warning time is normally taken
4197 from `org-deadline-warning-days', but can also be specified in the deadline
4198 timestamp itself, like this:
4200 DEADLINE: <2007-08-13 Mon -8d>
4202 You may use d for days, w for weeks, m for months and y for years. Months
4203 and years will only be treated in an approximate fashion (30.4 days for a
4204 month and 365.24 days for a year)."
4205 :group 'org-faces
4206 :group 'org-agenda-daily/weekly
4207 :type '(repeat
4208 (cons
4209 (number :tag "Fraction of head-warning time passed")
4210 (sexp :tag "Face"))))
4212 ;; FIXME: this is not a good face yet.
4213 (defface org-agenda-restriction-lock
4214 (org-compatible-face nil
4215 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4216 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4217 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4218 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4219 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4220 (t (:inverse-video t))))
4221 "Face for showing the agenda restriction lock."
4222 :group 'org-faces)
4224 (defface org-time-grid ;; font-lock-variable-name-face
4225 (org-compatible-face nil
4226 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4227 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4228 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4229 "Face used for time grids."
4230 :group 'org-faces)
4232 (defconst org-level-faces
4233 '(org-level-1 org-level-2 org-level-3 org-level-4
4234 org-level-5 org-level-6 org-level-7 org-level-8
4237 (defcustom org-n-level-faces (length org-level-faces)
4238 "The number of different faces to be used for headlines.
4239 Org-mode defines 8 different headline faces, so this can be at most 8.
4240 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4241 :type 'number
4242 :group 'org-faces)
4244 ;;; Functions and variables from ther packages
4245 ;; Declared here to avoid compiler warnings
4247 (eval-and-compile
4248 (unless (fboundp 'declare-function)
4249 (defmacro declare-function (fn file &optional arglist fileonly))))
4251 ;; XEmacs only
4252 (defvar outline-mode-menu-heading)
4253 (defvar outline-mode-menu-show)
4254 (defvar outline-mode-menu-hide)
4255 (defvar zmacs-regions) ; XEmacs regions
4257 ;; Emacs only
4258 (defvar mark-active)
4260 ;; Various packages
4261 ;; FIXME: get the argument lists for the UNKNOWN stuff
4262 (declare-function add-to-diary-list "diary-lib"
4263 (date string specifier &optional marker globcolor literal))
4264 (declare-function table--at-cell-p "table" (position &optional object at-column))
4265 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4266 (declare-function bbdb "ext:bbdb-com" (string elidep))
4267 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4268 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4269 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4270 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4271 (declare-function bbdb-record-name "ext:bbdb" (record))
4272 (declare-function bibtex-beginning-of-entry "bibtex" ())
4273 (declare-function bibtex-generate-autokey "bibtex" ())
4274 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4275 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4276 (defvar calc-embedded-close-formula)
4277 (defvar calc-embedded-open-formula)
4278 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4279 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4280 (declare-function calendar-check-holidays "holidays" (date))
4281 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4282 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4283 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4284 (declare-function calendar-forward-day "cal-move" (arg))
4285 (declare-function calendar-french-date-string "cal-french" (&optional date))
4286 (declare-function calendar-goto-date "cal-move" (date))
4287 (declare-function calendar-goto-today "cal-move" ())
4288 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4289 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4290 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4291 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4292 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4293 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4294 (defvar calendar-mode-map)
4295 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4296 (declare-function cdlatex-tab "ext:cdlatex" ())
4297 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4298 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4299 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4300 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4301 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4302 (defvar font-lock-unfontify-region-function)
4303 (declare-function gnus-article-show-summary "gnus-art" ())
4304 (declare-function gnus-summary-last-subject "gnus-sum" ())
4305 (defvar gnus-other-frame-object)
4306 (defvar gnus-group-name)
4307 (defvar gnus-article-current)
4308 (defvar Info-current-file)
4309 (defvar Info-current-node)
4310 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4311 (declare-function mh-find-path "mh-utils" ())
4312 (declare-function mh-get-header-field "mh-utils" (field))
4313 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4314 (declare-function mh-header-display "mh-show" ())
4315 (declare-function mh-index-previous-folder "mh-search" ())
4316 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4317 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4318 (declare-function mh-search-choose "mh-search" (&optional searcher))
4319 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4320 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4321 (declare-function mh-show-header-display "mh-show" t t)
4322 (declare-function mh-show-msg "mh-show" (msg))
4323 (declare-function mh-show-show "mh-show" t t)
4324 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4325 (defvar mh-progs)
4326 (defvar mh-current-folder)
4327 (defvar mh-show-folder-buffer)
4328 (defvar mh-index-folder)
4329 (defvar mh-searcher)
4330 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4331 (declare-function parse-time-string "parse-time" (string))
4332 (declare-function remember "remember" (&optional initial))
4333 (declare-function remember-buffer-desc "remember" ())
4334 (declare-function remember-finalize "remember" ())
4335 (defvar remember-save-after-remembering)
4336 (defvar remember-data-file)
4337 (defvar remember-register)
4338 (defvar remember-buffer)
4339 (defvar remember-handler-functions)
4340 (defvar remember-annotation-functions)
4341 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4342 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4343 (declare-function rmail-what-message "rmail" ())
4344 (defvar rmail-current-message)
4345 (defvar texmathp-why)
4346 (declare-function vm-beginning-of-message "ext:vm-page" ())
4347 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4348 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4349 (declare-function vm-isearch-narrow "ext:vm-search" ())
4350 (declare-function vm-isearch-update "ext:vm-search" ())
4351 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4352 (declare-function vm-su-message-id "ext:vm-summary" (m))
4353 (declare-function vm-su-subject "ext:vm-summary" (m))
4354 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4355 (defvar vm-message-pointer)
4356 (defvar vm-folder-directory)
4357 (defvar w3m-current-url)
4358 (defvar w3m-current-title)
4359 ;; backward compatibility to old version of wl
4360 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4361 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4362 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4363 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4364 (declare-function wl-summary-line-from "ext:wl-summary" ())
4365 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4366 (declare-function wl-summary-message-number "ext:wl-summary" ())
4367 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4368 (defvar wl-summary-buffer-elmo-folder)
4369 (defvar wl-summary-buffer-folder-name)
4370 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4372 (defvar org-latex-regexps)
4373 (defvar constants-unit-system)
4375 ;;; Variables for pre-computed regular expressions, all buffer local
4377 (defvar org-drawer-regexp nil
4378 "Matches first line of a hidden block.")
4379 (make-variable-buffer-local 'org-drawer-regexp)
4380 (defvar org-todo-regexp nil
4381 "Matches any of the TODO state keywords.")
4382 (make-variable-buffer-local 'org-todo-regexp)
4383 (defvar org-not-done-regexp nil
4384 "Matches any of the TODO state keywords except the last one.")
4385 (make-variable-buffer-local 'org-not-done-regexp)
4386 (defvar org-todo-line-regexp nil
4387 "Matches a headline and puts TODO state into group 2 if present.")
4388 (make-variable-buffer-local 'org-todo-line-regexp)
4389 (defvar org-complex-heading-regexp nil
4390 "Matches a headline and puts everything into groups:
4391 group 1: the stars
4392 group 2: The todo keyword, maybe
4393 group 3: Priority cookie
4394 group 4: True headline
4395 group 5: Tags")
4396 (make-variable-buffer-local 'org-complex-heading-regexp)
4397 (defvar org-todo-line-tags-regexp nil
4398 "Matches a headline and puts TODO state into group 2 if present.
4399 Also put tags into group 4 if tags are present.")
4400 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4401 (defvar org-nl-done-regexp nil
4402 "Matches newline followed by a headline with the DONE keyword.")
4403 (make-variable-buffer-local 'org-nl-done-regexp)
4404 (defvar org-looking-at-done-regexp nil
4405 "Matches the DONE keyword a point.")
4406 (make-variable-buffer-local 'org-looking-at-done-regexp)
4407 (defvar org-ds-keyword-length 12
4408 "Maximum length of the Deadline and SCHEDULED keywords.")
4409 (make-variable-buffer-local 'org-ds-keyword-length)
4410 (defvar org-deadline-regexp nil
4411 "Matches the DEADLINE keyword.")
4412 (make-variable-buffer-local 'org-deadline-regexp)
4413 (defvar org-deadline-time-regexp nil
4414 "Matches the DEADLINE keyword together with a time stamp.")
4415 (make-variable-buffer-local 'org-deadline-time-regexp)
4416 (defvar org-deadline-line-regexp nil
4417 "Matches the DEADLINE keyword and the rest of the line.")
4418 (make-variable-buffer-local 'org-deadline-line-regexp)
4419 (defvar org-scheduled-regexp nil
4420 "Matches the SCHEDULED keyword.")
4421 (make-variable-buffer-local 'org-scheduled-regexp)
4422 (defvar org-scheduled-time-regexp nil
4423 "Matches the SCHEDULED keyword together with a time stamp.")
4424 (make-variable-buffer-local 'org-scheduled-time-regexp)
4425 (defvar org-closed-time-regexp nil
4426 "Matches the CLOSED keyword together with a time stamp.")
4427 (make-variable-buffer-local 'org-closed-time-regexp)
4429 (defvar org-keyword-time-regexp nil
4430 "Matches any of the 4 keywords, together with the time stamp.")
4431 (make-variable-buffer-local 'org-keyword-time-regexp)
4432 (defvar org-keyword-time-not-clock-regexp nil
4433 "Matches any of the 3 keywords, together with the time stamp.")
4434 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4435 (defvar org-maybe-keyword-time-regexp nil
4436 "Matches a timestamp, possibly preceeded by a keyword.")
4437 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4438 (defvar org-planning-or-clock-line-re nil
4439 "Matches a line with planning or clock info.")
4440 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4442 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4443 rear-nonsticky t mouse-map t fontified t)
4444 "Properties to remove when a string without properties is wanted.")
4446 (defsubst org-match-string-no-properties (num &optional string)
4447 (if (featurep 'xemacs)
4448 (let ((s (match-string num string)))
4449 (remove-text-properties 0 (length s) org-rm-props s)
4451 (match-string-no-properties num string)))
4453 (defsubst org-no-properties (s)
4454 (if (fboundp 'set-text-properties)
4455 (set-text-properties 0 (length s) nil s)
4456 (remove-text-properties 0 (length s) org-rm-props s))
4459 (defsubst org-get-alist-option (option key)
4460 (cond ((eq key t) t)
4461 ((eq option t) t)
4462 ((assoc key option) (cdr (assoc key option)))
4463 (t (cdr (assq 'default option)))))
4465 (defsubst org-inhibit-invisibility ()
4466 "Modified `buffer-invisibility-spec' for Emacs 21.
4467 Some ops with invisible text do not work correctly on Emacs 21. For these
4468 we turn off invisibility temporarily. Use this in a `let' form."
4469 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4471 (defsubst org-set-local (var value)
4472 "Make VAR local in current buffer and set it to VALUE."
4473 (set (make-variable-buffer-local var) value))
4475 (defsubst org-mode-p ()
4476 "Check if the current buffer is in Org-mode."
4477 (eq major-mode 'org-mode))
4479 (defsubst org-last (list)
4480 "Return the last element of LIST."
4481 (car (last list)))
4483 (defun org-let (list &rest body)
4484 (eval (cons 'let (cons list body))))
4485 (put 'org-let 'lisp-indent-function 1)
4487 (defun org-let2 (list1 list2 &rest body)
4488 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4489 (put 'org-let2 'lisp-indent-function 2)
4490 (defconst org-startup-options
4491 '(("fold" org-startup-folded t)
4492 ("overview" org-startup-folded t)
4493 ("nofold" org-startup-folded nil)
4494 ("showall" org-startup-folded nil)
4495 ("content" org-startup-folded content)
4496 ("hidestars" org-hide-leading-stars t)
4497 ("showstars" org-hide-leading-stars nil)
4498 ("odd" org-odd-levels-only t)
4499 ("oddeven" org-odd-levels-only nil)
4500 ("align" org-startup-align-all-tables t)
4501 ("noalign" org-startup-align-all-tables nil)
4502 ("customtime" org-display-custom-times t)
4503 ("logdone" org-log-done time)
4504 ("lognotedone" org-log-done note)
4505 ("nologdone" org-log-done nil)
4506 ("lognoteclock-out" org-log-note-clock-out t)
4507 ("nolognoteclock-out" org-log-note-clock-out nil)
4508 ("logrepeat" org-log-repeat state)
4509 ("lognoterepeat" org-log-repeat note)
4510 ("nologrepeat" org-log-repeat nil)
4511 ("constcgs" constants-unit-system cgs)
4512 ("constSI" constants-unit-system SI))
4513 "Variable associated with STARTUP options for org-mode.
4514 Each element is a list of three items: The startup options as written
4515 in the #+STARTUP line, the corresponding variable, and the value to
4516 set this variable to if the option is found. An optional forth element PUSH
4517 means to push this value onto the list in the variable.")
4519 (defun org-set-regexps-and-options ()
4520 "Precompute regular expressions for current buffer."
4521 (when (org-mode-p)
4522 (org-set-local 'org-todo-kwd-alist nil)
4523 (org-set-local 'org-todo-key-alist nil)
4524 (org-set-local 'org-todo-key-trigger nil)
4525 (org-set-local 'org-todo-keywords-1 nil)
4526 (org-set-local 'org-done-keywords nil)
4527 (org-set-local 'org-todo-heads nil)
4528 (org-set-local 'org-todo-sets nil)
4529 (org-set-local 'org-todo-log-states nil)
4530 (let ((re (org-make-options-regexp
4531 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4532 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4533 "CONSTANTS" "PROPERTY" "DRAWERS")))
4534 (splitre "[ \t]+")
4535 kwds kws0 kwsa key log value cat arch tags const links hw dws
4536 tail sep kws1 prio props drawers)
4537 (save-excursion
4538 (save-restriction
4539 (widen)
4540 (goto-char (point-min))
4541 (while (re-search-forward re nil t)
4542 (setq key (match-string 1) value (org-match-string-no-properties 2))
4543 (cond
4544 ((equal key "CATEGORY")
4545 (if (string-match "[ \t]+$" value)
4546 (setq value (replace-match "" t t value)))
4547 (setq cat value))
4548 ((member key '("SEQ_TODO" "TODO"))
4549 (push (cons 'sequence (org-split-string value splitre)) kwds))
4550 ((equal key "TYP_TODO")
4551 (push (cons 'type (org-split-string value splitre)) kwds))
4552 ((equal key "TAGS")
4553 (setq tags (append tags (org-split-string value splitre))))
4554 ((equal key "COLUMNS")
4555 (org-set-local 'org-columns-default-format value))
4556 ((equal key "LINK")
4557 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4558 (push (cons (match-string 1 value)
4559 (org-trim (match-string 2 value)))
4560 links)))
4561 ((equal key "PRIORITIES")
4562 (setq prio (org-split-string value " +")))
4563 ((equal key "PROPERTY")
4564 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4565 (push (cons (match-string 1 value) (match-string 2 value))
4566 props)))
4567 ((equal key "DRAWERS")
4568 (setq drawers (org-split-string value splitre)))
4569 ((equal key "CONSTANTS")
4570 (setq const (append const (org-split-string value splitre))))
4571 ((equal key "STARTUP")
4572 (let ((opts (org-split-string value splitre))
4573 l var val)
4574 (while (setq l (pop opts))
4575 (when (setq l (assoc l org-startup-options))
4576 (setq var (nth 1 l) val (nth 2 l))
4577 (if (not (nth 3 l))
4578 (set (make-local-variable var) val)
4579 (if (not (listp (symbol-value var)))
4580 (set (make-local-variable var) nil))
4581 (set (make-local-variable var) (symbol-value var))
4582 (add-to-list var val))))))
4583 ((equal key "ARCHIVE")
4584 (string-match " *$" value)
4585 (setq arch (replace-match "" t t value))
4586 (remove-text-properties 0 (length arch)
4587 '(face t fontified t) arch)))
4589 (when cat
4590 (org-set-local 'org-category (intern cat))
4591 (push (cons "CATEGORY" cat) props))
4592 (when prio
4593 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4594 (setq prio (mapcar 'string-to-char prio))
4595 (org-set-local 'org-highest-priority (nth 0 prio))
4596 (org-set-local 'org-lowest-priority (nth 1 prio))
4597 (org-set-local 'org-default-priority (nth 2 prio)))
4598 (and props (org-set-local 'org-local-properties (nreverse props)))
4599 (and drawers (org-set-local 'org-drawers drawers))
4600 (and arch (org-set-local 'org-archive-location arch))
4601 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4602 ;; Process the TODO keywords
4603 (unless kwds
4604 ;; Use the global values as if they had been given locally.
4605 (setq kwds (default-value 'org-todo-keywords))
4606 (if (stringp (car kwds))
4607 (setq kwds (list (cons org-todo-interpretation
4608 (default-value 'org-todo-keywords)))))
4609 (setq kwds (reverse kwds)))
4610 (setq kwds (nreverse kwds))
4611 (let (inter kws kw)
4612 (while (setq kws (pop kwds))
4613 (setq inter (pop kws) sep (member "|" kws)
4614 kws0 (delete "|" (copy-sequence kws))
4615 kwsa nil
4616 kws1 (mapcar
4617 (lambda (x)
4618 ;; 1 2
4619 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4620 (progn
4621 (setq kw (match-string 1 x)
4622 key (and (match-end 2) (match-string 2 x))
4623 log (org-extract-log-state-settings x))
4624 (push (cons kw (and key (string-to-char key))) kwsa)
4625 (and log (push log org-todo-log-states))
4627 (error "Invalid TODO keyword %s" x)))
4628 kws0)
4629 kwsa (if kwsa (append '((:startgroup))
4630 (nreverse kwsa)
4631 '((:endgroup))))
4632 hw (car kws1)
4633 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4634 tail (list inter hw (car dws) (org-last dws)))
4635 (add-to-list 'org-todo-heads hw 'append)
4636 (push kws1 org-todo-sets)
4637 (setq org-done-keywords (append org-done-keywords dws nil))
4638 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4639 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4640 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4641 (setq org-todo-sets (nreverse org-todo-sets)
4642 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4643 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4644 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4645 ;; Process the constants
4646 (when const
4647 (let (e cst)
4648 (while (setq e (pop const))
4649 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4650 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4651 (setq org-table-formula-constants-local cst)))
4653 ;; Process the tags.
4654 (when tags
4655 (let (e tgs)
4656 (while (setq e (pop tags))
4657 (cond
4658 ((equal e "{") (push '(:startgroup) tgs))
4659 ((equal e "}") (push '(:endgroup) tgs))
4660 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4661 (push (cons (match-string 1 e)
4662 (string-to-char (match-string 2 e)))
4663 tgs))
4664 (t (push (list e) tgs))))
4665 (org-set-local 'org-tag-alist nil)
4666 (while (setq e (pop tgs))
4667 (or (and (stringp (car e))
4668 (assoc (car e) org-tag-alist))
4669 (push e org-tag-alist))))))
4671 ;; Compute the regular expressions and other local variables
4672 (if (not org-done-keywords)
4673 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4674 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4675 (length org-scheduled-string)))
4676 org-drawer-regexp
4677 (concat "^[ \t]*:\\("
4678 (mapconcat 'regexp-quote org-drawers "\\|")
4679 "\\):[ \t]*$")
4680 org-not-done-keywords
4681 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4682 org-todo-regexp
4683 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4684 "\\|") "\\)\\>")
4685 org-not-done-regexp
4686 (concat "\\<\\("
4687 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4688 "\\)\\>")
4689 org-todo-line-regexp
4690 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4691 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4692 "\\)\\>\\)?[ \t]*\\(.*\\)")
4693 org-complex-heading-regexp
4694 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4695 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4696 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4697 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4698 org-nl-done-regexp
4699 (concat "\n\\*+[ \t]+"
4700 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4701 "\\)" "\\>")
4702 org-todo-line-tags-regexp
4703 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4704 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4705 (org-re
4706 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4707 org-looking-at-done-regexp
4708 (concat "^" "\\(?:"
4709 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4710 "\\>")
4711 org-deadline-regexp (concat "\\<" org-deadline-string)
4712 org-deadline-time-regexp
4713 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4714 org-deadline-line-regexp
4715 (concat "\\<\\(" org-deadline-string "\\).*")
4716 org-scheduled-regexp
4717 (concat "\\<" org-scheduled-string)
4718 org-scheduled-time-regexp
4719 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4720 org-closed-time-regexp
4721 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4722 org-keyword-time-regexp
4723 (concat "\\<\\(" org-scheduled-string
4724 "\\|" org-deadline-string
4725 "\\|" org-closed-string
4726 "\\|" org-clock-string "\\)"
4727 " *[[<]\\([^]>]+\\)[]>]")
4728 org-keyword-time-not-clock-regexp
4729 (concat "\\<\\(" org-scheduled-string
4730 "\\|" org-deadline-string
4731 "\\|" org-closed-string
4732 "\\)"
4733 " *[[<]\\([^]>]+\\)[]>]")
4734 org-maybe-keyword-time-regexp
4735 (concat "\\(\\<\\(" org-scheduled-string
4736 "\\|" org-deadline-string
4737 "\\|" org-closed-string
4738 "\\|" org-clock-string "\\)\\)?"
4739 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4740 org-planning-or-clock-line-re
4741 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4742 "\\|" org-deadline-string
4743 "\\|" org-closed-string "\\|" org-clock-string
4744 "\\)\\>\\)")
4746 (org-compute-latex-and-specials-regexp)
4747 (org-set-font-lock-defaults)))
4749 (defun org-extract-log-state-settings (x)
4750 "Extract the log state setting from a TODO keyword string.
4751 This will extract info from a string like \"WAIT(w@/!)\"."
4752 (let (kw key log1 log2)
4753 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4754 (setq kw (match-string 1 x)
4755 key (and (match-end 2) (match-string 2 x))
4756 log1 (and (match-end 3) (match-string 3 x))
4757 log2 (and (match-end 4) (match-string 4 x)))
4758 (and (or log1 log2)
4759 (list kw
4760 (and log1 (if (equal log1 "!") 'time 'note))
4761 (and log2 (if (equal log2 "!") 'time 'note)))))))
4763 (defun org-remove-keyword-keys (list)
4764 "Remove a pair of parenthesis at the end of each string in LIST."
4765 (mapcar (lambda (x)
4766 (if (string-match "(.*)$" x)
4767 (substring x 0 (match-beginning 0))
4769 list))
4771 ;; FIXME: this could be done much better, using second characters etc.
4772 (defun org-assign-fast-keys (alist)
4773 "Assign fast keys to a keyword-key alist.
4774 Respect keys that are already there."
4775 (let (new e k c c1 c2 (char ?a))
4776 (while (setq e (pop alist))
4777 (cond
4778 ((equal e '(:startgroup)) (push e new))
4779 ((equal e '(:endgroup)) (push e new))
4781 (setq k (car e) c2 nil)
4782 (if (cdr e)
4783 (setq c (cdr e))
4784 ;; automatically assign a character.
4785 (setq c1 (string-to-char
4786 (downcase (substring
4787 k (if (= (string-to-char k) ?@) 1 0)))))
4788 (if (or (rassoc c1 new) (rassoc c1 alist))
4789 (while (or (rassoc char new) (rassoc char alist))
4790 (setq char (1+ char)))
4791 (setq c2 c1))
4792 (setq c (or c2 char)))
4793 (push (cons k c) new))))
4794 (nreverse new)))
4796 ;;; Some variables ujsed in various places
4798 (defvar org-window-configuration nil
4799 "Used in various places to store a window configuration.")
4800 (defvar org-finish-function nil
4801 "Function to be called when `C-c C-c' is used.
4802 This is for getting out of special buffers like remember.")
4805 ;; FIXME: Occasionally check by commenting these, to make sure
4806 ;; no other functions uses these, forgetting to let-bind them.
4807 (defvar entry)
4808 (defvar state)
4809 (defvar last-state)
4810 (defvar date)
4811 (defvar description)
4813 ;; Defined somewhere in this file, but used before definition.
4814 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4815 (defvar org-agenda-buffer-name)
4816 (defvar org-agenda-undo-list)
4817 (defvar org-agenda-pending-undo-list)
4818 (defvar org-agenda-overriding-header)
4819 (defvar orgtbl-mode)
4820 (defvar org-html-entities)
4821 (defvar org-struct-menu)
4822 (defvar org-org-menu)
4823 (defvar org-tbl-menu)
4824 (defvar org-agenda-keymap)
4826 ;;;; Emacs/XEmacs compatibility
4828 ;; Overlay compatibility functions
4829 (defun org-make-overlay (beg end &optional buffer)
4830 (if (featurep 'xemacs)
4831 (make-extent beg end buffer)
4832 (make-overlay beg end buffer)))
4833 (defun org-delete-overlay (ovl)
4834 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4835 (defun org-detach-overlay (ovl)
4836 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4837 (defun org-move-overlay (ovl beg end &optional buffer)
4838 (if (featurep 'xemacs)
4839 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4840 (move-overlay ovl beg end buffer)))
4841 (defun org-overlay-put (ovl prop value)
4842 (if (featurep 'xemacs)
4843 (set-extent-property ovl prop value)
4844 (overlay-put ovl prop value)))
4845 (defun org-overlay-display (ovl text &optional face evap)
4846 "Make overlay OVL display TEXT with face FACE."
4847 (if (featurep 'xemacs)
4848 (let ((gl (make-glyph text)))
4849 (and face (set-glyph-face gl face))
4850 (set-extent-property ovl 'invisible t)
4851 (set-extent-property ovl 'end-glyph gl))
4852 (overlay-put ovl 'display text)
4853 (if face (overlay-put ovl 'face face))
4854 (if evap (overlay-put ovl 'evaporate t))))
4855 (defun org-overlay-before-string (ovl text &optional face evap)
4856 "Make overlay OVL display TEXT with face FACE."
4857 (if (featurep 'xemacs)
4858 (let ((gl (make-glyph text)))
4859 (and face (set-glyph-face gl face))
4860 (set-extent-property ovl 'begin-glyph gl))
4861 (if face (org-add-props text nil 'face face))
4862 (overlay-put ovl 'before-string text)
4863 (if evap (overlay-put ovl 'evaporate t))))
4864 (defun org-overlay-get (ovl prop)
4865 (if (featurep 'xemacs)
4866 (extent-property ovl prop)
4867 (overlay-get ovl prop)))
4868 (defun org-overlays-at (pos)
4869 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4870 (defun org-overlays-in (&optional start end)
4871 (if (featurep 'xemacs)
4872 (extent-list nil start end)
4873 (overlays-in start end)))
4874 (defun org-overlay-start (o)
4875 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4876 (defun org-overlay-end (o)
4877 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4878 (defun org-find-overlays (prop &optional pos delete)
4879 "Find all overlays specifying PROP at POS or point.
4880 If DELETE is non-nil, delete all those overlays."
4881 (let ((overlays (org-overlays-at (or pos (point))))
4882 ov found)
4883 (while (setq ov (pop overlays))
4884 (if (org-overlay-get ov prop)
4885 (if delete (org-delete-overlay ov) (push ov found))))
4886 found))
4888 ;; Region compatibility
4890 (defun org-add-hook (hook function &optional append local)
4891 "Add-hook, compatible with both Emacsen."
4892 (if (and local (featurep 'xemacs))
4893 (add-local-hook hook function append)
4894 (add-hook hook function append local)))
4896 (defvar org-ignore-region nil
4897 "To temporarily disable the active region.")
4899 (defun org-region-active-p ()
4900 "Is `transient-mark-mode' on and the region active?
4901 Works on both Emacs and XEmacs."
4902 (if org-ignore-region
4904 (if (featurep 'xemacs)
4905 (and zmacs-regions (region-active-p))
4906 (if (fboundp 'use-region-p)
4907 (use-region-p)
4908 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4910 ;; Invisibility compatibility
4912 (defun org-add-to-invisibility-spec (arg)
4913 "Add elements to `buffer-invisibility-spec'.
4914 See documentation for `buffer-invisibility-spec' for the kind of elements
4915 that can be added."
4916 (cond
4917 ((fboundp 'add-to-invisibility-spec)
4918 (add-to-invisibility-spec arg))
4919 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4920 (setq buffer-invisibility-spec (list arg)))
4922 (setq buffer-invisibility-spec
4923 (cons arg buffer-invisibility-spec)))))
4925 (defun org-remove-from-invisibility-spec (arg)
4926 "Remove elements from `buffer-invisibility-spec'."
4927 (if (fboundp 'remove-from-invisibility-spec)
4928 (remove-from-invisibility-spec arg)
4929 (if (consp buffer-invisibility-spec)
4930 (setq buffer-invisibility-spec
4931 (delete arg buffer-invisibility-spec)))))
4933 (defun org-in-invisibility-spec-p (arg)
4934 "Is ARG a member of `buffer-invisibility-spec'?"
4935 (if (consp buffer-invisibility-spec)
4936 (member arg buffer-invisibility-spec)
4937 nil))
4939 ;;;; Define the Org-mode
4941 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4942 (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."))
4945 ;; We use a before-change function to check if a table might need
4946 ;; an update.
4947 (defvar org-table-may-need-update t
4948 "Indicates that a table might need an update.
4949 This variable is set by `org-before-change-function'.
4950 `org-table-align' sets it back to nil.")
4951 (defvar org-mode-map)
4952 (defvar org-mode-hook nil)
4953 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4954 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4955 (defvar org-table-buffer-is-an nil)
4956 (defconst org-outline-regexp "\\*+ ")
4958 ;;;###autoload
4959 (define-derived-mode org-mode outline-mode "Org"
4960 "Outline-based notes management and organizer, alias
4961 \"Carsten's outline-mode for keeping track of everything.\"
4963 Org-mode develops organizational tasks around a NOTES file which
4964 contains information about projects as plain text. Org-mode is
4965 implemented on top of outline-mode, which is ideal to keep the content
4966 of large files well structured. It supports ToDo items, deadlines and
4967 time stamps, which magically appear in the diary listing of the Emacs
4968 calendar. Tables are easily created with a built-in table editor.
4969 Plain text URL-like links connect to websites, emails (VM), Usenet
4970 messages (Gnus), BBDB entries, and any files related to the project.
4971 For printing and sharing of notes, an Org-mode file (or a part of it)
4972 can be exported as a structured ASCII or HTML file.
4974 The following commands are available:
4976 \\{org-mode-map}"
4978 ;; Get rid of Outline menus, they are not needed
4979 ;; Need to do this here because define-derived-mode sets up
4980 ;; the keymap so late. Still, it is a waste to call this each time
4981 ;; we switch another buffer into org-mode.
4982 (if (featurep 'xemacs)
4983 (when (boundp 'outline-mode-menu-heading)
4984 ;; Assume this is Greg's port, it used easymenu
4985 (easy-menu-remove outline-mode-menu-heading)
4986 (easy-menu-remove outline-mode-menu-show)
4987 (easy-menu-remove outline-mode-menu-hide))
4988 (define-key org-mode-map [menu-bar headings] 'undefined)
4989 (define-key org-mode-map [menu-bar hide] 'undefined)
4990 (define-key org-mode-map [menu-bar show] 'undefined))
4992 (easy-menu-add org-org-menu)
4993 (easy-menu-add org-tbl-menu)
4994 (org-install-agenda-files-menu)
4995 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4996 (org-add-to-invisibility-spec '(org-cwidth))
4997 (when (featurep 'xemacs)
4998 (org-set-local 'line-move-ignore-invisible t))
4999 (org-set-local 'outline-regexp org-outline-regexp)
5000 (org-set-local 'outline-level 'org-outline-level)
5001 (when (and org-ellipsis
5002 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5003 (fboundp 'make-glyph-code))
5004 (unless org-display-table
5005 (setq org-display-table (make-display-table)))
5006 (set-display-table-slot
5007 org-display-table 4
5008 (vconcat (mapcar
5009 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5010 org-ellipsis)))
5011 (if (stringp org-ellipsis) org-ellipsis "..."))))
5012 (setq buffer-display-table org-display-table))
5013 (org-set-regexps-and-options)
5014 ;; Calc embedded
5015 (org-set-local 'calc-embedded-open-mode "# ")
5016 (modify-syntax-entry ?# "<")
5017 (modify-syntax-entry ?@ "w")
5018 (if org-startup-truncated (setq truncate-lines t))
5019 (org-set-local 'font-lock-unfontify-region-function
5020 'org-unfontify-region)
5021 ;; Activate before-change-function
5022 (org-set-local 'org-table-may-need-update t)
5023 (org-add-hook 'before-change-functions 'org-before-change-function nil
5024 'local)
5025 ;; Check for running clock before killing a buffer
5026 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5027 ;; Paragraphs and auto-filling
5028 (org-set-autofill-regexps)
5029 (setq indent-line-function 'org-indent-line-function)
5030 (org-update-radio-target-regexp)
5032 ;; Comment characters
5033 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
5034 (org-set-local 'comment-padding " ")
5036 ;; Align options lines
5037 (org-set-local
5038 'align-mode-rules-list
5039 '((org-in-buffer-settings
5040 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5041 (modes . '(org-mode)))))
5043 ;; Imenu
5044 (org-set-local 'imenu-create-index-function
5045 'org-imenu-get-tree)
5047 ;; Make isearch reveal context
5048 (if (or (featurep 'xemacs)
5049 (not (boundp 'outline-isearch-open-invisible-function)))
5050 ;; Emacs 21 and XEmacs make use of the hook
5051 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5052 ;; Emacs 22 deals with this through a special variable
5053 (org-set-local 'outline-isearch-open-invisible-function
5054 (lambda (&rest ignore) (org-show-context 'isearch))))
5056 ;; If empty file that did not turn on org-mode automatically, make it to.
5057 (if (and org-insert-mode-line-in-empty-file
5058 (interactive-p)
5059 (= (point-min) (point-max)))
5060 (insert "# -*- mode: org -*-\n\n"))
5062 (unless org-inhibit-startup
5063 (when org-startup-align-all-tables
5064 (let ((bmp (buffer-modified-p)))
5065 (org-table-map-tables 'org-table-align)
5066 (set-buffer-modified-p bmp)))
5067 (org-cycle-hide-drawers 'all)
5068 (cond
5069 ((eq org-startup-folded t)
5070 (org-cycle '(4)))
5071 ((eq org-startup-folded 'content)
5072 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5073 (org-cycle '(4)) (org-cycle '(4)))))))
5075 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5077 (defsubst org-call-with-arg (command arg)
5078 "Call COMMAND interactively, but pretend prefix are was ARG."
5079 (let ((current-prefix-arg arg)) (call-interactively command)))
5081 (defsubst org-current-line (&optional pos)
5082 (save-excursion
5083 (and pos (goto-char pos))
5084 ;; works also in narrowed buffer, because we start at 1, not point-min
5085 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
5087 (defun org-current-time ()
5088 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5089 (if (> (car org-time-stamp-rounding-minutes) 1)
5090 (let ((r (car org-time-stamp-rounding-minutes))
5091 (time (decode-time)))
5092 (apply 'encode-time
5093 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5094 (nthcdr 2 time))))
5095 (current-time)))
5097 (defun org-add-props (string plist &rest props)
5098 "Add text properties to entire string, from beginning to end.
5099 PLIST may be a list of properties, PROPS are individual properties and values
5100 that will be added to PLIST. Returns the string that was modified."
5101 (add-text-properties
5102 0 (length string) (if props (append plist props) plist) string)
5103 string)
5104 (put 'org-add-props 'lisp-indent-function 2)
5107 ;;;; Font-Lock stuff, including the activators
5109 (defvar org-mouse-map (make-sparse-keymap))
5110 (org-defkey org-mouse-map
5111 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5112 (org-defkey org-mouse-map
5113 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5114 (when org-mouse-1-follows-link
5115 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5116 (when org-tab-follows-link
5117 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5118 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5119 (when org-return-follows-link
5120 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5121 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5123 (require 'font-lock)
5125 (defconst org-non-link-chars "]\t\n\r<>")
5126 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5127 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5128 (defvar org-link-re-with-space nil
5129 "Matches a link with spaces, optional angular brackets around it.")
5130 (defvar org-link-re-with-space2 nil
5131 "Matches a link with spaces, optional angular brackets around it.")
5132 (defvar org-angle-link-re nil
5133 "Matches link with angular brackets, spaces are allowed.")
5134 (defvar org-plain-link-re nil
5135 "Matches plain link, without spaces.")
5136 (defvar org-bracket-link-regexp nil
5137 "Matches a link in double brackets.")
5138 (defvar org-bracket-link-analytic-regexp nil
5139 "Regular expression used to analyze links.
5140 Here is what the match groups contain after a match:
5141 1: http:
5142 2: http
5143 3: path
5144 4: [desc]
5145 5: desc")
5146 (defvar org-any-link-re nil
5147 "Regular expression matching any link.")
5149 (defun org-make-link-regexps ()
5150 "Update the link regular expressions.
5151 This should be called after the variable `org-link-types' has changed."
5152 (setq org-link-re-with-space
5153 (concat
5154 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5155 "\\([^" org-non-link-chars " ]"
5156 "[^" org-non-link-chars "]*"
5157 "[^" org-non-link-chars " ]\\)>?")
5158 org-link-re-with-space2
5159 (concat
5160 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5161 "\\([^" org-non-link-chars " ]"
5162 "[^]\t\n\r]*"
5163 "[^" org-non-link-chars " ]\\)>?")
5164 org-angle-link-re
5165 (concat
5166 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5167 "\\([^" org-non-link-chars " ]"
5168 "[^" org-non-link-chars "]*"
5169 "\\)>")
5170 org-plain-link-re
5171 (concat
5172 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5173 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5174 org-bracket-link-regexp
5175 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5176 org-bracket-link-analytic-regexp
5177 (concat
5178 "\\[\\["
5179 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5180 "\\([^]]+\\)"
5181 "\\]"
5182 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5183 "\\]")
5184 org-any-link-re
5185 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5186 org-angle-link-re "\\)\\|\\("
5187 org-plain-link-re "\\)")))
5189 (org-make-link-regexps)
5191 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5192 "Regular expression for fast time stamp matching.")
5193 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5194 "Regular expression for fast time stamp matching.")
5195 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5196 "Regular expression matching time strings for analysis.
5197 This one does not require the space after the date.")
5198 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5199 "Regular expression matching time strings for analysis.")
5200 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5201 "Regular expression matching time stamps, with groups.")
5202 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5203 "Regular expression matching time stamps (also [..]), with groups.")
5204 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5205 "Regular expression matching a time stamp range.")
5206 (defconst org-tr-regexp-both
5207 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5208 "Regular expression matching a time stamp range.")
5209 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5210 org-ts-regexp "\\)?")
5211 "Regular expression matching a time stamp or time stamp range.")
5212 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5213 org-ts-regexp-both "\\)?")
5214 "Regular expression matching a time stamp or time stamp range.
5215 The time stamps may be either active or inactive.")
5217 (defvar org-emph-face nil)
5219 (defun org-do-emphasis-faces (limit)
5220 "Run through the buffer and add overlays to links."
5221 (let (rtn)
5222 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5223 (if (not (= (char-after (match-beginning 3))
5224 (char-after (match-beginning 4))))
5225 (progn
5226 (setq rtn t)
5227 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5228 'face
5229 (nth 1 (assoc (match-string 3)
5230 org-emphasis-alist)))
5231 (add-text-properties (match-beginning 2) (match-end 2)
5232 '(font-lock-multiline t))
5233 (when org-hide-emphasis-markers
5234 (add-text-properties (match-end 4) (match-beginning 5)
5235 '(invisible org-link))
5236 (add-text-properties (match-beginning 3) (match-end 3)
5237 '(invisible org-link)))))
5238 (backward-char 1))
5239 rtn))
5241 (defun org-emphasize (&optional char)
5242 "Insert or change an emphasis, i.e. a font like bold or italic.
5243 If there is an active region, change that region to a new emphasis.
5244 If there is no region, just insert the marker characters and position
5245 the cursor between them.
5246 CHAR should be either the marker character, or the first character of the
5247 HTML tag associated with that emphasis. If CHAR is a space, the means
5248 to remove the emphasis of the selected region.
5249 If char is not given (for example in an interactive call) it
5250 will be prompted for."
5251 (interactive)
5252 (let ((eal org-emphasis-alist) e det
5253 (erc org-emphasis-regexp-components)
5254 (prompt "")
5255 (string "") beg end move tag c s)
5256 (if (org-region-active-p)
5257 (setq beg (region-beginning) end (region-end)
5258 string (buffer-substring beg end))
5259 (setq move t))
5261 (while (setq e (pop eal))
5262 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5263 c (aref tag 0))
5264 (push (cons c (string-to-char (car e))) det)
5265 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5266 (substring tag 1)))))
5267 (unless char
5268 (message "%s" (concat "Emphasis marker or tag:" prompt))
5269 (setq char (read-char-exclusive)))
5270 (setq char (or (cdr (assoc char det)) char))
5271 (if (equal char ?\ )
5272 (setq s "" move nil)
5273 (unless (assoc (char-to-string char) org-emphasis-alist)
5274 (error "No such emphasis marker: \"%c\"" char))
5275 (setq s (char-to-string char)))
5276 (while (and (> (length string) 1)
5277 (equal (substring string 0 1) (substring string -1))
5278 (assoc (substring string 0 1) org-emphasis-alist))
5279 (setq string (substring string 1 -1)))
5280 (setq string (concat s string s))
5281 (if beg (delete-region beg end))
5282 (unless (or (bolp)
5283 (string-match (concat "[" (nth 0 erc) "\n]")
5284 (char-to-string (char-before (point)))))
5285 (insert " "))
5286 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5287 (char-to-string (char-after (point))))
5288 (insert " ") (backward-char 1))
5289 (insert string)
5290 (and move (backward-char 1))))
5292 (defconst org-nonsticky-props
5293 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5296 (defun org-activate-plain-links (limit)
5297 "Run through the buffer and add overlays to links."
5298 (catch 'exit
5299 (let (f)
5300 (while (re-search-forward org-plain-link-re limit t)
5301 (setq f (get-text-property (match-beginning 0) 'face))
5302 (if (or (eq f 'org-tag)
5303 (and (listp f) (memq 'org-tag f)))
5305 (add-text-properties (match-beginning 0) (match-end 0)
5306 (list 'mouse-face 'highlight
5307 'rear-nonsticky org-nonsticky-props
5308 'keymap org-mouse-map
5310 (throw 'exit t))))))
5312 (defun org-activate-code (limit)
5313 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5314 (unless (get-text-property (match-beginning 1) 'face)
5315 (remove-text-properties (match-beginning 0) (match-end 0)
5316 '(display t invisible t intangible t))
5317 t)))
5319 (defun org-activate-angle-links (limit)
5320 "Run through the buffer and add overlays to links."
5321 (if (re-search-forward org-angle-link-re limit t)
5322 (progn
5323 (add-text-properties (match-beginning 0) (match-end 0)
5324 (list 'mouse-face 'highlight
5325 'rear-nonsticky org-nonsticky-props
5326 'keymap org-mouse-map
5328 t)))
5330 (defmacro org-maybe-intangible (props)
5331 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5332 In emacs 21, invisible text is not avoided by the command loop, so the
5333 intangible property is needed to make sure point skips this text.
5334 In Emacs 22, this is not necessary. The intangible text property has
5335 led to problems with flyspell. These problems are fixed in flyspell.el,
5336 but we still avoid setting the property in Emacs 22 and later.
5337 We use a macro so that the test can happen at compilation time."
5338 (if (< emacs-major-version 22)
5339 `(append '(intangible t) ,props)
5340 props))
5342 (defun org-activate-bracket-links (limit)
5343 "Run through the buffer and add overlays to bracketed links."
5344 (if (re-search-forward org-bracket-link-regexp limit t)
5345 (let* ((help (concat "LINK: "
5346 (org-match-string-no-properties 1)))
5347 ;; FIXME: above we should remove the escapes.
5348 ;; but that requires another match, protecting match data,
5349 ;; a lot of overhead for font-lock.
5350 (ip (org-maybe-intangible
5351 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5352 'keymap org-mouse-map 'mouse-face 'highlight
5353 'font-lock-multiline t 'help-echo help)))
5354 (vp (list 'rear-nonsticky org-nonsticky-props
5355 'keymap org-mouse-map 'mouse-face 'highlight
5356 ' font-lock-multiline t 'help-echo help)))
5357 ;; We need to remove the invisible property here. Table narrowing
5358 ;; may have made some of this invisible.
5359 (remove-text-properties (match-beginning 0) (match-end 0)
5360 '(invisible nil))
5361 (if (match-end 3)
5362 (progn
5363 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5364 (add-text-properties (match-beginning 3) (match-end 3) vp)
5365 (add-text-properties (match-end 3) (match-end 0) ip))
5366 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5367 (add-text-properties (match-beginning 1) (match-end 1) vp)
5368 (add-text-properties (match-end 1) (match-end 0) ip))
5369 t)))
5371 (defun org-activate-dates (limit)
5372 "Run through the buffer and add overlays to dates."
5373 (if (re-search-forward org-tsr-regexp-both limit t)
5374 (progn
5375 (add-text-properties (match-beginning 0) (match-end 0)
5376 (list 'mouse-face 'highlight
5377 'rear-nonsticky org-nonsticky-props
5378 'keymap org-mouse-map))
5379 (when org-display-custom-times
5380 (if (match-end 3)
5381 (org-display-custom-time (match-beginning 3) (match-end 3)))
5382 (org-display-custom-time (match-beginning 1) (match-end 1)))
5383 t)))
5385 (defvar org-target-link-regexp nil
5386 "Regular expression matching radio targets in plain text.")
5387 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5388 "Regular expression matching a link target.")
5389 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5390 "Regular expression matching a radio target.")
5391 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5392 "Regular expression matching any target.")
5394 (defun org-activate-target-links (limit)
5395 "Run through the buffer and add overlays to target matches."
5396 (when org-target-link-regexp
5397 (let ((case-fold-search t))
5398 (if (re-search-forward org-target-link-regexp limit t)
5399 (progn
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
5404 'help-echo "Radio target link"
5405 'org-linked-text t))
5406 t)))))
5408 (defun org-update-radio-target-regexp ()
5409 "Find all radio targets in this file and update the regular expression."
5410 (interactive)
5411 (when (memq 'radio org-activate-links)
5412 (setq org-target-link-regexp
5413 (org-make-target-link-regexp (org-all-targets 'radio)))
5414 (org-restart-font-lock)))
5416 (defun org-hide-wide-columns (limit)
5417 (let (s e)
5418 (setq s (text-property-any (point) (or limit (point-max))
5419 'org-cwidth t))
5420 (when s
5421 (setq e (next-single-property-change s 'org-cwidth))
5422 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5423 (goto-char e)
5424 t)))
5426 (defvar org-latex-and-specials-regexp nil
5427 "Regular expression for highlighting export special stuff.")
5428 (defvar org-match-substring-regexp)
5429 (defvar org-match-substring-with-braces-regexp)
5430 (defvar org-export-html-special-string-regexps)
5432 (defun org-compute-latex-and-specials-regexp ()
5433 "Compute regular expression for stuff treated specially by exporters."
5434 (if (not org-highlight-latex-fragments-and-specials)
5435 (org-set-local 'org-latex-and-specials-regexp nil)
5436 (let*
5437 ((matchers (plist-get org-format-latex-options :matchers))
5438 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5439 org-latex-regexps)))
5440 (options (org-combine-plists (org-default-export-plist)
5441 (org-infile-export-plist)))
5442 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5443 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5444 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5445 (org-export-html-expand (plist-get options :expand-quoted-html))
5446 (org-export-with-special-strings (plist-get options :special-strings))
5447 (re-sub
5448 (cond
5449 ((equal org-export-with-sub-superscripts '{})
5450 (list org-match-substring-with-braces-regexp))
5451 (org-export-with-sub-superscripts
5452 (list org-match-substring-regexp))
5453 (t nil)))
5454 (re-latex
5455 (if org-export-with-LaTeX-fragments
5456 (mapcar (lambda (x) (nth 1 x)) latexs)))
5457 (re-macros
5458 (if org-export-with-TeX-macros
5459 (list (concat "\\\\"
5460 (regexp-opt
5461 (append (mapcar 'car org-html-entities)
5462 (if (boundp 'org-latex-entities)
5463 org-latex-entities nil))
5464 'words))) ; FIXME
5466 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5467 (re-special (if org-export-with-special-strings
5468 (mapcar (lambda (x) (car x))
5469 org-export-html-special-string-regexps)))
5470 (re-rest
5471 (delq nil
5472 (list
5473 (if org-export-html-expand "@<[^>\n]+>")
5474 ))))
5475 (org-set-local
5476 'org-latex-and-specials-regexp
5477 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5478 re-rest) "\\|")))))
5480 (defface org-latex-and-export-specials
5481 (let ((font (cond ((assq :inherit custom-face-attributes)
5482 '(:inherit underline))
5483 (t '(:underline t)))))
5484 `((((class grayscale) (background light))
5485 (:foreground "DimGray" ,@font))
5486 (((class grayscale) (background dark))
5487 (:foreground "LightGray" ,@font))
5488 (((class color) (background light))
5489 (:foreground "SaddleBrown"))
5490 (((class color) (background dark))
5491 (:foreground "burlywood"))
5492 (t (,@font))))
5493 "Face used to highlight math latex and other special exporter stuff."
5494 :group 'org-faces)
5496 (defun org-do-latex-and-special-faces (limit)
5497 "Run through the buffer and add overlays to links."
5498 (when org-latex-and-specials-regexp
5499 (let (rtn d)
5500 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5501 limit t))
5502 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5503 'face))
5504 '(org-code org-verbatim underline)))
5505 (progn
5506 (setq rtn t
5507 d (cond ((member (char-after (1+ (match-beginning 0)))
5508 '(?_ ?^)) 1)
5509 (t 0)))
5510 (font-lock-prepend-text-property
5511 (+ d (match-beginning 0)) (match-end 0)
5512 'face 'org-latex-and-export-specials)
5513 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5514 '(font-lock-multiline t)))))
5515 rtn)))
5517 (defun org-restart-font-lock ()
5518 "Restart font-lock-mode, to force refontification."
5519 (when (and (boundp 'font-lock-mode) font-lock-mode)
5520 (font-lock-mode -1)
5521 (font-lock-mode 1)))
5523 (defun org-all-targets (&optional radio)
5524 "Return a list of all targets in this file.
5525 With optional argument RADIO, only find radio targets."
5526 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5527 rtn)
5528 (save-excursion
5529 (goto-char (point-min))
5530 (while (re-search-forward re nil t)
5531 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5532 rtn)))
5534 (defun org-make-target-link-regexp (targets)
5535 "Make regular expression matching all strings in TARGETS.
5536 The regular expression finds the targets also if there is a line break
5537 between words."
5538 (and targets
5539 (concat
5540 "\\<\\("
5541 (mapconcat
5542 (lambda (x)
5543 (while (string-match " +" x)
5544 (setq x (replace-match "\\s-+" t t x)))
5546 targets
5547 "\\|")
5548 "\\)\\>")))
5550 (defun org-activate-tags (limit)
5551 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5552 (progn
5553 (add-text-properties (match-beginning 1) (match-end 1)
5554 (list 'mouse-face 'highlight
5555 'rear-nonsticky org-nonsticky-props
5556 'keymap org-mouse-map))
5557 t)))
5559 (defun org-outline-level ()
5560 (save-excursion
5561 (looking-at outline-regexp)
5562 (if (match-beginning 1)
5563 (+ (org-get-string-indentation (match-string 1)) 1000)
5564 (1- (- (match-end 0) (match-beginning 0))))))
5566 (defvar org-font-lock-keywords nil)
5568 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5569 "Regular expression matching a property line.")
5571 (defun org-set-font-lock-defaults ()
5572 (let* ((em org-fontify-emphasized-text)
5573 (lk org-activate-links)
5574 (org-font-lock-extra-keywords
5575 (list
5576 ;; Headlines
5577 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5578 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5579 ;; Table lines
5580 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5581 (1 'org-table t))
5582 ;; Table internals
5583 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5584 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5585 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5586 ;; Drawers
5587 (list org-drawer-regexp '(0 'org-special-keyword t))
5588 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5589 ;; Properties
5590 (list org-property-re
5591 '(1 'org-special-keyword t)
5592 '(3 'org-property-value t))
5593 (if org-format-transports-properties-p
5594 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5595 ;; Links
5596 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5597 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5598 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5599 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5600 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5601 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5602 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5603 '(org-hide-wide-columns (0 nil append))
5604 ;; TODO lines
5605 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5606 '(1 (org-get-todo-face 1) t))
5607 ;; DONE
5608 (if org-fontify-done-headline
5609 (list (concat "^[*]+ +\\<\\("
5610 (mapconcat 'regexp-quote org-done-keywords "\\|")
5611 "\\)\\(.*\\)")
5612 '(2 'org-headline-done t))
5613 nil)
5614 ;; Priorities
5615 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5616 ;; Special keywords
5617 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5618 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5619 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5620 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5621 ;; Emphasis
5622 (if em
5623 (if (featurep 'xemacs)
5624 '(org-do-emphasis-faces (0 nil append))
5625 '(org-do-emphasis-faces)))
5626 ;; Checkboxes
5627 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5628 2 'bold prepend)
5629 (if org-provide-checkbox-statistics
5630 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5631 (0 (org-get-checkbox-statistics-face) t)))
5632 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5633 '(1 'org-archived prepend))
5634 ;; Specials
5635 '(org-do-latex-and-special-faces)
5636 ;; Code
5637 '(org-activate-code (1 'org-code t))
5638 ;; COMMENT
5639 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5640 "\\|" org-quote-string "\\)\\>")
5641 '(1 'org-special-keyword t))
5642 '("^#.*" (0 'font-lock-comment-face t))
5644 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5645 ;; Now set the full font-lock-keywords
5646 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5647 (org-set-local 'font-lock-defaults
5648 '(org-font-lock-keywords t nil nil backward-paragraph))
5649 (kill-local-variable 'font-lock-keywords) nil))
5651 (defvar org-m nil)
5652 (defvar org-l nil)
5653 (defvar org-f nil)
5654 (defun org-get-level-face (n)
5655 "Get the right face for match N in font-lock matching of healdines."
5656 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5657 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5658 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5659 (cond
5660 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5661 ((eq n 2) org-f)
5662 (t (if org-level-color-stars-only nil org-f))))
5664 (defun org-get-todo-face (kwd)
5665 "Get the right face for a TODO keyword KWD.
5666 If KWD is a number, get the corresponding match group."
5667 (if (numberp kwd) (setq kwd (match-string kwd)))
5668 (or (cdr (assoc kwd org-todo-keyword-faces))
5669 (and (member kwd org-done-keywords) 'org-done)
5670 'org-todo))
5672 (defun org-unfontify-region (beg end &optional maybe_loudly)
5673 "Remove fontification and activation overlays from links."
5674 (font-lock-default-unfontify-region beg end)
5675 (let* ((buffer-undo-list t)
5676 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5677 (inhibit-modification-hooks t)
5678 deactivate-mark buffer-file-name buffer-file-truename)
5679 (remove-text-properties beg end
5680 '(mouse-face t keymap t org-linked-text t
5681 invisible t intangible t))))
5683 ;;;; Visibility cycling, including org-goto and indirect buffer
5685 ;;; Cycling
5687 (defvar org-cycle-global-status nil)
5688 (make-variable-buffer-local 'org-cycle-global-status)
5689 (defvar org-cycle-subtree-status nil)
5690 (make-variable-buffer-local 'org-cycle-subtree-status)
5692 ;;;###autoload
5693 (defun org-cycle (&optional arg)
5694 "Visibility cycling for Org-mode.
5696 - When this function is called with a prefix argument, rotate the entire
5697 buffer through 3 states (global cycling)
5698 1. OVERVIEW: Show only top-level headlines.
5699 2. CONTENTS: Show all headlines of all levels, but no body text.
5700 3. SHOW ALL: Show everything.
5702 - When point is at the beginning of a headline, rotate the subtree started
5703 by this line through 3 different states (local cycling)
5704 1. FOLDED: Only the main headline is shown.
5705 2. CHILDREN: The main headline and the direct children are shown.
5706 From this state, you can move to one of the children
5707 and zoom in further.
5708 3. SUBTREE: Show the entire subtree, including body text.
5710 - When there is a numeric prefix, go up to a heading with level ARG, do
5711 a `show-subtree' and return to the previous cursor position. If ARG
5712 is negative, go up that many levels.
5714 - When point is not at the beginning of a headline, execute
5715 `indent-relative', like TAB normally does. See the option
5716 `org-cycle-emulate-tab' for details.
5718 - Special case: if point is at the beginning of the buffer and there is
5719 no headline in line 1, this function will act as if called with prefix arg.
5720 But only if also the variable `org-cycle-global-at-bob' is t."
5721 (interactive "P")
5722 (let* ((outline-regexp
5723 (if (and (org-mode-p) org-cycle-include-plain-lists)
5724 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5725 outline-regexp))
5726 (bob-special (and org-cycle-global-at-bob (bobp)
5727 (not (looking-at outline-regexp))))
5728 (org-cycle-hook
5729 (if bob-special
5730 (delq 'org-optimize-window-after-visibility-change
5731 (copy-sequence org-cycle-hook))
5732 org-cycle-hook))
5733 (pos (point)))
5735 (if (or bob-special (equal arg '(4)))
5736 ;; special case: use global cycling
5737 (setq arg t))
5739 (cond
5741 ((org-at-table-p 'any)
5742 ;; Enter the table or move to the next field in the table
5743 (or (org-table-recognize-table.el)
5744 (progn
5745 (if arg (org-table-edit-field t)
5746 (org-table-justify-field-maybe)
5747 (call-interactively 'org-table-next-field)))))
5749 ((eq arg t) ;; Global cycling
5751 (cond
5752 ((and (eq last-command this-command)
5753 (eq org-cycle-global-status 'overview))
5754 ;; We just created the overview - now do table of contents
5755 ;; This can be slow in very large buffers, so indicate action
5756 (message "CONTENTS...")
5757 (org-content)
5758 (message "CONTENTS...done")
5759 (setq org-cycle-global-status 'contents)
5760 (run-hook-with-args 'org-cycle-hook 'contents))
5762 ((and (eq last-command this-command)
5763 (eq org-cycle-global-status 'contents))
5764 ;; We just showed the table of contents - now show everything
5765 (show-all)
5766 (message "SHOW ALL")
5767 (setq org-cycle-global-status 'all)
5768 (run-hook-with-args 'org-cycle-hook 'all))
5771 ;; Default action: go to overview
5772 (org-overview)
5773 (message "OVERVIEW")
5774 (setq org-cycle-global-status 'overview)
5775 (run-hook-with-args 'org-cycle-hook 'overview))))
5777 ((and org-drawers org-drawer-regexp
5778 (save-excursion
5779 (beginning-of-line 1)
5780 (looking-at org-drawer-regexp)))
5781 ;; Toggle block visibility
5782 (org-flag-drawer
5783 (not (get-char-property (match-end 0) 'invisible))))
5785 ((integerp arg)
5786 ;; Show-subtree, ARG levels up from here.
5787 (save-excursion
5788 (org-back-to-heading)
5789 (outline-up-heading (if (< arg 0) (- arg)
5790 (- (funcall outline-level) arg)))
5791 (org-show-subtree)))
5793 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5794 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5795 ;; At a heading: rotate between three different views
5796 (org-back-to-heading)
5797 (let ((goal-column 0) eoh eol eos)
5798 ;; First, some boundaries
5799 (save-excursion
5800 (org-back-to-heading)
5801 (save-excursion
5802 (beginning-of-line 2)
5803 (while (and (not (eobp)) ;; this is like `next-line'
5804 (get-char-property (1- (point)) 'invisible))
5805 (beginning-of-line 2)) (setq eol (point)))
5806 (outline-end-of-heading) (setq eoh (point))
5807 (org-end-of-subtree t)
5808 (unless (eobp)
5809 (skip-chars-forward " \t\n")
5810 (beginning-of-line 1) ; in case this is an item
5812 (setq eos (1- (point))))
5813 ;; Find out what to do next and set `this-command'
5814 (cond
5815 ((= eos eoh)
5816 ;; Nothing is hidden behind this heading
5817 (message "EMPTY ENTRY")
5818 (setq org-cycle-subtree-status nil)
5819 (save-excursion
5820 (goto-char eos)
5821 (outline-next-heading)
5822 (if (org-invisible-p) (org-flag-heading nil))))
5823 ((or (>= eol eos)
5824 (not (string-match "\\S-" (buffer-substring eol eos))))
5825 ;; Entire subtree is hidden in one line: open it
5826 (org-show-entry)
5827 (show-children)
5828 (message "CHILDREN")
5829 (save-excursion
5830 (goto-char eos)
5831 (outline-next-heading)
5832 (if (org-invisible-p) (org-flag-heading nil)))
5833 (setq org-cycle-subtree-status 'children)
5834 (run-hook-with-args 'org-cycle-hook 'children))
5835 ((and (eq last-command this-command)
5836 (eq org-cycle-subtree-status 'children))
5837 ;; We just showed the children, now show everything.
5838 (org-show-subtree)
5839 (message "SUBTREE")
5840 (setq org-cycle-subtree-status 'subtree)
5841 (run-hook-with-args 'org-cycle-hook 'subtree))
5843 ;; Default action: hide the subtree.
5844 (hide-subtree)
5845 (message "FOLDED")
5846 (setq org-cycle-subtree-status 'folded)
5847 (run-hook-with-args 'org-cycle-hook 'folded)))))
5849 ;; TAB emulation
5850 (buffer-read-only (org-back-to-heading))
5852 ((org-try-cdlatex-tab))
5854 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5855 (or (not (bolp))
5856 (not (looking-at outline-regexp))))
5857 (call-interactively (global-key-binding "\t")))
5859 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5860 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5861 (or (and (eq org-cycle-emulate-tab 'white)
5862 (= (match-end 0) (point-at-eol)))
5863 (and (eq org-cycle-emulate-tab 'whitestart)
5864 (>= (match-end 0) pos))))
5866 (eq org-cycle-emulate-tab t))
5867 ; (if (and (looking-at "[ \n\r\t]")
5868 ; (string-match "^[ \t]*$" (buffer-substring
5869 ; (point-at-bol) (point))))
5870 ; (progn
5871 ; (beginning-of-line 1)
5872 ; (and (looking-at "[ \t]+") (replace-match ""))))
5873 (call-interactively (global-key-binding "\t")))
5875 (t (save-excursion
5876 (org-back-to-heading)
5877 (org-cycle))))))
5879 ;;;###autoload
5880 (defun org-global-cycle (&optional arg)
5881 "Cycle the global visibility. For details see `org-cycle'."
5882 (interactive "P")
5883 (let ((org-cycle-include-plain-lists
5884 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5885 (if (integerp arg)
5886 (progn
5887 (show-all)
5888 (hide-sublevels arg)
5889 (setq org-cycle-global-status 'contents))
5890 (org-cycle '(4)))))
5892 (defun org-overview ()
5893 "Switch to overview mode, shoing only top-level headlines.
5894 Really, this shows all headlines with level equal or greater than the level
5895 of the first headline in the buffer. This is important, because if the
5896 first headline is not level one, then (hide-sublevels 1) gives confusing
5897 results."
5898 (interactive)
5899 (let ((level (save-excursion
5900 (goto-char (point-min))
5901 (if (re-search-forward (concat "^" outline-regexp) nil t)
5902 (progn
5903 (goto-char (match-beginning 0))
5904 (funcall outline-level))))))
5905 (and level (hide-sublevels level))))
5907 (defun org-content (&optional arg)
5908 "Show all headlines in the buffer, like a table of contents.
5909 With numerical argument N, show content up to level N."
5910 (interactive "P")
5911 (save-excursion
5912 ;; Visit all headings and show their offspring
5913 (and (integerp arg) (org-overview))
5914 (goto-char (point-max))
5915 (catch 'exit
5916 (while (and (progn (condition-case nil
5917 (outline-previous-visible-heading 1)
5918 (error (goto-char (point-min))))
5920 (looking-at outline-regexp))
5921 (if (integerp arg)
5922 (show-children (1- arg))
5923 (show-branches))
5924 (if (bobp) (throw 'exit nil))))))
5927 (defun org-optimize-window-after-visibility-change (state)
5928 "Adjust the window after a change in outline visibility.
5929 This function is the default value of the hook `org-cycle-hook'."
5930 (when (get-buffer-window (current-buffer))
5931 (cond
5932 ; ((eq state 'overview) (org-first-headline-recenter 1))
5933 ; ((eq state 'overview) (org-beginning-of-line))
5934 ((eq state 'content) nil)
5935 ((eq state 'all) nil)
5936 ((eq state 'folded) nil)
5937 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5938 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5940 (defun org-compact-display-after-subtree-move ()
5941 (let (beg end)
5942 (save-excursion
5943 (if (org-up-heading-safe)
5944 (progn
5945 (hide-subtree)
5946 (show-entry)
5947 (show-children)
5948 (org-cycle-show-empty-lines 'children)
5949 (org-cycle-hide-drawers 'children))
5950 (org-overview)))))
5952 (defun org-cycle-show-empty-lines (state)
5953 "Show empty lines above all visible headlines.
5954 The region to be covered depends on STATE when called through
5955 `org-cycle-hook'. Lisp program can use t for STATE to get the
5956 entire buffer covered. Note that an empty line is only shown if there
5957 are at least `org-cycle-separator-lines' empty lines before the headeline."
5958 (when (> org-cycle-separator-lines 0)
5959 (save-excursion
5960 (let* ((n org-cycle-separator-lines)
5961 (re (cond
5962 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5963 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5964 (t (let ((ns (number-to-string (- n 2))))
5965 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5966 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5967 beg end)
5968 (cond
5969 ((memq state '(overview contents t))
5970 (setq beg (point-min) end (point-max)))
5971 ((memq state '(children folded))
5972 (setq beg (point) end (progn (org-end-of-subtree t t)
5973 (beginning-of-line 2)
5974 (point)))))
5975 (when beg
5976 (goto-char beg)
5977 (while (re-search-forward re end t)
5978 (if (not (get-char-property (match-end 1) 'invisible))
5979 (outline-flag-region
5980 (match-beginning 1) (match-end 1) nil)))))))
5981 ;; Never hide empty lines at the end of the file.
5982 (save-excursion
5983 (goto-char (point-max))
5984 (outline-previous-heading)
5985 (outline-end-of-heading)
5986 (if (and (looking-at "[ \t\n]+")
5987 (= (match-end 0) (point-max)))
5988 (outline-flag-region (point) (match-end 0) nil))))
5990 (defun org-subtree-end-visible-p ()
5991 "Is the end of the current subtree visible?"
5992 (pos-visible-in-window-p
5993 (save-excursion (org-end-of-subtree t) (point))))
5995 (defun org-first-headline-recenter (&optional N)
5996 "Move cursor to the first headline and recenter the headline.
5997 Optional argument N means, put the headline into the Nth line of the window."
5998 (goto-char (point-min))
5999 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6000 (beginning-of-line)
6001 (recenter (prefix-numeric-value N))))
6003 ;;; Org-goto
6005 (defvar org-goto-window-configuration nil)
6006 (defvar org-goto-marker nil)
6007 (defvar org-goto-map
6008 (let ((map (make-sparse-keymap)))
6009 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6010 (while (setq cmd (pop cmds))
6011 (substitute-key-definition cmd cmd map global-map)))
6012 (suppress-keymap map)
6013 (org-defkey map "\C-m" 'org-goto-ret)
6014 (org-defkey map [(return)] 'org-goto-ret)
6015 (org-defkey map [(left)] 'org-goto-left)
6016 (org-defkey map [(right)] 'org-goto-right)
6017 (org-defkey map [(control ?g)] 'org-goto-quit)
6018 (org-defkey map "\C-i" 'org-cycle)
6019 (org-defkey map [(tab)] 'org-cycle)
6020 (org-defkey map [(down)] 'outline-next-visible-heading)
6021 (org-defkey map [(up)] 'outline-previous-visible-heading)
6022 (if org-goto-auto-isearch
6023 (if (fboundp 'define-key-after)
6024 (define-key-after map [t] 'org-goto-local-auto-isearch)
6025 nil)
6026 (org-defkey map "q" 'org-goto-quit)
6027 (org-defkey map "n" 'outline-next-visible-heading)
6028 (org-defkey map "p" 'outline-previous-visible-heading)
6029 (org-defkey map "f" 'outline-forward-same-level)
6030 (org-defkey map "b" 'outline-backward-same-level)
6031 (org-defkey map "u" 'outline-up-heading))
6032 (org-defkey map "/" 'org-occur)
6033 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6034 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6035 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6036 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6037 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6038 map))
6040 (defconst org-goto-help
6041 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6042 RET=jump to location [Q]uit and return to previous location
6043 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6045 (defvar org-goto-start-pos) ; dynamically scoped parameter
6047 (defun org-goto (&optional alternative-interface)
6048 "Look up a different location in the current file, keeping current visibility.
6050 When you want look-up or go to a different location in a document, the
6051 fastest way is often to fold the entire buffer and then dive into the tree.
6052 This method has the disadvantage, that the previous location will be folded,
6053 which may not be what you want.
6055 This command works around this by showing a copy of the current buffer
6056 in an indirect buffer, in overview mode. You can dive into the tree in
6057 that copy, use org-occur and incremental search to find a location.
6058 When pressing RET or `Q', the command returns to the original buffer in
6059 which the visibility is still unchanged. After RET is will also jump to
6060 the location selected in the indirect buffer and expose the
6061 the headline hierarchy above."
6062 (interactive "P")
6063 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
6064 (org-refile-use-outline-path t)
6065 (interface
6066 (if (not alternative-interface)
6067 org-goto-interface
6068 (if (eq org-goto-interface 'outline)
6069 'outline-path-completion
6070 'outline)))
6071 (org-goto-start-pos (point))
6072 (selected-point
6073 (if (eq interface 'outline)
6074 (car (org-get-location (current-buffer) org-goto-help))
6075 (nth 3 (org-refile-get-location "Goto: ")))))
6076 (if selected-point
6077 (progn
6078 (org-mark-ring-push org-goto-start-pos)
6079 (goto-char selected-point)
6080 (if (or (org-invisible-p) (org-invisible-p2))
6081 (org-show-context 'org-goto)))
6082 (message "Quit"))))
6084 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6085 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6086 (defvar org-goto-local-auto-isearch-map) ; defined below
6088 (defun org-get-location (buf help)
6089 "Let the user select a location in the Org-mode buffer BUF.
6090 This function uses a recursive edit. It returns the selected position
6091 or nil."
6092 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6093 (isearch-hide-immediately nil)
6094 (isearch-search-fun-function
6095 (lambda () 'org-goto-local-search-forward-headings))
6096 (org-goto-selected-point org-goto-exit-command))
6097 (save-excursion
6098 (save-window-excursion
6099 (delete-other-windows)
6100 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6101 (switch-to-buffer
6102 (condition-case nil
6103 (make-indirect-buffer (current-buffer) "*org-goto*")
6104 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6105 (with-output-to-temp-buffer "*Help*"
6106 (princ help))
6107 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6108 (setq buffer-read-only nil)
6109 (let ((org-startup-truncated t)
6110 (org-startup-folded nil)
6111 (org-startup-align-all-tables nil))
6112 (org-mode)
6113 (org-overview))
6114 (setq buffer-read-only t)
6115 (if (and (boundp 'org-goto-start-pos)
6116 (integer-or-marker-p org-goto-start-pos))
6117 (let ((org-show-hierarchy-above t)
6118 (org-show-siblings t)
6119 (org-show-following-heading t))
6120 (goto-char org-goto-start-pos)
6121 (and (org-invisible-p) (org-show-context)))
6122 (goto-char (point-min)))
6123 (org-beginning-of-line)
6124 (message "Select location and press RET")
6125 (use-local-map org-goto-map)
6126 (recursive-edit)
6128 (kill-buffer "*org-goto*")
6129 (cons org-goto-selected-point org-goto-exit-command)))
6131 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6132 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6133 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6134 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6136 (defun org-goto-local-search-forward-headings (string bound noerror)
6137 "Search and make sure that anu matches are in headlines."
6138 (catch 'return
6139 (while (search-forward string bound noerror)
6140 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6141 (and (member :headline context)
6142 (not (member :tags context))))
6143 (throw 'return (point))))))
6145 (defun org-goto-local-auto-isearch ()
6146 "Start isearch."
6147 (interactive)
6148 (goto-char (point-min))
6149 (let ((keys (this-command-keys)))
6150 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6151 (isearch-mode t)
6152 (isearch-process-search-char (string-to-char keys)))))
6154 (defun org-goto-ret (&optional arg)
6155 "Finish `org-goto' by going to the new location."
6156 (interactive "P")
6157 (setq org-goto-selected-point (point)
6158 org-goto-exit-command 'return)
6159 (throw 'exit nil))
6161 (defun org-goto-left ()
6162 "Finish `org-goto' by going to the new location."
6163 (interactive)
6164 (if (org-on-heading-p)
6165 (progn
6166 (beginning-of-line 1)
6167 (setq org-goto-selected-point (point)
6168 org-goto-exit-command 'left)
6169 (throw 'exit nil))
6170 (error "Not on a heading")))
6172 (defun org-goto-right ()
6173 "Finish `org-goto' by going to the new location."
6174 (interactive)
6175 (if (org-on-heading-p)
6176 (progn
6177 (setq org-goto-selected-point (point)
6178 org-goto-exit-command 'right)
6179 (throw 'exit nil))
6180 (error "Not on a heading")))
6182 (defun org-goto-quit ()
6183 "Finish `org-goto' without cursor motion."
6184 (interactive)
6185 (setq org-goto-selected-point nil)
6186 (setq org-goto-exit-command 'quit)
6187 (throw 'exit nil))
6189 ;;; Indirect buffer display of subtrees
6191 (defvar org-indirect-dedicated-frame nil
6192 "This is the frame being used for indirect tree display.")
6193 (defvar org-last-indirect-buffer nil)
6195 (defun org-tree-to-indirect-buffer (&optional arg)
6196 "Create indirect buffer and narrow it to current subtree.
6197 With numerical prefix ARG, go up to this level and then take that tree.
6198 If ARG is negative, go up that many levels.
6199 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6200 indirect buffer previously made with this command, to avoid proliferation of
6201 indirect buffers. However, when you call the command with a `C-u' prefix, or
6202 when `org-indirect-buffer-display' is `new-frame', the last buffer
6203 is kept so that you can work with several indirect buffers at the same time.
6204 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6205 requests that a new frame be made for the new buffer, so that the dedicated
6206 frame is not changed."
6207 (interactive "P")
6208 (let ((cbuf (current-buffer))
6209 (cwin (selected-window))
6210 (pos (point))
6211 beg end level heading ibuf)
6212 (save-excursion
6213 (org-back-to-heading t)
6214 (when (numberp arg)
6215 (setq level (org-outline-level))
6216 (if (< arg 0) (setq arg (+ level arg)))
6217 (while (> (setq level (org-outline-level)) arg)
6218 (outline-up-heading 1 t)))
6219 (setq beg (point)
6220 heading (org-get-heading))
6221 (org-end-of-subtree t) (setq end (point)))
6222 (if (and (buffer-live-p org-last-indirect-buffer)
6223 (not (eq org-indirect-buffer-display 'new-frame))
6224 (not arg))
6225 (kill-buffer org-last-indirect-buffer))
6226 (setq ibuf (org-get-indirect-buffer cbuf)
6227 org-last-indirect-buffer ibuf)
6228 (cond
6229 ((or (eq org-indirect-buffer-display 'new-frame)
6230 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6231 (select-frame (make-frame))
6232 (delete-other-windows)
6233 (switch-to-buffer ibuf)
6234 (org-set-frame-title heading))
6235 ((eq org-indirect-buffer-display 'dedicated-frame)
6236 (raise-frame
6237 (select-frame (or (and org-indirect-dedicated-frame
6238 (frame-live-p org-indirect-dedicated-frame)
6239 org-indirect-dedicated-frame)
6240 (setq org-indirect-dedicated-frame (make-frame)))))
6241 (delete-other-windows)
6242 (switch-to-buffer ibuf)
6243 (org-set-frame-title (concat "Indirect: " heading)))
6244 ((eq org-indirect-buffer-display 'current-window)
6245 (switch-to-buffer ibuf))
6246 ((eq org-indirect-buffer-display 'other-window)
6247 (pop-to-buffer ibuf))
6248 (t (error "Invalid value.")))
6249 (if (featurep 'xemacs)
6250 (save-excursion (org-mode) (turn-on-font-lock)))
6251 (narrow-to-region beg end)
6252 (show-all)
6253 (goto-char pos)
6254 (and (window-live-p cwin) (select-window cwin))))
6256 (defun org-get-indirect-buffer (&optional buffer)
6257 (setq buffer (or buffer (current-buffer)))
6258 (let ((n 1) (base (buffer-name buffer)) bname)
6259 (while (buffer-live-p
6260 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6261 (setq n (1+ n)))
6262 (condition-case nil
6263 (make-indirect-buffer buffer bname 'clone)
6264 (error (make-indirect-buffer buffer bname)))))
6266 (defun org-set-frame-title (title)
6267 "Set the title of the current frame to the string TITLE."
6268 ;; FIXME: how to name a single frame in XEmacs???
6269 (unless (featurep 'xemacs)
6270 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6272 ;;;; Structure editing
6274 ;;; Inserting headlines
6276 (defun org-insert-heading (&optional force-heading)
6277 "Insert a new heading or item with same depth at point.
6278 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6279 If point is at the beginning of a headline, insert a sibling before the
6280 current headline. If point is not at the beginning, do not split the line,
6281 but create the new hedline after the current line."
6282 (interactive "P")
6283 (if (= (buffer-size) 0)
6284 (insert "\n* ")
6285 (when (or force-heading (not (org-insert-item)))
6286 (let* ((head (save-excursion
6287 (condition-case nil
6288 (progn
6289 (org-back-to-heading)
6290 (match-string 0))
6291 (error "*"))))
6292 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6293 pos)
6294 (cond
6295 ((and (org-on-heading-p) (bolp)
6296 (or (bobp)
6297 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6298 ;; insert before the current line
6299 (open-line (if blank 2 1)))
6300 ((and (bolp)
6301 (or (bobp)
6302 (save-excursion
6303 (backward-char 1) (not (org-invisible-p)))))
6304 ;; insert right here
6305 nil)
6307 ; ;; in the middle of the line
6308 ; (org-show-entry)
6309 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
6310 ; (if (and
6311 ; (org-on-heading-p)
6312 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6313 ; ;; protect the tags
6314 ;; (let ((tags (match-string 2)) pos)
6315 ; (delete-region (match-beginning 1) (match-end 1))
6316 ; (setq pos (point-at-bol))
6317 ; (newline (if blank 2 1))
6318 ; (save-excursion
6319 ; (goto-char pos)
6320 ; (end-of-line 1)
6321 ; (insert " " tags)
6322 ; (org-set-tags nil 'align)))
6323 ; (newline (if blank 2 1)))
6324 ; (newline (if blank 2 1))))
6327 ;; in the middle of the line
6328 (org-show-entry)
6329 (let ((split
6330 (org-get-alist-option org-M-RET-may-split-line 'headline))
6331 tags pos)
6332 (if (org-on-heading-p)
6333 (progn
6334 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6335 (setq tags (and (match-end 2) (match-string 2)))
6336 (and (match-end 1)
6337 (delete-region (match-beginning 1) (match-end 1)))
6338 (setq pos (point-at-bol))
6339 (or split (end-of-line 1))
6340 (delete-horizontal-space)
6341 (newline (if blank 2 1))
6342 (when tags
6343 (save-excursion
6344 (goto-char pos)
6345 (end-of-line 1)
6346 (insert " " tags)
6347 (org-set-tags nil 'align))))
6348 (or split (end-of-line 1))
6349 (newline (if blank 2 1))))))
6350 (insert head) (just-one-space)
6351 (setq pos (point))
6352 (end-of-line 1)
6353 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6354 (run-hooks 'org-insert-heading-hook)))))
6356 (defun org-insert-heading-after-current ()
6357 "Insert a new heading with same level as current, after current subtree."
6358 (interactive)
6359 (org-back-to-heading)
6360 (org-insert-heading)
6361 (org-move-subtree-down)
6362 (end-of-line 1))
6364 (defun org-insert-todo-heading (arg)
6365 "Insert a new heading with the same level and TODO state as current heading.
6366 If the heading has no TODO state, or if the state is DONE, use the first
6367 state (TODO by default). Also with prefix arg, force first state."
6368 (interactive "P")
6369 (when (not (org-insert-item 'checkbox))
6370 (org-insert-heading)
6371 (save-excursion
6372 (org-back-to-heading)
6373 (outline-previous-heading)
6374 (looking-at org-todo-line-regexp))
6375 (if (or arg
6376 (not (match-beginning 2))
6377 (member (match-string 2) org-done-keywords))
6378 (insert (car org-todo-keywords-1) " ")
6379 (insert (match-string 2) " "))))
6381 (defun org-insert-subheading (arg)
6382 "Insert a new subheading and demote it.
6383 Works for outline headings and for plain lists alike."
6384 (interactive "P")
6385 (org-insert-heading arg)
6386 (cond
6387 ((org-on-heading-p) (org-do-demote))
6388 ((org-at-item-p) (org-indent-item 1))))
6390 (defun org-insert-todo-subheading (arg)
6391 "Insert a new subheading with TODO keyword or checkbox and demote it.
6392 Works for outline headings and for plain lists alike."
6393 (interactive "P")
6394 (org-insert-todo-heading arg)
6395 (cond
6396 ((org-on-heading-p) (org-do-demote))
6397 ((org-at-item-p) (org-indent-item 1))))
6399 ;;; Promotion and Demotion
6401 (defun org-promote-subtree ()
6402 "Promote the entire subtree.
6403 See also `org-promote'."
6404 (interactive)
6405 (save-excursion
6406 (org-map-tree 'org-promote))
6407 (org-fix-position-after-promote))
6409 (defun org-demote-subtree ()
6410 "Demote the entire subtree. See `org-demote'.
6411 See also `org-promote'."
6412 (interactive)
6413 (save-excursion
6414 (org-map-tree 'org-demote))
6415 (org-fix-position-after-promote))
6418 (defun org-do-promote ()
6419 "Promote the current heading higher up the tree.
6420 If the region is active in `transient-mark-mode', promote all headings
6421 in the region."
6422 (interactive)
6423 (save-excursion
6424 (if (org-region-active-p)
6425 (org-map-region 'org-promote (region-beginning) (region-end))
6426 (org-promote)))
6427 (org-fix-position-after-promote))
6429 (defun org-do-demote ()
6430 "Demote the current heading lower down the tree.
6431 If the region is active in `transient-mark-mode', demote all headings
6432 in the region."
6433 (interactive)
6434 (save-excursion
6435 (if (org-region-active-p)
6436 (org-map-region 'org-demote (region-beginning) (region-end))
6437 (org-demote)))
6438 (org-fix-position-after-promote))
6440 (defun org-fix-position-after-promote ()
6441 "Make sure that after pro/demotion cursor position is right."
6442 (let ((pos (point)))
6443 (when (save-excursion
6444 (beginning-of-line 1)
6445 (looking-at org-todo-line-regexp)
6446 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6447 (cond ((eobp) (insert " "))
6448 ((eolp) (insert " "))
6449 ((equal (char-after) ?\ ) (forward-char 1))))))
6451 (defun org-reduced-level (l)
6452 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6454 (defun org-get-legal-level (level &optional change)
6455 "Rectify a level change under the influence of `org-odd-levels-only'
6456 LEVEL is a current level, CHANGE is by how much the level should be
6457 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6458 even level numbers will become the next higher odd number."
6459 (if org-odd-levels-only
6460 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6461 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6462 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6463 (max 1 (+ level change))))
6465 (defun org-promote ()
6466 "Promote the current heading higher up the tree.
6467 If the region is active in `transient-mark-mode', promote all headings
6468 in the region."
6469 (org-back-to-heading t)
6470 (let* ((level (save-match-data (funcall outline-level)))
6471 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6472 (diff (abs (- level (length up-head) -1))))
6473 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6474 (replace-match up-head nil t)
6475 ;; Fixup tag positioning
6476 (and org-auto-align-tags (org-set-tags nil t))
6477 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6479 (defun org-demote ()
6480 "Demote the current heading lower down the tree.
6481 If the region is active in `transient-mark-mode', demote all headings
6482 in the region."
6483 (org-back-to-heading t)
6484 (let* ((level (save-match-data (funcall outline-level)))
6485 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6486 (diff (abs (- level (length down-head) -1))))
6487 (replace-match down-head nil t)
6488 ;; Fixup tag positioning
6489 (and org-auto-align-tags (org-set-tags nil t))
6490 (if org-adapt-indentation (org-fixup-indentation diff))))
6492 (defun org-map-tree (fun)
6493 "Call FUN for every heading underneath the current one."
6494 (org-back-to-heading)
6495 (let ((level (funcall outline-level)))
6496 (save-excursion
6497 (funcall fun)
6498 (while (and (progn
6499 (outline-next-heading)
6500 (> (funcall outline-level) level))
6501 (not (eobp)))
6502 (funcall fun)))))
6504 (defun org-map-region (fun beg end)
6505 "Call FUN for every heading between BEG and END."
6506 (let ((org-ignore-region t))
6507 (save-excursion
6508 (setq end (copy-marker end))
6509 (goto-char beg)
6510 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6511 (< (point) end))
6512 (funcall fun))
6513 (while (and (progn
6514 (outline-next-heading)
6515 (< (point) end))
6516 (not (eobp)))
6517 (funcall fun)))))
6519 (defun org-fixup-indentation (diff)
6520 "Change the indentation in the current entry by DIFF
6521 However, if any line in the current entry has no indentation, or if it
6522 would end up with no indentation after the change, nothing at all is done."
6523 (save-excursion
6524 (let ((end (save-excursion (outline-next-heading)
6525 (point-marker)))
6526 (prohibit (if (> diff 0)
6527 "^\\S-"
6528 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6529 col)
6530 (unless (save-excursion (end-of-line 1)
6531 (re-search-forward prohibit end t))
6532 (while (and (< (point) end)
6533 (re-search-forward "^[ \t]+" end t))
6534 (goto-char (match-end 0))
6535 (setq col (current-column))
6536 (if (< diff 0) (replace-match ""))
6537 (indent-to (+ diff col))))
6538 (move-marker end nil))))
6540 (defun org-convert-to-odd-levels ()
6541 "Convert an org-mode file with all levels allowed to one with odd levels.
6542 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6543 level 5 etc."
6544 (interactive)
6545 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6546 (let ((org-odd-levels-only nil) n)
6547 (save-excursion
6548 (goto-char (point-min))
6549 (while (re-search-forward "^\\*\\*+ " nil t)
6550 (setq n (- (length (match-string 0)) 2))
6551 (while (>= (setq n (1- n)) 0)
6552 (org-demote))
6553 (end-of-line 1))))))
6556 (defun org-convert-to-oddeven-levels ()
6557 "Convert an org-mode file with only odd levels to one with odd and even levels.
6558 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6559 section with an even level, conversion would destroy the structure of the file. An error
6560 is signaled in this case."
6561 (interactive)
6562 (goto-char (point-min))
6563 ;; First check if there are no even levels
6564 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6565 (org-show-context t)
6566 (error "Not all levels are odd in this file. Conversion not possible."))
6567 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6568 (let ((org-odd-levels-only nil) n)
6569 (save-excursion
6570 (goto-char (point-min))
6571 (while (re-search-forward "^\\*\\*+ " nil t)
6572 (setq n (/ (1- (length (match-string 0))) 2))
6573 (while (>= (setq n (1- n)) 0)
6574 (org-promote))
6575 (end-of-line 1))))))
6577 (defun org-tr-level (n)
6578 "Make N odd if required."
6579 (if org-odd-levels-only (1+ (/ n 2)) n))
6581 ;;; Vertical tree motion, cutting and pasting of subtrees
6583 (defun org-move-subtree-up (&optional arg)
6584 "Move the current subtree up past ARG headlines of the same level."
6585 (interactive "p")
6586 (org-move-subtree-down (- (prefix-numeric-value arg))))
6588 (defun org-move-subtree-down (&optional arg)
6589 "Move the current subtree down past ARG headlines of the same level."
6590 (interactive "p")
6591 (setq arg (prefix-numeric-value arg))
6592 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6593 'outline-get-last-sibling))
6594 (ins-point (make-marker))
6595 (cnt (abs arg))
6596 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6597 ;; Select the tree
6598 (org-back-to-heading)
6599 (setq beg0 (point))
6600 (save-excursion
6601 (setq ne-beg (org-back-over-empty-lines))
6602 (setq beg (point)))
6603 (save-match-data
6604 (save-excursion (outline-end-of-heading)
6605 (setq folded (org-invisible-p)))
6606 (outline-end-of-subtree))
6607 (outline-next-heading)
6608 (setq ne-end (org-back-over-empty-lines))
6609 (setq end (point))
6610 (goto-char beg0)
6611 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6612 ;; include less whitespace
6613 (save-excursion
6614 (goto-char beg)
6615 (forward-line (- ne-beg ne-end))
6616 (setq beg (point))))
6617 ;; Find insertion point, with error handling
6618 (while (> cnt 0)
6619 (or (and (funcall movfunc) (looking-at outline-regexp))
6620 (progn (goto-char beg0)
6621 (error "Cannot move past superior level or buffer limit")))
6622 (setq cnt (1- cnt)))
6623 (if (> arg 0)
6624 ;; Moving forward - still need to move over subtree
6625 (progn (org-end-of-subtree t t)
6626 (save-excursion
6627 (org-back-over-empty-lines)
6628 (or (bolp) (newline)))))
6629 (setq ne-ins (org-back-over-empty-lines))
6630 (move-marker ins-point (point))
6631 (setq txt (buffer-substring beg end))
6632 (delete-region beg end)
6633 (outline-flag-region (1- beg) beg nil)
6634 (outline-flag-region (1- (point)) (point) nil)
6635 (insert txt)
6636 (or (bolp) (insert "\n"))
6637 (setq ins-end (point))
6638 (goto-char ins-point)
6639 (org-skip-whitespace)
6640 (when (and (< arg 0)
6641 (org-first-sibling-p)
6642 (> ne-ins ne-beg))
6643 ;; Move whitespace back to beginning
6644 (save-excursion
6645 (goto-char ins-end)
6646 (let ((kill-whole-line t))
6647 (kill-line (- ne-ins ne-beg)) (point)))
6648 (insert (make-string (- ne-ins ne-beg) ?\n)))
6649 (move-marker ins-point nil)
6650 (org-compact-display-after-subtree-move)
6651 (unless folded
6652 (org-show-entry)
6653 (show-children)
6654 (org-cycle-hide-drawers 'children))))
6656 (defvar org-subtree-clip ""
6657 "Clipboard for cut and paste of subtrees.
6658 This is actually only a copy of the kill, because we use the normal kill
6659 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6661 (defvar org-subtree-clip-folded nil
6662 "Was the last copied subtree folded?
6663 This is used to fold the tree back after pasting.")
6665 (defun org-cut-subtree (&optional n)
6666 "Cut the current subtree into the clipboard.
6667 With prefix arg N, cut this many sequential subtrees.
6668 This is a short-hand for marking the subtree and then cutting it."
6669 (interactive "p")
6670 (org-copy-subtree n 'cut))
6672 (defun org-copy-subtree (&optional n cut)
6673 "Cut the current subtree into the clipboard.
6674 With prefix arg N, cut this many sequential subtrees.
6675 This is a short-hand for marking the subtree and then copying it.
6676 If CUT is non-nil, actually cut the subtree."
6677 (interactive "p")
6678 (let (beg end folded (beg0 (point)))
6679 (if (interactive-p)
6680 (org-back-to-heading nil) ; take what looks like a subtree
6681 (org-back-to-heading t)) ; take what is really there
6682 (org-back-over-empty-lines)
6683 (setq beg (point))
6684 (skip-chars-forward " \t\r\n")
6685 (save-match-data
6686 (save-excursion (outline-end-of-heading)
6687 (setq folded (org-invisible-p)))
6688 (condition-case nil
6689 (outline-forward-same-level (1- n))
6690 (error nil))
6691 (org-end-of-subtree t t))
6692 (org-back-over-empty-lines)
6693 (setq end (point))
6694 (goto-char beg0)
6695 (when (> end beg)
6696 (setq org-subtree-clip-folded folded)
6697 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6698 (setq org-subtree-clip (current-kill 0))
6699 (message "%s: Subtree(s) with %d characters"
6700 (if cut "Cut" "Copied")
6701 (length org-subtree-clip)))))
6703 (defun org-paste-subtree (&optional level tree)
6704 "Paste the clipboard as a subtree, with modification of headline level.
6705 The entire subtree is promoted or demoted in order to match a new headline
6706 level. By default, the new level is derived from the visible headings
6707 before and after the insertion point, and taken to be the inferior headline
6708 level of the two. So if the previous visible heading is level 3 and the
6709 next is level 4 (or vice versa), level 4 will be used for insertion.
6710 This makes sure that the subtree remains an independent subtree and does
6711 not swallow low level entries.
6713 You can also force a different level, either by using a numeric prefix
6714 argument, or by inserting the heading marker by hand. For example, if the
6715 cursor is after \"*****\", then the tree will be shifted to level 5.
6717 If you want to insert the tree as is, just use \\[yank].
6719 If optional TREE is given, use this text instead of the kill ring."
6720 (interactive "P")
6721 (unless (org-kill-is-subtree-p tree)
6722 (error "%s"
6723 (substitute-command-keys
6724 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6725 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6726 (^re (concat "^\\(" outline-regexp "\\)"))
6727 (re (concat "\\(" outline-regexp "\\)"))
6728 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6730 (old-level (if (string-match ^re txt)
6731 (- (match-end 0) (match-beginning 0) 1)
6732 -1))
6733 (force-level (cond (level (prefix-numeric-value level))
6734 ((string-match
6735 ^re_ (buffer-substring (point-at-bol) (point)))
6736 (- (match-end 1) (match-beginning 1)))
6737 (t nil)))
6738 (previous-level (save-excursion
6739 (condition-case nil
6740 (progn
6741 (outline-previous-visible-heading 1)
6742 (if (looking-at re)
6743 (- (match-end 0) (match-beginning 0) 1)
6745 (error 1))))
6746 (next-level (save-excursion
6747 (condition-case nil
6748 (progn
6749 (or (looking-at outline-regexp)
6750 (outline-next-visible-heading 1))
6751 (if (looking-at re)
6752 (- (match-end 0) (match-beginning 0) 1)
6754 (error 1))))
6755 (new-level (or force-level (max previous-level next-level)))
6756 (shift (if (or (= old-level -1)
6757 (= new-level -1)
6758 (= old-level new-level))
6760 (- new-level old-level)))
6761 (delta (if (> shift 0) -1 1))
6762 (func (if (> shift 0) 'org-demote 'org-promote))
6763 (org-odd-levels-only nil)
6764 beg end)
6765 ;; Remove the forced level indicator
6766 (if force-level
6767 (delete-region (point-at-bol) (point)))
6768 ;; Paste
6769 (beginning-of-line 1)
6770 (org-back-over-empty-lines) ;; FIXME: correct fix????
6771 (setq beg (point))
6772 (insert-before-markers txt) ;; FIXME: correct fix????
6773 (unless (string-match "\n\\'" txt) (insert "\n"))
6774 (setq end (point))
6775 (goto-char beg)
6776 (skip-chars-forward " \t\n\r")
6777 (setq beg (point))
6778 ;; Shift if necessary
6779 (unless (= shift 0)
6780 (save-restriction
6781 (narrow-to-region beg end)
6782 (while (not (= shift 0))
6783 (org-map-region func (point-min) (point-max))
6784 (setq shift (+ delta shift)))
6785 (goto-char (point-min))))
6786 (when (interactive-p)
6787 (message "Clipboard pasted as level %d subtree" new-level))
6788 (if (and kill-ring
6789 (eq org-subtree-clip (current-kill 0))
6790 org-subtree-clip-folded)
6791 ;; The tree was folded before it was killed/copied
6792 (hide-subtree))))
6794 (defun org-kill-is-subtree-p (&optional txt)
6795 "Check if the current kill is an outline subtree, or a set of trees.
6796 Returns nil if kill does not start with a headline, or if the first
6797 headline level is not the largest headline level in the tree.
6798 So this will actually accept several entries of equal levels as well,
6799 which is OK for `org-paste-subtree'.
6800 If optional TXT is given, check this string instead of the current kill."
6801 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6802 (start-level (and kill
6803 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6804 org-outline-regexp "\\)")
6805 kill)
6806 (- (match-end 2) (match-beginning 2) 1)))
6807 (re (concat "^" org-outline-regexp))
6808 (start (1+ (match-beginning 2))))
6809 (if (not start-level)
6810 (progn
6811 nil) ;; does not even start with a heading
6812 (catch 'exit
6813 (while (setq start (string-match re kill (1+ start)))
6814 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6815 (throw 'exit nil)))
6816 t))))
6818 (defun org-narrow-to-subtree ()
6819 "Narrow buffer to the current subtree."
6820 (interactive)
6821 (save-excursion
6822 (save-match-data
6823 (narrow-to-region
6824 (progn (org-back-to-heading) (point))
6825 (progn (org-end-of-subtree t t) (point))))))
6828 ;;; Outline Sorting
6830 (defun org-sort (with-case)
6831 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6832 Optional argument WITH-CASE means sort case-sensitively."
6833 (interactive "P")
6834 (if (org-at-table-p)
6835 (org-call-with-arg 'org-table-sort-lines with-case)
6836 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6838 (defvar org-priority-regexp) ; defined later in the file
6840 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6841 "Sort entries on a certain level of an outline tree.
6842 If there is an active region, the entries in the region are sorted.
6843 Else, if the cursor is before the first entry, sort the top-level items.
6844 Else, the children of the entry at point are sorted.
6846 Sorting can be alphabetically, numerically, and by date/time as given by
6847 the first time stamp in the entry. The command prompts for the sorting
6848 type unless it has been given to the function through the SORTING-TYPE
6849 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6850 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6851 called with point at the beginning of the record. It must return either
6852 a string or a number that should serve as the sorting key for that record.
6854 Comparing entries ignores case by default. However, with an optional argument
6855 WITH-CASE, the sorting considers case as well."
6856 (interactive "P")
6857 (let ((case-func (if with-case 'identity 'downcase))
6858 start beg end stars re re2
6859 txt what tmp plain-list-p)
6860 ;; Find beginning and end of region to sort
6861 (cond
6862 ((org-region-active-p)
6863 ;; we will sort the region
6864 (setq end (region-end)
6865 what "region")
6866 (goto-char (region-beginning))
6867 (if (not (org-on-heading-p)) (outline-next-heading))
6868 (setq start (point)))
6869 ((org-at-item-p)
6870 ;; we will sort this plain list
6871 (org-beginning-of-item-list) (setq start (point))
6872 (org-end-of-item-list) (setq end (point))
6873 (goto-char start)
6874 (setq plain-list-p t
6875 what "plain list"))
6876 ((or (org-on-heading-p)
6877 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6878 ;; we will sort the children of the current headline
6879 (org-back-to-heading)
6880 (setq start (point)
6881 end (progn (org-end-of-subtree t t)
6882 (org-back-over-empty-lines)
6883 (point))
6884 what "children")
6885 (goto-char start)
6886 (show-subtree)
6887 (outline-next-heading))
6889 ;; we will sort the top-level entries in this file
6890 (goto-char (point-min))
6891 (or (org-on-heading-p) (outline-next-heading))
6892 (setq start (point) end (point-max) what "top-level")
6893 (goto-char start)
6894 (show-all)))
6896 (setq beg (point))
6897 (if (>= beg end) (error "Nothing to sort"))
6899 (unless plain-list-p
6900 (looking-at "\\(\\*+\\)")
6901 (setq stars (match-string 1)
6902 re (concat "^" (regexp-quote stars) " +")
6903 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6904 txt (buffer-substring beg end))
6905 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6906 (if (and (not (equal stars "*")) (string-match re2 txt))
6907 (error "Region to sort contains a level above the first entry")))
6909 (unless sorting-type
6910 (message
6911 (if plain-list-p
6912 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6913 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6914 what)
6915 (setq sorting-type (read-char-exclusive))
6917 (and (= (downcase sorting-type) ?f)
6918 (setq getkey-func
6919 (completing-read "Sort using function: "
6920 obarray 'fboundp t nil nil))
6921 (setq getkey-func (intern getkey-func)))
6923 (and (= (downcase sorting-type) ?r)
6924 (setq property
6925 (completing-read "Property: "
6926 (mapcar 'list (org-buffer-property-keys t))
6927 nil t))))
6929 (message "Sorting entries...")
6931 (save-restriction
6932 (narrow-to-region start end)
6934 (let ((dcst (downcase sorting-type))
6935 (now (current-time)))
6936 (sort-subr
6937 (/= dcst sorting-type)
6938 ;; This function moves to the beginning character of the "record" to
6939 ;; be sorted.
6940 (if plain-list-p
6941 (lambda nil
6942 (if (org-at-item-p) t (goto-char (point-max))))
6943 (lambda nil
6944 (if (re-search-forward re nil t)
6945 (goto-char (match-beginning 0))
6946 (goto-char (point-max)))))
6947 ;; This function moves to the last character of the "record" being
6948 ;; sorted.
6949 (if plain-list-p
6950 'org-end-of-item
6951 (lambda nil
6952 (save-match-data
6953 (condition-case nil
6954 (outline-forward-same-level 1)
6955 (error
6956 (goto-char (point-max)))))))
6958 ;; This function returns the value that gets sorted against.
6959 (if plain-list-p
6960 (lambda nil
6961 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6962 (cond
6963 ((= dcst ?n)
6964 (string-to-number (buffer-substring (match-end 0)
6965 (point-at-eol))))
6966 ((= dcst ?a)
6967 (buffer-substring (match-end 0) (point-at-eol)))
6968 ((= dcst ?t)
6969 (if (re-search-forward org-ts-regexp
6970 (point-at-eol) t)
6971 (org-time-string-to-time (match-string 0))
6972 now))
6973 ((= dcst ?f)
6974 (if getkey-func
6975 (progn
6976 (setq tmp (funcall getkey-func))
6977 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6978 tmp)
6979 (error "Invalid key function `%s'" getkey-func)))
6980 (t (error "Invalid sorting type `%c'" sorting-type)))))
6981 (lambda nil
6982 (cond
6983 ((= dcst ?n)
6984 (if (looking-at outline-regexp)
6985 (string-to-number (buffer-substring (match-end 0)
6986 (point-at-eol)))
6987 nil))
6988 ((= dcst ?a)
6989 (funcall case-func (buffer-substring (point-at-bol)
6990 (point-at-eol))))
6991 ((= dcst ?t)
6992 (if (re-search-forward org-ts-regexp
6993 (save-excursion
6994 (forward-line 2)
6995 (point)) t)
6996 (org-time-string-to-time (match-string 0))
6997 now))
6998 ((= dcst ?p)
6999 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7000 (string-to-char (match-string 2))
7001 org-default-priority))
7002 ((= dcst ?r)
7003 (or (org-entry-get nil property) ""))
7004 ((= dcst ?f)
7005 (if getkey-func
7006 (progn
7007 (setq tmp (funcall getkey-func))
7008 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7009 tmp)
7010 (error "Invalid key function `%s'" getkey-func)))
7011 (t (error "Invalid sorting type `%c'" sorting-type)))))
7013 (cond
7014 ((= dcst ?a) 'string<)
7015 ((= dcst ?t) 'time-less-p)
7016 (t nil)))))
7017 (message "Sorting entries...done")))
7019 (defun org-do-sort (table what &optional with-case sorting-type)
7020 "Sort TABLE of WHAT according to SORTING-TYPE.
7021 The user will be prompted for the SORTING-TYPE if the call to this
7022 function does not specify it. WHAT is only for the prompt, to indicate
7023 what is being sorted. The sorting key will be extracted from
7024 the car of the elements of the table.
7025 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7026 (unless sorting-type
7027 (message
7028 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7029 what)
7030 (setq sorting-type (read-char-exclusive)))
7031 (let ((dcst (downcase sorting-type))
7032 extractfun comparefun)
7033 ;; Define the appropriate functions
7034 (cond
7035 ((= dcst ?n)
7036 (setq extractfun 'string-to-number
7037 comparefun (if (= dcst sorting-type) '< '>)))
7038 ((= dcst ?a)
7039 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7040 (lambda(x) (downcase (org-sort-remove-invisible x))))
7041 comparefun (if (= dcst sorting-type)
7042 'string<
7043 (lambda (a b) (and (not (string< a b))
7044 (not (string= a b)))))))
7045 ((= dcst ?t)
7046 (setq extractfun
7047 (lambda (x)
7048 (if (string-match org-ts-regexp x)
7049 (time-to-seconds
7050 (org-time-string-to-time (match-string 0 x)))
7052 comparefun (if (= dcst sorting-type) '< '>)))
7053 (t (error "Invalid sorting type `%c'" sorting-type)))
7055 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7056 table)
7057 (lambda (a b) (funcall comparefun (car a) (car b))))))
7059 ;;;; Plain list items, including checkboxes
7061 ;;; Plain list items
7063 (defun org-at-item-p ()
7064 "Is point in a line starting a hand-formatted item?"
7065 (let ((llt org-plain-list-ordered-item-terminator))
7066 (save-excursion
7067 (goto-char (point-at-bol))
7068 (looking-at
7069 (cond
7070 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7071 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7072 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7073 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7075 (defun org-in-item-p ()
7076 "It the cursor inside a plain list item.
7077 Does not have to be the first line."
7078 (save-excursion
7079 (condition-case nil
7080 (progn
7081 (org-beginning-of-item)
7082 (org-at-item-p)
7084 (error nil))))
7086 (defun org-insert-item (&optional checkbox)
7087 "Insert a new item at the current level.
7088 Return t when things worked, nil when we are not in an item."
7089 (when (save-excursion
7090 (condition-case nil
7091 (progn
7092 (org-beginning-of-item)
7093 (org-at-item-p)
7094 (if (org-invisible-p) (error "Invisible item"))
7096 (error nil)))
7097 (let* ((bul (match-string 0))
7098 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7099 (match-end 0)))
7100 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7101 pos)
7102 (cond
7103 ((and (org-at-item-p) (<= (point) eow))
7104 ;; before the bullet
7105 (beginning-of-line 1)
7106 (open-line (if blank 2 1)))
7107 ((<= (point) eow)
7108 (beginning-of-line 1))
7110 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7111 (end-of-line 1)
7112 (delete-horizontal-space))
7113 (newline (if blank 2 1))))
7114 (insert bul (if checkbox "[ ]" ""))
7115 (just-one-space)
7116 (setq pos (point))
7117 (end-of-line 1)
7118 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7119 (org-maybe-renumber-ordered-list)
7120 (and checkbox (org-update-checkbox-count-maybe))
7123 ;;; Checkboxes
7125 (defun org-at-item-checkbox-p ()
7126 "Is point at a line starting a plain-list item with a checklet?"
7127 (and (org-at-item-p)
7128 (save-excursion
7129 (goto-char (match-end 0))
7130 (skip-chars-forward " \t")
7131 (looking-at "\\[[- X]\\]"))))
7133 (defun org-toggle-checkbox (&optional arg)
7134 "Toggle the checkbox in the current line."
7135 (interactive "P")
7136 (catch 'exit
7137 (let (beg end status (firstnew 'unknown))
7138 (cond
7139 ((org-region-active-p)
7140 (setq beg (region-beginning) end (region-end)))
7141 ((org-on-heading-p)
7142 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7143 ((org-at-item-checkbox-p)
7144 (let ((pos (point)))
7145 (replace-match
7146 (cond (arg "[-]")
7147 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7148 (t "[ ]"))
7149 t t)
7150 (goto-char pos))
7151 (throw 'exit t))
7152 (t (error "Not at a checkbox or heading, and no active region")))
7153 (save-excursion
7154 (goto-char beg)
7155 (while (< (point) end)
7156 (when (org-at-item-checkbox-p)
7157 (setq status (equal (match-string 0) "[X]"))
7158 (when (eq firstnew 'unknown)
7159 (setq firstnew (not status)))
7160 (replace-match
7161 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7162 (beginning-of-line 2)))))
7163 (org-update-checkbox-count-maybe))
7165 (defun org-update-checkbox-count-maybe ()
7166 "Update checkbox statistics unless turned off by user."
7167 (when org-provide-checkbox-statistics
7168 (org-update-checkbox-count)))
7170 (defun org-update-checkbox-count (&optional all)
7171 "Update the checkbox statistics in the current section.
7172 This will find all statistic cookies like [57%] and [6/12] and update them
7173 with the current numbers. With optional prefix argument ALL, do this for
7174 the whole buffer."
7175 (interactive "P")
7176 (save-excursion
7177 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7178 (beg (condition-case nil
7179 (progn (outline-back-to-heading) (point))
7180 (error (point-min))))
7181 (end (move-marker (make-marker)
7182 (progn (outline-next-heading) (point))))
7183 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7184 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7185 (re-find (concat re "\\|" re-box))
7186 beg-cookie end-cookie is-percent c-on c-off lim
7187 eline curr-ind next-ind continue-from startsearch
7188 (cstat 0)
7190 (when all
7191 (goto-char (point-min))
7192 (outline-next-heading)
7193 (setq beg (point) end (point-max)))
7194 (goto-char end)
7195 ;; find each statistic cookie
7196 (while (re-search-backward re-find beg t)
7197 (setq beg-cookie (match-beginning 1)
7198 end-cookie (match-end 1)
7199 cstat (+ cstat (if end-cookie 1 0))
7200 startsearch (point-at-eol)
7201 continue-from (point-at-bol)
7202 is-percent (match-beginning 2)
7203 lim (cond
7204 ((org-on-heading-p) (outline-next-heading) (point))
7205 ((org-at-item-p) (org-end-of-item) (point))
7206 (t nil))
7207 c-on 0
7208 c-off 0)
7209 (when lim
7210 ;; find first checkbox for this cookie and gather
7211 ;; statistics from all that are at this indentation level
7212 (goto-char startsearch)
7213 (if (re-search-forward re-box lim t)
7214 (progn
7215 (org-beginning-of-item)
7216 (setq curr-ind (org-get-indentation))
7217 (setq next-ind curr-ind)
7218 (while (= curr-ind next-ind)
7219 (save-excursion (end-of-line) (setq eline (point)))
7220 (if (re-search-forward re-box eline t)
7221 (if (member (match-string 2) '("[ ]" "[-]"))
7222 (setq c-off (1+ c-off))
7223 (setq c-on (1+ c-on))
7226 (org-end-of-item)
7227 (setq next-ind (org-get-indentation))
7229 (goto-char continue-from)
7230 ;; update cookie
7231 (when end-cookie
7232 (delete-region beg-cookie end-cookie)
7233 (goto-char beg-cookie)
7234 (insert
7235 (if is-percent
7236 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7237 (format "[%d/%d]" c-on (+ c-on c-off)))))
7238 ;; update items checkbox if it has one
7239 (when (org-at-item-p)
7240 (org-beginning-of-item)
7241 (when (and (> (+ c-on c-off) 0)
7242 (re-search-forward re-box (point-at-eol) t))
7243 (setq beg-cookie (match-beginning 2)
7244 end-cookie (match-end 2))
7245 (delete-region beg-cookie end-cookie)
7246 (goto-char beg-cookie)
7247 (cond ((= c-off 0) (insert "[X]"))
7248 ((= c-on 0) (insert "[ ]"))
7249 (t (insert "[-]")))
7251 (goto-char continue-from))
7252 (when (interactive-p)
7253 (message "Checkbox satistics updated %s (%d places)"
7254 (if all "in entire file" "in current outline entry") cstat)))))
7256 (defun org-get-checkbox-statistics-face ()
7257 "Select the face for checkbox statistics.
7258 The face will be `org-done' when all relevant boxes are checked. Otherwise
7259 it will be `org-todo'."
7260 (if (match-end 1)
7261 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7262 (if (and (> (match-end 2) (match-beginning 2))
7263 (equal (match-string 2) (match-string 3)))
7264 'org-done
7265 'org-todo)))
7267 (defun org-get-indentation (&optional line)
7268 "Get the indentation of the current line, interpreting tabs.
7269 When LINE is given, assume it represents a line and compute its indentation."
7270 (if line
7271 (if (string-match "^ *" (org-remove-tabs line))
7272 (match-end 0))
7273 (save-excursion
7274 (beginning-of-line 1)
7275 (skip-chars-forward " \t")
7276 (current-column))))
7278 (defun org-remove-tabs (s &optional width)
7279 "Replace tabulators in S with spaces.
7280 Assumes that s is a single line, starting in column 0."
7281 (setq width (or width tab-width))
7282 (while (string-match "\t" s)
7283 (setq s (replace-match
7284 (make-string
7285 (- (* width (/ (+ (match-beginning 0) width) width))
7286 (match-beginning 0)) ?\ )
7287 t t s)))
7290 (defun org-fix-indentation (line ind)
7291 "Fix indentation in LINE.
7292 IND is a cons cell with target and minimum indentation.
7293 If the current indenation in LINE is smaller than the minimum,
7294 leave it alone. If it is larger than ind, set it to the target."
7295 (let* ((l (org-remove-tabs line))
7296 (i (org-get-indentation l))
7297 (i1 (car ind)) (i2 (cdr ind)))
7298 (if (>= i i2) (setq l (substring line i2)))
7299 (if (> i1 0)
7300 (concat (make-string i1 ?\ ) l)
7301 l)))
7303 (defcustom org-empty-line-terminates-plain-lists nil
7304 "Non-nil means, an empty line ends all plain list levels.
7305 When nil, empty lines are part of the preceeding item."
7306 :group 'org-plain-lists
7307 :type 'boolean)
7309 (defun org-beginning-of-item ()
7310 "Go to the beginning of the current hand-formatted item.
7311 If the cursor is not in an item, throw an error."
7312 (interactive)
7313 (let ((pos (point))
7314 (limit (save-excursion
7315 (condition-case nil
7316 (progn
7317 (org-back-to-heading)
7318 (beginning-of-line 2) (point))
7319 (error (point-min)))))
7320 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7321 ind ind1)
7322 (if (org-at-item-p)
7323 (beginning-of-line 1)
7324 (beginning-of-line 1)
7325 (skip-chars-forward " \t")
7326 (setq ind (current-column))
7327 (if (catch 'exit
7328 (while t
7329 (beginning-of-line 0)
7330 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7332 (if (looking-at "[ \t]*$")
7333 (setq ind1 ind-empty)
7334 (skip-chars-forward " \t")
7335 (setq ind1 (current-column)))
7336 (if (< ind1 ind)
7337 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7339 (goto-char pos)
7340 (error "Not in an item")))))
7342 (defun org-end-of-item ()
7343 "Go to the end of the current hand-formatted item.
7344 If the cursor is not in an item, throw an error."
7345 (interactive)
7346 (let* ((pos (point))
7347 ind1
7348 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7349 (limit (save-excursion (outline-next-heading) (point)))
7350 (ind (save-excursion
7351 (org-beginning-of-item)
7352 (skip-chars-forward " \t")
7353 (current-column)))
7354 (end (catch 'exit
7355 (while t
7356 (beginning-of-line 2)
7357 (if (eobp) (throw 'exit (point)))
7358 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7359 (if (looking-at "[ \t]*$")
7360 (setq ind1 ind-empty)
7361 (skip-chars-forward " \t")
7362 (setq ind1 (current-column)))
7363 (if (<= ind1 ind)
7364 (throw 'exit (point-at-bol)))))))
7365 (if end
7366 (goto-char end)
7367 (goto-char pos)
7368 (error "Not in an item"))))
7370 (defun org-next-item ()
7371 "Move to the beginning of the next item in the current plain list.
7372 Error if not at a plain list, or if this is the last item in the list."
7373 (interactive)
7374 (let (ind ind1 (pos (point)))
7375 (org-beginning-of-item)
7376 (setq ind (org-get-indentation))
7377 (org-end-of-item)
7378 (setq ind1 (org-get-indentation))
7379 (unless (and (org-at-item-p) (= ind ind1))
7380 (goto-char pos)
7381 (error "On last item"))))
7383 (defun org-previous-item ()
7384 "Move to the beginning of the previous item in the current plain list.
7385 Error if not at a plain list, or if this is the first item in the list."
7386 (interactive)
7387 (let (beg ind ind1 (pos (point)))
7388 (org-beginning-of-item)
7389 (setq beg (point))
7390 (setq ind (org-get-indentation))
7391 (goto-char beg)
7392 (catch 'exit
7393 (while t
7394 (beginning-of-line 0)
7395 (if (looking-at "[ \t]*$")
7397 (if (<= (setq ind1 (org-get-indentation)) ind)
7398 (throw 'exit t)))))
7399 (condition-case nil
7400 (if (or (not (org-at-item-p))
7401 (< ind1 (1- ind)))
7402 (error "")
7403 (org-beginning-of-item))
7404 (error (goto-char pos)
7405 (error "On first item")))))
7407 (defun org-first-list-item-p ()
7408 "Is this heading the item in a plain list?"
7409 (unless (org-at-item-p)
7410 (error "Not at a plain list item"))
7411 (org-beginning-of-item)
7412 (= (point) (save-excursion (org-beginning-of-item-list))))
7414 (defun org-move-item-down ()
7415 "Move the plain list item at point down, i.e. swap with following item.
7416 Subitems (items with larger indentation) are considered part of the item,
7417 so this really moves item trees."
7418 (interactive)
7419 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7420 (org-beginning-of-item)
7421 (setq beg0 (point))
7422 (save-excursion
7423 (setq ne-beg (org-back-over-empty-lines))
7424 (setq beg (point)))
7425 (goto-char beg0)
7426 (setq ind (org-get-indentation))
7427 (org-end-of-item)
7428 (setq end0 (point))
7429 (setq ind1 (org-get-indentation))
7430 (setq ne-end (org-back-over-empty-lines))
7431 (setq end (point))
7432 (goto-char beg0)
7433 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7434 ;; include less whitespace
7435 (save-excursion
7436 (goto-char beg)
7437 (forward-line (- ne-beg ne-end))
7438 (setq beg (point))))
7439 (goto-char end0)
7440 (if (and (org-at-item-p) (= ind ind1))
7441 (progn
7442 (org-end-of-item)
7443 (org-back-over-empty-lines)
7444 (setq txt (buffer-substring beg end))
7445 (save-excursion
7446 (delete-region beg end))
7447 (setq pos (point))
7448 (insert txt)
7449 (goto-char pos) (org-skip-whitespace)
7450 (org-maybe-renumber-ordered-list))
7451 (goto-char pos)
7452 (error "Cannot move this item further down"))))
7454 (defun org-move-item-up (arg)
7455 "Move the plain list item at point up, i.e. swap with previous item.
7456 Subitems (items with larger indentation) are considered part of the item,
7457 so this really moves item trees."
7458 (interactive "p")
7459 (let (beg beg0 end ind ind1 (pos (point)) txt
7460 ne-beg ne-ins ins-end)
7461 (org-beginning-of-item)
7462 (setq beg0 (point))
7463 (setq ind (org-get-indentation))
7464 (save-excursion
7465 (setq ne-beg (org-back-over-empty-lines))
7466 (setq beg (point)))
7467 (goto-char beg0)
7468 (org-end-of-item)
7469 (setq end (point))
7470 (goto-char beg0)
7471 (catch 'exit
7472 (while t
7473 (beginning-of-line 0)
7474 (if (looking-at "[ \t]*$")
7475 (if org-empty-line-terminates-plain-lists
7476 (progn
7477 (goto-char pos)
7478 (error "Cannot move this item further up"))
7479 nil)
7480 (if (<= (setq ind1 (org-get-indentation)) ind)
7481 (throw 'exit t)))))
7482 (condition-case nil
7483 (org-beginning-of-item)
7484 (error (goto-char beg)
7485 (error "Cannot move this item further up")))
7486 (setq ind1 (org-get-indentation))
7487 (if (and (org-at-item-p) (= ind ind1))
7488 (progn
7489 (setq ne-ins (org-back-over-empty-lines))
7490 (setq txt (buffer-substring beg end))
7491 (save-excursion
7492 (delete-region beg end))
7493 (setq pos (point))
7494 (insert txt)
7495 (setq ins-end (point))
7496 (goto-char pos) (org-skip-whitespace)
7498 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7499 ;; Move whitespace back to beginning
7500 (save-excursion
7501 (goto-char ins-end)
7502 (let ((kill-whole-line t))
7503 (kill-line (- ne-ins ne-beg)) (point)))
7504 (insert (make-string (- ne-ins ne-beg) ?\n)))
7506 (org-maybe-renumber-ordered-list))
7507 (goto-char pos)
7508 (error "Cannot move this item further up"))))
7510 (defun org-maybe-renumber-ordered-list ()
7511 "Renumber the ordered list at point if setup allows it.
7512 This tests the user option `org-auto-renumber-ordered-lists' before
7513 doing the renumbering."
7514 (interactive)
7515 (when (and org-auto-renumber-ordered-lists
7516 (org-at-item-p))
7517 (if (match-beginning 3)
7518 (org-renumber-ordered-list 1)
7519 (org-fix-bullet-type))))
7521 (defun org-maybe-renumber-ordered-list-safe ()
7522 (condition-case nil
7523 (save-excursion
7524 (org-maybe-renumber-ordered-list))
7525 (error nil)))
7527 (defun org-cycle-list-bullet (&optional which)
7528 "Cycle through the different itemize/enumerate bullets.
7529 This cycle the entire list level through the sequence:
7531 `-' -> `+' -> `*' -> `1.' -> `1)'
7533 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7534 0 meand `-', 1 means `+' etc."
7535 (interactive "P")
7536 (org-preserve-lc
7537 (org-beginning-of-item-list)
7538 (org-at-item-p)
7539 (beginning-of-line 1)
7540 (let ((current (match-string 0))
7541 (prevp (eq which 'previous))
7542 new)
7543 (setq new (cond
7544 ((and (numberp which)
7545 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7546 ((string-match "-" current) (if prevp "1)" "+"))
7547 ((string-match "\\+" current)
7548 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7549 ((string-match "\\*" current) (if prevp "+" "1."))
7550 ((string-match "\\." current) (if prevp "*" "1)"))
7551 ((string-match ")" current) (if prevp "1." "-"))
7552 (t (error "This should not happen"))))
7553 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7554 (org-fix-bullet-type)
7555 (org-maybe-renumber-ordered-list))))
7557 (defun org-get-string-indentation (s)
7558 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7559 (let ((n -1) (i 0) (w tab-width) c)
7560 (catch 'exit
7561 (while (< (setq n (1+ n)) (length s))
7562 (setq c (aref s n))
7563 (cond ((= c ?\ ) (setq i (1+ i)))
7564 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7565 (t (throw 'exit t)))))
7568 (defun org-renumber-ordered-list (arg)
7569 "Renumber an ordered plain list.
7570 Cursor needs to be in the first line of an item, the line that starts
7571 with something like \"1.\" or \"2)\"."
7572 (interactive "p")
7573 (unless (and (org-at-item-p)
7574 (match-beginning 3))
7575 (error "This is not an ordered list"))
7576 (let ((line (org-current-line))
7577 (col (current-column))
7578 (ind (org-get-string-indentation
7579 (buffer-substring (point-at-bol) (match-beginning 3))))
7580 ;; (term (substring (match-string 3) -1))
7581 ind1 (n (1- arg))
7582 fmt)
7583 ;; find where this list begins
7584 (org-beginning-of-item-list)
7585 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7586 (setq fmt (concat "%d" (match-string 1)))
7587 (beginning-of-line 0)
7588 ;; walk forward and replace these numbers
7589 (catch 'exit
7590 (while t
7591 (catch 'next
7592 (beginning-of-line 2)
7593 (if (eobp) (throw 'exit nil))
7594 (if (looking-at "[ \t]*$") (throw 'next nil))
7595 (skip-chars-forward " \t") (setq ind1 (current-column))
7596 (if (> ind1 ind) (throw 'next t))
7597 (if (< ind1 ind) (throw 'exit t))
7598 (if (not (org-at-item-p)) (throw 'exit nil))
7599 (delete-region (match-beginning 2) (match-end 2))
7600 (goto-char (match-beginning 2))
7601 (insert (format fmt (setq n (1+ n)))))))
7602 (goto-line line)
7603 (move-to-column col)))
7605 (defun org-fix-bullet-type ()
7606 "Make sure all items in this list have the same bullet as the firsst item."
7607 (interactive)
7608 (unless (org-at-item-p) (error "This is not a list"))
7609 (let ((line (org-current-line))
7610 (col (current-column))
7611 (ind (current-indentation))
7612 ind1 bullet)
7613 ;; find where this list begins
7614 (org-beginning-of-item-list)
7615 (beginning-of-line 1)
7616 ;; find out what the bullet type is
7617 (looking-at "[ \t]*\\(\\S-+\\)")
7618 (setq bullet (match-string 1))
7619 ;; walk forward and replace these numbers
7620 (beginning-of-line 0)
7621 (catch 'exit
7622 (while t
7623 (catch 'next
7624 (beginning-of-line 2)
7625 (if (eobp) (throw 'exit nil))
7626 (if (looking-at "[ \t]*$") (throw 'next nil))
7627 (skip-chars-forward " \t") (setq ind1 (current-column))
7628 (if (> ind1 ind) (throw 'next t))
7629 (if (< ind1 ind) (throw 'exit t))
7630 (if (not (org-at-item-p)) (throw 'exit nil))
7631 (skip-chars-forward " \t")
7632 (looking-at "\\S-+")
7633 (replace-match bullet))))
7634 (goto-line line)
7635 (move-to-column col)
7636 (if (string-match "[0-9]" bullet)
7637 (org-renumber-ordered-list 1))))
7639 (defun org-beginning-of-item-list ()
7640 "Go to the beginning of the current item list.
7641 I.e. to the first item in this list."
7642 (interactive)
7643 (org-beginning-of-item)
7644 (let ((pos (point-at-bol))
7645 (ind (org-get-indentation))
7646 ind1)
7647 ;; find where this list begins
7648 (catch 'exit
7649 (while t
7650 (catch 'next
7651 (beginning-of-line 0)
7652 (if (looking-at "[ \t]*$")
7653 (throw (if (bobp) 'exit 'next) t))
7654 (skip-chars-forward " \t") (setq ind1 (current-column))
7655 (if (or (< ind1 ind)
7656 (and (= ind1 ind)
7657 (not (org-at-item-p)))
7658 (bobp))
7659 (throw 'exit t)
7660 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7661 (goto-char pos)))
7664 (defun org-end-of-item-list ()
7665 "Go to the end of the current item list.
7666 I.e. to the text after the last item."
7667 (interactive)
7668 (org-beginning-of-item)
7669 (let ((pos (point-at-bol))
7670 (ind (org-get-indentation))
7671 ind1)
7672 ;; find where this list begins
7673 (catch 'exit
7674 (while t
7675 (catch 'next
7676 (beginning-of-line 2)
7677 (if (looking-at "[ \t]*$")
7678 (throw (if (eobp) 'exit 'next) t))
7679 (skip-chars-forward " \t") (setq ind1 (current-column))
7680 (if (or (< ind1 ind)
7681 (and (= ind1 ind)
7682 (not (org-at-item-p)))
7683 (eobp))
7684 (progn
7685 (setq pos (point-at-bol))
7686 (throw 'exit t))))))
7687 (goto-char pos)))
7690 (defvar org-last-indent-begin-marker (make-marker))
7691 (defvar org-last-indent-end-marker (make-marker))
7693 (defun org-outdent-item (arg)
7694 "Outdent a local list item."
7695 (interactive "p")
7696 (org-indent-item (- arg)))
7698 (defun org-indent-item (arg)
7699 "Indent a local list item."
7700 (interactive "p")
7701 (unless (org-at-item-p)
7702 (error "Not on an item"))
7703 (save-excursion
7704 (let (beg end ind ind1 tmp delta ind-down ind-up)
7705 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7706 (setq beg org-last-indent-begin-marker
7707 end org-last-indent-end-marker)
7708 (org-beginning-of-item)
7709 (setq beg (move-marker org-last-indent-begin-marker (point)))
7710 (org-end-of-item)
7711 (setq end (move-marker org-last-indent-end-marker (point))))
7712 (goto-char beg)
7713 (setq tmp (org-item-indent-positions)
7714 ind (car tmp)
7715 ind-down (nth 2 tmp)
7716 ind-up (nth 1 tmp)
7717 delta (if (> arg 0)
7718 (if ind-down (- ind-down ind) 2)
7719 (if ind-up (- ind-up ind) -2)))
7720 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7721 (while (< (point) end)
7722 (beginning-of-line 1)
7723 (skip-chars-forward " \t") (setq ind1 (current-column))
7724 (delete-region (point-at-bol) (point))
7725 (or (eolp) (indent-to-column (+ ind1 delta)))
7726 (beginning-of-line 2))))
7727 (org-fix-bullet-type)
7728 (org-maybe-renumber-ordered-list-safe)
7729 (save-excursion
7730 (beginning-of-line 0)
7731 (condition-case nil (org-beginning-of-item) (error nil))
7732 (org-maybe-renumber-ordered-list-safe)))
7734 (defun org-item-indent-positions ()
7735 "Return indentation for plain list items.
7736 This returns a list with three values: The current indentation, the
7737 parent indentation and the indentation a child should habe.
7738 Assumes cursor in item line."
7739 (let* ((bolpos (point-at-bol))
7740 (ind (org-get-indentation))
7741 ind-down ind-up pos)
7742 (save-excursion
7743 (org-beginning-of-item-list)
7744 (skip-chars-backward "\n\r \t")
7745 (when (org-in-item-p)
7746 (org-beginning-of-item)
7747 (setq ind-up (org-get-indentation))))
7748 (setq pos (point))
7749 (save-excursion
7750 (cond
7751 ((and (condition-case nil (progn (org-previous-item) t)
7752 (error nil))
7753 (or (forward-char 1) t)
7754 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7755 (setq ind-down (org-get-indentation)))
7756 ((and (goto-char pos)
7757 (org-at-item-p))
7758 (goto-char (match-end 0))
7759 (skip-chars-forward " \t")
7760 (setq ind-down (current-column)))))
7761 (list ind ind-up ind-down)))
7763 ;;; The orgstruct minor mode
7765 ;; Define a minor mode which can be used in other modes in order to
7766 ;; integrate the org-mode structure editing commands.
7768 ;; This is really a hack, because the org-mode structure commands use
7769 ;; keys which normally belong to the major mode. Here is how it
7770 ;; works: The minor mode defines all the keys necessary to operate the
7771 ;; structure commands, but wraps the commands into a function which
7772 ;; tests if the cursor is currently at a headline or a plain list
7773 ;; item. If that is the case, the structure command is used,
7774 ;; temporarily setting many Org-mode variables like regular
7775 ;; expressions for filling etc. However, when any of those keys is
7776 ;; used at a different location, function uses `key-binding' to look
7777 ;; up if the key has an associated command in another currently active
7778 ;; keymap (minor modes, major mode, global), and executes that
7779 ;; command. There might be problems if any of the keys is otherwise
7780 ;; used as a prefix key.
7782 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7783 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7784 ;; addresses this by checking explicitly for both bindings.
7786 (defvar orgstruct-mode-map (make-sparse-keymap)
7787 "Keymap for the minor `orgstruct-mode'.")
7789 (defvar org-local-vars nil
7790 "List of local variables, for use by `orgstruct-mode'")
7792 ;;;###autoload
7793 (define-minor-mode orgstruct-mode
7794 "Toggle the minor more `orgstruct-mode'.
7795 This mode is for using Org-mode structure commands in other modes.
7796 The following key behave as if Org-mode was active, if the cursor
7797 is on a headline, or on a plain list item (both in the definition
7798 of Org-mode).
7800 M-up Move entry/item up
7801 M-down Move entry/item down
7802 M-left Promote
7803 M-right Demote
7804 M-S-up Move entry/item up
7805 M-S-down Move entry/item down
7806 M-S-left Promote subtree
7807 M-S-right Demote subtree
7808 M-q Fill paragraph and items like in Org-mode
7809 C-c ^ Sort entries
7810 C-c - Cycle list bullet
7811 TAB Cycle item visibility
7812 M-RET Insert new heading/item
7813 S-M-RET Insert new TODO heading / Chekbox item
7814 C-c C-c Set tags / toggle checkbox"
7815 nil " OrgStruct" nil
7816 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7818 ;;;###autoload
7819 (defun turn-on-orgstruct ()
7820 "Unconditionally turn on `orgstruct-mode'."
7821 (orgstruct-mode 1))
7823 ;;;###autoload
7824 (defun turn-on-orgstruct++ ()
7825 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7826 In addition to setting orgstruct-mode, this also exports all indentation and
7827 autofilling variables from org-mode into the buffer. Note that turning
7828 off orgstruct-mode will *not* remove these additional settings."
7829 (orgstruct-mode 1)
7830 (let (var val)
7831 (mapc
7832 (lambda (x)
7833 (when (string-match
7834 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7835 (symbol-name (car x)))
7836 (setq var (car x) val (nth 1 x))
7837 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7838 org-local-vars)))
7840 (defun orgstruct-error ()
7841 "Error when there is no default binding for a structure key."
7842 (interactive)
7843 (error "This key has no function outside structure elements"))
7845 (defun orgstruct-setup ()
7846 "Setup orgstruct keymaps."
7847 (let ((nfunc 0)
7848 (bindings
7849 (list
7850 '([(meta up)] org-metaup)
7851 '([(meta down)] org-metadown)
7852 '([(meta left)] org-metaleft)
7853 '([(meta right)] org-metaright)
7854 '([(meta shift up)] org-shiftmetaup)
7855 '([(meta shift down)] org-shiftmetadown)
7856 '([(meta shift left)] org-shiftmetaleft)
7857 '([(meta shift right)] org-shiftmetaright)
7858 '([(shift up)] org-shiftup)
7859 '([(shift down)] org-shiftdown)
7860 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7861 '("\M-q" fill-paragraph)
7862 '("\C-c^" org-sort)
7863 '("\C-c-" org-cycle-list-bullet)))
7864 elt key fun cmd)
7865 (while (setq elt (pop bindings))
7866 (setq nfunc (1+ nfunc))
7867 (setq key (org-key (car elt))
7868 fun (nth 1 elt)
7869 cmd (orgstruct-make-binding fun nfunc key))
7870 (org-defkey orgstruct-mode-map key cmd))
7872 ;; Special treatment needed for TAB and RET
7873 (org-defkey orgstruct-mode-map [(tab)]
7874 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7875 (org-defkey orgstruct-mode-map "\C-i"
7876 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7878 (org-defkey orgstruct-mode-map "\M-\C-m"
7879 (orgstruct-make-binding 'org-insert-heading 105
7880 "\M-\C-m" [(meta return)]))
7881 (org-defkey orgstruct-mode-map [(meta return)]
7882 (orgstruct-make-binding 'org-insert-heading 106
7883 [(meta return)] "\M-\C-m"))
7885 (org-defkey orgstruct-mode-map [(shift meta return)]
7886 (orgstruct-make-binding 'org-insert-todo-heading 107
7887 [(meta return)] "\M-\C-m"))
7889 (unless org-local-vars
7890 (setq org-local-vars (org-get-local-variables)))
7894 (defun orgstruct-make-binding (fun n &rest keys)
7895 "Create a function for binding in the structure minor mode.
7896 FUN is the command to call inside a table. N is used to create a unique
7897 command name. KEYS are keys that should be checked in for a command
7898 to execute outside of tables."
7899 (eval
7900 (list 'defun
7901 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7902 '(arg)
7903 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7904 "Outside of structure, run the binding of `"
7905 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7906 "'.")
7907 '(interactive "p")
7908 (list 'if
7909 '(org-context-p 'headline 'item)
7910 (list 'org-run-like-in-org-mode (list 'quote fun))
7911 (list 'let '(orgstruct-mode)
7912 (list 'call-interactively
7913 (append '(or)
7914 (mapcar (lambda (k)
7915 (list 'key-binding k))
7916 keys)
7917 '('orgstruct-error))))))))
7919 (defun org-context-p (&rest contexts)
7920 "Check if local context is and of CONTEXTS.
7921 Possible values in the list of contexts are `table', `headline', and `item'."
7922 (let ((pos (point)))
7923 (goto-char (point-at-bol))
7924 (prog1 (or (and (memq 'table contexts)
7925 (looking-at "[ \t]*|"))
7926 (and (memq 'headline contexts)
7927 (looking-at "\\*+"))
7928 (and (memq 'item contexts)
7929 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7930 (goto-char pos))))
7932 (defun org-get-local-variables ()
7933 "Return a list of all local variables in an org-mode buffer."
7934 (let (varlist)
7935 (with-current-buffer (get-buffer-create "*Org tmp*")
7936 (erase-buffer)
7937 (org-mode)
7938 (setq varlist (buffer-local-variables)))
7939 (kill-buffer "*Org tmp*")
7940 (delq nil
7941 (mapcar
7942 (lambda (x)
7943 (setq x
7944 (if (symbolp x)
7945 (list x)
7946 (list (car x) (list 'quote (cdr x)))))
7947 (if (string-match
7948 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7949 (symbol-name (car x)))
7950 x nil))
7951 varlist))))
7953 ;;;###autoload
7954 (defun org-run-like-in-org-mode (cmd)
7955 (unless org-local-vars
7956 (setq org-local-vars (org-get-local-variables)))
7957 (eval (list 'let org-local-vars
7958 (list 'call-interactively (list 'quote cmd)))))
7960 ;;;; Archiving
7962 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7964 (defun org-archive-subtree (&optional find-done)
7965 "Move the current subtree to the archive.
7966 The archive can be a certain top-level heading in the current file, or in
7967 a different file. The tree will be moved to that location, the subtree
7968 heading be marked DONE, and the current time will be added.
7970 When called with prefix argument FIND-DONE, find whole trees without any
7971 open TODO items and archive them (after getting confirmation from the user).
7972 If the cursor is not at a headline when this comand is called, try all level
7973 1 trees. If the cursor is on a headline, only try the direct children of
7974 this heading."
7975 (interactive "P")
7976 (if find-done
7977 (org-archive-all-done)
7978 ;; Save all relevant TODO keyword-relatex variables
7980 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7981 (tr-org-todo-keywords-1 org-todo-keywords-1)
7982 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7983 (tr-org-done-keywords org-done-keywords)
7984 (tr-org-todo-regexp org-todo-regexp)
7985 (tr-org-todo-line-regexp org-todo-line-regexp)
7986 (tr-org-odd-levels-only org-odd-levels-only)
7987 (this-buffer (current-buffer))
7988 (org-archive-location org-archive-location)
7989 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7990 ;; start of variables that will be used for saving context
7991 ;; The compiler complains about them - keep them anyway!
7992 (file (abbreviate-file-name (buffer-file-name)))
7993 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
7994 (time (format-time-string
7995 (substring (cdr org-time-stamp-formats) 1 -1)
7996 (current-time)))
7997 afile heading buffer level newfile-p
7998 category todo priority
7999 ;; start of variables that will be used for savind context
8000 ltags itags prop)
8002 ;; Try to find a local archive location
8003 (save-excursion
8004 (save-restriction
8005 (widen)
8006 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
8007 (if (and prop (string-match "\\S-" prop))
8008 (setq org-archive-location prop)
8009 (if (or (re-search-backward re nil t)
8010 (re-search-forward re nil t))
8011 (setq org-archive-location (match-string 1))))))
8013 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
8014 (progn
8015 (setq afile (format (match-string 1 org-archive-location)
8016 (file-name-nondirectory buffer-file-name))
8017 heading (match-string 2 org-archive-location)))
8018 (error "Invalid `org-archive-location'"))
8019 (if (> (length afile) 0)
8020 (setq newfile-p (not (file-exists-p afile))
8021 buffer (find-file-noselect afile))
8022 (setq buffer (current-buffer)))
8023 (unless buffer
8024 (error "Cannot access file \"%s\"" afile))
8025 (if (and (> (length heading) 0)
8026 (string-match "^\\*+" heading))
8027 (setq level (match-end 0))
8028 (setq heading nil level 0))
8029 (save-excursion
8030 (org-back-to-heading t)
8031 ;; Get context information that will be lost by moving the tree
8032 (org-refresh-category-properties)
8033 (setq category (org-get-category)
8034 todo (and (looking-at org-todo-line-regexp)
8035 (match-string 2))
8036 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
8037 ltags (org-get-tags)
8038 itags (org-delete-all ltags (org-get-tags-at)))
8039 (setq ltags (mapconcat 'identity ltags " ")
8040 itags (mapconcat 'identity itags " "))
8041 ;; We first only copy, in case something goes wrong
8042 ;; we need to protect this-command, to avoid kill-region sets it,
8043 ;; which would lead to duplication of subtrees
8044 (let (this-command) (org-copy-subtree))
8045 (set-buffer buffer)
8046 ;; Enforce org-mode for the archive buffer
8047 (if (not (org-mode-p))
8048 ;; Force the mode for future visits.
8049 (let ((org-insert-mode-line-in-empty-file t)
8050 (org-inhibit-startup t))
8051 (call-interactively 'org-mode)))
8052 (when newfile-p
8053 (goto-char (point-max))
8054 (insert (format "\nArchived entries from file %s\n\n"
8055 (buffer-file-name this-buffer))))
8056 ;; Force the TODO keywords of the original buffer
8057 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
8058 (org-todo-keywords-1 tr-org-todo-keywords-1)
8059 (org-todo-kwd-alist tr-org-todo-kwd-alist)
8060 (org-done-keywords tr-org-done-keywords)
8061 (org-todo-regexp tr-org-todo-regexp)
8062 (org-todo-line-regexp tr-org-todo-line-regexp)
8063 (org-odd-levels-only
8064 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8065 org-odd-levels-only
8066 tr-org-odd-levels-only)))
8067 (goto-char (point-min))
8068 (show-all)
8069 (if heading
8070 (progn
8071 (if (re-search-forward
8072 (concat "^" (regexp-quote heading)
8073 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8074 nil t)
8075 (goto-char (match-end 0))
8076 ;; Heading not found, just insert it at the end
8077 (goto-char (point-max))
8078 (or (bolp) (insert "\n"))
8079 (insert "\n" heading "\n")
8080 (end-of-line 0))
8081 ;; Make the subtree visible
8082 (show-subtree)
8083 (org-end-of-subtree t)
8084 (skip-chars-backward " \t\r\n")
8085 (and (looking-at "[ \t\r\n]*")
8086 (replace-match "\n\n")))
8087 ;; No specific heading, just go to end of file.
8088 (goto-char (point-max)) (insert "\n"))
8089 ;; Paste
8090 (org-paste-subtree (org-get-legal-level level 1))
8092 ;; Mark the entry as done
8093 (when (and org-archive-mark-done
8094 (looking-at org-todo-line-regexp)
8095 (or (not (match-end 2))
8096 (not (member (match-string 2) org-done-keywords))))
8097 (let (org-log-done org-todo-log-states)
8098 (org-todo
8099 (car (or (member org-archive-mark-done org-done-keywords)
8100 org-done-keywords)))))
8102 ;; Add the context info
8103 (when org-archive-save-context-info
8104 (let ((l org-archive-save-context-info) e n v)
8105 (while (setq e (pop l))
8106 (when (and (setq v (symbol-value e))
8107 (stringp v) (string-match "\\S-" v))
8108 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8109 (org-entry-put (point) n v)))))
8111 ;; Save and kill the buffer, if it is not the same buffer.
8112 (if (not (eq this-buffer buffer))
8113 (progn (save-buffer) (kill-buffer buffer)))))
8114 ;; Here we are back in the original buffer. Everything seems to have
8115 ;; worked. So now cut the tree and finish up.
8116 (let (this-command) (org-cut-subtree))
8117 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8118 (message "Subtree archived %s"
8119 (if (eq this-buffer buffer)
8120 (concat "under heading: " heading)
8121 (concat "in file: " (abbreviate-file-name afile)))))))
8123 (defun org-refresh-category-properties ()
8124 "Refresh category text properties in teh buffer."
8125 (let ((def-cat (cond
8126 ((null org-category)
8127 (if buffer-file-name
8128 (file-name-sans-extension
8129 (file-name-nondirectory buffer-file-name))
8130 "???"))
8131 ((symbolp org-category) (symbol-name org-category))
8132 (t org-category)))
8133 beg end cat pos optionp)
8134 (org-unmodified
8135 (save-excursion
8136 (save-restriction
8137 (widen)
8138 (goto-char (point-min))
8139 (put-text-property (point) (point-max) 'org-category def-cat)
8140 (while (re-search-forward
8141 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8142 (setq pos (match-end 0)
8143 optionp (equal (char-after (match-beginning 0)) ?#)
8144 cat (org-trim (match-string 2)))
8145 (if optionp
8146 (setq beg (point-at-bol) end (point-max))
8147 (org-back-to-heading t)
8148 (setq beg (point) end (org-end-of-subtree t t)))
8149 (put-text-property beg end 'org-category cat)
8150 (goto-char pos)))))))
8152 (defun org-archive-all-done (&optional tag)
8153 "Archive sublevels of the current tree without open TODO items.
8154 If the cursor is not on a headline, try all level 1 trees. If
8155 it is on a headline, try all direct children.
8156 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8157 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8158 (rea (concat ".*:" org-archive-tag ":"))
8159 (begm (make-marker))
8160 (endm (make-marker))
8161 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8162 "Move subtree to archive (no open TODO items)? "))
8163 beg end (cntarch 0))
8164 (if (org-on-heading-p)
8165 (progn
8166 (setq re1 (concat "^" (regexp-quote
8167 (make-string
8168 (1+ (- (match-end 0) (match-beginning 0) 1))
8169 ?*))
8170 " "))
8171 (move-marker begm (point))
8172 (move-marker endm (org-end-of-subtree t)))
8173 (setq re1 "^* ")
8174 (move-marker begm (point-min))
8175 (move-marker endm (point-max)))
8176 (save-excursion
8177 (goto-char begm)
8178 (while (re-search-forward re1 endm t)
8179 (setq beg (match-beginning 0)
8180 end (save-excursion (org-end-of-subtree t) (point)))
8181 (goto-char beg)
8182 (if (re-search-forward re end t)
8183 (goto-char end)
8184 (goto-char beg)
8185 (if (and (or (not tag) (not (looking-at rea)))
8186 (y-or-n-p question))
8187 (progn
8188 (if tag
8189 (org-toggle-tag org-archive-tag 'on)
8190 (org-archive-subtree))
8191 (setq cntarch (1+ cntarch)))
8192 (goto-char end)))))
8193 (message "%d trees archived" cntarch)))
8195 (defun org-cycle-hide-drawers (state)
8196 "Re-hide all drawers after a visibility state change."
8197 (when (and (org-mode-p)
8198 (not (memq state '(overview folded))))
8199 (save-excursion
8200 (let* ((globalp (memq state '(contents all)))
8201 (beg (if globalp (point-min) (point)))
8202 (end (if globalp (point-max) (org-end-of-subtree t))))
8203 (goto-char beg)
8204 (while (re-search-forward org-drawer-regexp end t)
8205 (org-flag-drawer t))))))
8207 (defun org-flag-drawer (flag)
8208 (save-excursion
8209 (beginning-of-line 1)
8210 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8211 (let ((b (match-end 0))
8212 (outline-regexp org-outline-regexp))
8213 (if (re-search-forward
8214 "^[ \t]*:END:"
8215 (save-excursion (outline-next-heading) (point)) t)
8216 (outline-flag-region b (point-at-eol) flag)
8217 (error ":END: line missing"))))))
8219 (defun org-cycle-hide-archived-subtrees (state)
8220 "Re-hide all archived subtrees after a visibility state change."
8221 (when (and (not org-cycle-open-archived-trees)
8222 (not (memq state '(overview folded))))
8223 (save-excursion
8224 (let* ((globalp (memq state '(contents all)))
8225 (beg (if globalp (point-min) (point)))
8226 (end (if globalp (point-max) (org-end-of-subtree t))))
8227 (org-hide-archived-subtrees beg end)
8228 (goto-char beg)
8229 (if (looking-at (concat ".*:" org-archive-tag ":"))
8230 (message "%s" (substitute-command-keys
8231 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8233 (defun org-force-cycle-archived ()
8234 "Cycle subtree even if it is archived."
8235 (interactive)
8236 (setq this-command 'org-cycle)
8237 (let ((org-cycle-open-archived-trees t))
8238 (call-interactively 'org-cycle)))
8240 (defun org-hide-archived-subtrees (beg end)
8241 "Re-hide all archived subtrees after a visibility state change."
8242 (save-excursion
8243 (let* ((re (concat ":" org-archive-tag ":")))
8244 (goto-char beg)
8245 (while (re-search-forward re end t)
8246 (and (org-on-heading-p) (hide-subtree))
8247 (org-end-of-subtree t)))))
8249 (defun org-toggle-tag (tag &optional onoff)
8250 "Toggle the tag TAG for the current line.
8251 If ONOFF is `on' or `off', don't toggle but set to this state."
8252 (unless (org-on-heading-p t) (error "Not on headling"))
8253 (let (res current)
8254 (save-excursion
8255 (beginning-of-line)
8256 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8257 (point-at-eol) t)
8258 (progn
8259 (setq current (match-string 1))
8260 (replace-match ""))
8261 (setq current ""))
8262 (setq current (nreverse (org-split-string current ":")))
8263 (cond
8264 ((eq onoff 'on)
8265 (setq res t)
8266 (or (member tag current) (push tag current)))
8267 ((eq onoff 'off)
8268 (or (not (member tag current)) (setq current (delete tag current))))
8269 (t (if (member tag current)
8270 (setq current (delete tag current))
8271 (setq res t)
8272 (push tag current))))
8273 (end-of-line 1)
8274 (if current
8275 (progn
8276 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8277 (org-set-tags nil t))
8278 (delete-horizontal-space))
8279 (run-hooks 'org-after-tags-change-hook))
8280 res))
8282 (defun org-toggle-archive-tag (&optional arg)
8283 "Toggle the archive tag for the current headline.
8284 With prefix ARG, check all children of current headline and offer tagging
8285 the children that do not contain any open TODO items."
8286 (interactive "P")
8287 (if arg
8288 (org-archive-all-done 'tag)
8289 (let (set)
8290 (save-excursion
8291 (org-back-to-heading t)
8292 (setq set (org-toggle-tag org-archive-tag))
8293 (when set (hide-subtree)))
8294 (and set (beginning-of-line 1))
8295 (message "Subtree %s" (if set "archived" "unarchived")))))
8298 ;;;; Tables
8300 ;;; The table editor
8302 ;; Watch out: Here we are talking about two different kind of tables.
8303 ;; Most of the code is for the tables created with the Org-mode table editor.
8304 ;; Sometimes, we talk about tables created and edited with the table.el
8305 ;; Emacs package. We call the former org-type tables, and the latter
8306 ;; table.el-type tables.
8308 (defun org-before-change-function (beg end)
8309 "Every change indicates that a table might need an update."
8310 (setq org-table-may-need-update t))
8312 (defconst org-table-line-regexp "^[ \t]*|"
8313 "Detects an org-type table line.")
8314 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8315 "Detects an org-type table line.")
8316 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8317 "Detects a table line marked for automatic recalculation.")
8318 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8319 "Detects a table line marked for automatic recalculation.")
8320 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8321 "Detects a table line marked for automatic recalculation.")
8322 (defconst org-table-hline-regexp "^[ \t]*|-"
8323 "Detects an org-type table hline.")
8324 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8325 "Detects a table-type table hline.")
8326 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8327 "Detects an org-type or table-type table.")
8328 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8329 "Searching from within a table (any type) this finds the first line
8330 outside the table.")
8331 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8332 "Searching from within a table (any type) this finds the first line
8333 outside the table.")
8335 (defvar org-table-last-highlighted-reference nil)
8336 (defvar org-table-formula-history nil)
8338 (defvar org-table-column-names nil
8339 "Alist with column names, derived from the `!' line.")
8340 (defvar org-table-column-name-regexp nil
8341 "Regular expression matching the current column names.")
8342 (defvar org-table-local-parameters nil
8343 "Alist with parameter names, derived from the `$' line.")
8344 (defvar org-table-named-field-locations nil
8345 "Alist with locations of named fields.")
8347 (defvar org-table-current-line-types nil
8348 "Table row types, non-nil only for the duration of a comand.")
8349 (defvar org-table-current-begin-line nil
8350 "Table begin line, non-nil only for the duration of a comand.")
8351 (defvar org-table-current-begin-pos nil
8352 "Table begin position, non-nil only for the duration of a comand.")
8353 (defvar org-table-dlines nil
8354 "Vector of data line line numbers in the current table.")
8355 (defvar org-table-hlines nil
8356 "Vector of hline line numbers in the current table.")
8358 (defconst org-table-range-regexp
8359 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8360 ;; 1 2 3 4 5
8361 "Regular expression for matching ranges in formulas.")
8363 (defconst org-table-range-regexp2
8364 (concat
8365 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8366 "\\.\\."
8367 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8368 "Match a range for reference display.")
8370 (defconst org-table-translate-regexp
8371 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8372 "Match a reference that needs translation, for reference display.")
8374 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8376 (defun org-table-create-with-table.el ()
8377 "Use the table.el package to insert a new table.
8378 If there is already a table at point, convert between Org-mode tables
8379 and table.el tables."
8380 (interactive)
8381 (require 'table)
8382 (cond
8383 ((org-at-table.el-p)
8384 (if (y-or-n-p "Convert table to Org-mode table? ")
8385 (org-table-convert)))
8386 ((org-at-table-p)
8387 (if (y-or-n-p "Convert table to table.el table? ")
8388 (org-table-convert)))
8389 (t (call-interactively 'table-insert))))
8391 (defun org-table-create-or-convert-from-region (arg)
8392 "Convert region to table, or create an empty table.
8393 If there is an active region, convert it to a table, using the function
8394 `org-table-convert-region'. See the documentation of that function
8395 to learn how the prefix argument is interpreted to determine the field
8396 separator.
8397 If there is no such region, create an empty table with `org-table-create'."
8398 (interactive "P")
8399 (if (org-region-active-p)
8400 (org-table-convert-region (region-beginning) (region-end) arg)
8401 (org-table-create arg)))
8403 (defun org-table-create (&optional size)
8404 "Query for a size and insert a table skeleton.
8405 SIZE is a string Columns x Rows like for example \"3x2\"."
8406 (interactive "P")
8407 (unless size
8408 (setq size (read-string
8409 (concat "Table size Columns x Rows [e.g. "
8410 org-table-default-size "]: ")
8411 "" nil org-table-default-size)))
8413 (let* ((pos (point))
8414 (indent (make-string (current-column) ?\ ))
8415 (split (org-split-string size " *x *"))
8416 (rows (string-to-number (nth 1 split)))
8417 (columns (string-to-number (car split)))
8418 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8419 "\n")))
8420 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8421 (point-at-bol) (point)))
8422 (beginning-of-line 1)
8423 (newline))
8424 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8425 (dotimes (i rows) (insert line))
8426 (goto-char pos)
8427 (if (> rows 1)
8428 ;; Insert a hline after the first row.
8429 (progn
8430 (end-of-line 1)
8431 (insert "\n|-")
8432 (goto-char pos)))
8433 (org-table-align)))
8435 (defun org-table-convert-region (beg0 end0 &optional separator)
8436 "Convert region to a table.
8437 The region goes from BEG0 to END0, but these borders will be moved
8438 slightly, to make sure a beginning of line in the first line is included.
8440 SEPARATOR specifies the field separator in the lines. It can have the
8441 following values:
8443 '(4) Use the comma as a field separator
8444 '(16) Use a TAB as field separator
8445 integer When a number, use that many spaces as field separator
8446 nil When nil, the command tries to be smart and figure out the
8447 separator in the following way:
8448 - when each line contains a TAB, assume TAB-separated material
8449 - when each line contains a comme, assume CSV material
8450 - else, assume one or more SPACE charcters as separator."
8451 (interactive "rP")
8452 (let* ((beg (min beg0 end0))
8453 (end (max beg0 end0))
8455 (goto-char beg)
8456 (beginning-of-line 1)
8457 (setq beg (move-marker (make-marker) (point)))
8458 (goto-char end)
8459 (if (bolp) (backward-char 1) (end-of-line 1))
8460 (setq end (move-marker (make-marker) (point)))
8461 ;; Get the right field separator
8462 (unless separator
8463 (goto-char beg)
8464 (setq separator
8465 (cond
8466 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8467 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8468 (t 1))))
8469 (setq re (cond
8470 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8471 ((equal separator '(16)) "^\\|\t")
8472 ((integerp separator)
8473 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8474 (t (error "This should not happen"))))
8475 (goto-char beg)
8476 (while (re-search-forward re end t)
8477 (replace-match "| " t t))
8478 (goto-char beg)
8479 (insert " ")
8480 (org-table-align)))
8482 (defun org-table-import (file arg)
8483 "Import FILE as a table.
8484 The file is assumed to be tab-separated. Such files can be produced by most
8485 spreadsheet and database applications. If no tabs (at least one per line)
8486 are found, lines will be split on whitespace into fields."
8487 (interactive "f\nP")
8488 (or (bolp) (newline))
8489 (let ((beg (point))
8490 (pm (point-max)))
8491 (insert-file-contents file)
8492 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8494 (defun org-table-export ()
8495 "Export table as a tab-separated file.
8496 Such a file can be imported into a spreadsheet program like Excel."
8497 (interactive)
8498 (let* ((beg (org-table-begin))
8499 (end (org-table-end))
8500 (table (buffer-substring beg end))
8501 (file (read-file-name "Export table to: "))
8502 buf)
8503 (unless (or (not (file-exists-p file))
8504 (y-or-n-p (format "Overwrite file %s? " file)))
8505 (error "Abort"))
8506 (with-current-buffer (find-file-noselect file)
8507 (setq buf (current-buffer))
8508 (erase-buffer)
8509 (fundamental-mode)
8510 (insert table)
8511 (goto-char (point-min))
8512 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8513 (replace-match "" t t)
8514 (end-of-line 1))
8515 (goto-char (point-min))
8516 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8517 (replace-match "" t t)
8518 (goto-char (min (1+ (point)) (point-max))))
8519 (goto-char (point-min))
8520 (while (re-search-forward "^-[-+]*$" nil t)
8521 (replace-match "")
8522 (if (looking-at "\n")
8523 (delete-char 1)))
8524 (goto-char (point-min))
8525 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8526 (replace-match "\t" t t))
8527 (save-buffer))
8528 (kill-buffer buf)))
8530 (defvar org-table-aligned-begin-marker (make-marker)
8531 "Marker at the beginning of the table last aligned.
8532 Used to check if cursor still is in that table, to minimize realignment.")
8533 (defvar org-table-aligned-end-marker (make-marker)
8534 "Marker at the end of the table last aligned.
8535 Used to check if cursor still is in that table, to minimize realignment.")
8536 (defvar org-table-last-alignment nil
8537 "List of flags for flushright alignment, from the last re-alignment.
8538 This is being used to correctly align a single field after TAB or RET.")
8539 (defvar org-table-last-column-widths nil
8540 "List of max width of fields in each column.
8541 This is being used to correctly align a single field after TAB or RET.")
8542 (defvar org-table-overlay-coordinates nil
8543 "Overlay coordinates after each align of a table.")
8544 (make-variable-buffer-local 'org-table-overlay-coordinates)
8546 (defvar org-last-recalc-line nil)
8547 (defconst org-narrow-column-arrow "=>"
8548 "Used as display property in narrowed table columns.")
8550 (defun org-table-align ()
8551 "Align the table at point by aligning all vertical bars."
8552 (interactive)
8553 (let* (
8554 ;; Limits of table
8555 (beg (org-table-begin))
8556 (end (org-table-end))
8557 ;; Current cursor position
8558 (linepos (org-current-line))
8559 (colpos (org-table-current-column))
8560 (winstart (window-start))
8561 (winstartline (org-current-line (min winstart (1- (point-max)))))
8562 lines (new "") lengths l typenums ty fields maxfields i
8563 column
8564 (indent "") cnt frac
8565 rfmt hfmt
8566 (spaces '(1 . 1))
8567 (sp1 (car spaces))
8568 (sp2 (cdr spaces))
8569 (rfmt1 (concat
8570 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8571 (hfmt1 (concat
8572 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8573 emptystrings links dates emph narrow fmax f1 len c e)
8574 (untabify beg end)
8575 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8576 ;; Check if we have links or dates
8577 (goto-char beg)
8578 (setq links (re-search-forward org-bracket-link-regexp end t))
8579 (goto-char beg)
8580 (setq emph (and org-hide-emphasis-markers
8581 (re-search-forward org-emph-re end t)))
8582 (goto-char beg)
8583 (setq dates (and org-display-custom-times
8584 (re-search-forward org-ts-regexp-both end t)))
8585 ;; Make sure the link properties are right
8586 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8587 ;; Make sure the date properties are right
8588 (when dates (goto-char beg) (while (org-activate-dates end)))
8589 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8591 ;; Check if we are narrowing any columns
8592 (goto-char beg)
8593 (setq narrow (and org-format-transports-properties-p
8594 (re-search-forward "<[0-9]+>" end t)))
8595 ;; Get the rows
8596 (setq lines (org-split-string
8597 (buffer-substring beg end) "\n"))
8598 ;; Store the indentation of the first line
8599 (if (string-match "^ *" (car lines))
8600 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8601 ;; Mark the hlines by setting the corresponding element to nil
8602 ;; At the same time, we remove trailing space.
8603 (setq lines (mapcar (lambda (l)
8604 (if (string-match "^ *|-" l)
8606 (if (string-match "[ \t]+$" l)
8607 (substring l 0 (match-beginning 0))
8608 l)))
8609 lines))
8610 ;; Get the data fields by splitting the lines.
8611 (setq fields (mapcar
8612 (lambda (l)
8613 (org-split-string l " *| *"))
8614 (delq nil (copy-sequence lines))))
8615 ;; How many fields in the longest line?
8616 (condition-case nil
8617 (setq maxfields (apply 'max (mapcar 'length fields)))
8618 (error
8619 (kill-region beg end)
8620 (org-table-create org-table-default-size)
8621 (error "Empty table - created default table")))
8622 ;; A list of empty strings to fill any short rows on output
8623 (setq emptystrings (make-list maxfields ""))
8624 ;; Check for special formatting.
8625 (setq i -1)
8626 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8627 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8628 ;; Check if there is an explicit width specified
8629 (when narrow
8630 (setq c column fmax nil)
8631 (while c
8632 (setq e (pop c))
8633 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8634 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8635 ;; Find fields that are wider than fmax, and shorten them
8636 (when fmax
8637 (loop for xx in column do
8638 (when (and (stringp xx)
8639 (> (org-string-width xx) fmax))
8640 (org-add-props xx nil
8641 'help-echo
8642 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8643 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8644 (unless (> f1 1)
8645 (error "Cannot narrow field starting with wide link \"%s\""
8646 (match-string 0 xx)))
8647 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8648 (add-text-properties (- f1 2) f1
8649 (list 'display org-narrow-column-arrow)
8650 xx)))))
8651 ;; Get the maximum width for each column
8652 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8653 ;; Get the fraction of numbers, to decide about alignment of the column
8654 (setq cnt 0 frac 0.0)
8655 (loop for x in column do
8656 (if (equal x "")
8658 (setq frac ( / (+ (* frac cnt)
8659 (if (string-match org-table-number-regexp x) 1 0))
8660 (setq cnt (1+ cnt))))))
8661 (push (>= frac org-table-number-fraction) typenums))
8662 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8664 ;; Store the alignment of this table, for later editing of single fields
8665 (setq org-table-last-alignment typenums
8666 org-table-last-column-widths lengths)
8668 ;; With invisible characters, `format' does not get the field width right
8669 ;; So we need to make these fields wide by hand.
8670 (when (or links emph)
8671 (loop for i from 0 upto (1- maxfields) do
8672 (setq len (nth i lengths))
8673 (loop for j from 0 upto (1- (length fields)) do
8674 (setq c (nthcdr i (car (nthcdr j fields))))
8675 (if (and (stringp (car c))
8676 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8677 ; (string-match org-bracket-link-regexp (car c))
8678 (< (org-string-width (car c)) len))
8679 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8681 ;; Compute the formats needed for output of the table
8682 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8683 (while (setq l (pop lengths))
8684 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8685 (setq rfmt (concat rfmt (format rfmt1 ty l))
8686 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8687 (setq rfmt (concat rfmt "\n")
8688 hfmt (concat (substring hfmt 0 -1) "|\n"))
8690 (setq new (mapconcat
8691 (lambda (l)
8692 (if l (apply 'format rfmt
8693 (append (pop fields) emptystrings))
8694 hfmt))
8695 lines ""))
8696 ;; Replace the old one
8697 (delete-region beg end)
8698 (move-marker end nil)
8699 (move-marker org-table-aligned-begin-marker (point))
8700 (insert new)
8701 (move-marker org-table-aligned-end-marker (point))
8702 (when (and orgtbl-mode (not (org-mode-p)))
8703 (goto-char org-table-aligned-begin-marker)
8704 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8705 ;; Try to move to the old location
8706 (goto-line winstartline)
8707 (setq winstart (point-at-bol))
8708 (goto-line linepos)
8709 (set-window-start (selected-window) winstart 'noforce)
8710 (org-table-goto-column colpos)
8711 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8712 (setq org-table-may-need-update nil)
8715 (defun org-string-width (s)
8716 "Compute width of string, ignoring invisible characters.
8717 This ignores character with invisibility property `org-link', and also
8718 characters with property `org-cwidth', because these will become invisible
8719 upon the next fontification round."
8720 (let (b l)
8721 (when (or (eq t buffer-invisibility-spec)
8722 (assq 'org-link buffer-invisibility-spec))
8723 (while (setq b (text-property-any 0 (length s)
8724 'invisible 'org-link s))
8725 (setq s (concat (substring s 0 b)
8726 (substring s (or (next-single-property-change
8727 b 'invisible s) (length s)))))))
8728 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8729 (setq s (concat (substring s 0 b)
8730 (substring s (or (next-single-property-change
8731 b 'org-cwidth s) (length s))))))
8732 (setq l (string-width s) b -1)
8733 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8734 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8737 (defun org-table-begin (&optional table-type)
8738 "Find the beginning of the table and return its position.
8739 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8740 (save-excursion
8741 (if (not (re-search-backward
8742 (if table-type org-table-any-border-regexp
8743 org-table-border-regexp)
8744 nil t))
8745 (progn (goto-char (point-min)) (point))
8746 (goto-char (match-beginning 0))
8747 (beginning-of-line 2)
8748 (point))))
8750 (defun org-table-end (&optional table-type)
8751 "Find the end of the table and return its position.
8752 With argument TABLE-TYPE, go to the end of a table.el-type table."
8753 (save-excursion
8754 (if (not (re-search-forward
8755 (if table-type org-table-any-border-regexp
8756 org-table-border-regexp)
8757 nil t))
8758 (goto-char (point-max))
8759 (goto-char (match-beginning 0)))
8760 (point-marker)))
8762 (defun org-table-justify-field-maybe (&optional new)
8763 "Justify the current field, text to left, number to right.
8764 Optional argument NEW may specify text to replace the current field content."
8765 (cond
8766 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8767 ((org-at-table-hline-p))
8768 ((and (not new)
8769 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8770 (current-buffer)))
8771 (< (point) org-table-aligned-begin-marker)
8772 (>= (point) org-table-aligned-end-marker)))
8773 ;; This is not the same table, force a full re-align
8774 (setq org-table-may-need-update t))
8775 (t ;; realign the current field, based on previous full realign
8776 (let* ((pos (point)) s
8777 (col (org-table-current-column))
8778 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8779 l f n o e)
8780 (when (> col 0)
8781 (skip-chars-backward "^|\n")
8782 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8783 (progn
8784 (setq s (match-string 1)
8785 o (match-string 0)
8786 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8787 e (not (= (match-beginning 2) (match-end 2))))
8788 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8789 l (if e "|" (setq org-table-may-need-update t) ""))
8790 n (format f s))
8791 (if new
8792 (if (<= (length new) l) ;; FIXME: length -> str-width?
8793 (setq n (format f new))
8794 (setq n (concat new "|") org-table-may-need-update t)))
8795 (or (equal n o)
8796 (let (org-table-may-need-update)
8797 (replace-match n t t))))
8798 (setq org-table-may-need-update t))
8799 (goto-char pos))))))
8801 (defun org-table-next-field ()
8802 "Go to the next field in the current table, creating new lines as needed.
8803 Before doing so, re-align the table if necessary."
8804 (interactive)
8805 (org-table-maybe-eval-formula)
8806 (org-table-maybe-recalculate-line)
8807 (if (and org-table-automatic-realign
8808 org-table-may-need-update)
8809 (org-table-align))
8810 (let ((end (org-table-end)))
8811 (if (org-at-table-hline-p)
8812 (end-of-line 1))
8813 (condition-case nil
8814 (progn
8815 (re-search-forward "|" end)
8816 (if (looking-at "[ \t]*$")
8817 (re-search-forward "|" end))
8818 (if (and (looking-at "-")
8819 org-table-tab-jumps-over-hlines
8820 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8821 (goto-char (match-beginning 1)))
8822 (if (looking-at "-")
8823 (progn
8824 (beginning-of-line 0)
8825 (org-table-insert-row 'below))
8826 (if (looking-at " ") (forward-char 1))))
8827 (error
8828 (org-table-insert-row 'below)))))
8830 (defun org-table-previous-field ()
8831 "Go to the previous field in the table.
8832 Before doing so, re-align the table if necessary."
8833 (interactive)
8834 (org-table-justify-field-maybe)
8835 (org-table-maybe-recalculate-line)
8836 (if (and org-table-automatic-realign
8837 org-table-may-need-update)
8838 (org-table-align))
8839 (if (org-at-table-hline-p)
8840 (end-of-line 1))
8841 (re-search-backward "|" (org-table-begin))
8842 (re-search-backward "|" (org-table-begin))
8843 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8844 (re-search-backward "|" (org-table-begin)))
8845 (if (looking-at "| ?")
8846 (goto-char (match-end 0))))
8848 (defun org-table-next-row ()
8849 "Go to the next row (same column) in the current table.
8850 Before doing so, re-align the table if necessary."
8851 (interactive)
8852 (org-table-maybe-eval-formula)
8853 (org-table-maybe-recalculate-line)
8854 (if (or (looking-at "[ \t]*$")
8855 (save-excursion (skip-chars-backward " \t") (bolp)))
8856 (newline)
8857 (if (and org-table-automatic-realign
8858 org-table-may-need-update)
8859 (org-table-align))
8860 (let ((col (org-table-current-column)))
8861 (beginning-of-line 2)
8862 (if (or (not (org-at-table-p))
8863 (org-at-table-hline-p))
8864 (progn
8865 (beginning-of-line 0)
8866 (org-table-insert-row 'below)))
8867 (org-table-goto-column col)
8868 (skip-chars-backward "^|\n\r")
8869 (if (looking-at " ") (forward-char 1)))))
8871 (defun org-table-copy-down (n)
8872 "Copy a field down in the current column.
8873 If the field at the cursor is empty, copy into it the content of the nearest
8874 non-empty field above. With argument N, use the Nth non-empty field.
8875 If the current field is not empty, it is copied down to the next row, and
8876 the cursor is moved with it. Therefore, repeating this command causes the
8877 column to be filled row-by-row.
8878 If the variable `org-table-copy-increment' is non-nil and the field is an
8879 integer or a timestamp, it will be incremented while copying. In the case of
8880 a timestamp, if the cursor is on the year, change the year. If it is on the
8881 month or the day, change that. Point will stay on the current date field
8882 in order to easily repeat the interval."
8883 (interactive "p")
8884 (let* ((colpos (org-table-current-column))
8885 (col (current-column))
8886 (field (org-table-get-field))
8887 (non-empty (string-match "[^ \t]" field))
8888 (beg (org-table-begin))
8889 txt)
8890 (org-table-check-inside-data-field)
8891 (if non-empty
8892 (progn
8893 (setq txt (org-trim field))
8894 (org-table-next-row)
8895 (org-table-blank-field))
8896 (save-excursion
8897 (setq txt
8898 (catch 'exit
8899 (while (progn (beginning-of-line 1)
8900 (re-search-backward org-table-dataline-regexp
8901 beg t))
8902 (org-table-goto-column colpos t)
8903 (if (and (looking-at
8904 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8905 (= (setq n (1- n)) 0))
8906 (throw 'exit (match-string 1))))))))
8907 (if txt
8908 (progn
8909 (if (and org-table-copy-increment
8910 (string-match "^[0-9]+$" txt))
8911 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8912 (insert txt)
8913 (move-to-column col)
8914 (if (and org-table-copy-increment (org-at-timestamp-p t))
8915 (org-timestamp-up 1)
8916 (org-table-maybe-recalculate-line))
8917 (org-table-align)
8918 (move-to-column col))
8919 (error "No non-empty field found"))))
8921 (defun org-table-check-inside-data-field ()
8922 "Is point inside a table data field?
8923 I.e. not on a hline or before the first or after the last column?
8924 This actually throws an error, so it aborts the current command."
8925 (if (or (not (org-at-table-p))
8926 (= (org-table-current-column) 0)
8927 (org-at-table-hline-p)
8928 (looking-at "[ \t]*$"))
8929 (error "Not in table data field")))
8931 (defvar org-table-clip nil
8932 "Clipboard for table regions.")
8934 (defun org-table-blank-field ()
8935 "Blank the current table field or active region."
8936 (interactive)
8937 (org-table-check-inside-data-field)
8938 (if (and (interactive-p) (org-region-active-p))
8939 (let (org-table-clip)
8940 (org-table-cut-region (region-beginning) (region-end)))
8941 (skip-chars-backward "^|")
8942 (backward-char 1)
8943 (if (looking-at "|[^|\n]+")
8944 (let* ((pos (match-beginning 0))
8945 (match (match-string 0))
8946 (len (org-string-width match)))
8947 (replace-match (concat "|" (make-string (1- len) ?\ )))
8948 (goto-char (+ 2 pos))
8949 (substring match 1)))))
8951 (defun org-table-get-field (&optional n replace)
8952 "Return the value of the field in column N of current row.
8953 N defaults to current field.
8954 If REPLACE is a string, replace field with this value. The return value
8955 is always the old value."
8956 (and n (org-table-goto-column n))
8957 (skip-chars-backward "^|\n")
8958 (backward-char 1)
8959 (if (looking-at "|[^|\r\n]*")
8960 (let* ((pos (match-beginning 0))
8961 (val (buffer-substring (1+ pos) (match-end 0))))
8962 (if replace
8963 (replace-match (concat "|" replace) t t))
8964 (goto-char (min (point-at-eol) (+ 2 pos)))
8965 val)
8966 (forward-char 1) ""))
8968 (defun org-table-field-info (arg)
8969 "Show info about the current field, and highlight any reference at point."
8970 (interactive "P")
8971 (org-table-get-specials)
8972 (save-excursion
8973 (let* ((pos (point))
8974 (col (org-table-current-column))
8975 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8976 (name (car (rassoc (list (org-current-line) col)
8977 org-table-named-field-locations)))
8978 (eql (org-table-get-stored-formulas))
8979 (dline (org-table-current-dline))
8980 (ref (format "@%d$%d" dline col))
8981 (ref1 (org-table-convert-refs-to-an ref))
8982 (fequation (or (assoc name eql) (assoc ref eql)))
8983 (cequation (assoc (int-to-string col) eql))
8984 (eqn (or fequation cequation)))
8985 (goto-char pos)
8986 (condition-case nil
8987 (org-table-show-reference 'local)
8988 (error nil))
8989 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8990 dline col
8991 (if cname (concat " or $" cname) "")
8992 dline col ref1
8993 (if name (concat " or $" name) "")
8994 ;; FIXME: formula info not correct if special table line
8995 (if eqn
8996 (concat ", formula: "
8997 (org-table-formula-to-user
8998 (concat
8999 (if (string-match "^[$@]"(car eqn)) "" "$")
9000 (car eqn) "=" (cdr eqn))))
9001 "")))))
9003 (defun org-table-current-column ()
9004 "Find out which column we are in.
9005 When called interactively, column is also displayed in echo area."
9006 (interactive)
9007 (if (interactive-p) (org-table-check-inside-data-field))
9008 (save-excursion
9009 (let ((cnt 0) (pos (point)))
9010 (beginning-of-line 1)
9011 (while (search-forward "|" pos t)
9012 (setq cnt (1+ cnt)))
9013 (if (interactive-p) (message "This is table column %d" cnt))
9014 cnt)))
9016 (defun org-table-current-dline ()
9017 "Find out what table data line we are in.
9018 Only datalins count for this."
9019 (interactive)
9020 (if (interactive-p) (org-table-check-inside-data-field))
9021 (save-excursion
9022 (let ((cnt 0) (pos (point)))
9023 (goto-char (org-table-begin))
9024 (while (<= (point) pos)
9025 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
9026 (beginning-of-line 2))
9027 (if (interactive-p) (message "This is table line %d" cnt))
9028 cnt)))
9030 (defun org-table-goto-column (n &optional on-delim force)
9031 "Move the cursor to the Nth column in the current table line.
9032 With optional argument ON-DELIM, stop with point before the left delimiter
9033 of the field.
9034 If there are less than N fields, just go to after the last delimiter.
9035 However, when FORCE is non-nil, create new columns if necessary."
9036 (interactive "p")
9037 (let ((pos (point-at-eol)))
9038 (beginning-of-line 1)
9039 (when (> n 0)
9040 (while (and (> (setq n (1- n)) -1)
9041 (or (search-forward "|" pos t)
9042 (and force
9043 (progn (end-of-line 1)
9044 (skip-chars-backward "^|")
9045 (insert " | "))))))
9046 ; (backward-char 2) t)))))
9047 (when (and force (not (looking-at ".*|")))
9048 (save-excursion (end-of-line 1) (insert " | ")))
9049 (if on-delim
9050 (backward-char 1)
9051 (if (looking-at " ") (forward-char 1))))))
9053 (defun org-at-table-p (&optional table-type)
9054 "Return t if the cursor is inside an org-type table.
9055 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9056 (if org-enable-table-editor
9057 (save-excursion
9058 (beginning-of-line 1)
9059 (looking-at (if table-type org-table-any-line-regexp
9060 org-table-line-regexp)))
9061 nil))
9063 (defun org-at-table.el-p ()
9064 "Return t if and only if we are at a table.el table."
9065 (and (org-at-table-p 'any)
9066 (save-excursion
9067 (goto-char (org-table-begin 'any))
9068 (looking-at org-table1-hline-regexp))))
9070 (defun org-table-recognize-table.el ()
9071 "If there is a table.el table nearby, recognize it and move into it."
9072 (if org-table-tab-recognizes-table.el
9073 (if (org-at-table.el-p)
9074 (progn
9075 (beginning-of-line 1)
9076 (if (looking-at org-table-dataline-regexp)
9078 (if (looking-at org-table1-hline-regexp)
9079 (progn
9080 (beginning-of-line 2)
9081 (if (looking-at org-table-any-border-regexp)
9082 (beginning-of-line -1)))))
9083 (if (re-search-forward "|" (org-table-end t) t)
9084 (progn
9085 (require 'table)
9086 (if (table--at-cell-p (point))
9088 (message "recognizing table.el table...")
9089 (table-recognize-table)
9090 (message "recognizing table.el table...done")))
9091 (error "This should not happen..."))
9093 nil)
9094 nil))
9096 (defun org-at-table-hline-p ()
9097 "Return t if the cursor is inside a hline in a table."
9098 (if org-enable-table-editor
9099 (save-excursion
9100 (beginning-of-line 1)
9101 (looking-at org-table-hline-regexp))
9102 nil))
9104 (defun org-table-insert-column ()
9105 "Insert a new column into the table."
9106 (interactive)
9107 (if (not (org-at-table-p))
9108 (error "Not at a table"))
9109 (org-table-find-dataline)
9110 (let* ((col (max 1 (org-table-current-column)))
9111 (beg (org-table-begin))
9112 (end (org-table-end))
9113 ;; Current cursor position
9114 (linepos (org-current-line))
9115 (colpos col))
9116 (goto-char beg)
9117 (while (< (point) end)
9118 (if (org-at-table-hline-p)
9120 (org-table-goto-column col t)
9121 (insert "| "))
9122 (beginning-of-line 2))
9123 (move-marker end nil)
9124 (goto-line linepos)
9125 (org-table-goto-column colpos)
9126 (org-table-align)
9127 (org-table-fix-formulas "$" nil (1- col) 1)))
9129 (defun org-table-find-dataline ()
9130 "Find a dataline in the current table, which is needed for column commands."
9131 (if (and (org-at-table-p)
9132 (not (org-at-table-hline-p)))
9134 (let ((col (current-column))
9135 (end (org-table-end)))
9136 (move-to-column col)
9137 (while (and (< (point) end)
9138 (or (not (= (current-column) col))
9139 (org-at-table-hline-p)))
9140 (beginning-of-line 2)
9141 (move-to-column col))
9142 (if (and (org-at-table-p)
9143 (not (org-at-table-hline-p)))
9145 (error
9146 "Please position cursor in a data line for column operations")))))
9148 (defun org-table-delete-column ()
9149 "Delete a column from the table."
9150 (interactive)
9151 (if (not (org-at-table-p))
9152 (error "Not at a table"))
9153 (org-table-find-dataline)
9154 (org-table-check-inside-data-field)
9155 (let* ((col (org-table-current-column))
9156 (beg (org-table-begin))
9157 (end (org-table-end))
9158 ;; Current cursor position
9159 (linepos (org-current-line))
9160 (colpos col))
9161 (goto-char beg)
9162 (while (< (point) end)
9163 (if (org-at-table-hline-p)
9165 (org-table-goto-column col t)
9166 (and (looking-at "|[^|\n]+|")
9167 (replace-match "|")))
9168 (beginning-of-line 2))
9169 (move-marker end nil)
9170 (goto-line linepos)
9171 (org-table-goto-column colpos)
9172 (org-table-align)
9173 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9174 col -1 col)))
9176 (defun org-table-move-column-right ()
9177 "Move column to the right."
9178 (interactive)
9179 (org-table-move-column nil))
9180 (defun org-table-move-column-left ()
9181 "Move column to the left."
9182 (interactive)
9183 (org-table-move-column 'left))
9185 (defun org-table-move-column (&optional left)
9186 "Move the current column to the right. With arg LEFT, move to the left."
9187 (interactive "P")
9188 (if (not (org-at-table-p))
9189 (error "Not at a table"))
9190 (org-table-find-dataline)
9191 (org-table-check-inside-data-field)
9192 (let* ((col (org-table-current-column))
9193 (col1 (if left (1- col) col))
9194 (beg (org-table-begin))
9195 (end (org-table-end))
9196 ;; Current cursor position
9197 (linepos (org-current-line))
9198 (colpos (if left (1- col) (1+ col))))
9199 (if (and left (= col 1))
9200 (error "Cannot move column further left"))
9201 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9202 (error "Cannot move column further right"))
9203 (goto-char beg)
9204 (while (< (point) end)
9205 (if (org-at-table-hline-p)
9207 (org-table-goto-column col1 t)
9208 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9209 (replace-match "|\\2|\\1|")))
9210 (beginning-of-line 2))
9211 (move-marker end nil)
9212 (goto-line linepos)
9213 (org-table-goto-column colpos)
9214 (org-table-align)
9215 (org-table-fix-formulas
9216 "$" (list (cons (number-to-string col) (number-to-string colpos))
9217 (cons (number-to-string colpos) (number-to-string col))))))
9219 (defun org-table-move-row-down ()
9220 "Move table row down."
9221 (interactive)
9222 (org-table-move-row nil))
9223 (defun org-table-move-row-up ()
9224 "Move table row up."
9225 (interactive)
9226 (org-table-move-row 'up))
9228 (defun org-table-move-row (&optional up)
9229 "Move the current table line down. With arg UP, move it up."
9230 (interactive "P")
9231 (let* ((col (current-column))
9232 (pos (point))
9233 (hline1p (save-excursion (beginning-of-line 1)
9234 (looking-at org-table-hline-regexp)))
9235 (dline1 (org-table-current-dline))
9236 (dline2 (+ dline1 (if up -1 1)))
9237 (tonew (if up 0 2))
9238 txt hline2p)
9239 (beginning-of-line tonew)
9240 (unless (org-at-table-p)
9241 (goto-char pos)
9242 (error "Cannot move row further"))
9243 (setq hline2p (looking-at org-table-hline-regexp))
9244 (goto-char pos)
9245 (beginning-of-line 1)
9246 (setq pos (point))
9247 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9248 (delete-region (point) (1+ (point-at-eol)))
9249 (beginning-of-line tonew)
9250 (insert txt)
9251 (beginning-of-line 0)
9252 (move-to-column col)
9253 (unless (or hline1p hline2p)
9254 (org-table-fix-formulas
9255 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9256 (cons (number-to-string dline2) (number-to-string dline1)))))))
9258 (defun org-table-insert-row (&optional arg)
9259 "Insert a new row above the current line into the table.
9260 With prefix ARG, insert below the current line."
9261 (interactive "P")
9262 (if (not (org-at-table-p))
9263 (error "Not at a table"))
9264 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9265 (new (org-table-clean-line line)))
9266 ;; Fix the first field if necessary
9267 (if (string-match "^[ \t]*| *[#$] *|" line)
9268 (setq new (replace-match (match-string 0 line) t t new)))
9269 (beginning-of-line (if arg 2 1))
9270 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9271 (beginning-of-line 0)
9272 (re-search-forward "| ?" (point-at-eol) t)
9273 (and (or org-table-may-need-update org-table-overlay-coordinates)
9274 (org-table-align))
9275 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9277 (defun org-table-insert-hline (&optional above)
9278 "Insert a horizontal-line below the current line into the table.
9279 With prefix ABOVE, insert above the current line."
9280 (interactive "P")
9281 (if (not (org-at-table-p))
9282 (error "Not at a table"))
9283 (let ((line (org-table-clean-line
9284 (buffer-substring (point-at-bol) (point-at-eol))))
9285 (col (current-column)))
9286 (while (string-match "|\\( +\\)|" line)
9287 (setq line (replace-match
9288 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9289 ?-) "|") t t line)))
9290 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9291 (beginning-of-line (if above 1 2))
9292 (insert line "\n")
9293 (beginning-of-line (if above 1 -1))
9294 (move-to-column col)
9295 (and org-table-overlay-coordinates (org-table-align))))
9297 (defun org-table-hline-and-move (&optional same-column)
9298 "Insert a hline and move to the row below that line."
9299 (interactive "P")
9300 (let ((col (org-table-current-column)))
9301 (org-table-maybe-eval-formula)
9302 (org-table-maybe-recalculate-line)
9303 (org-table-insert-hline)
9304 (end-of-line 2)
9305 (if (looking-at "\n[ \t]*|-")
9306 (progn (insert "\n|") (org-table-align))
9307 (org-table-next-field))
9308 (if same-column (org-table-goto-column col))))
9310 (defun org-table-clean-line (s)
9311 "Convert a table line S into a string with only \"|\" and space.
9312 In particular, this does handle wide and invisible characters."
9313 (if (string-match "^[ \t]*|-" s)
9314 ;; It's a hline, just map the characters
9315 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9316 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9317 (setq s (replace-match
9318 (concat "|" (make-string (org-string-width (match-string 1 s))
9319 ?\ ) "|")
9320 t t s)))
9323 (defun org-table-kill-row ()
9324 "Delete the current row or horizontal line from the table."
9325 (interactive)
9326 (if (not (org-at-table-p))
9327 (error "Not at a table"))
9328 (let ((col (current-column))
9329 (dline (org-table-current-dline)))
9330 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9331 (if (not (org-at-table-p)) (beginning-of-line 0))
9332 (move-to-column col)
9333 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9334 dline -1 dline)))
9336 (defun org-table-sort-lines (with-case &optional sorting-type)
9337 "Sort table lines according to the column at point.
9339 The position of point indicates the column to be used for
9340 sorting, and the range of lines is the range between the nearest
9341 horizontal separator lines, or the entire table of no such lines
9342 exist. If point is before the first column, you will be prompted
9343 for the sorting column. If there is an active region, the mark
9344 specifies the first line and the sorting column, while point
9345 should be in the last line to be included into the sorting.
9347 The command then prompts for the sorting type which can be
9348 alphabetically, numerically, or by time (as given in a time stamp
9349 in the field). Sorting in reverse order is also possible.
9351 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9353 If SORTING-TYPE is specified when this function is called from a Lisp
9354 program, no prompting will take place. SORTING-TYPE must be a character,
9355 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9356 should be done in reverse order."
9357 (interactive "P")
9358 (let* ((thisline (org-current-line))
9359 (thiscol (org-table-current-column))
9360 beg end bcol ecol tend tbeg column lns pos)
9361 (when (equal thiscol 0)
9362 (if (interactive-p)
9363 (setq thiscol
9364 (string-to-number
9365 (read-string "Use column N for sorting: ")))
9366 (setq thiscol 1))
9367 (org-table-goto-column thiscol))
9368 (org-table-check-inside-data-field)
9369 (if (org-region-active-p)
9370 (progn
9371 (setq beg (region-beginning) end (region-end))
9372 (goto-char beg)
9373 (setq column (org-table-current-column)
9374 beg (point-at-bol))
9375 (goto-char end)
9376 (setq end (point-at-bol 2)))
9377 (setq column (org-table-current-column)
9378 pos (point)
9379 tbeg (org-table-begin)
9380 tend (org-table-end))
9381 (if (re-search-backward org-table-hline-regexp tbeg t)
9382 (setq beg (point-at-bol 2))
9383 (goto-char tbeg)
9384 (setq beg (point-at-bol 1)))
9385 (goto-char pos)
9386 (if (re-search-forward org-table-hline-regexp tend t)
9387 (setq end (point-at-bol 1))
9388 (goto-char tend)
9389 (setq end (point-at-bol))))
9390 (setq beg (move-marker (make-marker) beg)
9391 end (move-marker (make-marker) end))
9392 (untabify beg end)
9393 (goto-char beg)
9394 (org-table-goto-column column)
9395 (skip-chars-backward "^|")
9396 (setq bcol (current-column))
9397 (org-table-goto-column (1+ column))
9398 (skip-chars-backward "^|")
9399 (setq ecol (1- (current-column)))
9400 (org-table-goto-column column)
9401 (setq lns (mapcar (lambda(x) (cons
9402 (org-sort-remove-invisible
9403 (nth (1- column)
9404 (org-split-string x "[ \t]*|[ \t]*")))
9406 (org-split-string (buffer-substring beg end) "\n")))
9407 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9408 (delete-region beg end)
9409 (move-marker beg nil)
9410 (move-marker end nil)
9411 (insert (mapconcat 'cdr lns "\n") "\n")
9412 (goto-line thisline)
9413 (org-table-goto-column thiscol)
9414 (message "%d lines sorted, based on column %d" (length lns) column)))
9416 ;; FIXME: maybe we will not need this? Table sorting is broken....
9417 (defun org-sort-remove-invisible (s)
9418 (remove-text-properties 0 (length s) org-rm-props s)
9419 (while (string-match org-bracket-link-regexp s)
9420 (setq s (replace-match (if (match-end 2)
9421 (match-string 3 s)
9422 (match-string 1 s)) t t s)))
9425 (defun org-table-cut-region (beg end)
9426 "Copy region in table to the clipboard and blank all relevant fields."
9427 (interactive "r")
9428 (org-table-copy-region beg end 'cut))
9430 (defun org-table-copy-region (beg end &optional cut)
9431 "Copy rectangular region in table to clipboard.
9432 A special clipboard is used which can only be accessed
9433 with `org-table-paste-rectangle'."
9434 (interactive "rP")
9435 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9436 region cols
9437 (rpl (if cut " " nil)))
9438 (goto-char beg)
9439 (org-table-check-inside-data-field)
9440 (setq l01 (org-current-line)
9441 c01 (org-table-current-column))
9442 (goto-char end)
9443 (org-table-check-inside-data-field)
9444 (setq l02 (org-current-line)
9445 c02 (org-table-current-column))
9446 (setq l1 (min l01 l02) l2 (max l01 l02)
9447 c1 (min c01 c02) c2 (max c01 c02))
9448 (catch 'exit
9449 (while t
9450 (catch 'nextline
9451 (if (> l1 l2) (throw 'exit t))
9452 (goto-line l1)
9453 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9454 (setq cols nil ic1 c1 ic2 c2)
9455 (while (< ic1 (1+ ic2))
9456 (push (org-table-get-field ic1 rpl) cols)
9457 (setq ic1 (1+ ic1)))
9458 (push (nreverse cols) region)
9459 (setq l1 (1+ l1)))))
9460 (setq org-table-clip (nreverse region))
9461 (if cut (org-table-align))
9462 org-table-clip))
9464 (defun org-table-paste-rectangle ()
9465 "Paste a rectangular region into a table.
9466 The upper right corner ends up in the current field. All involved fields
9467 will be overwritten. If the rectangle does not fit into the present table,
9468 the table is enlarged as needed. The process ignores horizontal separator
9469 lines."
9470 (interactive)
9471 (unless (and org-table-clip (listp org-table-clip))
9472 (error "First cut/copy a region to paste!"))
9473 (org-table-check-inside-data-field)
9474 (let* ((clip org-table-clip)
9475 (line (org-current-line))
9476 (col (org-table-current-column))
9477 (org-enable-table-editor t)
9478 (org-table-automatic-realign nil)
9479 c cols field)
9480 (while (setq cols (pop clip))
9481 (while (org-at-table-hline-p) (beginning-of-line 2))
9482 (if (not (org-at-table-p))
9483 (progn (end-of-line 0) (org-table-next-field)))
9484 (setq c col)
9485 (while (setq field (pop cols))
9486 (org-table-goto-column c nil 'force)
9487 (org-table-get-field nil field)
9488 (setq c (1+ c)))
9489 (beginning-of-line 2))
9490 (goto-line line)
9491 (org-table-goto-column col)
9492 (org-table-align)))
9494 (defun org-table-convert ()
9495 "Convert from `org-mode' table to table.el and back.
9496 Obviously, this only works within limits. When an Org-mode table is
9497 converted to table.el, all horizontal separator lines get lost, because
9498 table.el uses these as cell boundaries and has no notion of horizontal lines.
9499 A table.el table can be converted to an Org-mode table only if it does not
9500 do row or column spanning. Multiline cells will become multiple cells.
9501 Beware, Org-mode does not test if the table can be successfully converted - it
9502 blindly applies a recipe that works for simple tables."
9503 (interactive)
9504 (require 'table)
9505 (if (org-at-table.el-p)
9506 ;; convert to Org-mode table
9507 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9508 (end (move-marker (make-marker) (org-table-end t))))
9509 (table-unrecognize-region beg end)
9510 (goto-char beg)
9511 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9512 (replace-match ""))
9513 (goto-char beg))
9514 (if (org-at-table-p)
9515 ;; convert to table.el table
9516 (let ((beg (move-marker (make-marker) (org-table-begin)))
9517 (end (move-marker (make-marker) (org-table-end))))
9518 ;; first, get rid of all horizontal lines
9519 (goto-char beg)
9520 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9521 (replace-match ""))
9522 ;; insert a hline before first
9523 (goto-char beg)
9524 (org-table-insert-hline 'above)
9525 (beginning-of-line -1)
9526 ;; insert a hline after each line
9527 (while (progn (beginning-of-line 3) (< (point) end))
9528 (org-table-insert-hline))
9529 (goto-char beg)
9530 (setq end (move-marker end (org-table-end)))
9531 ;; replace "+" at beginning and ending of hlines
9532 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9533 (replace-match "\\1+-"))
9534 (goto-char beg)
9535 (while (re-search-forward "-|[ \t]*$" end t)
9536 (replace-match "-+"))
9537 (goto-char beg)))))
9539 (defun org-table-wrap-region (arg)
9540 "Wrap several fields in a column like a paragraph.
9541 This is useful if you'd like to spread the contents of a field over several
9542 lines, in order to keep the table compact.
9544 If there is an active region, and both point and mark are in the same column,
9545 the text in the column is wrapped to minimum width for the given number of
9546 lines. Generally, this makes the table more compact. A prefix ARG may be
9547 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9548 formats the selected text to two lines. If the region was longer than two
9549 lines, the remaining lines remain empty. A negative prefix argument reduces
9550 the current number of lines by that amount. The wrapped text is pasted back
9551 into the table. If you formatted it to more lines than it was before, fields
9552 further down in the table get overwritten - so you might need to make space in
9553 the table first.
9555 If there is no region, the current field is split at the cursor position and
9556 the text fragment to the right of the cursor is prepended to the field one
9557 line down.
9559 If there is no region, but you specify a prefix ARG, the current field gets
9560 blank, and the content is appended to the field above."
9561 (interactive "P")
9562 (org-table-check-inside-data-field)
9563 (if (org-region-active-p)
9564 ;; There is a region: fill as a paragraph
9565 (let* ((beg (region-beginning))
9566 (cline (save-excursion (goto-char beg) (org-current-line)))
9567 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9568 nlines)
9569 (org-table-cut-region (region-beginning) (region-end))
9570 (if (> (length (car org-table-clip)) 1)
9571 (error "Region must be limited to single column"))
9572 (setq nlines (if arg
9573 (if (< arg 1)
9574 (+ (length org-table-clip) arg)
9575 arg)
9576 (length org-table-clip)))
9577 (setq org-table-clip
9578 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9579 nil nlines)))
9580 (goto-line cline)
9581 (org-table-goto-column ccol)
9582 (org-table-paste-rectangle))
9583 ;; No region, split the current field at point
9584 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9585 (skip-chars-forward "^\r\n|"))
9586 (if arg
9587 ;; combine with field above
9588 (let ((s (org-table-blank-field))
9589 (col (org-table-current-column)))
9590 (beginning-of-line 0)
9591 (while (org-at-table-hline-p) (beginning-of-line 0))
9592 (org-table-goto-column col)
9593 (skip-chars-forward "^|")
9594 (skip-chars-backward " ")
9595 (insert " " (org-trim s))
9596 (org-table-align))
9597 ;; split field
9598 (if (looking-at "\\([^|]+\\)+|")
9599 (let ((s (match-string 1)))
9600 (replace-match " |")
9601 (goto-char (match-beginning 0))
9602 (org-table-next-row)
9603 (insert (org-trim s) " ")
9604 (org-table-align))
9605 (org-table-next-row)))))
9607 (defvar org-field-marker nil)
9609 (defun org-table-edit-field (arg)
9610 "Edit table field in a different window.
9611 This is mainly useful for fields that contain hidden parts.
9612 When called with a \\[universal-argument] prefix, just make the full field visible so that
9613 it can be edited in place."
9614 (interactive "P")
9615 (if arg
9616 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9617 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9618 (remove-text-properties b e '(org-cwidth t invisible t
9619 display t intangible t))
9620 (if (and (boundp 'font-lock-mode) font-lock-mode)
9621 (font-lock-fontify-block)))
9622 (let ((pos (move-marker (make-marker) (point)))
9623 (field (org-table-get-field))
9624 (cw (current-window-configuration))
9626 (org-switch-to-buffer-other-window "*Org tmp*")
9627 (erase-buffer)
9628 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9629 (let ((org-inhibit-startup t)) (org-mode))
9630 (goto-char (setq p (point-max)))
9631 (insert (org-trim field))
9632 (remove-text-properties p (point-max)
9633 '(invisible t org-cwidth t display t
9634 intangible t))
9635 (goto-char p)
9636 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9637 (org-set-local 'org-window-configuration cw)
9638 (org-set-local 'org-field-marker pos)
9639 (message "Edit and finish with C-c C-c"))))
9641 (defun org-table-finish-edit-field ()
9642 "Finish editing a table data field.
9643 Remove all newline characters, insert the result into the table, realign
9644 the table and kill the editing buffer."
9645 (let ((pos org-field-marker)
9646 (cw org-window-configuration)
9647 (cb (current-buffer))
9648 text)
9649 (goto-char (point-min))
9650 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9651 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9652 (replace-match " "))
9653 (setq text (org-trim (buffer-string)))
9654 (set-window-configuration cw)
9655 (kill-buffer cb)
9656 (select-window (get-buffer-window (marker-buffer pos)))
9657 (goto-char pos)
9658 (move-marker pos nil)
9659 (org-table-check-inside-data-field)
9660 (org-table-get-field nil text)
9661 (org-table-align)
9662 (message "New field value inserted")))
9664 (defun org-trim (s)
9665 "Remove whitespace at beginning and end of string."
9666 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9667 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9670 (defun org-wrap (string &optional width lines)
9671 "Wrap string to either a number of lines, or a width in characters.
9672 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9673 that costs. If there is a word longer than WIDTH, the text is actually
9674 wrapped to the length of that word.
9675 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9676 many lines, whatever width that takes.
9677 The return value is a list of lines, without newlines at the end."
9678 (let* ((words (org-split-string string "[ \t\n]+"))
9679 (maxword (apply 'max (mapcar 'org-string-width words)))
9680 w ll)
9681 (cond (width
9682 (org-do-wrap words (max maxword width)))
9683 (lines
9684 (setq w maxword)
9685 (setq ll (org-do-wrap words maxword))
9686 (if (<= (length ll) lines)
9688 (setq ll words)
9689 (while (> (length ll) lines)
9690 (setq w (1+ w))
9691 (setq ll (org-do-wrap words w)))
9692 ll))
9693 (t (error "Cannot wrap this")))))
9696 (defun org-do-wrap (words width)
9697 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9698 (let (lines line)
9699 (while words
9700 (setq line (pop words))
9701 (while (and words (< (+ (length line) (length (car words))) width))
9702 (setq line (concat line " " (pop words))))
9703 (setq lines (push line lines)))
9704 (nreverse lines)))
9706 (defun org-split-string (string &optional separators)
9707 "Splits STRING into substrings at SEPARATORS.
9708 No empty strings are returned if there are matches at the beginning
9709 and end of string."
9710 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9711 (start 0)
9712 notfirst
9713 (list nil))
9714 (while (and (string-match rexp string
9715 (if (and notfirst
9716 (= start (match-beginning 0))
9717 (< start (length string)))
9718 (1+ start) start))
9719 (< (match-beginning 0) (length string)))
9720 (setq notfirst t)
9721 (or (eq (match-beginning 0) 0)
9722 (and (eq (match-beginning 0) (match-end 0))
9723 (eq (match-beginning 0) start))
9724 (setq list
9725 (cons (substring string start (match-beginning 0))
9726 list)))
9727 (setq start (match-end 0)))
9728 (or (eq start (length string))
9729 (setq list
9730 (cons (substring string start)
9731 list)))
9732 (nreverse list)))
9734 (defun org-table-map-tables (function)
9735 "Apply FUNCTION to the start of all tables in the buffer."
9736 (save-excursion
9737 (save-restriction
9738 (widen)
9739 (goto-char (point-min))
9740 (while (re-search-forward org-table-any-line-regexp nil t)
9741 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9742 (beginning-of-line 1)
9743 (if (looking-at org-table-line-regexp)
9744 (save-excursion (funcall function)))
9745 (re-search-forward org-table-any-border-regexp nil 1))))
9746 (message "Mapping tables: done"))
9748 (defvar org-timecnt) ; dynamically scoped parameter
9750 (defun org-table-sum (&optional beg end nlast)
9751 "Sum numbers in region of current table column.
9752 The result will be displayed in the echo area, and will be available
9753 as kill to be inserted with \\[yank].
9755 If there is an active region, it is interpreted as a rectangle and all
9756 numbers in that rectangle will be summed. If there is no active
9757 region and point is located in a table column, sum all numbers in that
9758 column.
9760 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9761 numbers are assumed to be times as well (in decimal hours) and the
9762 numbers are added as such.
9764 If NLAST is a number, only the NLAST fields will actually be summed."
9765 (interactive)
9766 (save-excursion
9767 (let (col (org-timecnt 0) diff h m s org-table-clip)
9768 (cond
9769 ((and beg end)) ; beg and end given explicitly
9770 ((org-region-active-p)
9771 (setq beg (region-beginning) end (region-end)))
9773 (setq col (org-table-current-column))
9774 (goto-char (org-table-begin))
9775 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9776 (error "No table data"))
9777 (org-table-goto-column col)
9778 (setq beg (point))
9779 (goto-char (org-table-end))
9780 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9781 (error "No table data"))
9782 (org-table-goto-column col)
9783 (setq end (point))))
9784 (let* ((items (apply 'append (org-table-copy-region beg end)))
9785 (items1 (cond ((not nlast) items)
9786 ((>= nlast (length items)) items)
9787 (t (setq items (reverse items))
9788 (setcdr (nthcdr (1- nlast) items) nil)
9789 (nreverse items))))
9790 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9791 items1)))
9792 (res (apply '+ numbers))
9793 (sres (if (= org-timecnt 0)
9794 (format "%g" res)
9795 (setq diff (* 3600 res)
9796 h (floor (/ diff 3600)) diff (mod diff 3600)
9797 m (floor (/ diff 60)) diff (mod diff 60)
9798 s diff)
9799 (format "%d:%02d:%02d" h m s))))
9800 (kill-new sres)
9801 (if (interactive-p)
9802 (message "%s"
9803 (substitute-command-keys
9804 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9805 (length numbers) sres))))
9806 sres))))
9808 (defun org-table-get-number-for-summing (s)
9809 (let (n)
9810 (if (string-match "^ *|? *" s)
9811 (setq s (replace-match "" nil nil s)))
9812 (if (string-match " *|? *$" s)
9813 (setq s (replace-match "" nil nil s)))
9814 (setq n (string-to-number s))
9815 (cond
9816 ((and (string-match "0" s)
9817 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9818 ((string-match "\\`[ \t]+\\'" s) nil)
9819 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9820 (let ((h (string-to-number (or (match-string 1 s) "0")))
9821 (m (string-to-number (or (match-string 2 s) "0")))
9822 (s (string-to-number (or (match-string 4 s) "0"))))
9823 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9824 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9825 ((equal n 0) nil)
9826 (t n))))
9828 (defun org-table-current-field-formula (&optional key noerror)
9829 "Return the formula active for the current field.
9830 Assumes that specials are in place.
9831 If KEY is given, return the key to this formula.
9832 Otherwise return the formula preceeded with \"=\" or \":=\"."
9833 (let* ((name (car (rassoc (list (org-current-line)
9834 (org-table-current-column))
9835 org-table-named-field-locations)))
9836 (col (org-table-current-column))
9837 (scol (int-to-string col))
9838 (ref (format "@%d$%d" (org-table-current-dline) col))
9839 (stored-list (org-table-get-stored-formulas noerror))
9840 (ass (or (assoc name stored-list)
9841 (assoc ref stored-list)
9842 (assoc scol stored-list))))
9843 (if key
9844 (car ass)
9845 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9846 (cdr ass))))))
9848 (defun org-table-get-formula (&optional equation named)
9849 "Read a formula from the minibuffer, offer stored formula as default.
9850 When NAMED is non-nil, look for a named equation."
9851 (let* ((stored-list (org-table-get-stored-formulas))
9852 (name (car (rassoc (list (org-current-line)
9853 (org-table-current-column))
9854 org-table-named-field-locations)))
9855 (ref (format "@%d$%d" (org-table-current-dline)
9856 (org-table-current-column)))
9857 (refass (assoc ref stored-list))
9858 (scol (if named
9859 (if name name ref)
9860 (int-to-string (org-table-current-column))))
9861 (dummy (and (or name refass) (not named)
9862 (not (y-or-n-p "Replace field formula with column formula? " ))
9863 (error "Abort")))
9864 (name (or name ref))
9865 (org-table-may-need-update nil)
9866 (stored (cdr (assoc scol stored-list)))
9867 (eq (cond
9868 ((and stored equation (string-match "^ *=? *$" equation))
9869 stored)
9870 ((stringp equation)
9871 equation)
9872 (t (org-table-formula-from-user
9873 (read-string
9874 (org-table-formula-to-user
9875 (format "%s formula %s%s="
9876 (if named "Field" "Column")
9877 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9878 scol))
9879 (if stored (org-table-formula-to-user stored) "")
9880 'org-table-formula-history
9881 )))))
9882 mustsave)
9883 (when (not (string-match "\\S-" eq))
9884 ;; remove formula
9885 (setq stored-list (delq (assoc scol stored-list) stored-list))
9886 (org-table-store-formulas stored-list)
9887 (error "Formula removed"))
9888 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9889 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9890 (if (and name (not named))
9891 ;; We set the column equation, delete the named one.
9892 (setq stored-list (delq (assoc name stored-list) stored-list)
9893 mustsave t))
9894 (if stored
9895 (setcdr (assoc scol stored-list) eq)
9896 (setq stored-list (cons (cons scol eq) stored-list)))
9897 (if (or mustsave (not (equal stored eq)))
9898 (org-table-store-formulas stored-list))
9899 eq))
9901 (defun org-table-store-formulas (alist)
9902 "Store the list of formulas below the current table."
9903 (setq alist (sort alist 'org-table-formula-less-p))
9904 (save-excursion
9905 (goto-char (org-table-end))
9906 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9907 (progn
9908 ;; don't overwrite TBLFM, we might use text properties to store stuff
9909 (goto-char (match-beginning 2))
9910 (delete-region (match-beginning 2) (match-end 0)))
9911 (insert "#+TBLFM:"))
9912 (insert " "
9913 (mapconcat (lambda (x)
9914 (concat
9915 (if (equal (string-to-char (car x)) ?@) "" "$")
9916 (car x) "=" (cdr x)))
9917 alist "::")
9918 "\n")))
9920 (defsubst org-table-formula-make-cmp-string (a)
9921 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9922 (concat
9923 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9924 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9925 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9927 (defun org-table-formula-less-p (a b)
9928 "Compare two formulas for sorting."
9929 (let ((as (org-table-formula-make-cmp-string (car a)))
9930 (bs (org-table-formula-make-cmp-string (car b))))
9931 (and as bs (string< as bs))))
9933 (defun org-table-get-stored-formulas (&optional noerror)
9934 "Return an alist with the stored formulas directly after current table."
9935 (interactive)
9936 (let (scol eq eq-alist strings string seen)
9937 (save-excursion
9938 (goto-char (org-table-end))
9939 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9940 (setq strings (org-split-string (match-string 2) " *:: *"))
9941 (while (setq string (pop strings))
9942 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9943 (setq scol (if (match-end 2)
9944 (match-string 2 string)
9945 (match-string 1 string))
9946 eq (match-string 3 string)
9947 eq-alist (cons (cons scol eq) eq-alist))
9948 (if (member scol seen)
9949 (if noerror
9950 (progn
9951 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9952 (ding)
9953 (sit-for 2))
9954 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9955 (push scol seen))))))
9956 (nreverse eq-alist)))
9958 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9959 "Modify the equations after the table structure has been edited.
9960 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9961 For all numbers larger than LIMIT, shift them by DELTA."
9962 (save-excursion
9963 (goto-char (org-table-end))
9964 (when (looking-at "#\\+TBLFM:")
9965 (let ((re (concat key "\\([0-9]+\\)"))
9966 (re2
9967 (when remove
9968 (if (equal key "$")
9969 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9970 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9971 s n a)
9972 (when remove
9973 (while (re-search-forward re2 (point-at-eol) t)
9974 (replace-match "")))
9975 (while (re-search-forward re (point-at-eol) t)
9976 (setq s (match-string 1) n (string-to-number s))
9977 (cond
9978 ((setq a (assoc s replace))
9979 (replace-match (concat key (cdr a)) t t))
9980 ((and limit (> n limit))
9981 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9983 (defun org-table-get-specials ()
9984 "Get the column names and local parameters for this table."
9985 (save-excursion
9986 (let ((beg (org-table-begin)) (end (org-table-end))
9987 names name fields fields1 field cnt
9988 c v l line col types dlines hlines)
9989 (setq org-table-column-names nil
9990 org-table-local-parameters nil
9991 org-table-named-field-locations nil
9992 org-table-current-begin-line nil
9993 org-table-current-begin-pos nil
9994 org-table-current-line-types nil)
9995 (goto-char beg)
9996 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9997 (setq names (org-split-string (match-string 1) " *| *")
9998 cnt 1)
9999 (while (setq name (pop names))
10000 (setq cnt (1+ cnt))
10001 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10002 (push (cons name (int-to-string cnt)) org-table-column-names))))
10003 (setq org-table-column-names (nreverse org-table-column-names))
10004 (setq org-table-column-name-regexp
10005 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10006 (goto-char beg)
10007 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10008 (setq fields (org-split-string (match-string 1) " *| *"))
10009 (while (setq field (pop fields))
10010 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10011 (push (cons (match-string 1 field) (match-string 2 field))
10012 org-table-local-parameters))))
10013 (goto-char beg)
10014 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10015 (setq c (match-string 1)
10016 fields (org-split-string (match-string 2) " *| *"))
10017 (save-excursion
10018 (beginning-of-line (if (equal c "_") 2 0))
10019 (setq line (org-current-line) col 1)
10020 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10021 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10022 (while (and fields1 (setq field (pop fields)))
10023 (setq v (pop fields1) col (1+ col))
10024 (when (and (stringp field) (stringp v)
10025 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10026 (push (cons field v) org-table-local-parameters)
10027 (push (list field line col) org-table-named-field-locations))))
10028 ;; Analyse the line types
10029 (goto-char beg)
10030 (setq org-table-current-begin-line (org-current-line)
10031 org-table-current-begin-pos (point)
10032 l org-table-current-begin-line)
10033 (while (looking-at "[ \t]*|\\(-\\)?")
10034 (push (if (match-end 1) 'hline 'dline) types)
10035 (if (match-end 1) (push l hlines) (push l dlines))
10036 (beginning-of-line 2)
10037 (setq l (1+ l)))
10038 (setq org-table-current-line-types (apply 'vector (nreverse types))
10039 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
10040 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
10042 (defun org-table-maybe-eval-formula ()
10043 "Check if the current field starts with \"=\" or \":=\".
10044 If yes, store the formula and apply it."
10045 ;; We already know we are in a table. Get field will only return a formula
10046 ;; when appropriate. It might return a separator line, but no problem.
10047 (when org-table-formula-evaluate-inline
10048 (let* ((field (org-trim (or (org-table-get-field) "")))
10049 named eq)
10050 (when (string-match "^:?=\\(.*\\)" field)
10051 (setq named (equal (string-to-char field) ?:)
10052 eq (match-string 1 field))
10053 (if (or (fboundp 'calc-eval)
10054 (equal (substring eq 0 (min 2 (length eq))) "'("))
10055 (org-table-eval-formula (if named '(4) nil)
10056 (org-table-formula-from-user eq))
10057 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10059 (defvar org-recalc-commands nil
10060 "List of commands triggering the recalculation of a line.
10061 Will be filled automatically during use.")
10063 (defvar org-recalc-marks
10064 '((" " . "Unmarked: no special line, no automatic recalculation")
10065 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10066 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10067 ("!" . "Column name definition line. Reference in formula as $name.")
10068 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10069 ("_" . "Names for values in row below this one.")
10070 ("^" . "Names for values in row above this one.")))
10072 (defun org-table-rotate-recalc-marks (&optional newchar)
10073 "Rotate the recalculation mark in the first column.
10074 If in any row, the first field is not consistent with a mark,
10075 insert a new column for the markers.
10076 When there is an active region, change all the lines in the region,
10077 after prompting for the marking character.
10078 After each change, a message will be displayed indicating the meaning
10079 of the new mark."
10080 (interactive)
10081 (unless (org-at-table-p) (error "Not at a table"))
10082 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10083 (beg (org-table-begin))
10084 (end (org-table-end))
10085 (l (org-current-line))
10086 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10087 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10088 (have-col
10089 (save-excursion
10090 (goto-char beg)
10091 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10092 (col (org-table-current-column))
10093 (forcenew (car (assoc newchar org-recalc-marks)))
10094 epos new)
10095 (when l1
10096 (message "Change region to what mark? Type # * ! $ or SPC: ")
10097 (setq newchar (char-to-string (read-char-exclusive))
10098 forcenew (car (assoc newchar org-recalc-marks))))
10099 (if (and newchar (not forcenew))
10100 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10101 newchar))
10102 (if l1 (goto-line l1))
10103 (save-excursion
10104 (beginning-of-line 1)
10105 (unless (looking-at org-table-dataline-regexp)
10106 (error "Not at a table data line")))
10107 (unless have-col
10108 (org-table-goto-column 1)
10109 (org-table-insert-column)
10110 (org-table-goto-column (1+ col)))
10111 (setq epos (point-at-eol))
10112 (save-excursion
10113 (beginning-of-line 1)
10114 (org-table-get-field
10115 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10116 (concat " "
10117 (setq new (or forcenew
10118 (cadr (member (match-string 1) marks))))
10119 " ")
10120 " # ")))
10121 (if (and l1 l2)
10122 (progn
10123 (goto-line l1)
10124 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10125 (and (looking-at org-table-dataline-regexp)
10126 (org-table-get-field 1 (concat " " new " "))))
10127 (goto-line l1)))
10128 (if (not (= epos (point-at-eol))) (org-table-align))
10129 (goto-line l)
10130 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10132 (defun org-table-maybe-recalculate-line ()
10133 "Recompute the current line if marked for it, and if we haven't just done it."
10134 (interactive)
10135 (and org-table-allow-automatic-line-recalculation
10136 (not (and (memq last-command org-recalc-commands)
10137 (equal org-last-recalc-line (org-current-line))))
10138 (save-excursion (beginning-of-line 1)
10139 (looking-at org-table-auto-recalculate-regexp))
10140 (org-table-recalculate) t))
10142 (defvar org-table-formula-debug nil
10143 "Non-nil means, debug table formulas.
10144 When nil, simply write \"#ERROR\" in corrupted fields.")
10145 (make-variable-buffer-local 'org-table-formula-debug)
10147 (defvar modes)
10148 (defsubst org-set-calc-mode (var &optional value)
10149 (if (stringp var)
10150 (setq var (assoc var '(("D" calc-angle-mode deg)
10151 ("R" calc-angle-mode rad)
10152 ("F" calc-prefer-frac t)
10153 ("S" calc-symbolic-mode t)))
10154 value (nth 2 var) var (nth 1 var)))
10155 (if (memq var modes)
10156 (setcar (cdr (memq var modes)) value)
10157 (cons var (cons value modes)))
10158 modes)
10160 (defun org-table-eval-formula (&optional arg equation
10161 suppress-align suppress-const
10162 suppress-store suppress-analysis)
10163 "Replace the table field value at the cursor by the result of a calculation.
10165 This function makes use of Dave Gillespie's Calc package, in my view the
10166 most exciting program ever written for GNU Emacs. So you need to have Calc
10167 installed in order to use this function.
10169 In a table, this command replaces the value in the current field with the
10170 result of a formula. It also installs the formula as the \"current\" column
10171 formula, by storing it in a special line below the table. When called
10172 with a `C-u' prefix, the current field must ba a named field, and the
10173 formula is installed as valid in only this specific field.
10175 When called with two `C-u' prefixes, insert the active equation
10176 for the field back into the current field, so that it can be
10177 edited there. This is useful in order to use \\[org-table-show-reference]
10178 to check the referenced fields.
10180 When called, the command first prompts for a formula, which is read in
10181 the minibuffer. Previously entered formulas are available through the
10182 history list, and the last used formula is offered as a default.
10183 These stored formulas are adapted correctly when moving, inserting, or
10184 deleting columns with the corresponding commands.
10186 The formula can be any algebraic expression understood by the Calc package.
10187 For details, see the Org-mode manual.
10189 This function can also be called from Lisp programs and offers
10190 additional arguments: EQUATION can be the formula to apply. If this
10191 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10192 used to speed-up recursive calls by by-passing unnecessary aligns.
10193 SUPPRESS-CONST suppresses the interpretation of constants in the
10194 formula, assuming that this has been done already outside the function.
10195 SUPPRESS-STORE means the formula should not be stored, either because
10196 it is already stored, or because it is a modified equation that should
10197 not overwrite the stored one."
10198 (interactive "P")
10199 (org-table-check-inside-data-field)
10200 (or suppress-analysis (org-table-get-specials))
10201 (if (equal arg '(16))
10202 (let ((eq (org-table-current-field-formula)))
10203 (or eq (error "No equation active for current field"))
10204 (org-table-get-field nil eq)
10205 (org-table-align)
10206 (setq org-table-may-need-update t))
10207 (let* (fields
10208 (ndown (if (integerp arg) arg 1))
10209 (org-table-automatic-realign nil)
10210 (case-fold-search nil)
10211 (down (> ndown 1))
10212 (formula (if (and equation suppress-store)
10213 equation
10214 (org-table-get-formula equation (equal arg '(4)))))
10215 (n0 (org-table-current-column))
10216 (modes (copy-sequence org-calc-default-modes))
10217 (numbers nil) ; was a variable, now fixed default
10218 (keep-empty nil)
10219 n form form0 bw fmt x ev orig c lispp literal)
10220 ;; Parse the format string. Since we have a lot of modes, this is
10221 ;; a lot of work. However, I think calc still uses most of the time.
10222 (if (string-match ";" formula)
10223 (let ((tmp (org-split-string formula ";")))
10224 (setq formula (car tmp)
10225 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10226 (nth 1 tmp)))
10227 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10228 (setq c (string-to-char (match-string 1 fmt))
10229 n (string-to-number (match-string 2 fmt)))
10230 (if (= c ?p)
10231 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10232 (setq modes (org-set-calc-mode
10233 'calc-float-format
10234 (list (cdr (assoc c '((?n . float) (?f . fix)
10235 (?s . sci) (?e . eng))))
10236 n))))
10237 (setq fmt (replace-match "" t t fmt)))
10238 (if (string-match "[NT]" fmt)
10239 (setq numbers (equal (match-string 0 fmt) "N")
10240 fmt (replace-match "" t t fmt)))
10241 (if (string-match "L" fmt)
10242 (setq literal t
10243 fmt (replace-match "" t t fmt)))
10244 (if (string-match "E" fmt)
10245 (setq keep-empty t
10246 fmt (replace-match "" t t fmt)))
10247 (while (string-match "[DRFS]" fmt)
10248 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10249 (setq fmt (replace-match "" t t fmt)))
10250 (unless (string-match "\\S-" fmt)
10251 (setq fmt nil))))
10252 (if (and (not suppress-const) org-table-formula-use-constants)
10253 (setq formula (org-table-formula-substitute-names formula)))
10254 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10255 (while (> ndown 0)
10256 (setq fields (org-split-string
10257 (org-no-properties
10258 (buffer-substring (point-at-bol) (point-at-eol)))
10259 " *| *"))
10260 (if (eq numbers t)
10261 (setq fields (mapcar
10262 (lambda (x) (number-to-string (string-to-number x)))
10263 fields)))
10264 (setq ndown (1- ndown))
10265 (setq form (copy-sequence formula)
10266 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10267 (if (and lispp literal) (setq lispp 'literal))
10268 ;; Check for old vertical references
10269 (setq form (org-rewrite-old-row-references form))
10270 ;; Insert complex ranges
10271 (while (string-match org-table-range-regexp form)
10272 (setq form
10273 (replace-match
10274 (save-match-data
10275 (org-table-make-reference
10276 (org-table-get-range (match-string 0 form) nil n0)
10277 keep-empty numbers lispp))
10278 t t form)))
10279 ;; Insert simple ranges
10280 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10281 (setq form
10282 (replace-match
10283 (save-match-data
10284 (org-table-make-reference
10285 (org-sublist
10286 fields (string-to-number (match-string 1 form))
10287 (string-to-number (match-string 2 form)))
10288 keep-empty numbers lispp))
10289 t t form)))
10290 (setq form0 form)
10291 ;; Insert the references to fields in same row
10292 (while (string-match "\\$\\([0-9]+\\)" form)
10293 (setq n (string-to-number (match-string 1 form))
10294 x (nth (1- (if (= n 0) n0 n)) fields))
10295 (unless x (error "Invalid field specifier \"%s\""
10296 (match-string 0 form)))
10297 (setq form (replace-match
10298 (save-match-data
10299 (org-table-make-reference x nil numbers lispp))
10300 t t form)))
10302 (if lispp
10303 (setq ev (condition-case nil
10304 (eval (eval (read form)))
10305 (error "#ERROR"))
10306 ev (if (numberp ev) (number-to-string ev) ev))
10307 (or (fboundp 'calc-eval)
10308 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10309 (setq ev (calc-eval (cons form modes)
10310 (if numbers 'num))))
10312 (when org-table-formula-debug
10313 (with-output-to-temp-buffer "*Substitution History*"
10314 (princ (format "Substitution history of formula
10315 Orig: %s
10316 $xyz-> %s
10317 @r$c-> %s
10318 $1-> %s\n" orig formula form0 form))
10319 (if (listp ev)
10320 (princ (format " %s^\nError: %s"
10321 (make-string (car ev) ?\-) (nth 1 ev)))
10322 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10323 ev (or fmt "NONE")
10324 (if fmt (format fmt (string-to-number ev)) ev)))))
10325 (setq bw (get-buffer-window "*Substitution History*"))
10326 (shrink-window-if-larger-than-buffer bw)
10327 (unless (and (interactive-p) (not ndown))
10328 (unless (let (inhibit-redisplay)
10329 (y-or-n-p "Debugging Formula. Continue to next? "))
10330 (org-table-align)
10331 (error "Abort"))
10332 (delete-window bw)
10333 (message "")))
10334 (if (listp ev) (setq fmt nil ev "#ERROR"))
10335 (org-table-justify-field-maybe
10336 (if fmt (format fmt (string-to-number ev)) ev))
10337 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10338 (call-interactively 'org-return)
10339 (setq ndown 0)))
10340 (and down (org-table-maybe-recalculate-line))
10341 (or suppress-align (and org-table-may-need-update
10342 (org-table-align))))))
10344 (defun org-table-put-field-property (prop value)
10345 (save-excursion
10346 (put-text-property (progn (skip-chars-backward "^|") (point))
10347 (progn (skip-chars-forward "^|") (point))
10348 prop value)))
10350 (defun org-table-get-range (desc &optional tbeg col highlight)
10351 "Get a calc vector from a column, accorting to descriptor DESC.
10352 Optional arguments TBEG and COL can give the beginning of the table and
10353 the current column, to avoid unnecessary parsing.
10354 HIGHLIGHT means, just highlight the range."
10355 (if (not (equal (string-to-char desc) ?@))
10356 (setq desc (concat "@" desc)))
10357 (save-excursion
10358 (or tbeg (setq tbeg (org-table-begin)))
10359 (or col (setq col (org-table-current-column)))
10360 (let ((thisline (org-current-line))
10361 beg end c1 c2 r1 r2 rangep tmp)
10362 (unless (string-match org-table-range-regexp desc)
10363 (error "Invalid table range specifier `%s'" desc))
10364 (setq rangep (match-end 3)
10365 r1 (and (match-end 1) (match-string 1 desc))
10366 r2 (and (match-end 4) (match-string 4 desc))
10367 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10368 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10370 (and c1 (setq c1 (+ (string-to-number c1)
10371 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10372 (and c2 (setq c2 (+ (string-to-number c2)
10373 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10374 (if (equal r1 "") (setq r1 nil))
10375 (if (equal r2 "") (setq r2 nil))
10376 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10377 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10378 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10379 (if (not r1) (setq r1 thisline))
10380 (if (not r2) (setq r2 thisline))
10381 (if (not c1) (setq c1 col))
10382 (if (not c2) (setq c2 col))
10383 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10384 ;; just one field
10385 (progn
10386 (goto-line r1)
10387 (while (not (looking-at org-table-dataline-regexp))
10388 (beginning-of-line 2))
10389 (prog1 (org-trim (org-table-get-field c1))
10390 (if highlight (org-table-highlight-rectangle (point) (point)))))
10391 ;; A range, return a vector
10392 ;; First sort the numbers to get a regular ractangle
10393 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10394 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10395 (goto-line r1)
10396 (while (not (looking-at org-table-dataline-regexp))
10397 (beginning-of-line 2))
10398 (org-table-goto-column c1)
10399 (setq beg (point))
10400 (goto-line r2)
10401 (while (not (looking-at org-table-dataline-regexp))
10402 (beginning-of-line 0))
10403 (org-table-goto-column c2)
10404 (setq end (point))
10405 (if highlight
10406 (org-table-highlight-rectangle
10407 beg (progn (skip-chars-forward "^|\n") (point))))
10408 ;; return string representation of calc vector
10409 (mapcar 'org-trim
10410 (apply 'append (org-table-copy-region beg end)))))))
10412 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10413 "Analyze descriptor DESC and retrieve the corresponding line number.
10414 The cursor is currently in line CLINE, the table begins in line BLINE,
10415 and TABLE is a vector with line types."
10416 (if (string-match "^[0-9]+$" desc)
10417 (aref org-table-dlines (string-to-number desc))
10418 (setq cline (or cline (org-current-line))
10419 bline (or bline org-table-current-begin-line)
10420 table (or table org-table-current-line-types))
10421 (if (or
10422 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10423 ;; 1 2 3 4 5 6
10424 (and (not (match-end 3)) (not (match-end 6)))
10425 (and (match-end 3) (match-end 6) (not (match-end 5))))
10426 (error "invalid row descriptor `%s'" desc))
10427 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10428 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10429 (odir (and (match-end 5) (match-string 5 desc)))
10430 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10431 (i (- cline bline))
10432 (rel (and (match-end 6)
10433 (or (and (match-end 1) (not (match-end 3)))
10434 (match-end 5)))))
10435 (if (and hn (not hdir))
10436 (progn
10437 (setq i 0 hdir "+")
10438 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10439 (if (and (not hn) on (not odir))
10440 (error "should never happen");;(aref org-table-dlines on)
10441 (if (and hn (> hn 0))
10442 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10443 (if on
10444 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10445 (+ bline i)))))
10447 (defun org-find-row-type (table i type backwards relative n)
10448 (let ((l (length table)))
10449 (while (> n 0)
10450 (while (and (setq i (+ i (if backwards -1 1)))
10451 (>= i 0) (< i l)
10452 (not (eq (aref table i) type))
10453 (if (and relative (eq (aref table i) 'hline))
10454 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10455 t)))
10456 (setq n (1- n)))
10457 (if (or (< i 0) (>= i l))
10458 (error "Row descriptior leads outside table")
10459 i)))
10461 (defun org-rewrite-old-row-references (s)
10462 (if (string-match "&[-+0-9I]" s)
10463 (error "Formula contains old &row reference, please rewrite using @-syntax")
10466 (defun org-table-make-reference (elements keep-empty numbers lispp)
10467 "Convert list ELEMENTS to something appropriate to insert into formula.
10468 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10469 NUMBERS indicates that everything should be converted to numbers.
10470 LISPP means to return something appropriate for a Lisp list."
10471 (if (stringp elements) ; just a single val
10472 (if lispp
10473 (if (eq lispp 'literal)
10474 elements
10475 (prin1-to-string (if numbers (string-to-number elements) elements)))
10476 (if (equal elements "") (setq elements "0"))
10477 (if numbers (number-to-string (string-to-number elements)) elements))
10478 (unless keep-empty
10479 (setq elements
10480 (delq nil
10481 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10482 elements))))
10483 (setq elements (or elements '("0")))
10484 (if lispp
10485 (mapconcat
10486 (lambda (x)
10487 (if (eq lispp 'literal)
10489 (prin1-to-string (if numbers (string-to-number x) x))))
10490 elements " ")
10491 (concat "[" (mapconcat
10492 (lambda (x)
10493 (if numbers (number-to-string (string-to-number x)) x))
10494 elements
10495 ",") "]"))))
10497 (defun org-table-recalculate (&optional all noalign)
10498 "Recalculate the current table line by applying all stored formulas.
10499 With prefix arg ALL, do this for all lines in the table."
10500 (interactive "P")
10501 (or (memq this-command org-recalc-commands)
10502 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10503 (unless (org-at-table-p) (error "Not at a table"))
10504 (if (equal all '(16))
10505 (org-table-iterate)
10506 (org-table-get-specials)
10507 (let* ((eqlist (sort (org-table-get-stored-formulas)
10508 (lambda (a b) (string< (car a) (car b)))))
10509 (inhibit-redisplay (not debug-on-error))
10510 (line-re org-table-dataline-regexp)
10511 (thisline (org-current-line))
10512 (thiscol (org-table-current-column))
10513 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10514 ;; Insert constants in all formulas
10515 (setq eqlist
10516 (mapcar (lambda (x)
10517 (setcdr x (org-table-formula-substitute-names (cdr x)))
10519 eqlist))
10520 ;; Split the equation list
10521 (while (setq eq (pop eqlist))
10522 (if (<= (string-to-char (car eq)) ?9)
10523 (push eq eqlnum)
10524 (push eq eqlname)))
10525 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10526 (if all
10527 (progn
10528 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10529 (goto-char (setq beg (org-table-begin)))
10530 (if (re-search-forward org-table-calculate-mark-regexp end t)
10531 ;; This is a table with marked lines, compute selected lines
10532 (setq line-re org-table-recalculate-regexp)
10533 ;; Move forward to the first non-header line
10534 (if (and (re-search-forward org-table-dataline-regexp end t)
10535 (re-search-forward org-table-hline-regexp end t)
10536 (re-search-forward org-table-dataline-regexp end t))
10537 (setq beg (match-beginning 0))
10538 nil))) ;; just leave beg where it is
10539 (setq beg (point-at-bol)
10540 end (move-marker (make-marker) (1+ (point-at-eol)))))
10541 (goto-char beg)
10542 (and all (message "Re-applying formulas to full table..."))
10544 ;; First find the named fields, and mark them untouchanble
10545 (remove-text-properties beg end '(org-untouchable t))
10546 (while (setq eq (pop eqlname))
10547 (setq name (car eq)
10548 a (assoc name org-table-named-field-locations))
10549 (and (not a)
10550 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10551 (setq a (list name
10552 (aref org-table-dlines
10553 (string-to-number (match-string 1 name)))
10554 (string-to-number (match-string 2 name)))))
10555 (when (and a (or all (equal (nth 1 a) thisline)))
10556 (message "Re-applying formula to field: %s" name)
10557 (goto-line (nth 1 a))
10558 (org-table-goto-column (nth 2 a))
10559 (push (append a (list (cdr eq))) eqlname1)
10560 (org-table-put-field-property :org-untouchable t)))
10562 ;; Now evauluate the column formulas, but skip fields covered by
10563 ;; field formulas
10564 (goto-char beg)
10565 (while (re-search-forward line-re end t)
10566 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10567 ;; Unprotected line, recalculate
10568 (and all (message "Re-applying formulas to full table...(line %d)"
10569 (setq cnt (1+ cnt))))
10570 (setq org-last-recalc-line (org-current-line))
10571 (setq eql eqlnum)
10572 (while (setq entry (pop eql))
10573 (goto-line org-last-recalc-line)
10574 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10575 (unless (get-text-property (point) :org-untouchable)
10576 (org-table-eval-formula nil (cdr entry)
10577 'noalign 'nocst 'nostore 'noanalysis)))))
10579 ;; Now evaluate the field formulas
10580 (while (setq eq (pop eqlname1))
10581 (message "Re-applying formula to field: %s" (car eq))
10582 (goto-line (nth 1 eq))
10583 (org-table-goto-column (nth 2 eq))
10584 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10585 'nostore 'noanalysis))
10587 (goto-line thisline)
10588 (org-table-goto-column thiscol)
10589 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10590 (or noalign (and org-table-may-need-update (org-table-align))
10591 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10593 ;; back to initial position
10594 (message "Re-applying formulas...done")
10595 (goto-line thisline)
10596 (org-table-goto-column thiscol)
10597 (or noalign (and org-table-may-need-update (org-table-align))
10598 (and all (message "Re-applying formulas...done"))))))
10600 (defun org-table-iterate (&optional arg)
10601 "Recalculate the table until it does not change anymore."
10602 (interactive "P")
10603 (let ((imax (if arg (prefix-numeric-value arg) 10))
10604 (i 0)
10605 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10606 thistbl)
10607 (catch 'exit
10608 (while (< i imax)
10609 (setq i (1+ i))
10610 (org-table-recalculate 'all)
10611 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10612 (if (not (string= lasttbl thistbl))
10613 (setq lasttbl thistbl)
10614 (if (> i 1)
10615 (message "Convergence after %d iterations" i)
10616 (message "Table was already stable"))
10617 (throw 'exit t)))
10618 (error "No convergence after %d iterations" i))))
10620 (defun org-table-formula-substitute-names (f)
10621 "Replace $const with values in string F."
10622 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10623 ;; First, check for column names
10624 (while (setq start (string-match org-table-column-name-regexp f start))
10625 (setq start (1+ start))
10626 (setq a (assoc (match-string 1 f) org-table-column-names))
10627 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10628 ;; Parameters and constants
10629 (setq start 0)
10630 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10631 (setq start (1+ start))
10632 (if (setq a (save-match-data
10633 (org-table-get-constant (match-string 1 f))))
10634 (setq f (replace-match
10635 (concat (if pp "(") a (if pp ")")) t t f))))
10636 (if org-table-formula-debug
10637 (put-text-property 0 (length f) :orig-formula f1 f))
10640 (defun org-table-get-constant (const)
10641 "Find the value for a parameter or constant in a formula.
10642 Parameters get priority."
10643 (or (cdr (assoc const org-table-local-parameters))
10644 (cdr (assoc const org-table-formula-constants-local))
10645 (cdr (assoc const org-table-formula-constants))
10646 (and (fboundp 'constants-get) (constants-get const))
10647 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10648 (org-entry-get nil (substring const 5) 'inherit))
10649 "#UNDEFINED_NAME"))
10651 (defvar org-table-fedit-map
10652 (let ((map (make-sparse-keymap)))
10653 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10654 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10655 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10656 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10657 (org-defkey map "\C-c?" 'org-table-show-reference)
10658 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10659 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10660 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10661 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10662 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10663 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10664 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10665 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10666 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10667 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10668 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10669 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10670 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10671 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10672 map))
10674 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10675 '("Edit-Formulas"
10676 ["Finish and Install" org-table-fedit-finish t]
10677 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10678 ["Abort" org-table-fedit-abort t]
10679 "--"
10680 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10681 ["Complete Lisp Symbol" lisp-complete-symbol t]
10682 "--"
10683 "Shift Reference at Point"
10684 ["Up" org-table-fedit-ref-up t]
10685 ["Down" org-table-fedit-ref-down t]
10686 ["Left" org-table-fedit-ref-left t]
10687 ["Right" org-table-fedit-ref-right t]
10689 "Change Test Row for Column Formulas"
10690 ["Up" org-table-fedit-line-up t]
10691 ["Down" org-table-fedit-line-down t]
10692 "--"
10693 ["Scroll Table Window" org-table-fedit-scroll t]
10694 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10695 ["Show Table Grid" org-table-fedit-toggle-coordinates
10696 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10697 org-table-overlay-coordinates)]
10698 "--"
10699 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10700 :style toggle :selected org-table-buffer-is-an]))
10702 (defvar org-pos)
10704 (defun org-table-edit-formulas ()
10705 "Edit the formulas of the current table in a separate buffer."
10706 (interactive)
10707 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10708 (beginning-of-line 0))
10709 (unless (org-at-table-p) (error "Not at a table"))
10710 (org-table-get-specials)
10711 (let ((key (org-table-current-field-formula 'key 'noerror))
10712 (eql (sort (org-table-get-stored-formulas 'noerror)
10713 'org-table-formula-less-p))
10714 (pos (move-marker (make-marker) (point)))
10715 (startline 1)
10716 (wc (current-window-configuration))
10717 (titles '((column . "# Column Formulas\n")
10718 (field . "# Field Formulas\n")
10719 (named . "# Named Field Formulas\n")))
10720 entry s type title)
10721 (org-switch-to-buffer-other-window "*Edit Formulas*")
10722 (erase-buffer)
10723 ;; Keep global-font-lock-mode from turning on font-lock-mode
10724 (let ((font-lock-global-modes '(not fundamental-mode)))
10725 (fundamental-mode))
10726 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10727 (org-set-local 'org-pos pos)
10728 (org-set-local 'org-window-configuration wc)
10729 (use-local-map org-table-fedit-map)
10730 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10731 (easy-menu-add org-table-fedit-menu)
10732 (setq startline (org-current-line))
10733 (while (setq entry (pop eql))
10734 (setq type (cond
10735 ((equal (string-to-char (car entry)) ?@) 'field)
10736 ((string-match "^[0-9]" (car entry)) 'column)
10737 (t 'named)))
10738 (when (setq title (assq type titles))
10739 (or (bobp) (insert "\n"))
10740 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10741 (setq titles (delq title titles)))
10742 (if (equal key (car entry)) (setq startline (org-current-line)))
10743 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10744 (car entry) " = " (cdr entry) "\n"))
10745 (remove-text-properties 0 (length s) '(face nil) s)
10746 (insert s))
10747 (if (eq org-table-use-standard-references t)
10748 (org-table-fedit-toggle-ref-type))
10749 (goto-line startline)
10750 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10752 (defun org-table-fedit-post-command ()
10753 (when (not (memq this-command '(lisp-complete-symbol)))
10754 (let ((win (selected-window)))
10755 (save-excursion
10756 (condition-case nil
10757 (org-table-show-reference)
10758 (error nil))
10759 (select-window win)))))
10761 (defun org-table-formula-to-user (s)
10762 "Convert a formula from internal to user representation."
10763 (if (eq org-table-use-standard-references t)
10764 (org-table-convert-refs-to-an s)
10767 (defun org-table-formula-from-user (s)
10768 "Convert a formula from user to internal representation."
10769 (if org-table-use-standard-references
10770 (org-table-convert-refs-to-rc s)
10773 (defun org-table-convert-refs-to-rc (s)
10774 "Convert spreadsheet references from AB7 to @7$28.
10775 Works for single references, but also for entire formulas and even the
10776 full TBLFM line."
10777 (let ((start 0))
10778 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10779 (cond
10780 ((match-end 3)
10781 ;; format match, just advance
10782 (setq start (match-end 0)))
10783 ((and (> (match-beginning 0) 0)
10784 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10785 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10786 ;; 3.e5 or something like this.
10787 (setq start (match-end 0)))
10789 (setq start (match-beginning 0)
10790 s (replace-match
10791 (if (equal (match-string 2 s) "&")
10792 (format "$%d" (org-letters-to-number (match-string 1 s)))
10793 (format "@%d$%d"
10794 (string-to-number (match-string 2 s))
10795 (org-letters-to-number (match-string 1 s))))
10796 t t s)))))
10799 (defun org-table-convert-refs-to-an (s)
10800 "Convert spreadsheet references from to @7$28 to AB7.
10801 Works for single references, but also for entire formulas and even the
10802 full TBLFM line."
10803 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10804 (setq s (replace-match
10805 (format "%s%d"
10806 (org-number-to-letters
10807 (string-to-number (match-string 2 s)))
10808 (string-to-number (match-string 1 s)))
10809 t t s)))
10810 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10811 (setq s (replace-match (concat "\\1"
10812 (org-number-to-letters
10813 (string-to-number (match-string 2 s))) "&")
10814 t nil s)))
10817 (defun org-letters-to-number (s)
10818 "Convert a base 26 number represented by letters into an integer.
10819 For example: AB -> 28."
10820 (let ((n 0))
10821 (setq s (upcase s))
10822 (while (> (length s) 0)
10823 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10824 s (substring s 1)))
10827 (defun org-number-to-letters (n)
10828 "Convert an integer into a base 26 number represented by letters.
10829 For example: 28 -> AB."
10830 (let ((s ""))
10831 (while (> n 0)
10832 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10833 n (/ (1- n) 26)))
10836 (defun org-table-fedit-convert-buffer (function)
10837 "Convert all references in this buffer, using FUNTION."
10838 (let ((line (org-current-line)))
10839 (goto-char (point-min))
10840 (while (not (eobp))
10841 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10842 (delete-region (point) (point-at-eol))
10843 (or (eobp) (forward-char 1)))
10844 (goto-line line)))
10846 (defun org-table-fedit-toggle-ref-type ()
10847 "Convert all references in the buffer from B3 to @3$2 and back."
10848 (interactive)
10849 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10850 (org-table-fedit-convert-buffer
10851 (if org-table-buffer-is-an
10852 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10853 (message "Reference type switched to %s"
10854 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10856 (defun org-table-fedit-ref-up ()
10857 "Shift the reference at point one row/hline up."
10858 (interactive)
10859 (org-table-fedit-shift-reference 'up))
10860 (defun org-table-fedit-ref-down ()
10861 "Shift the reference at point one row/hline down."
10862 (interactive)
10863 (org-table-fedit-shift-reference 'down))
10864 (defun org-table-fedit-ref-left ()
10865 "Shift the reference at point one field to the left."
10866 (interactive)
10867 (org-table-fedit-shift-reference 'left))
10868 (defun org-table-fedit-ref-right ()
10869 "Shift the reference at point one field to the right."
10870 (interactive)
10871 (org-table-fedit-shift-reference 'right))
10873 (defun org-table-fedit-shift-reference (dir)
10874 (cond
10875 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10876 (if (memq dir '(left right))
10877 (org-rematch-and-replace 1 (eq dir 'left))
10878 (error "Cannot shift reference in this direction")))
10879 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10880 ;; A B3-like reference
10881 (if (memq dir '(up down))
10882 (org-rematch-and-replace 2 (eq dir 'up))
10883 (org-rematch-and-replace 1 (eq dir 'left))))
10884 ((org-at-regexp-p
10885 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10886 ;; An internal reference
10887 (if (memq dir '(up down))
10888 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10889 (org-rematch-and-replace 5 (eq dir 'left))))))
10891 (defun org-rematch-and-replace (n &optional decr hline)
10892 "Re-match the group N, and replace it with the shifted refrence."
10893 (or (match-end n) (error "Cannot shift reference in this direction"))
10894 (goto-char (match-beginning n))
10895 (and (looking-at (regexp-quote (match-string n)))
10896 (replace-match (org-shift-refpart (match-string 0) decr hline)
10897 t t)))
10899 (defun org-shift-refpart (ref &optional decr hline)
10900 "Shift a refrence part REF.
10901 If DECR is set, decrease the references row/column, else increase.
10902 If HLINE is set, this may be a hline reference, it certainly is not
10903 a translation reference."
10904 (save-match-data
10905 (let* ((sign (string-match "^[-+]" ref)) n)
10907 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10908 (cond
10909 ((and hline (string-match "^I+" ref))
10910 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10911 (setq n (+ n (if decr -1 1)))
10912 (if (= n 0) (setq n (+ n (if decr -1 1))))
10913 (if sign
10914 (setq sign (if (< n 0) "-" "+") n (abs n))
10915 (setq n (max 1 n)))
10916 (concat sign (make-string n ?I)))
10918 ((string-match "^[0-9]+" ref)
10919 (setq n (string-to-number (concat sign ref)))
10920 (setq n (+ n (if decr -1 1)))
10921 (if sign
10922 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10923 (number-to-string (max 1 n))))
10925 ((string-match "^[a-zA-Z]+" ref)
10926 (org-number-to-letters
10927 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10929 (t (error "Cannot shift reference"))))))
10931 (defun org-table-fedit-toggle-coordinates ()
10932 "Toggle the display of coordinates in the refrenced table."
10933 (interactive)
10934 (let ((pos (marker-position org-pos)))
10935 (with-current-buffer (marker-buffer org-pos)
10936 (save-excursion
10937 (goto-char pos)
10938 (org-table-toggle-coordinate-overlays)))))
10940 (defun org-table-fedit-finish (&optional arg)
10941 "Parse the buffer for formula definitions and install them.
10942 With prefix ARG, apply the new formulas to the table."
10943 (interactive "P")
10944 (org-table-remove-rectangle-highlight)
10945 (if org-table-use-standard-references
10946 (progn
10947 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10948 (setq org-table-buffer-is-an nil)))
10949 (let ((pos org-pos) eql var form)
10950 (goto-char (point-min))
10951 (while (re-search-forward
10952 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10953 nil t)
10954 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10955 form (match-string 3))
10956 (setq form (org-trim form))
10957 (when (not (equal form ""))
10958 (while (string-match "[ \t]*\n[ \t]*" form)
10959 (setq form (replace-match " " t t form)))
10960 (when (assoc var eql)
10961 (error "Double formulas for %s" var))
10962 (push (cons var form) eql)))
10963 (setq org-pos nil)
10964 (set-window-configuration org-window-configuration)
10965 (select-window (get-buffer-window (marker-buffer pos)))
10966 (goto-char pos)
10967 (unless (org-at-table-p)
10968 (error "Lost table position - cannot install formulae"))
10969 (org-table-store-formulas eql)
10970 (move-marker pos nil)
10971 (kill-buffer "*Edit Formulas*")
10972 (if arg
10973 (org-table-recalculate 'all)
10974 (message "New formulas installed - press C-u C-c C-c to apply."))))
10976 (defun org-table-fedit-abort ()
10977 "Abort editing formulas, without installing the changes."
10978 (interactive)
10979 (org-table-remove-rectangle-highlight)
10980 (let ((pos org-pos))
10981 (set-window-configuration org-window-configuration)
10982 (select-window (get-buffer-window (marker-buffer pos)))
10983 (goto-char pos)
10984 (move-marker pos nil)
10985 (message "Formula editing aborted without installing changes")))
10987 (defun org-table-fedit-lisp-indent ()
10988 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10989 (interactive)
10990 (let ((pos (point)) beg end ind)
10991 (beginning-of-line 1)
10992 (cond
10993 ((looking-at "[ \t]")
10994 (goto-char pos)
10995 (call-interactively 'lisp-indent-line))
10996 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10997 ((not (fboundp 'pp-buffer))
10998 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10999 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
11000 (goto-char (- (match-end 0) 2))
11001 (setq beg (point))
11002 (setq ind (make-string (current-column) ?\ ))
11003 (condition-case nil (forward-sexp 1)
11004 (error
11005 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
11006 (setq end (point))
11007 (save-restriction
11008 (narrow-to-region beg end)
11009 (if (eq last-command this-command)
11010 (progn
11011 (goto-char (point-min))
11012 (setq this-command nil)
11013 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
11014 (replace-match " ")))
11015 (pp-buffer)
11016 (untabify (point-min) (point-max))
11017 (goto-char (1+ (point-min)))
11018 (while (re-search-forward "^." nil t)
11019 (beginning-of-line 1)
11020 (insert ind))
11021 (goto-char (point-max))
11022 (backward-delete-char 1)))
11023 (goto-char beg))
11024 (t nil))))
11026 (defvar org-show-positions nil)
11028 (defun org-table-show-reference (&optional local)
11029 "Show the location/value of the $ expression at point."
11030 (interactive)
11031 (org-table-remove-rectangle-highlight)
11032 (catch 'exit
11033 (let ((pos (if local (point) org-pos))
11034 (face2 'highlight)
11035 (org-inhibit-highlight-removal t)
11036 (win (selected-window))
11037 (org-show-positions nil)
11038 var name e what match dest)
11039 (if local (org-table-get-specials))
11040 (setq what (cond
11041 ((or (org-at-regexp-p org-table-range-regexp2)
11042 (org-at-regexp-p org-table-translate-regexp)
11043 (org-at-regexp-p org-table-range-regexp))
11044 (setq match
11045 (save-match-data
11046 (org-table-convert-refs-to-rc (match-string 0))))
11047 'range)
11048 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11049 ((org-at-regexp-p "\\$[0-9]+") 'column)
11050 ((not local) nil)
11051 (t (error "No reference at point")))
11052 match (and what (or match (match-string 0))))
11053 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11054 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11055 'secondary-selection))
11056 (org-add-hook 'before-change-functions
11057 'org-table-remove-rectangle-highlight)
11058 (if (eq what 'name) (setq var (substring match 1)))
11059 (when (eq what 'range)
11060 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11061 (setq match (org-table-formula-substitute-names match)))
11062 (unless local
11063 (save-excursion
11064 (end-of-line 1)
11065 (re-search-backward "^\\S-" nil t)
11066 (beginning-of-line 1)
11067 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11068 (setq dest
11069 (save-match-data
11070 (org-table-convert-refs-to-rc (match-string 1))))
11071 (org-table-add-rectangle-overlay
11072 (match-beginning 1) (match-end 1) face2))))
11073 (if (and (markerp pos) (marker-buffer pos))
11074 (if (get-buffer-window (marker-buffer pos))
11075 (select-window (get-buffer-window (marker-buffer pos)))
11076 (org-switch-to-buffer-other-window (get-buffer-window
11077 (marker-buffer pos)))))
11078 (goto-char pos)
11079 (org-table-force-dataline)
11080 (when dest
11081 (setq name (substring dest 1))
11082 (cond
11083 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11084 (setq e (assoc name org-table-named-field-locations))
11085 (goto-line (nth 1 e))
11086 (org-table-goto-column (nth 2 e)))
11087 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11088 (let ((l (string-to-number (match-string 1 dest)))
11089 (c (string-to-number (match-string 2 dest))))
11090 (goto-line (aref org-table-dlines l))
11091 (org-table-goto-column c)))
11092 (t (org-table-goto-column (string-to-number name))))
11093 (move-marker pos (point))
11094 (org-table-highlight-rectangle nil nil face2))
11095 (cond
11096 ((equal dest match))
11097 ((not match))
11098 ((eq what 'range)
11099 (condition-case nil
11100 (save-excursion
11101 (org-table-get-range match nil nil 'highlight))
11102 (error nil)))
11103 ((setq e (assoc var org-table-named-field-locations))
11104 (goto-line (nth 1 e))
11105 (org-table-goto-column (nth 2 e))
11106 (org-table-highlight-rectangle (point) (point))
11107 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11108 ((setq e (assoc var org-table-column-names))
11109 (org-table-goto-column (string-to-number (cdr e)))
11110 (org-table-highlight-rectangle (point) (point))
11111 (goto-char (org-table-begin))
11112 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11113 (org-table-end) t)
11114 (progn
11115 (goto-char (match-beginning 1))
11116 (org-table-highlight-rectangle)
11117 (message "Named column (column %s)" (cdr e)))
11118 (error "Column name not found")))
11119 ((eq what 'column)
11120 ;; column number
11121 (org-table-goto-column (string-to-number (substring match 1)))
11122 (org-table-highlight-rectangle (point) (point))
11123 (message "Column %s" (substring match 1)))
11124 ((setq e (assoc var org-table-local-parameters))
11125 (goto-char (org-table-begin))
11126 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11127 (progn
11128 (goto-char (match-beginning 1))
11129 (org-table-highlight-rectangle)
11130 (message "Local parameter."))
11131 (error "Parameter not found")))
11133 (cond
11134 ((not var) (error "No reference at point"))
11135 ((setq e (assoc var org-table-formula-constants-local))
11136 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11137 var (cdr e)))
11138 ((setq e (assoc var org-table-formula-constants))
11139 (message "Constant: $%s=%s in `org-table-formula-constants'."
11140 var (cdr e)))
11141 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11142 (message "Constant: $%s=%s, from `constants.el'%s."
11143 var e (format " (%s units)" constants-unit-system)))
11144 (t (error "Undefined name $%s" var)))))
11145 (goto-char pos)
11146 (when (and org-show-positions
11147 (not (memq this-command '(org-table-fedit-scroll
11148 org-table-fedit-scroll-down))))
11149 (push pos org-show-positions)
11150 (push org-table-current-begin-pos org-show-positions)
11151 (let ((min (apply 'min org-show-positions))
11152 (max (apply 'max org-show-positions)))
11153 (goto-char min) (recenter 0)
11154 (goto-char max)
11155 (or (pos-visible-in-window-p max) (recenter -1))))
11156 (select-window win))))
11158 (defun org-table-force-dataline ()
11159 "Make sure the cursor is in a dataline in a table."
11160 (unless (save-excursion
11161 (beginning-of-line 1)
11162 (looking-at org-table-dataline-regexp))
11163 (let* ((re org-table-dataline-regexp)
11164 (p1 (save-excursion (re-search-forward re nil 'move)))
11165 (p2 (save-excursion (re-search-backward re nil 'move))))
11166 (cond ((and p1 p2)
11167 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11168 p1 p2)))
11169 ((or p1 p2) (goto-char (or p1 p2)))
11170 (t (error "No table dataline around here"))))))
11172 (defun org-table-fedit-line-up ()
11173 "Move cursor one line up in the window showing the table."
11174 (interactive)
11175 (org-table-fedit-move 'previous-line))
11177 (defun org-table-fedit-line-down ()
11178 "Move cursor one line down in the window showing the table."
11179 (interactive)
11180 (org-table-fedit-move 'next-line))
11182 (defun org-table-fedit-move (command)
11183 "Move the cursor in the window shoinw the table.
11184 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11185 (let ((org-table-allow-automatic-line-recalculation nil)
11186 (pos org-pos) (win (selected-window)) p)
11187 (select-window (get-buffer-window (marker-buffer org-pos)))
11188 (setq p (point))
11189 (call-interactively command)
11190 (while (and (org-at-table-p)
11191 (org-at-table-hline-p))
11192 (call-interactively command))
11193 (or (org-at-table-p) (goto-char p))
11194 (move-marker pos (point))
11195 (select-window win)))
11197 (defun org-table-fedit-scroll (N)
11198 (interactive "p")
11199 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11200 (scroll-other-window N)))
11202 (defun org-table-fedit-scroll-down (N)
11203 (interactive "p")
11204 (org-table-fedit-scroll (- N)))
11206 (defvar org-table-rectangle-overlays nil)
11208 (defun org-table-add-rectangle-overlay (beg end &optional face)
11209 "Add a new overlay."
11210 (let ((ov (org-make-overlay beg end)))
11211 (org-overlay-put ov 'face (or face 'secondary-selection))
11212 (push ov org-table-rectangle-overlays)))
11214 (defun org-table-highlight-rectangle (&optional beg end face)
11215 "Highlight rectangular region in a table."
11216 (setq beg (or beg (point)) end (or end (point)))
11217 (let ((b (min beg end))
11218 (e (max beg end))
11219 l1 c1 l2 c2 tmp)
11220 (and (boundp 'org-show-positions)
11221 (setq org-show-positions (cons b (cons e org-show-positions))))
11222 (goto-char (min beg end))
11223 (setq l1 (org-current-line)
11224 c1 (org-table-current-column))
11225 (goto-char (max beg end))
11226 (setq l2 (org-current-line)
11227 c2 (org-table-current-column))
11228 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11229 (goto-line l1)
11230 (beginning-of-line 1)
11231 (loop for line from l1 to l2 do
11232 (when (looking-at org-table-dataline-regexp)
11233 (org-table-goto-column c1)
11234 (skip-chars-backward "^|\n") (setq beg (point))
11235 (org-table-goto-column c2)
11236 (skip-chars-forward "^|\n") (setq end (point))
11237 (org-table-add-rectangle-overlay beg end face))
11238 (beginning-of-line 2))
11239 (goto-char b))
11240 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11242 (defun org-table-remove-rectangle-highlight (&rest ignore)
11243 "Remove the rectangle overlays."
11244 (unless org-inhibit-highlight-removal
11245 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11246 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11247 (setq org-table-rectangle-overlays nil)))
11249 (defvar org-table-coordinate-overlays nil
11250 "Collects the cooordinate grid overlays, so that they can be removed.")
11251 (make-variable-buffer-local 'org-table-coordinate-overlays)
11253 (defun org-table-overlay-coordinates ()
11254 "Add overlays to the table at point, to show row/column coordinates."
11255 (interactive)
11256 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11257 (setq org-table-coordinate-overlays nil)
11258 (save-excursion
11259 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11260 (goto-char (org-table-begin))
11261 (while (org-at-table-p)
11262 (setq eol (point-at-eol))
11263 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11264 (push ov org-table-coordinate-overlays)
11265 (setq hline (looking-at org-table-hline-regexp))
11266 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11267 (format "%4d" (setq id (1+ id)))))
11268 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11269 (when hline
11270 (setq ic 0)
11271 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11272 (setq beg (1+ (match-beginning 0))
11273 ic (1+ ic)
11274 s1 (concat "$" (int-to-string ic))
11275 s2 (org-number-to-letters ic)
11276 str (if (eq org-table-use-standard-references t) s2 s1))
11277 (setq ov (org-make-overlay beg (+ beg (length str))))
11278 (push ov org-table-coordinate-overlays)
11279 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11280 (beginning-of-line 2)))))
11282 (defun org-table-toggle-coordinate-overlays ()
11283 "Toggle the display of Row/Column numbers in tables."
11284 (interactive)
11285 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11286 (message "Row/Column number display turned %s"
11287 (if org-table-overlay-coordinates "on" "off"))
11288 (if (and (org-at-table-p) org-table-overlay-coordinates)
11289 (org-table-align))
11290 (unless org-table-overlay-coordinates
11291 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11292 (setq org-table-coordinate-overlays nil)))
11294 (defun org-table-toggle-formula-debugger ()
11295 "Toggle the formula debugger in tables."
11296 (interactive)
11297 (setq org-table-formula-debug (not org-table-formula-debug))
11298 (message "Formula debugging has been turned %s"
11299 (if org-table-formula-debug "on" "off")))
11301 ;;; The orgtbl minor mode
11303 ;; Define a minor mode which can be used in other modes in order to
11304 ;; integrate the org-mode table editor.
11306 ;; This is really a hack, because the org-mode table editor uses several
11307 ;; keys which normally belong to the major mode, for example the TAB and
11308 ;; RET keys. Here is how it works: The minor mode defines all the keys
11309 ;; necessary to operate the table editor, but wraps the commands into a
11310 ;; function which tests if the cursor is currently inside a table. If that
11311 ;; is the case, the table editor command is executed. However, when any of
11312 ;; those keys is used outside a table, the function uses `key-binding' to
11313 ;; look up if the key has an associated command in another currently active
11314 ;; keymap (minor modes, major mode, global), and executes that command.
11315 ;; There might be problems if any of the keys used by the table editor is
11316 ;; otherwise used as a prefix key.
11318 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11319 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11320 ;; addresses this by checking explicitly for both bindings.
11322 ;; The optimized version (see variable `orgtbl-optimized') takes over
11323 ;; all keys which are bound to `self-insert-command' in the *global map*.
11324 ;; Some modes bind other commands to simple characters, for example
11325 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11326 ;; active, this binding is ignored inside tables and replaced with a
11327 ;; modified self-insert.
11329 (defvar orgtbl-mode nil
11330 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11331 table editor in arbitrary modes.")
11332 (make-variable-buffer-local 'orgtbl-mode)
11334 (defvar orgtbl-mode-map (make-keymap)
11335 "Keymap for `orgtbl-mode'.")
11337 ;;;###autoload
11338 (defun turn-on-orgtbl ()
11339 "Unconditionally turn on `orgtbl-mode'."
11340 (orgtbl-mode 1))
11342 (defvar org-old-auto-fill-inhibit-regexp nil
11343 "Local variable used by `orgtbl-mode'")
11345 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11346 "Matches a line belonging to an orgtbl.")
11348 (defconst orgtbl-extra-font-lock-keywords
11349 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11350 0 (quote 'org-table) 'prepend))
11351 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11353 ;;;###autoload
11354 (defun orgtbl-mode (&optional arg)
11355 "The `org-mode' table editor as a minor mode for use in other modes."
11356 (interactive)
11357 (if (org-mode-p)
11358 ;; Exit without error, in case some hook functions calls this
11359 ;; by accident in org-mode.
11360 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11361 (setq orgtbl-mode
11362 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11363 (if orgtbl-mode
11364 (progn
11365 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11366 ;; Make sure we are first in minor-mode-map-alist
11367 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11368 (and c (setq minor-mode-map-alist
11369 (cons c (delq c minor-mode-map-alist)))))
11370 (org-set-local (quote org-table-may-need-update) t)
11371 (org-add-hook 'before-change-functions 'org-before-change-function
11372 nil 'local)
11373 (org-set-local 'org-old-auto-fill-inhibit-regexp
11374 auto-fill-inhibit-regexp)
11375 (org-set-local 'auto-fill-inhibit-regexp
11376 (if auto-fill-inhibit-regexp
11377 (concat orgtbl-line-start-regexp "\\|"
11378 auto-fill-inhibit-regexp)
11379 orgtbl-line-start-regexp))
11380 (org-add-to-invisibility-spec '(org-cwidth))
11381 (when (fboundp 'font-lock-add-keywords)
11382 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11383 (org-restart-font-lock))
11384 (easy-menu-add orgtbl-mode-menu)
11385 (run-hooks 'orgtbl-mode-hook))
11386 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11387 (org-cleanup-narrow-column-properties)
11388 (org-remove-from-invisibility-spec '(org-cwidth))
11389 (remove-hook 'before-change-functions 'org-before-change-function t)
11390 (when (fboundp 'font-lock-remove-keywords)
11391 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11392 (org-restart-font-lock))
11393 (easy-menu-remove orgtbl-mode-menu)
11394 (force-mode-line-update 'all))))
11396 (defun org-cleanup-narrow-column-properties ()
11397 "Remove all properties related to narrow-column invisibility."
11398 (let ((s 1))
11399 (while (setq s (text-property-any s (point-max)
11400 'display org-narrow-column-arrow))
11401 (remove-text-properties s (1+ s) '(display t)))
11402 (setq s 1)
11403 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11404 (remove-text-properties s (1+ s) '(org-cwidth t)))
11405 (setq s 1)
11406 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11407 (remove-text-properties s (1+ s) '(invisible t)))))
11409 ;; Install it as a minor mode.
11410 (put 'orgtbl-mode :included t)
11411 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11412 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11414 (defun orgtbl-make-binding (fun n &rest keys)
11415 "Create a function for binding in the table minor mode.
11416 FUN is the command to call inside a table. N is used to create a unique
11417 command name. KEYS are keys that should be checked in for a command
11418 to execute outside of tables."
11419 (eval
11420 (list 'defun
11421 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11422 '(arg)
11423 (concat "In tables, run `" (symbol-name fun) "'.\n"
11424 "Outside of tables, run the binding of `"
11425 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11426 "'.")
11427 '(interactive "p")
11428 (list 'if
11429 '(org-at-table-p)
11430 (list 'call-interactively (list 'quote fun))
11431 (list 'let '(orgtbl-mode)
11432 (list 'call-interactively
11433 (append '(or)
11434 (mapcar (lambda (k)
11435 (list 'key-binding k))
11436 keys)
11437 '('orgtbl-error))))))))
11439 (defun orgtbl-error ()
11440 "Error when there is no default binding for a table key."
11441 (interactive)
11442 (error "This key has no function outside tables"))
11444 (defun orgtbl-setup ()
11445 "Setup orgtbl keymaps."
11446 (let ((nfunc 0)
11447 (bindings
11448 (list
11449 '([(meta shift left)] org-table-delete-column)
11450 '([(meta left)] org-table-move-column-left)
11451 '([(meta right)] org-table-move-column-right)
11452 '([(meta shift right)] org-table-insert-column)
11453 '([(meta shift up)] org-table-kill-row)
11454 '([(meta shift down)] org-table-insert-row)
11455 '([(meta up)] org-table-move-row-up)
11456 '([(meta down)] org-table-move-row-down)
11457 '("\C-c\C-w" org-table-cut-region)
11458 '("\C-c\M-w" org-table-copy-region)
11459 '("\C-c\C-y" org-table-paste-rectangle)
11460 '("\C-c-" org-table-insert-hline)
11461 '("\C-c}" org-table-toggle-coordinate-overlays)
11462 '("\C-c{" org-table-toggle-formula-debugger)
11463 '("\C-m" org-table-next-row)
11464 '([(shift return)] org-table-copy-down)
11465 '("\C-c\C-q" org-table-wrap-region)
11466 '("\C-c?" org-table-field-info)
11467 '("\C-c " org-table-blank-field)
11468 '("\C-c+" org-table-sum)
11469 '("\C-c=" org-table-eval-formula)
11470 '("\C-c'" org-table-edit-formulas)
11471 '("\C-c`" org-table-edit-field)
11472 '("\C-c*" org-table-recalculate)
11473 '("\C-c|" org-table-create-or-convert-from-region)
11474 '("\C-c^" org-table-sort-lines)
11475 '([(control ?#)] org-table-rotate-recalc-marks)))
11476 elt key fun cmd)
11477 (while (setq elt (pop bindings))
11478 (setq nfunc (1+ nfunc))
11479 (setq key (org-key (car elt))
11480 fun (nth 1 elt)
11481 cmd (orgtbl-make-binding fun nfunc key))
11482 (org-defkey orgtbl-mode-map key cmd))
11484 ;; Special treatment needed for TAB and RET
11485 (org-defkey orgtbl-mode-map [(return)]
11486 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11487 (org-defkey orgtbl-mode-map "\C-m"
11488 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11490 (org-defkey orgtbl-mode-map [(tab)]
11491 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11492 (org-defkey orgtbl-mode-map "\C-i"
11493 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11495 (org-defkey orgtbl-mode-map [(shift tab)]
11496 (orgtbl-make-binding 'org-table-previous-field 104
11497 [(shift tab)] [(tab)] "\C-i"))
11499 (org-defkey orgtbl-mode-map "\M-\C-m"
11500 (orgtbl-make-binding 'org-table-wrap-region 105
11501 "\M-\C-m" [(meta return)]))
11502 (org-defkey orgtbl-mode-map [(meta return)]
11503 (orgtbl-make-binding 'org-table-wrap-region 106
11504 [(meta return)] "\M-\C-m"))
11506 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11507 (when orgtbl-optimized
11508 ;; If the user wants maximum table support, we need to hijack
11509 ;; some standard editing functions
11510 (org-remap orgtbl-mode-map
11511 'self-insert-command 'orgtbl-self-insert-command
11512 'delete-char 'org-delete-char
11513 'delete-backward-char 'org-delete-backward-char)
11514 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11515 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11516 '("OrgTbl"
11517 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11518 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11519 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11520 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11521 "--"
11522 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11523 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11524 ["Copy Field from Above"
11525 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11526 "--"
11527 ("Column"
11528 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11529 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11530 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11531 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11532 ("Row"
11533 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11534 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11535 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11536 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11537 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
11538 "--"
11539 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11540 ("Rectangle"
11541 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11542 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11543 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11544 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11545 "--"
11546 ("Radio tables"
11547 ["Insert table template" orgtbl-insert-radio-table
11548 (assq major-mode orgtbl-radio-table-templates)]
11549 ["Comment/uncomment table" orgtbl-toggle-comment t])
11550 "--"
11551 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11552 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11553 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11554 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11555 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11556 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11557 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11558 ["Sum Column/Rectangle" org-table-sum
11559 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11560 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11561 ["Debug Formulas"
11562 org-table-toggle-formula-debugger :active (org-at-table-p)
11563 :keys "C-c {"
11564 :style toggle :selected org-table-formula-debug]
11565 ["Show Col/Row Numbers"
11566 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11567 :keys "C-c }"
11568 :style toggle :selected org-table-overlay-coordinates]
11572 (defun orgtbl-ctrl-c-ctrl-c (arg)
11573 "If the cursor is inside a table, realign the table.
11574 It it is a table to be sent away to a receiver, do it.
11575 With prefix arg, also recompute table."
11576 (interactive "P")
11577 (let ((pos (point)) action)
11578 (save-excursion
11579 (beginning-of-line 1)
11580 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11581 ((looking-at "[ \t]*|") pos)
11582 ((looking-at "#\\+TBLFM:") 'recalc))))
11583 (cond
11584 ((integerp action)
11585 (goto-char action)
11586 (org-table-maybe-eval-formula)
11587 (if arg
11588 (call-interactively 'org-table-recalculate)
11589 (org-table-maybe-recalculate-line))
11590 (call-interactively 'org-table-align)
11591 (orgtbl-send-table 'maybe))
11592 ((eq action 'recalc)
11593 (save-excursion
11594 (beginning-of-line 1)
11595 (skip-chars-backward " \r\n\t")
11596 (if (org-at-table-p)
11597 (org-call-with-arg 'org-table-recalculate t))))
11598 (t (let (orgtbl-mode)
11599 (call-interactively (key-binding "\C-c\C-c")))))))
11601 (defun orgtbl-tab (arg)
11602 "Justification and field motion for `orgtbl-mode'."
11603 (interactive "P")
11604 (if arg (org-table-edit-field t)
11605 (org-table-justify-field-maybe)
11606 (org-table-next-field)))
11608 (defun orgtbl-ret ()
11609 "Justification and field motion for `orgtbl-mode'."
11610 (interactive)
11611 (org-table-justify-field-maybe)
11612 (org-table-next-row))
11614 (defun orgtbl-self-insert-command (N)
11615 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11616 If the cursor is in a table looking at whitespace, the whitespace is
11617 overwritten, and the table is not marked as requiring realignment."
11618 (interactive "p")
11619 (if (and (org-at-table-p)
11621 (and org-table-auto-blank-field
11622 (member last-command
11623 '(orgtbl-hijacker-command-100
11624 orgtbl-hijacker-command-101
11625 orgtbl-hijacker-command-102
11626 orgtbl-hijacker-command-103
11627 orgtbl-hijacker-command-104
11628 orgtbl-hijacker-command-105))
11629 (org-table-blank-field))
11631 (eq N 1)
11632 (looking-at "[^|\n]* +|"))
11633 (let (org-table-may-need-update)
11634 (goto-char (1- (match-end 0)))
11635 (delete-backward-char 1)
11636 (goto-char (match-beginning 0))
11637 (self-insert-command N))
11638 (setq org-table-may-need-update t)
11639 (let (orgtbl-mode)
11640 (call-interactively (key-binding (vector last-input-event))))))
11642 (defun org-force-self-insert (N)
11643 "Needed to enforce self-insert under remapping."
11644 (interactive "p")
11645 (self-insert-command N))
11647 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11648 "Regula expression matching exponentials as produced by calc.")
11650 (defvar org-table-clean-did-remove-column nil)
11652 (defun orgtbl-export (table target)
11653 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11654 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11655 org-table-last-alignment org-table-last-column-widths
11656 maxcol column)
11657 (if (not (fboundp func))
11658 (error "Cannot export orgtbl table to %s" target))
11659 (setq lines (org-table-clean-before-export lines))
11660 (setq table
11661 (mapcar
11662 (lambda (x)
11663 (if (string-match org-table-hline-regexp x)
11664 'hline
11665 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11666 lines))
11667 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11668 table)))
11669 (loop for i from (1- maxcol) downto 0 do
11670 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11671 (setq column (delq nil column))
11672 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11673 (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))
11674 (funcall func table nil)))
11676 (defun orgtbl-send-table (&optional maybe)
11677 "Send a tranformed version of this table to the receiver position.
11678 With argument MAYBE, fail quietly if no transformation is defined for
11679 this table."
11680 (interactive)
11681 (catch 'exit
11682 (unless (org-at-table-p) (error "Not at a table"))
11683 ;; when non-interactive, we assume align has just happened.
11684 (when (interactive-p) (org-table-align))
11685 (save-excursion
11686 (goto-char (org-table-begin))
11687 (beginning-of-line 0)
11688 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11689 (if maybe
11690 (throw 'exit nil)
11691 (error "Don't know how to transform this table."))))
11692 (let* ((name (match-string 1))
11694 (transform (intern (match-string 2)))
11695 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11696 (skip (plist-get params :skip))
11697 (skipcols (plist-get params :skipcols))
11698 (txt (buffer-substring-no-properties
11699 (org-table-begin) (org-table-end)))
11700 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11701 (lines (org-table-clean-before-export lines))
11702 (i0 (if org-table-clean-did-remove-column 2 1))
11703 (table (mapcar
11704 (lambda (x)
11705 (if (string-match org-table-hline-regexp x)
11706 'hline
11707 (org-remove-by-index
11708 (org-split-string (org-trim x) "\\s-*|\\s-*")
11709 skipcols i0)))
11710 lines))
11711 (fun (if (= i0 2) 'cdr 'identity))
11712 (org-table-last-alignment
11713 (org-remove-by-index (funcall fun org-table-last-alignment)
11714 skipcols i0))
11715 (org-table-last-column-widths
11716 (org-remove-by-index (funcall fun org-table-last-column-widths)
11717 skipcols i0)))
11719 (unless (fboundp transform)
11720 (error "No such transformation function %s" transform))
11721 (setq txt (funcall transform table params))
11722 ;; Find the insertion place
11723 (save-excursion
11724 (goto-char (point-min))
11725 (unless (re-search-forward
11726 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11727 (error "Don't know where to insert translated table"))
11728 (goto-char (match-beginning 0))
11729 (beginning-of-line 2)
11730 (setq beg (point))
11731 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11732 (error "Cannot find end of insertion region"))
11733 (beginning-of-line 1)
11734 (delete-region beg (point))
11735 (goto-char beg)
11736 (insert txt "\n"))
11737 (message "Table converted and installed at receiver location"))))
11739 (defun org-remove-by-index (list indices &optional i0)
11740 "Remove the elements in LIST with indices in INDICES.
11741 First element has index 0, or I0 if given."
11742 (if (not indices)
11743 list
11744 (if (integerp indices) (setq indices (list indices)))
11745 (setq i0 (1- (or i0 0)))
11746 (delq :rm (mapcar (lambda (x)
11747 (setq i0 (1+ i0))
11748 (if (memq i0 indices) :rm x))
11749 list))))
11751 (defun orgtbl-toggle-comment ()
11752 "Comment or uncomment the orgtbl at point."
11753 (interactive)
11754 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11755 (re2 (concat "^" orgtbl-line-start-regexp))
11756 (commented (save-excursion (beginning-of-line 1)
11757 (cond ((looking-at re1) t)
11758 ((looking-at re2) nil)
11759 (t (error "Not at an org table")))))
11760 (re (if commented re1 re2))
11761 beg end)
11762 (save-excursion
11763 (beginning-of-line 1)
11764 (while (looking-at re) (beginning-of-line 0))
11765 (beginning-of-line 2)
11766 (setq beg (point))
11767 (while (looking-at re) (beginning-of-line 2))
11768 (setq end (point)))
11769 (comment-region beg end (if commented '(4) nil))))
11771 (defun orgtbl-insert-radio-table ()
11772 "Insert a radio table template appropriate for this major mode."
11773 (interactive)
11774 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11775 (txt (nth 1 e))
11776 name pos)
11777 (unless e (error "No radio table setup defined for %s" major-mode))
11778 (setq name (read-string "Table name: "))
11779 (while (string-match "%n" txt)
11780 (setq txt (replace-match name t t txt)))
11781 (or (bolp) (insert "\n"))
11782 (setq pos (point))
11783 (insert txt)
11784 (goto-char pos)))
11786 (defun org-get-param (params header i sym &optional hsym)
11787 "Get parameter value for symbol SYM.
11788 If this is a header line, actually get the value for the symbol with an
11789 additional \"h\" inserted after the colon.
11790 If the value is a protperty list, get the element for the current column.
11791 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11792 (let ((val (plist-get params sym)))
11793 (and hsym header (setq val (or (plist-get params hsym) val)))
11794 (if (consp val) (plist-get val i) val)))
11796 (defun orgtbl-to-generic (table params)
11797 "Convert the orgtbl-mode TABLE to some other format.
11798 This generic routine can be used for many standard cases.
11799 TABLE is a list, each entry either the symbol `hline' for a horizontal
11800 separator line, or a list of fields for that line.
11801 PARAMS is a property list of parameters that can influence the conversion.
11802 For the generic converter, some parameters are obligatory: You need to
11803 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11804 :splice, you must have :tstart and :tend.
11806 Valid parameters are
11808 :tstart String to start the table. Ignored when :splice is t.
11809 :tend String to end the table. Ignored when :splice is t.
11811 :splice When set to t, return only table body lines, don't wrap
11812 them into :tstart and :tend. Default is nil.
11814 :hline String to be inserted on horizontal separation lines.
11815 May be nil to ignore hlines.
11817 :lstart String to start a new table line.
11818 :lend String to end a table line
11819 :sep Separator between two fields
11820 :lfmt Format for entire line, with enough %s to capture all fields.
11821 If this is present, :lstart, :lend, and :sep are ignored.
11822 :fmt A format to be used to wrap the field, should contain
11823 %s for the original field value. For example, to wrap
11824 everything in dollars, you could use :fmt \"$%s$\".
11825 This may also be a property list with column numbers and
11826 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11828 :hlstart :hlend :hlsep :hlfmt :hfmt
11829 Same as above, specific for the header lines in the table.
11830 All lines before the first hline are treated as header.
11831 If any of these is not present, the data line value is used.
11833 :efmt Use this format to print numbers with exponentials.
11834 The format should have %s twice for inserting mantissa
11835 and exponent, for example \"%s\\\\times10^{%s}\". This
11836 may also be a property list with column numbers and
11837 formats. :fmt will still be applied after :efmt.
11839 In addition to this, the parameters :skip and :skipcols are always handled
11840 directly by `orgtbl-send-table'. See manual."
11841 (interactive)
11842 (let* ((p params)
11843 (splicep (plist-get p :splice))
11844 (hline (plist-get p :hline))
11845 rtn line i fm efm lfmt h)
11847 ;; Do we have a header?
11848 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11849 (setq h t))
11851 ;; Put header
11852 (unless splicep
11853 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11855 ;; Now loop over all lines
11856 (while (setq line (pop table))
11857 (if (eq line 'hline)
11858 ;; A horizontal separator line
11859 (progn (if hline (push hline rtn))
11860 (setq h nil)) ; no longer in header
11861 ;; A normal line. Convert the fields, push line onto the result list
11862 (setq i 0)
11863 (setq line
11864 (mapcar
11865 (lambda (f)
11866 (setq i (1+ i)
11867 fm (org-get-param p h i :fmt :hfmt)
11868 efm (org-get-param p h i :efmt))
11869 (if (and efm (string-match orgtbl-exp-regexp f))
11870 (setq f (format
11871 efm (match-string 1 f) (match-string 2 f))))
11872 (if fm (setq f (format fm f)))
11874 line))
11875 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11876 (push (apply 'format lfmt line) rtn)
11877 (push (concat
11878 (org-get-param p h i :lstart :hlstart)
11879 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11880 (org-get-param p h i :lend :hlend))
11881 rtn))))
11883 (unless splicep
11884 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11886 (mapconcat 'identity (nreverse rtn) "\n")))
11888 (defun orgtbl-to-latex (table params)
11889 "Convert the orgtbl-mode TABLE to LaTeX.
11890 TABLE is a list, each entry either the symbol `hline' for a horizontal
11891 separator line, or a list of fields for that line.
11892 PARAMS is a property list of parameters that can influence the conversion.
11893 Supports all parameters from `orgtbl-to-generic'. Most important for
11894 LaTeX are:
11896 :splice When set to t, return only table body lines, don't wrap
11897 them into a tabular environment. Default is nil.
11899 :fmt A format to be used to wrap the field, should contain %s for the
11900 original field value. For example, to wrap everything in dollars,
11901 use :fmt \"$%s$\". This may also be a property list with column
11902 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11904 :efmt Format for transforming numbers with exponentials. The format
11905 should have %s twice for inserting mantissa and exponent, for
11906 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11907 This may also be a property list with column numbers and formats.
11909 The general parameters :skip and :skipcols have already been applied when
11910 this function is called."
11911 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11912 org-table-last-alignment ""))
11913 (params2
11914 (list
11915 :tstart (concat "\\begin{tabular}{" alignment "}")
11916 :tend "\\end{tabular}"
11917 :lstart "" :lend " \\\\" :sep " & "
11918 :efmt "%s\\,(%s)" :hline "\\hline")))
11919 (orgtbl-to-generic table (org-combine-plists params2 params))))
11921 (defun orgtbl-to-html (table params)
11922 "Convert the orgtbl-mode TABLE to LaTeX.
11923 TABLE is a list, each entry either the symbol `hline' for a horizontal
11924 separator line, or a list of fields for that line.
11925 PARAMS is a property list of parameters that can influence the conversion.
11926 Currently this function recognizes the following parameters:
11928 :splice When set to t, return only table body lines, don't wrap
11929 them into a <table> environment. Default is nil.
11931 The general parameters :skip and :skipcols have already been applied when
11932 this function is called. The function does *not* use `orgtbl-to-generic',
11933 so you cannot specify parameters for it."
11934 (let* ((splicep (plist-get params :splice))
11935 html)
11936 ;; Just call the formatter we already have
11937 ;; We need to make text lines for it, so put the fields back together.
11938 (setq html (org-format-org-table-html
11939 (mapcar
11940 (lambda (x)
11941 (if (eq x 'hline)
11942 "|----+----|"
11943 (concat "| " (mapconcat 'identity x " | ") " |")))
11944 table)
11945 splicep))
11946 (if (string-match "\n+\\'" html)
11947 (setq html (replace-match "" t t html)))
11948 html))
11950 (defun orgtbl-to-texinfo (table params)
11951 "Convert the orgtbl-mode TABLE to TeXInfo.
11952 TABLE is a list, each entry either the symbol `hline' for a horizontal
11953 separator line, or a list of fields for that line.
11954 PARAMS is a property list of parameters that can influence the conversion.
11955 Supports all parameters from `orgtbl-to-generic'. Most important for
11956 TeXInfo are:
11958 :splice nil/t When set to t, return only table body lines, don't wrap
11959 them into a multitable environment. Default is nil.
11961 :fmt fmt A format to be used to wrap the field, should contain
11962 %s for the original field value. For example, to wrap
11963 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11964 This may also be a property list with column numbers and
11965 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11967 :cf \"f1 f2..\" The column fractions for the table. By default these
11968 are computed automatically from the width of the columns
11969 under org-mode.
11971 The general parameters :skip and :skipcols have already been applied when
11972 this function is called."
11973 (let* ((total (float (apply '+ org-table-last-column-widths)))
11974 (colfrac (or (plist-get params :cf)
11975 (mapconcat
11976 (lambda (x) (format "%.3f" (/ (float x) total)))
11977 org-table-last-column-widths " ")))
11978 (params2
11979 (list
11980 :tstart (concat "@multitable @columnfractions " colfrac)
11981 :tend "@end multitable"
11982 :lstart "@item " :lend "" :sep " @tab "
11983 :hlstart "@headitem ")))
11984 (orgtbl-to-generic table (org-combine-plists params2 params))))
11986 ;;;; Link Stuff
11988 ;;; Link abbreviations
11990 (defun org-link-expand-abbrev (link)
11991 "Apply replacements as defined in `org-link-abbrev-alist."
11992 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11993 (let* ((key (match-string 1 link))
11994 (as (or (assoc key org-link-abbrev-alist-local)
11995 (assoc key org-link-abbrev-alist)))
11996 (tag (and (match-end 2) (match-string 3 link)))
11997 rpl)
11998 (if (not as)
11999 link
12000 (setq rpl (cdr as))
12001 (cond
12002 ((symbolp rpl) (funcall rpl tag))
12003 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
12004 (t (concat rpl tag)))))
12005 link))
12007 ;;; Storing and inserting links
12009 (defvar org-insert-link-history nil
12010 "Minibuffer history for links inserted with `org-insert-link'.")
12012 (defvar org-stored-links nil
12013 "Contains the links stored with `org-store-link'.")
12015 (defvar org-store-link-plist nil
12016 "Plist with info about the most recently link created with `org-store-link'.")
12018 (defvar org-link-protocols nil
12019 "Link protocols added to Org-mode using `org-add-link-type'.")
12021 (defvar org-store-link-functions nil
12022 "List of functions that are called to create and store a link.
12023 Each function will be called in turn until one returns a non-nil
12024 value. Each function should check if it is responsible for creating
12025 this link (for example by looking at the major mode).
12026 If not, it must exit and return nil.
12027 If yes, it should return a non-nil value after a calling
12028 `org-store-link-props' with a list of properties and values.
12029 Special properties are:
12031 :type The link prefix. like \"http\". This must be given.
12032 :link The link, like \"http://www.astro.uva.nl/~dominik\".
12033 This is obligatory as well.
12034 :description Optional default description for the second pair
12035 of brackets in an Org-mode link. The user can still change
12036 this when inserting this link into an Org-mode buffer.
12038 In addition to these, any additional properties can be specified
12039 and then used in remember templates.")
12041 (defun org-add-link-type (type &optional follow publish)
12042 "Add TYPE to the list of `org-link-types'.
12043 Re-compute all regular expressions depending on `org-link-types'
12044 FOLLOW and PUBLISH are two functions. Both take the link path as
12045 an argument.
12046 FOLLOW should do whatever is necessary to follow the link, for example
12047 to find a file or display a mail message.
12049 PUBLISH takes the path and retuns the string that should be used when
12050 this document is published. FIMXE: This is actually not yet implemented."
12051 (add-to-list 'org-link-types type t)
12052 (org-make-link-regexps)
12053 (add-to-list 'org-link-protocols
12054 (list type follow publish)))
12056 (defun org-add-agenda-custom-command (entry)
12057 "Replace or add a command in `org-agenda-custom-commands'.
12058 This is mostly for hacking and trying a new command - once the command
12059 works you probably want to add it to `org-agenda-custom-commands' for good."
12060 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12061 (if ass
12062 (setcdr ass (cdr entry))
12063 (push entry org-agenda-custom-commands))))
12065 ;;;###autoload
12066 (defun org-store-link (arg)
12067 "\\<org-mode-map>Store an org-link to the current location.
12068 This link is added to `org-stored-links' and can later be inserted
12069 into an org-buffer with \\[org-insert-link].
12071 For some link types, a prefix arg is interpreted:
12072 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12073 For file links, arg negates `org-context-in-file-links'."
12074 (interactive "P")
12075 (setq org-store-link-plist nil) ; reset
12076 (let (link cpltxt desc description search txt)
12077 (cond
12079 ((run-hook-with-args-until-success 'org-store-link-functions)
12080 (setq link (plist-get org-store-link-plist :link)
12081 desc (or (plist-get org-store-link-plist :description) link)))
12083 ((eq major-mode 'bbdb-mode)
12084 (let ((name (bbdb-record-name (bbdb-current-record)))
12085 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
12086 (setq cpltxt (concat "bbdb:" (or name company))
12087 link (org-make-link cpltxt))
12088 (org-store-link-props :type "bbdb" :name name :company company)))
12090 ((eq major-mode 'Info-mode)
12091 (setq link (org-make-link "info:"
12092 (file-name-nondirectory Info-current-file)
12093 ":" Info-current-node))
12094 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
12095 ":" Info-current-node))
12096 (org-store-link-props :type "info" :file Info-current-file
12097 :node Info-current-node))
12099 ((eq major-mode 'calendar-mode)
12100 (let ((cd (calendar-cursor-to-date)))
12101 (setq link
12102 (format-time-string
12103 (car org-time-stamp-formats)
12104 (apply 'encode-time
12105 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12106 nil nil nil))))
12107 (org-store-link-props :type "calendar" :date cd)))
12109 ((or (eq major-mode 'vm-summary-mode)
12110 (eq major-mode 'vm-presentation-mode))
12111 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
12112 (vm-follow-summary-cursor)
12113 (save-excursion
12114 (vm-select-folder-buffer)
12115 (let* ((message (car vm-message-pointer))
12116 (folder buffer-file-name)
12117 (subject (vm-su-subject message))
12118 (to (vm-get-header-contents message "To"))
12119 (from (vm-get-header-contents message "From"))
12120 (message-id (vm-su-message-id message)))
12121 (org-store-link-props :type "vm" :from from :to to :subject subject
12122 :message-id message-id)
12123 (setq message-id (org-remove-angle-brackets message-id))
12124 (setq folder (abbreviate-file-name folder))
12125 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
12126 folder)
12127 (setq folder (replace-match "" t t folder)))
12128 (setq cpltxt (org-email-link-description))
12129 (setq link (org-make-link "vm:" folder "#" message-id)))))
12131 ((eq major-mode 'wl-summary-mode)
12132 (let* ((msgnum (wl-summary-message-number))
12133 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
12134 msgnum 'message-id))
12135 (wl-message-entity
12136 (if (fboundp 'elmo-message-entity)
12137 (elmo-message-entity
12138 wl-summary-buffer-elmo-folder msgnum)
12139 (elmo-msgdb-overview-get-entity
12140 msgnum (wl-summary-buffer-msgdb))))
12141 (from (wl-summary-line-from))
12142 (to (car (elmo-message-entity-field wl-message-entity 'to)))
12143 (subject (let (wl-thr-indent-string wl-parent-message-entity)
12144 (wl-summary-line-subject))))
12145 (org-store-link-props :type "wl" :from from :to to
12146 :subject subject :message-id message-id)
12147 (setq message-id (org-remove-angle-brackets message-id))
12148 (setq cpltxt (org-email-link-description))
12149 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
12150 "#" message-id))))
12152 ((or (equal major-mode 'mh-folder-mode)
12153 (equal major-mode 'mh-show-mode))
12154 (let ((from (org-mhe-get-header "From:"))
12155 (to (org-mhe-get-header "To:"))
12156 (message-id (org-mhe-get-header "Message-Id:"))
12157 (subject (org-mhe-get-header "Subject:")))
12158 (org-store-link-props :type "mh" :from from :to to
12159 :subject subject :message-id message-id)
12160 (setq cpltxt (org-email-link-description))
12161 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
12162 (org-remove-angle-brackets message-id)))))
12164 ((or (eq major-mode 'rmail-mode)
12165 (eq major-mode 'rmail-summary-mode))
12166 (save-window-excursion
12167 (save-restriction
12168 (when (eq major-mode 'rmail-summary-mode)
12169 (rmail-show-message rmail-current-message))
12170 (rmail-narrow-to-non-pruned-header)
12171 (let ((folder buffer-file-name)
12172 (message-id (mail-fetch-field "message-id"))
12173 (from (mail-fetch-field "from"))
12174 (to (mail-fetch-field "to"))
12175 (subject (mail-fetch-field "subject")))
12176 (org-store-link-props
12177 :type "rmail" :from from :to to
12178 :subject subject :message-id message-id)
12179 (setq message-id (org-remove-angle-brackets message-id))
12180 (setq cpltxt (org-email-link-description))
12181 (setq link (org-make-link "rmail:" folder "#" message-id)))
12182 (rmail-show-message rmail-current-message))))
12184 ((eq major-mode 'gnus-group-mode)
12185 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12186 (gnus-group-group-name)) ; version
12187 ((fboundp 'gnus-group-name)
12188 (gnus-group-name))
12189 (t "???"))))
12190 (unless group (error "Not on a group"))
12191 (org-store-link-props :type "gnus" :group group)
12192 (setq cpltxt (concat
12193 (if (org-xor arg org-usenet-links-prefer-google)
12194 "http://groups.google.com/groups?group="
12195 "gnus:")
12196 group)
12197 link (org-make-link cpltxt))))
12199 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12200 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12201 (let* ((group gnus-newsgroup-name)
12202 (article (gnus-summary-article-number))
12203 (header (gnus-summary-article-header article))
12204 (from (mail-header-from header))
12205 (message-id (mail-header-id header))
12206 (date (mail-header-date header))
12207 (subject (gnus-summary-subject-string)))
12208 (org-store-link-props :type "gnus" :from from :subject subject
12209 :message-id message-id :group group)
12210 (setq cpltxt (org-email-link-description))
12211 (if (org-xor arg org-usenet-links-prefer-google)
12212 (setq link
12213 (concat
12214 cpltxt "\n "
12215 (format "http://groups.google.com/groups?as_umsgid=%s"
12216 (org-fixup-message-id-for-http message-id))))
12217 (setq link (org-make-link "gnus:" group
12218 "#" (number-to-string article))))))
12220 ((eq major-mode 'w3-mode)
12221 (setq cpltxt (url-view-url t)
12222 link (org-make-link cpltxt))
12223 (org-store-link-props :type "w3" :url (url-view-url t)))
12225 ((eq major-mode 'w3m-mode)
12226 (setq cpltxt (or w3m-current-title w3m-current-url)
12227 link (org-make-link w3m-current-url))
12228 (org-store-link-props :type "w3m" :url (url-view-url t)))
12230 ((setq search (run-hook-with-args-until-success
12231 'org-create-file-search-functions))
12232 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12233 "::" search))
12234 (setq cpltxt (or description link)))
12236 ((eq major-mode 'image-mode)
12237 (setq cpltxt (concat "file:"
12238 (abbreviate-file-name buffer-file-name))
12239 link (org-make-link cpltxt))
12240 (org-store-link-props :type "image" :file buffer-file-name))
12242 ((eq major-mode 'dired-mode)
12243 ;; link to the file in the current line
12244 (setq cpltxt (concat "file:"
12245 (abbreviate-file-name
12246 (expand-file-name
12247 (dired-get-filename nil t))))
12248 link (org-make-link cpltxt)))
12250 ((and buffer-file-name (org-mode-p))
12251 ;; Just link to current headline
12252 (setq cpltxt (concat "file:"
12253 (abbreviate-file-name buffer-file-name)))
12254 ;; Add a context search string
12255 (when (org-xor org-context-in-file-links arg)
12256 ;; Check if we are on a target
12257 (if (org-in-regexp "<<\\(.*?\\)>>")
12258 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12259 (setq txt (cond
12260 ((org-on-heading-p) nil)
12261 ((org-region-active-p)
12262 (buffer-substring (region-beginning) (region-end)))
12263 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12264 (when (or (null txt) (string-match "\\S-" txt))
12265 (setq cpltxt
12266 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12267 desc "NONE"))))
12268 (if (string-match "::\\'" cpltxt)
12269 (setq cpltxt (substring cpltxt 0 -2)))
12270 (setq link (org-make-link cpltxt)))
12272 ((buffer-file-name (buffer-base-buffer))
12273 ;; Just link to this file here.
12274 (setq cpltxt (concat "file:"
12275 (abbreviate-file-name
12276 (buffer-file-name (buffer-base-buffer)))))
12277 ;; Add a context string
12278 (when (org-xor org-context-in-file-links arg)
12279 (setq txt (if (org-region-active-p)
12280 (buffer-substring (region-beginning) (region-end))
12281 (buffer-substring (point-at-bol) (point-at-eol))))
12282 ;; Only use search option if there is some text.
12283 (when (string-match "\\S-" txt)
12284 (setq cpltxt
12285 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12286 desc "NONE")))
12287 (setq link (org-make-link cpltxt)))
12289 ((interactive-p)
12290 (error "Cannot link to a buffer which is not visiting a file"))
12292 (t (setq link nil)))
12294 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12295 (setq link (or link cpltxt)
12296 desc (or desc cpltxt))
12297 (if (equal desc "NONE") (setq desc nil))
12299 (if (and (interactive-p) link)
12300 (progn
12301 (setq org-stored-links
12302 (cons (list link desc) org-stored-links))
12303 (message "Stored: %s" (or desc link)))
12304 (and link (org-make-link-string link desc)))))
12306 (defun org-store-link-props (&rest plist)
12307 "Store link properties, extract names and addresses."
12308 (let (x adr)
12309 (when (setq x (plist-get plist :from))
12310 (setq adr (mail-extract-address-components x))
12311 (plist-put plist :fromname (car adr))
12312 (plist-put plist :fromaddress (nth 1 adr)))
12313 (when (setq x (plist-get plist :to))
12314 (setq adr (mail-extract-address-components x))
12315 (plist-put plist :toname (car adr))
12316 (plist-put plist :toaddress (nth 1 adr))))
12317 (let ((from (plist-get plist :from))
12318 (to (plist-get plist :to)))
12319 (when (and from to org-from-is-user-regexp)
12320 (plist-put plist :fromto
12321 (if (string-match org-from-is-user-regexp from)
12322 (concat "to %t")
12323 (concat "from %f")))))
12324 (setq org-store-link-plist plist))
12326 (defun org-email-link-description (&optional fmt)
12327 "Return the description part of an email link.
12328 This takes information from `org-store-link-plist' and formats it
12329 according to FMT (default from `org-email-link-description-format')."
12330 (setq fmt (or fmt org-email-link-description-format))
12331 (let* ((p org-store-link-plist)
12332 (to (plist-get p :toaddress))
12333 (from (plist-get p :fromaddress))
12334 (table
12335 (list
12336 (cons "%c" (plist-get p :fromto))
12337 (cons "%F" (plist-get p :from))
12338 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12339 (cons "%T" (plist-get p :to))
12340 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12341 (cons "%s" (plist-get p :subject))
12342 (cons "%m" (plist-get p :message-id)))))
12343 (when (string-match "%c" fmt)
12344 ;; Check if the user wrote this message
12345 (if (and org-from-is-user-regexp from to
12346 (save-match-data (string-match org-from-is-user-regexp from)))
12347 (setq fmt (replace-match "to %t" t t fmt))
12348 (setq fmt (replace-match "from %f" t t fmt))))
12349 (org-replace-escapes fmt table)))
12351 (defun org-make-org-heading-search-string (&optional string heading)
12352 "Make search string for STRING or current headline."
12353 (interactive)
12354 (let ((s (or string (org-get-heading))))
12355 (unless (and string (not heading))
12356 ;; We are using a headline, clean up garbage in there.
12357 (if (string-match org-todo-regexp s)
12358 (setq s (replace-match "" t t s)))
12359 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12360 (setq s (replace-match "" t t s)))
12361 (setq s (org-trim s))
12362 (if (string-match (concat "^\\(" org-quote-string "\\|"
12363 org-comment-string "\\)") s)
12364 (setq s (replace-match "" t t s)))
12365 (while (string-match org-ts-regexp s)
12366 (setq s (replace-match "" t t s))))
12367 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12368 (setq s (replace-match " " t t s)))
12369 (or string (setq s (concat "*" s))) ; Add * for headlines
12370 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12372 (defun org-make-link (&rest strings)
12373 "Concatenate STRINGS."
12374 (apply 'concat strings))
12376 (defun org-make-link-string (link &optional description)
12377 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12378 (unless (string-match "\\S-" link)
12379 (error "Empty link"))
12380 (when (stringp description)
12381 ;; Remove brackets from the description, they are fatal.
12382 (while (string-match "\\[" description)
12383 (setq description (replace-match "{" t t description)))
12384 (while (string-match "\\]" description)
12385 (setq description (replace-match "}" t t description))))
12386 (when (equal (org-link-escape link) description)
12387 ;; No description needed, it is identical
12388 (setq description nil))
12389 (when (and (not description)
12390 (not (equal link (org-link-escape link))))
12391 (setq description link))
12392 (concat "[[" (org-link-escape link) "]"
12393 (if description (concat "[" description "]") "")
12394 "]"))
12396 (defconst org-link-escape-chars
12397 '((?\ . "%20")
12398 (?\[ . "%5B")
12399 (?\] . "%5D")
12400 (?\340 . "%E0") ; `a
12401 (?\342 . "%E2") ; ^a
12402 (?\347 . "%E7") ; ,c
12403 (?\350 . "%E8") ; `e
12404 (?\351 . "%E9") ; 'e
12405 (?\352 . "%EA") ; ^e
12406 (?\356 . "%EE") ; ^i
12407 (?\364 . "%F4") ; ^o
12408 (?\371 . "%F9") ; `u
12409 (?\373 . "%FB") ; ^u
12410 (?\; . "%3B")
12411 (?? . "%3F")
12412 (?= . "%3D")
12413 (?+ . "%2B")
12415 "Association list of escapes for some characters problematic in links.
12416 This is the list that is used for internal purposes.")
12418 (defconst org-link-escape-chars-browser
12419 '((?\ . "%20")) ; 32 for the SPC char
12420 "Association list of escapes for some characters problematic in links.
12421 This is the list that is used before handing over to the browser.")
12423 (defun org-link-escape (text &optional table)
12424 "Escape charaters in TEXT that are problematic for links."
12425 (setq table (or table org-link-escape-chars))
12426 (when text
12427 (let ((re (mapconcat (lambda (x) (regexp-quote
12428 (char-to-string (car x))))
12429 table "\\|")))
12430 (while (string-match re text)
12431 (setq text
12432 (replace-match
12433 (cdr (assoc (string-to-char (match-string 0 text))
12434 table))
12435 t t text)))
12436 text)))
12438 (defun org-link-unescape (text &optional table)
12439 "Reverse the action of `org-link-escape'."
12440 (setq table (or table org-link-escape-chars))
12441 (when text
12442 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12443 table "\\|")))
12444 (while (string-match re text)
12445 (setq text
12446 (replace-match
12447 (char-to-string (car (rassoc (match-string 0 text) table)))
12448 t t text)))
12449 text)))
12451 (defun org-xor (a b)
12452 "Exclusive or."
12453 (if a (not b) b))
12455 (defun org-get-header (header)
12456 "Find a header field in the current buffer."
12457 (save-excursion
12458 (goto-char (point-min))
12459 (let ((case-fold-search t) s)
12460 (cond
12461 ((eq header 'from)
12462 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12463 (setq s (match-string 1)))
12464 (while (string-match "\"" s)
12465 (setq s (replace-match "" t t s)))
12466 (if (string-match "[<(].*" s)
12467 (setq s (replace-match "" t t s))))
12468 ((eq header 'message-id)
12469 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12470 (setq s (match-string 1))))
12471 ((eq header 'subject)
12472 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12473 (setq s (match-string 1)))))
12474 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12475 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12476 s)))
12479 (defun org-fixup-message-id-for-http (s)
12480 "Replace special characters in a message id, so it can be used in an http query."
12481 (while (string-match "<" s)
12482 (setq s (replace-match "%3C" t t s)))
12483 (while (string-match ">" s)
12484 (setq s (replace-match "%3E" t t s)))
12485 (while (string-match "@" s)
12486 (setq s (replace-match "%40" t t s)))
12489 ;;;###autoload
12490 (defun org-insert-link-global ()
12491 "Insert a link like Org-mode does.
12492 This command can be called in any mode to insert a link in Org-mode syntax."
12493 (interactive)
12494 (org-run-like-in-org-mode 'org-insert-link))
12496 (defun org-insert-link (&optional complete-file)
12497 "Insert a link. At the prompt, enter the link.
12499 Completion can be used to select a link previously stored with
12500 `org-store-link'. When the empty string is entered (i.e. if you just
12501 press RET at the prompt), the link defaults to the most recently
12502 stored link. As SPC triggers completion in the minibuffer, you need to
12503 use M-SPC or C-q SPC to force the insertion of a space character.
12505 You will also be prompted for a description, and if one is given, it will
12506 be displayed in the buffer instead of the link.
12508 If there is already a link at point, this command will allow you to edit link
12509 and description parts.
12511 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12512 selected using completion. The path to the file will be relative to
12513 the current directory if the file is in the current directory or a
12514 subdirectory. Otherwise, the link will be the absolute path as
12515 completed in the minibuffer (i.e. normally ~/path/to/file).
12517 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12518 is in the current directory or below.
12519 With three \\[universal-argument] prefixes, negate the meaning of
12520 `org-keep-stored-link-after-insertion'."
12521 (interactive "P")
12522 (let* ((wcf (current-window-configuration))
12523 (region (if (org-region-active-p)
12524 (buffer-substring (region-beginning) (region-end))))
12525 (remove (and region (list (region-beginning) (region-end))))
12526 (desc region)
12527 tmphist ; byte-compile incorrectly complains about this
12528 link entry file)
12529 (cond
12530 ((org-in-regexp org-bracket-link-regexp 1)
12531 ;; We do have a link at point, and we are going to edit it.
12532 (setq remove (list (match-beginning 0) (match-end 0)))
12533 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12534 (setq link (read-string "Link: "
12535 (org-link-unescape
12536 (org-match-string-no-properties 1)))))
12537 ((or (org-in-regexp org-angle-link-re)
12538 (org-in-regexp org-plain-link-re))
12539 ;; Convert to bracket link
12540 (setq remove (list (match-beginning 0) (match-end 0))
12541 link (read-string "Link: "
12542 (org-remove-angle-brackets (match-string 0)))))
12543 ((equal complete-file '(4))
12544 ;; Completing read for file names.
12545 (setq file (read-file-name "File: "))
12546 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12547 (pwd1 (file-name-as-directory (abbreviate-file-name
12548 (expand-file-name ".")))))
12549 (cond
12550 ((equal complete-file '(16))
12551 (setq link (org-make-link
12552 "file:"
12553 (abbreviate-file-name (expand-file-name file)))))
12554 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12555 (setq link (org-make-link "file:" (match-string 1 file))))
12556 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12557 (expand-file-name file))
12558 (setq link (org-make-link
12559 "file:" (match-string 1 (expand-file-name file)))))
12560 (t (setq link (org-make-link "file:" file))))))
12562 ;; Read link, with completion for stored links.
12563 (with-output-to-temp-buffer "*Org Links*"
12564 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12565 (when org-stored-links
12566 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12567 (princ (mapconcat
12568 (lambda (x)
12569 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12570 (reverse org-stored-links) "\n"))))
12571 (let ((cw (selected-window)))
12572 (select-window (get-buffer-window "*Org Links*"))
12573 (shrink-window-if-larger-than-buffer)
12574 (setq truncate-lines t)
12575 (select-window cw))
12576 ;; Fake a link history, containing the stored links.
12577 (setq tmphist (append (mapcar 'car org-stored-links)
12578 org-insert-link-history))
12579 (unwind-protect
12580 (setq link (org-completing-read
12581 "Link: "
12582 (append
12583 (mapcar (lambda (x) (list (concat (car x) ":")))
12584 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12585 (mapcar (lambda (x) (list (concat x ":")))
12586 org-link-types))
12587 nil nil nil
12588 'tmphist
12589 (or (car (car org-stored-links)))))
12590 (set-window-configuration wcf)
12591 (kill-buffer "*Org Links*"))
12592 (setq entry (assoc link org-stored-links))
12593 (or entry (push link org-insert-link-history))
12594 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12595 (not org-keep-stored-link-after-insertion))
12596 (setq org-stored-links (delq (assoc link org-stored-links)
12597 org-stored-links)))
12598 (setq desc (or desc (nth 1 entry)))))
12600 (if (string-match org-plain-link-re link)
12601 ;; URL-like link, normalize the use of angular brackets.
12602 (setq link (org-make-link (org-remove-angle-brackets link))))
12604 ;; Check if we are linking to the current file with a search option
12605 ;; If yes, simplify the link by using only the search option.
12606 (when (and buffer-file-name
12607 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12608 (let* ((path (match-string 1 link))
12609 (case-fold-search nil)
12610 (search (match-string 2 link)))
12611 (save-match-data
12612 (if (equal (file-truename buffer-file-name) (file-truename path))
12613 ;; We are linking to this same file, with a search option
12614 (setq link search)))))
12616 ;; Check if we can/should use a relative path. If yes, simplify the link
12617 (when (string-match "\\<file:\\(.*\\)" link)
12618 (let* ((path (match-string 1 link))
12619 (origpath path)
12620 (case-fold-search nil))
12621 (cond
12622 ((eq org-link-file-path-type 'absolute)
12623 (setq path (abbreviate-file-name (expand-file-name path))))
12624 ((eq org-link-file-path-type 'noabbrev)
12625 (setq path (expand-file-name path)))
12626 ((eq org-link-file-path-type 'relative)
12627 (setq path (file-relative-name path)))
12629 (save-match-data
12630 (if (string-match (concat "^" (regexp-quote
12631 (file-name-as-directory
12632 (expand-file-name "."))))
12633 (expand-file-name path))
12634 ;; We are linking a file with relative path name.
12635 (setq path (substring (expand-file-name path)
12636 (match-end 0)))))))
12637 (setq link (concat "file:" path))
12638 (if (equal desc origpath)
12639 (setq desc path))))
12641 (setq desc (read-string "Description: " desc))
12642 (unless (string-match "\\S-" desc) (setq desc nil))
12643 (if remove (apply 'delete-region remove))
12644 (insert (org-make-link-string link desc))))
12646 (defun org-completing-read (&rest args)
12647 (let ((minibuffer-local-completion-map
12648 (copy-keymap minibuffer-local-completion-map)))
12649 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12650 (apply 'completing-read args)))
12652 ;;; Opening/following a link
12653 (defvar org-link-search-failed nil)
12655 (defun org-next-link ()
12656 "Move forward to the next link.
12657 If the link is in hidden text, expose it."
12658 (interactive)
12659 (when (and org-link-search-failed (eq this-command last-command))
12660 (goto-char (point-min))
12661 (message "Link search wrapped back to beginning of buffer"))
12662 (setq org-link-search-failed nil)
12663 (let* ((pos (point))
12664 (ct (org-context))
12665 (a (assoc :link ct)))
12666 (if a (goto-char (nth 2 a)))
12667 (if (re-search-forward org-any-link-re nil t)
12668 (progn
12669 (goto-char (match-beginning 0))
12670 (if (org-invisible-p) (org-show-context)))
12671 (goto-char pos)
12672 (setq org-link-search-failed t)
12673 (error "No further link found"))))
12675 (defun org-previous-link ()
12676 "Move backward to the previous link.
12677 If the link is in hidden text, expose it."
12678 (interactive)
12679 (when (and org-link-search-failed (eq this-command last-command))
12680 (goto-char (point-max))
12681 (message "Link search wrapped back to end of buffer"))
12682 (setq org-link-search-failed nil)
12683 (let* ((pos (point))
12684 (ct (org-context))
12685 (a (assoc :link ct)))
12686 (if a (goto-char (nth 1 a)))
12687 (if (re-search-backward org-any-link-re nil t)
12688 (progn
12689 (goto-char (match-beginning 0))
12690 (if (org-invisible-p) (org-show-context)))
12691 (goto-char pos)
12692 (setq org-link-search-failed t)
12693 (error "No further link found"))))
12695 (defun org-find-file-at-mouse (ev)
12696 "Open file link or URL at mouse."
12697 (interactive "e")
12698 (mouse-set-point ev)
12699 (org-open-at-point 'in-emacs))
12701 (defun org-open-at-mouse (ev)
12702 "Open file link or URL at mouse."
12703 (interactive "e")
12704 (mouse-set-point ev)
12705 (org-open-at-point))
12707 (defvar org-window-config-before-follow-link nil
12708 "The window configuration before following a link.
12709 This is saved in case the need arises to restore it.")
12711 (defvar org-open-link-marker (make-marker)
12712 "Marker pointing to the location where `org-open-at-point; was called.")
12714 ;;;###autoload
12715 (defun org-open-at-point-global ()
12716 "Follow a link like Org-mode does.
12717 This command can be called in any mode to follow a link that has
12718 Org-mode syntax."
12719 (interactive)
12720 (org-run-like-in-org-mode 'org-open-at-point))
12722 (defun org-open-at-point (&optional in-emacs)
12723 "Open link at or after point.
12724 If there is no link at point, this function will search forward up to
12725 the end of the current subtree.
12726 Normally, files will be opened by an appropriate application. If the
12727 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12728 (interactive "P")
12729 (move-marker org-open-link-marker (point))
12730 (setq org-window-config-before-follow-link (current-window-configuration))
12731 (org-remove-occur-highlights nil nil t)
12732 (if (org-at-timestamp-p t)
12733 (org-follow-timestamp-link)
12734 (let (type path link line search (pos (point)))
12735 (catch 'match
12736 (save-excursion
12737 (skip-chars-forward "^]\n\r")
12738 (when (org-in-regexp org-bracket-link-regexp)
12739 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12740 (while (string-match " *\n *" link)
12741 (setq link (replace-match " " t t link)))
12742 (setq link (org-link-expand-abbrev link))
12743 (if (string-match org-link-re-with-space2 link)
12744 (setq type (match-string 1 link) path (match-string 2 link))
12745 (setq type "thisfile" path link))
12746 (throw 'match t)))
12748 (when (get-text-property (point) 'org-linked-text)
12749 (setq type "thisfile"
12750 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12751 (1+ (point)) (point))
12752 path (buffer-substring
12753 (previous-single-property-change pos 'org-linked-text)
12754 (next-single-property-change pos 'org-linked-text)))
12755 (throw 'match t))
12757 (save-excursion
12758 (when (or (org-in-regexp org-angle-link-re)
12759 (org-in-regexp org-plain-link-re))
12760 (setq type (match-string 1) path (match-string 2))
12761 (throw 'match t)))
12762 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12763 (setq type "tree-match"
12764 path (match-string 1))
12765 (throw 'match t))
12766 (save-excursion
12767 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12768 (setq type "tags"
12769 path (match-string 1))
12770 (while (string-match ":" path)
12771 (setq path (replace-match "+" t t path)))
12772 (throw 'match t))))
12773 (unless path
12774 (error "No link found"))
12775 ;; Remove any trailing spaces in path
12776 (if (string-match " +\\'" path)
12777 (setq path (replace-match "" t t path)))
12779 (cond
12781 ((assoc type org-link-protocols)
12782 (funcall (nth 1 (assoc type org-link-protocols)) path))
12784 ((equal type "mailto")
12785 (let ((cmd (car org-link-mailto-program))
12786 (args (cdr org-link-mailto-program)) args1
12787 (address path) (subject "") a)
12788 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12789 (setq address (match-string 1 path)
12790 subject (org-link-escape (match-string 2 path))))
12791 (while args
12792 (cond
12793 ((not (stringp (car args))) (push (pop args) args1))
12794 (t (setq a (pop args))
12795 (if (string-match "%a" a)
12796 (setq a (replace-match address t t a)))
12797 (if (string-match "%s" a)
12798 (setq a (replace-match subject t t a)))
12799 (push a args1))))
12800 (apply cmd (nreverse args1))))
12802 ((member type '("http" "https" "ftp" "news"))
12803 (browse-url (concat type ":" (org-link-escape
12804 path org-link-escape-chars-browser))))
12806 ((member type '("message"))
12807 (browse-url (concat type ":" path)))
12809 ((string= type "tags")
12810 (org-tags-view in-emacs path))
12811 ((string= type "thisfile")
12812 (if in-emacs
12813 (switch-to-buffer-other-window
12814 (org-get-buffer-for-internal-link (current-buffer)))
12815 (org-mark-ring-push))
12816 (let ((cmd `(org-link-search
12817 ,path
12818 ,(cond ((equal in-emacs '(4)) 'occur)
12819 ((equal in-emacs '(16)) 'org-occur)
12820 (t nil))
12821 ,pos)))
12822 (condition-case nil (eval cmd)
12823 (error (progn (widen) (eval cmd))))))
12825 ((string= type "tree-match")
12826 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12828 ((string= type "file")
12829 (if (string-match "::\\([0-9]+\\)\\'" path)
12830 (setq line (string-to-number (match-string 1 path))
12831 path (substring path 0 (match-beginning 0)))
12832 (if (string-match "::\\(.+\\)\\'" path)
12833 (setq search (match-string 1 path)
12834 path (substring path 0 (match-beginning 0)))))
12835 (if (string-match "[*?{]" (file-name-nondirectory path))
12836 (dired path)
12837 (org-open-file path in-emacs line search)))
12839 ((string= type "news")
12840 (org-follow-gnus-link path))
12842 ((string= type "bbdb")
12843 (org-follow-bbdb-link path))
12845 ((string= type "info")
12846 (org-follow-info-link path))
12848 ((string= type "gnus")
12849 (let (group article)
12850 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12851 (error "Error in Gnus link"))
12852 (setq group (match-string 1 path)
12853 article (match-string 3 path))
12854 (org-follow-gnus-link group article)))
12856 ((string= type "vm")
12857 (let (folder article)
12858 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12859 (error "Error in VM link"))
12860 (setq folder (match-string 1 path)
12861 article (match-string 3 path))
12862 ;; in-emacs is the prefix arg, will be interpreted as read-only
12863 (org-follow-vm-link folder article in-emacs)))
12865 ((string= type "wl")
12866 (let (folder article)
12867 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12868 (error "Error in Wanderlust link"))
12869 (setq folder (match-string 1 path)
12870 article (match-string 3 path))
12871 (org-follow-wl-link folder article)))
12873 ((string= type "mhe")
12874 (let (folder article)
12875 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12876 (error "Error in MHE link"))
12877 (setq folder (match-string 1 path)
12878 article (match-string 3 path))
12879 (org-follow-mhe-link folder article)))
12881 ((string= type "rmail")
12882 (let (folder article)
12883 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12884 (error "Error in RMAIL link"))
12885 (setq folder (match-string 1 path)
12886 article (match-string 3 path))
12887 (org-follow-rmail-link folder article)))
12889 ((string= type "shell")
12890 (let ((cmd path))
12891 (if (or (not org-confirm-shell-link-function)
12892 (funcall org-confirm-shell-link-function
12893 (format "Execute \"%s\" in shell? "
12894 (org-add-props cmd nil
12895 'face 'org-warning))))
12896 (progn
12897 (message "Executing %s" cmd)
12898 (shell-command cmd))
12899 (error "Abort"))))
12901 ((string= type "elisp")
12902 (let ((cmd path))
12903 (if (or (not org-confirm-elisp-link-function)
12904 (funcall org-confirm-elisp-link-function
12905 (format "Execute \"%s\" as elisp? "
12906 (org-add-props cmd nil
12907 'face 'org-warning))))
12908 (message "%s => %s" cmd (eval (read cmd)))
12909 (error "Abort"))))
12912 (browse-url-at-point)))))
12913 (move-marker org-open-link-marker nil))
12915 ;;; File search
12917 (defvar org-create-file-search-functions nil
12918 "List of functions to construct the right search string for a file link.
12919 These functions are called in turn with point at the location to
12920 which the link should point.
12922 A function in the hook should first test if it would like to
12923 handle this file type, for example by checking the major-mode or
12924 the file extension. If it decides not to handle this file, it
12925 should just return nil to give other functions a chance. If it
12926 does handle the file, it must return the search string to be used
12927 when following the link. The search string will be part of the
12928 file link, given after a double colon, and `org-open-at-point'
12929 will automatically search for it. If special measures must be
12930 taken to make the search successful, another function should be
12931 added to the companion hook `org-execute-file-search-functions',
12932 which see.
12934 A function in this hook may also use `setq' to set the variable
12935 `description' to provide a suggestion for the descriptive text to
12936 be used for this link when it gets inserted into an Org-mode
12937 buffer with \\[org-insert-link].")
12939 (defvar org-execute-file-search-functions nil
12940 "List of functions to execute a file search triggered by a link.
12942 Functions added to this hook must accept a single argument, the
12943 search string that was part of the file link, the part after the
12944 double colon. The function must first check if it would like to
12945 handle this search, for example by checking the major-mode or the
12946 file extension. If it decides not to handle this search, it
12947 should just return nil to give other functions a chance. If it
12948 does handle the search, it must return a non-nil value to keep
12949 other functions from trying.
12951 Each function can access the current prefix argument through the
12952 variable `current-prefix-argument'. Note that a single prefix is
12953 used to force opening a link in Emacs, so it may be good to only
12954 use a numeric or double prefix to guide the search function.
12956 In case this is needed, a function in this hook can also restore
12957 the window configuration before `org-open-at-point' was called using:
12959 (set-window-configuration org-window-config-before-follow-link)")
12961 (defun org-link-search (s &optional type avoid-pos)
12962 "Search for a link search option.
12963 If S is surrounded by forward slashes, it is interpreted as a
12964 regular expression. In org-mode files, this will create an `org-occur'
12965 sparse tree. In ordinary files, `occur' will be used to list matches.
12966 If the current buffer is in `dired-mode', grep will be used to search
12967 in all files. If AVOID-POS is given, ignore matches near that position."
12968 (let ((case-fold-search t)
12969 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12970 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12971 (append '(("") (" ") ("\t") ("\n"))
12972 org-emphasis-alist)
12973 "\\|") "\\)"))
12974 (pos (point))
12975 (pre "") (post "")
12976 words re0 re1 re2 re3 re4 re5 re2a reall)
12977 (cond
12978 ;; First check if there are any special
12979 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12980 ;; Now try the builtin stuff
12981 ((save-excursion
12982 (goto-char (point-min))
12983 (and
12984 (re-search-forward
12985 (concat "<<" (regexp-quote s0) ">>") nil t)
12986 (setq pos (match-beginning 0))))
12987 ;; There is an exact target for this
12988 (goto-char pos))
12989 ((string-match "^/\\(.*\\)/$" s)
12990 ;; A regular expression
12991 (cond
12992 ((org-mode-p)
12993 (org-occur (match-string 1 s)))
12994 ;;((eq major-mode 'dired-mode)
12995 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12996 (t (org-do-occur (match-string 1 s)))))
12998 ;; A normal search strings
12999 (when (equal (string-to-char s) ?*)
13000 ;; Anchor on headlines, post may include tags.
13001 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
13002 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
13003 s (substring s 1)))
13004 (remove-text-properties
13005 0 (length s)
13006 '(face nil mouse-face nil keymap nil fontified nil) s)
13007 ;; Make a series of regular expressions to find a match
13008 (setq words (org-split-string s "[ \n\r\t]+")
13009 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
13010 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
13011 "\\)" markers)
13012 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
13013 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
13014 re1 (concat pre re2 post)
13015 re3 (concat pre re4 post)
13016 re5 (concat pre ".*" re4)
13017 re2 (concat pre re2)
13018 re2a (concat pre re2a)
13019 re4 (concat pre re4)
13020 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
13021 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
13022 re5 "\\)"
13024 (cond
13025 ((eq type 'org-occur) (org-occur reall))
13026 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
13027 (t (goto-char (point-min))
13028 (if (or (org-search-not-self 1 re0 nil t)
13029 (org-search-not-self 1 re1 nil t)
13030 (org-search-not-self 1 re2 nil t)
13031 (org-search-not-self 1 re2a nil t)
13032 (org-search-not-self 1 re3 nil t)
13033 (org-search-not-self 1 re4 nil t)
13034 (org-search-not-self 1 re5 nil t)
13036 (goto-char (match-beginning 1))
13037 (goto-char pos)
13038 (error "No match")))))
13040 ;; Normal string-search
13041 (goto-char (point-min))
13042 (if (search-forward s nil t)
13043 (goto-char (match-beginning 0))
13044 (error "No match"))))
13045 (and (org-mode-p) (org-show-context 'link-search))))
13047 (defun org-search-not-self (group &rest args)
13048 "Execute `re-search-forward', but only accept matches that do not
13049 enclose the position of `org-open-link-marker'."
13050 (let ((m org-open-link-marker))
13051 (catch 'exit
13052 (while (apply 're-search-forward args)
13053 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
13054 (goto-char (match-end group))
13055 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
13056 (> (match-beginning 0) (marker-position m))
13057 (< (match-end 0) (marker-position m)))
13058 (save-match-data
13059 (or (not (org-in-regexp
13060 org-bracket-link-analytic-regexp 1))
13061 (not (match-end 4)) ; no description
13062 (and (<= (match-beginning 4) (point))
13063 (>= (match-end 4) (point))))))
13064 (throw 'exit (point))))))))
13066 (defun org-get-buffer-for-internal-link (buffer)
13067 "Return a buffer to be used for displaying the link target of internal links."
13068 (cond
13069 ((not org-display-internal-link-with-indirect-buffer)
13070 buffer)
13071 ((string-match "(Clone)$" (buffer-name buffer))
13072 (message "Buffer is already a clone, not making another one")
13073 ;; we also do not modify visibility in this case
13074 buffer)
13075 (t ; make a new indirect buffer for displaying the link
13076 (let* ((bn (buffer-name buffer))
13077 (ibn (concat bn "(Clone)"))
13078 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13079 (with-current-buffer ib (org-overview))
13080 ib))))
13082 (defun org-do-occur (regexp &optional cleanup)
13083 "Call the Emacs command `occur'.
13084 If CLEANUP is non-nil, remove the printout of the regular expression
13085 in the *Occur* buffer. This is useful if the regex is long and not useful
13086 to read."
13087 (occur regexp)
13088 (when cleanup
13089 (let ((cwin (selected-window)) win beg end)
13090 (when (setq win (get-buffer-window "*Occur*"))
13091 (select-window win))
13092 (goto-char (point-min))
13093 (when (re-search-forward "match[a-z]+" nil t)
13094 (setq beg (match-end 0))
13095 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13096 (setq end (1- (match-beginning 0)))))
13097 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13098 (goto-char (point-min))
13099 (select-window cwin))))
13101 ;;; The mark ring for links jumps
13103 (defvar org-mark-ring nil
13104 "Mark ring for positions before jumps in Org-mode.")
13105 (defvar org-mark-ring-last-goto nil
13106 "Last position in the mark ring used to go back.")
13107 ;; Fill and close the ring
13108 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13109 (loop for i from 1 to org-mark-ring-length do
13110 (push (make-marker) org-mark-ring))
13111 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13112 org-mark-ring)
13114 (defun org-mark-ring-push (&optional pos buffer)
13115 "Put the current position or POS into the mark ring and rotate it."
13116 (interactive)
13117 (setq pos (or pos (point)))
13118 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13119 (move-marker (car org-mark-ring)
13120 (or pos (point))
13121 (or buffer (current-buffer)))
13122 (message "%s"
13123 (substitute-command-keys
13124 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13126 (defun org-mark-ring-goto (&optional n)
13127 "Jump to the previous position in the mark ring.
13128 With prefix arg N, jump back that many stored positions. When
13129 called several times in succession, walk through the entire ring.
13130 Org-mode commands jumping to a different position in the current file,
13131 or to another Org-mode file, automatically push the old position
13132 onto the ring."
13133 (interactive "p")
13134 (let (p m)
13135 (if (eq last-command this-command)
13136 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13137 (setq p org-mark-ring))
13138 (setq org-mark-ring-last-goto p)
13139 (setq m (car p))
13140 (switch-to-buffer (marker-buffer m))
13141 (goto-char m)
13142 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13144 (defun org-remove-angle-brackets (s)
13145 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13146 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13148 (defun org-add-angle-brackets (s)
13149 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13150 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13153 ;;; Following specific links
13155 (defun org-follow-timestamp-link ()
13156 (cond
13157 ((org-at-date-range-p t)
13158 (let ((org-agenda-start-on-weekday)
13159 (t1 (match-string 1))
13160 (t2 (match-string 2)))
13161 (setq t1 (time-to-days (org-time-string-to-time t1))
13162 t2 (time-to-days (org-time-string-to-time t2)))
13163 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13164 ((org-at-timestamp-p t)
13165 (org-agenda-list nil (time-to-days (org-time-string-to-time
13166 (substring (match-string 1) 0 10)))
13168 (t (error "This should not happen"))))
13171 (defun org-follow-bbdb-link (name)
13172 "Follow a BBDB link to NAME."
13173 (require 'bbdb)
13174 (let ((inhibit-redisplay (not debug-on-error))
13175 (bbdb-electric-p nil))
13176 (catch 'exit
13177 ;; Exact match on name
13178 (bbdb-name (concat "\\`" name "\\'") nil)
13179 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13180 ;; Exact match on name
13181 (bbdb-company (concat "\\`" name "\\'") nil)
13182 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13183 ;; Partial match on name
13184 (bbdb-name name nil)
13185 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13186 ;; Partial match on company
13187 (bbdb-company name nil)
13188 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13189 ;; General match including network address and notes
13190 (bbdb name nil)
13191 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13192 (delete-window (get-buffer-window "*BBDB*"))
13193 (error "No matching BBDB record")))))
13195 (defun org-follow-info-link (name)
13196 "Follow an info file & node link to NAME."
13197 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13198 (string-match "\\(.*\\)" name))
13199 (progn
13200 (require 'info)
13201 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13202 (Info-find-node (match-string 1 name) (match-string 2 name))
13203 (Info-find-node (match-string 1 name) "Top")))
13204 (message "Could not open: %s" name)))
13206 (defun org-follow-gnus-link (&optional group article)
13207 "Follow a Gnus link to GROUP and ARTICLE."
13208 (require 'gnus)
13209 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13210 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13211 (cond ((and group article)
13212 (gnus-group-read-group 1 nil group)
13213 (gnus-summary-goto-article (string-to-number article) nil t))
13214 (group (gnus-group-jump-to-group group))))
13216 (defun org-follow-vm-link (&optional folder article readonly)
13217 "Follow a VM link to FOLDER and ARTICLE."
13218 (require 'vm)
13219 (setq article (org-add-angle-brackets article))
13220 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13221 ;; ange-ftp or efs or tramp access
13222 (let ((user (or (match-string 1 folder) (user-login-name)))
13223 (host (match-string 2 folder))
13224 (file (match-string 3 folder)))
13225 (cond
13226 ((featurep 'tramp)
13227 ;; use tramp to access the file
13228 (if (featurep 'xemacs)
13229 (setq folder (format "[%s@%s]%s" user host file))
13230 (setq folder (format "/%s@%s:%s" user host file))))
13232 ;; use ange-ftp or efs
13233 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13234 (setq folder (format "/%s@%s:%s" user host file))))))
13235 (when folder
13236 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13237 (sit-for 0.1)
13238 (when article
13239 (vm-select-folder-buffer)
13240 (widen)
13241 (let ((case-fold-search t))
13242 (goto-char (point-min))
13243 (if (not (re-search-forward
13244 (concat "^" "message-id: *" (regexp-quote article))))
13245 (error "Could not find the specified message in this folder"))
13246 (vm-isearch-update)
13247 (vm-isearch-narrow)
13248 (vm-beginning-of-message)
13249 (vm-summarize)))))
13251 (defun org-follow-wl-link (folder article)
13252 "Follow a Wanderlust link to FOLDER and ARTICLE."
13253 (if (and (string= folder "%")
13254 article
13255 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13256 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13257 ;; Thus, we recompose folder and article ids.
13258 (setq folder (format "%s#%s" folder (match-string 1 article))
13259 article (match-string 3 article)))
13260 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13261 (error "No such folder: %s" folder))
13262 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13263 (and article
13264 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13265 (wl-summary-redisplay)))
13267 (defun org-follow-rmail-link (folder article)
13268 "Follow an RMAIL link to FOLDER and ARTICLE."
13269 (setq article (org-add-angle-brackets article))
13270 (let (message-number)
13271 (save-excursion
13272 (save-window-excursion
13273 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13274 (setq message-number
13275 (save-restriction
13276 (widen)
13277 (goto-char (point-max))
13278 (if (re-search-backward
13279 (concat "^Message-ID:\\s-+" (regexp-quote
13280 (or article "")))
13281 nil t)
13282 (rmail-what-message))))))
13283 (if message-number
13284 (progn
13285 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13286 (rmail-show-message message-number)
13287 message-number)
13288 (error "Message not found"))))
13290 ;;; mh-e integration based on planner-mode
13291 (defun org-mhe-get-message-real-folder ()
13292 "Return the name of the current message real folder, so if you use
13293 sequences, it will now work."
13294 (save-excursion
13295 (let* ((folder
13296 (if (equal major-mode 'mh-folder-mode)
13297 mh-current-folder
13298 ;; Refer to the show buffer
13299 mh-show-folder-buffer))
13300 (end-index
13301 (if (boundp 'mh-index-folder)
13302 (min (length mh-index-folder) (length folder))))
13304 ;; a simple test on mh-index-data does not work, because
13305 ;; mh-index-data is always nil in a show buffer.
13306 (if (and (boundp 'mh-index-folder)
13307 (string= mh-index-folder (substring folder 0 end-index)))
13308 (if (equal major-mode 'mh-show-mode)
13309 (save-window-excursion
13310 (let (pop-up-frames)
13311 (when (buffer-live-p (get-buffer folder))
13312 (progn
13313 (pop-to-buffer folder)
13314 (org-mhe-get-message-folder-from-index)
13317 (org-mhe-get-message-folder-from-index)
13319 folder
13323 (defun org-mhe-get-message-folder-from-index ()
13324 "Returns the name of the message folder in a index folder buffer."
13325 (save-excursion
13326 (mh-index-previous-folder)
13327 (re-search-forward "^\\(+.*\\)$" nil t)
13328 (message "%s" (match-string 1))))
13330 (defun org-mhe-get-message-folder ()
13331 "Return the name of the current message folder. Be careful if you
13332 use sequences."
13333 (save-excursion
13334 (if (equal major-mode 'mh-folder-mode)
13335 mh-current-folder
13336 ;; Refer to the show buffer
13337 mh-show-folder-buffer)))
13339 (defun org-mhe-get-message-num ()
13340 "Return the number of the current message. Be careful if you
13341 use sequences."
13342 (save-excursion
13343 (if (equal major-mode 'mh-folder-mode)
13344 (mh-get-msg-num nil)
13345 ;; Refer to the show buffer
13346 (mh-show-buffer-message-number))))
13348 (defun org-mhe-get-header (header)
13349 "Return a header of the message in folder mode. This will create a
13350 show buffer for the corresponding message. If you have a more clever
13351 idea..."
13352 (let* ((folder (org-mhe-get-message-folder))
13353 (num (org-mhe-get-message-num))
13354 (buffer (get-buffer-create (concat "show-" folder)))
13355 (header-field))
13356 (with-current-buffer buffer
13357 (mh-display-msg num folder)
13358 (if (equal major-mode 'mh-folder-mode)
13359 (mh-header-display)
13360 (mh-show-header-display))
13361 (set-buffer buffer)
13362 (setq header-field (mh-get-header-field header))
13363 (if (equal major-mode 'mh-folder-mode)
13364 (mh-show)
13365 (mh-show-show))
13366 header-field)))
13368 (defun org-follow-mhe-link (folder article)
13369 "Follow an MHE link to FOLDER and ARTICLE.
13370 If ARTICLE is nil FOLDER is shown. If the configuration variable
13371 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13372 ARTICLE is searched in all folders. Indexed searches (swish++,
13373 namazu, and others supported by MH-E) will always search in all
13374 folders."
13375 (require 'mh-e)
13376 (require 'mh-search)
13377 (require 'mh-utils)
13378 (mh-find-path)
13379 (if (not article)
13380 (mh-visit-folder (mh-normalize-folder-name folder))
13381 (setq article (org-add-angle-brackets article))
13382 (mh-search-choose)
13383 (if (equal mh-searcher 'pick)
13384 (progn
13385 (mh-search folder (list "--message-id" article))
13386 (when (and org-mhe-search-all-folders
13387 (not (org-mhe-get-message-real-folder)))
13388 (kill-this-buffer)
13389 (mh-search "+" (list "--message-id" article))))
13390 (mh-search "+" article))
13391 (if (org-mhe-get-message-real-folder)
13392 (mh-show-msg 1)
13393 (kill-this-buffer)
13394 (error "Message not found"))))
13396 ;;; BibTeX links
13398 ;; Use the custom search meachnism to construct and use search strings for
13399 ;; file links to BibTeX database entries.
13401 (defun org-create-file-search-in-bibtex ()
13402 "Create the search string and description for a BibTeX database entry."
13403 (when (eq major-mode 'bibtex-mode)
13404 ;; yes, we want to construct this search string.
13405 ;; Make a good description for this entry, using names, year and the title
13406 ;; Put it into the `description' variable which is dynamically scoped.
13407 (let ((bibtex-autokey-names 1)
13408 (bibtex-autokey-names-stretch 1)
13409 (bibtex-autokey-name-case-convert-function 'identity)
13410 (bibtex-autokey-name-separator " & ")
13411 (bibtex-autokey-additional-names " et al.")
13412 (bibtex-autokey-year-length 4)
13413 (bibtex-autokey-name-year-separator " ")
13414 (bibtex-autokey-titlewords 3)
13415 (bibtex-autokey-titleword-separator " ")
13416 (bibtex-autokey-titleword-case-convert-function 'identity)
13417 (bibtex-autokey-titleword-length 'infty)
13418 (bibtex-autokey-year-title-separator ": "))
13419 (setq description (bibtex-generate-autokey)))
13420 ;; Now parse the entry, get the key and return it.
13421 (save-excursion
13422 (bibtex-beginning-of-entry)
13423 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13425 (defun org-execute-file-search-in-bibtex (s)
13426 "Find the link search string S as a key for a database entry."
13427 (when (eq major-mode 'bibtex-mode)
13428 ;; Yes, we want to do the search in this file.
13429 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13430 (goto-char (point-min))
13431 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13432 (regexp-quote s) "[ \t\n]*,") nil t)
13433 (goto-char (match-beginning 0)))
13434 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13435 ;; Use double prefix to indicate that any web link should be browsed
13436 (let ((b (current-buffer)) (p (point)))
13437 ;; Restore the window configuration because we just use the web link
13438 (set-window-configuration org-window-config-before-follow-link)
13439 (save-excursion (set-buffer b) (goto-char p)
13440 (bibtex-url)))
13441 (recenter 0)) ; Move entry start to beginning of window
13442 ;; return t to indicate that the search is done.
13445 ;; Finally add the functions to the right hooks.
13446 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13447 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13449 ;; end of Bibtex link setup
13451 ;;; Following file links
13453 (defun org-open-file (path &optional in-emacs line search)
13454 "Open the file at PATH.
13455 First, this expands any special file name abbreviations. Then the
13456 configuration variable `org-file-apps' is checked if it contains an
13457 entry for this file type, and if yes, the corresponding command is launched.
13458 If no application is found, Emacs simply visits the file.
13459 With optional argument IN-EMACS, Emacs will visit the file.
13460 Optional LINE specifies a line to go to, optional SEARCH a string to
13461 search for. If LINE or SEARCH is given, the file will always be
13462 opened in Emacs.
13463 If the file does not exist, an error is thrown."
13464 (setq in-emacs (or in-emacs line search))
13465 (let* ((file (if (equal path "")
13466 buffer-file-name
13467 (substitute-in-file-name (expand-file-name path))))
13468 (apps (append org-file-apps (org-default-apps)))
13469 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13470 (dirp (if remp nil (file-directory-p file)))
13471 (dfile (downcase file))
13472 (old-buffer (current-buffer))
13473 (old-pos (point))
13474 (old-mode major-mode)
13475 ext cmd)
13476 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13477 (setq ext (match-string 1 dfile))
13478 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13479 (setq ext (match-string 1 dfile))))
13480 (if in-emacs
13481 (setq cmd 'emacs)
13482 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13483 (and dirp (cdr (assoc 'directory apps)))
13484 (cdr (assoc ext apps))
13485 (cdr (assoc t apps)))))
13486 (when (eq cmd 'mailcap)
13487 (require 'mailcap)
13488 (mailcap-parse-mailcaps)
13489 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13490 (command (mailcap-mime-info mime-type)))
13491 (if (stringp command)
13492 (setq cmd command)
13493 (setq cmd 'emacs))))
13494 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13495 (not (file-exists-p file))
13496 (not org-open-non-existing-files))
13497 (error "No such file: %s" file))
13498 (cond
13499 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13500 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13501 (while (string-match "['\"]%s['\"]" cmd)
13502 (setq cmd (replace-match "%s" t t cmd)))
13503 (while (string-match "%s" cmd)
13504 (setq cmd (replace-match
13505 (save-match-data (shell-quote-argument file))
13506 t t cmd)))
13507 (save-window-excursion
13508 (start-process-shell-command cmd nil cmd)))
13509 ((or (stringp cmd)
13510 (eq cmd 'emacs))
13511 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13512 (widen)
13513 (if line (goto-line line)
13514 (if search (org-link-search search))))
13515 ((consp cmd)
13516 (eval cmd))
13517 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13518 (and (org-mode-p) (eq old-mode 'org-mode)
13519 (or (not (equal old-buffer (current-buffer)))
13520 (not (equal old-pos (point))))
13521 (org-mark-ring-push old-pos old-buffer))))
13523 (defun org-default-apps ()
13524 "Return the default applications for this operating system."
13525 (cond
13526 ((eq system-type 'darwin)
13527 org-file-apps-defaults-macosx)
13528 ((eq system-type 'windows-nt)
13529 org-file-apps-defaults-windowsnt)
13530 (t org-file-apps-defaults-gnu)))
13532 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13533 (defun org-file-remote-p (file)
13534 "Test whether FILE specifies a location on a remote system.
13535 Return non-nil if the location is indeed remote.
13537 For example, the filename \"/user@host:/foo\" specifies a location
13538 on the system \"/user@host:\"."
13539 (cond ((fboundp 'file-remote-p)
13540 (file-remote-p file))
13541 ((fboundp 'tramp-handle-file-remote-p)
13542 (tramp-handle-file-remote-p file))
13543 ((and (boundp 'ange-ftp-name-format)
13544 (string-match (car ange-ftp-name-format) file))
13546 (t nil)))
13549 ;;;; Hooks for remember.el, and refiling
13551 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13552 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13554 ;;;###autoload
13555 (defun org-remember-insinuate ()
13556 "Setup remember.el for use wiht Org-mode."
13557 (require 'remember)
13558 (setq remember-annotation-functions '(org-remember-annotation))
13559 (setq remember-handler-functions '(org-remember-handler))
13560 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13562 ;;;###autoload
13563 (defun org-remember-annotation ()
13564 "Return a link to the current location as an annotation for remember.el.
13565 If you are using Org-mode files as target for data storage with
13566 remember.el, then the annotations should include a link compatible with the
13567 conventions in Org-mode. This function returns such a link."
13568 (org-store-link nil))
13570 (defconst org-remember-help
13571 "Select a destination location for the note.
13572 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13573 RET on headline -> Store as sublevel entry to current headline
13574 RET at beg-of-buf -> Append to file as level 2 headline
13575 <left>/<right> -> before/after current headline, same headings level")
13577 (defvar org-remember-previous-location nil)
13578 (defvar org-force-remember-template-char) ;; dynamically scoped
13580 (defun org-select-remember-template (&optional use-char)
13581 (when org-remember-templates
13582 (let* ((templates (mapcar (lambda (x)
13583 (if (stringp (car x))
13584 (append (list (nth 1 x) (car x)) (cddr x))
13585 (append (list (car x) "") (cdr x))))
13586 org-remember-templates))
13587 (char (or use-char
13588 (cond
13589 ((= (length templates) 1)
13590 (caar templates))
13591 ((and (boundp 'org-force-remember-template-char)
13592 org-force-remember-template-char)
13593 (if (stringp org-force-remember-template-char)
13594 (string-to-char org-force-remember-template-char)
13595 org-force-remember-template-char))
13597 (message "Select template: %s"
13598 (mapconcat
13599 (lambda (x)
13600 (cond
13601 ((not (string-match "\\S-" (nth 1 x)))
13602 (format "[%c]" (car x)))
13603 ((equal (downcase (car x))
13604 (downcase (aref (nth 1 x) 0)))
13605 (format "[%c]%s" (car x)
13606 (substring (nth 1 x) 1)))
13607 (t (format "[%c]%s" (car x) (nth 1 x)))))
13608 templates " "))
13609 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13610 (when (equal char0 ?\C-g)
13611 (jump-to-register remember-register)
13612 (kill-buffer remember-buffer))
13613 char0))))))
13614 (cddr (assoc char templates)))))
13616 (defvar x-last-selected-text)
13617 (defvar x-last-selected-text-primary)
13619 ;;;###autoload
13620 (defun org-remember-apply-template (&optional use-char skip-interactive)
13621 "Initialize *remember* buffer with template, invoke `org-mode'.
13622 This function should be placed into `remember-mode-hook' and in fact requires
13623 to be run from that hook to function properly."
13624 (if org-remember-templates
13625 (let* ((entry (org-select-remember-template use-char))
13626 (tpl (car entry))
13627 (plist-p (if org-store-link-plist t nil))
13628 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13629 (string-match "\\S-" (nth 1 entry)))
13630 (nth 1 entry)
13631 org-default-notes-file))
13632 (headline (nth 2 entry))
13633 (v-c (or (and (eq window-system 'x)
13634 (fboundp 'x-cut-buffer-or-selection-value)
13635 (x-cut-buffer-or-selection-value))
13636 (org-bound-and-true-p x-last-selected-text)
13637 (org-bound-and-true-p x-last-selected-text-primary)
13638 (and (> (length kill-ring) 0) (current-kill 0))))
13639 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13640 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13641 (v-u (concat "[" (substring v-t 1 -1) "]"))
13642 (v-U (concat "[" (substring v-T 1 -1) "]"))
13643 ;; `initial' and `annotation' are bound in `remember'
13644 (v-i (if (boundp 'initial) initial))
13645 (v-a (if (and (boundp 'annotation) annotation)
13646 (if (equal annotation "[[]]") "" annotation)
13647 ""))
13648 (v-A (if (and v-a
13649 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13650 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13651 v-a))
13652 (v-n user-full-name)
13653 (org-startup-folded nil)
13654 org-time-was-given org-end-time-was-given x
13655 prompt completions char time pos default histvar)
13656 (setq org-store-link-plist
13657 (append (list :annotation v-a :initial v-i)
13658 org-store-link-plist))
13659 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13660 (erase-buffer)
13661 (insert (substitute-command-keys
13662 (format
13663 "## Filing location: Select interactively, default, or last used:
13664 ## %s to select file and header location interactively.
13665 ## %s \"%s\" -> \"* %s\"
13666 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13667 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13668 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13669 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13670 (abbreviate-file-name (or file org-default-notes-file))
13671 (or headline "")
13672 (or (car org-remember-previous-location) "???")
13673 (or (cdr org-remember-previous-location) "???"))))
13674 (insert tpl) (goto-char (point-min))
13675 ;; Simple %-escapes
13676 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13677 (when (and initial (equal (match-string 0) "%i"))
13678 (save-match-data
13679 (let* ((lead (buffer-substring
13680 (point-at-bol) (match-beginning 0))))
13681 (setq v-i (mapconcat 'identity
13682 (org-split-string initial "\n")
13683 (concat "\n" lead))))))
13684 (replace-match
13685 (or (eval (intern (concat "v-" (match-string 1)))) "")
13686 t t))
13688 ;; %[] Insert contents of a file.
13689 (goto-char (point-min))
13690 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13691 (let ((start (match-beginning 0))
13692 (end (match-end 0))
13693 (filename (expand-file-name (match-string 1))))
13694 (goto-char start)
13695 (delete-region start end)
13696 (condition-case error
13697 (insert-file-contents filename)
13698 (error (insert (format "%%![Couldn't insert %s: %s]"
13699 filename error))))))
13700 ;; %() embedded elisp
13701 (goto-char (point-min))
13702 (while (re-search-forward "%\\((.+)\\)" nil t)
13703 (goto-char (match-beginning 0))
13704 (let ((template-start (point)))
13705 (forward-char 1)
13706 (let ((result
13707 (condition-case error
13708 (eval (read (current-buffer)))
13709 (error (format "%%![Error: %s]" error)))))
13710 (delete-region template-start (point))
13711 (insert result))))
13713 ;; From the property list
13714 (when plist-p
13715 (goto-char (point-min))
13716 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13717 (and (setq x (or (plist-get org-store-link-plist
13718 (intern (match-string 1))) ""))
13719 (replace-match x t t))))
13721 ;; Turn on org-mode in the remember buffer, set local variables
13722 (org-mode)
13723 (org-set-local 'org-finish-function 'org-remember-finalize)
13724 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13725 (org-set-local 'org-default-notes-file file))
13726 (if (and headline (stringp headline) (string-match "\\S-" headline))
13727 (org-set-local 'org-remember-default-headline headline))
13728 ;; Interactive template entries
13729 (goto-char (point-min))
13730 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13731 (setq char (if (match-end 3) (match-string 3))
13732 prompt (if (match-end 2) (match-string 2)))
13733 (goto-char (match-beginning 0))
13734 (replace-match "")
13735 (setq completions nil default nil)
13736 (when prompt
13737 (setq completions (org-split-string prompt "|")
13738 prompt (pop completions)
13739 default (car completions)
13740 histvar (intern (concat
13741 "org-remember-template-prompt-history::"
13742 (or prompt "")))
13743 completions (mapcar 'list completions)))
13744 (cond
13745 ((member char '("G" "g"))
13746 (let* ((org-last-tags-completion-table
13747 (org-global-tags-completion-table
13748 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13749 (org-add-colon-after-tag-completion t)
13750 (ins (completing-read
13751 (if prompt (concat prompt ": ") "Tags: ")
13752 'org-tags-completion-function nil nil nil
13753 'org-tags-history)))
13754 (setq ins (mapconcat 'identity
13755 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13756 ":"))
13757 (when (string-match "\\S-" ins)
13758 (or (equal (char-before) ?:) (insert ":"))
13759 (insert ins)
13760 (or (equal (char-after) ?:) (insert ":")))))
13761 (char
13762 (setq org-time-was-given (equal (upcase char) char))
13763 (setq time (org-read-date (equal (upcase char) "U") t nil
13764 prompt))
13765 (org-insert-time-stamp time org-time-was-given
13766 (member char '("u" "U"))
13767 nil nil (list org-end-time-was-given)))
13769 (insert (org-completing-read
13770 (concat (if prompt prompt "Enter string")
13771 (if default (concat " [" default "]"))
13772 ": ")
13773 completions nil nil nil histvar default)))))
13774 (goto-char (point-min))
13775 (if (re-search-forward "%\\?" nil t)
13776 (replace-match "")
13777 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13778 (org-mode)
13779 (org-set-local 'org-finish-function 'org-remember-finalize))
13780 (when (save-excursion
13781 (goto-char (point-min))
13782 (re-search-forward "%!" nil t))
13783 (replace-match "")
13784 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13786 (defun org-remember-finish-immediately ()
13787 "File remember note immediately.
13788 This should be run in `post-command-hook' and will remove itself
13789 from that hook."
13790 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13791 (when org-finish-function
13792 (funcall org-finish-function)))
13794 (defvar org-clock-marker) ; Defined below
13795 (defun org-remember-finalize ()
13796 "Finalize the remember process."
13797 (unless (fboundp 'remember-finalize)
13798 (defalias 'remember-finalize 'remember-buffer))
13799 (when (and org-clock-marker
13800 (equal (marker-buffer org-clock-marker) (current-buffer)))
13801 ;; FIXME: test this, this is w/o notetaking!
13802 (let (org-log-note-clock-out) (org-clock-out)))
13803 (when buffer-file-name
13804 (save-buffer)
13805 (setq buffer-file-name nil))
13806 (remember-finalize))
13808 ;;;###autoload
13809 (defun org-remember (&optional goto org-force-remember-template-char)
13810 "Call `remember'. If this is already a remember buffer, re-apply template.
13811 If there is an active region, make sure remember uses it as initial content
13812 of the remember buffer.
13814 When called interactively with a `C-u' prefix argument GOTO, don't remember
13815 anything, just go to the file/headline where the selected template usually
13816 stores its notes. With a double prefix arg `C-u C-u', go to the last
13817 note stored by remember.
13819 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13820 associated with a template in `org-remember-templates'."
13821 (interactive "P")
13822 (cond
13823 ((equal goto '(4)) (org-go-to-remember-target))
13824 ((equal goto '(16)) (org-remember-goto-last-stored))
13826 (if (memq org-finish-function '(remember-buffer remember-finalize))
13827 (progn
13828 (when (< (length org-remember-templates) 2)
13829 (error "No other template available"))
13830 (erase-buffer)
13831 (let ((annotation (plist-get org-store-link-plist :annotation))
13832 (initial (plist-get org-store-link-plist :initial)))
13833 (org-remember-apply-template))
13834 (message "Press C-c C-c to remember data"))
13835 (if (org-region-active-p)
13836 (remember (buffer-substring (point) (mark)))
13837 (call-interactively 'remember))))))
13839 (defun org-remember-goto-last-stored ()
13840 "Go to the location where the last remember note was stored."
13841 (interactive)
13842 (bookmark-jump "org-remember-last-stored")
13843 (message "This is the last note stored by remember"))
13845 (defun org-go-to-remember-target (&optional template-key)
13846 "Go to the target location of a remember template.
13847 The user is queried for the template."
13848 (interactive)
13849 (let* ((entry (org-select-remember-template template-key))
13850 (file (nth 1 entry))
13851 (heading (nth 2 entry))
13852 visiting)
13853 (unless (and file (stringp file) (string-match "\\S-" file))
13854 (setq file org-default-notes-file))
13855 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13856 (setq heading org-remember-default-headline))
13857 (setq visiting (org-find-base-buffer-visiting file))
13858 (if (not visiting) (find-file-noselect file))
13859 (switch-to-buffer (or visiting (get-file-buffer file)))
13860 (widen)
13861 (goto-char (point-min))
13862 (if (re-search-forward
13863 (concat "^\\*+[ \t]+" (regexp-quote heading)
13864 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13865 nil t)
13866 (goto-char (match-beginning 0))
13867 (error "Target headline not found: %s" heading))))
13869 (defvar org-note-abort nil) ; dynamically scoped
13871 ;;;###autoload
13872 (defun org-remember-handler ()
13873 "Store stuff from remember.el into an org file.
13874 First prompts for an org file. If the user just presses return, the value
13875 of `org-default-notes-file' is used.
13876 Then the command offers the headings tree of the selected file in order to
13877 file the text at a specific location.
13878 You can either immediately press RET to get the note appended to the
13879 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13880 find a better place. Then press RET or <left> or <right> in insert the note.
13882 Key Cursor position Note gets inserted
13883 -----------------------------------------------------------------------------
13884 RET buffer-start as level 1 heading at end of file
13885 RET on headline as sublevel of the heading at cursor
13886 RET no heading at cursor position, level taken from context.
13887 Or use prefix arg to specify level manually.
13888 <left> on headline as same level, before current heading
13889 <right> on headline as same level, after current heading
13891 So the fastest way to store the note is to press RET RET to append it to
13892 the default file. This way your current train of thought is not
13893 interrupted, in accordance with the principles of remember.el.
13894 You can also get the fast execution without prompting by using
13895 C-u C-c C-c to exit the remember buffer. See also the variable
13896 `org-remember-store-without-prompt'.
13898 Before being stored away, the function ensures that the text has a
13899 headline, i.e. a first line that starts with a \"*\". If not, a headline
13900 is constructed from the current date and some additional data.
13902 If the variable `org-adapt-indentation' is non-nil, the entire text is
13903 also indented so that it starts in the same column as the headline
13904 \(i.e. after the stars).
13906 See also the variable `org-reverse-note-order'."
13907 (goto-char (point-min))
13908 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13909 (replace-match ""))
13910 (goto-char (point-max))
13911 (beginning-of-line 1)
13912 (while (looking-at "[ \t]*$\\|##.*")
13913 (delete-region (1- (point)) (point-max))
13914 (beginning-of-line 1))
13915 (catch 'quit
13916 (if org-note-abort (throw 'quit nil))
13917 (let* ((txt (buffer-substring (point-min) (point-max)))
13918 (fastp (org-xor (equal current-prefix-arg '(4))
13919 org-remember-store-without-prompt))
13920 (file (cond
13921 (fastp org-default-notes-file)
13922 ((and (eq org-remember-interactive-interface 'refile)
13923 org-refile-targets)
13924 org-default-notes-file)
13925 ((not (and (equal current-prefix-arg '(16))
13926 org-remember-previous-location))
13927 (org-get-org-file))))
13928 (heading org-remember-default-headline)
13929 (visiting (and file (org-find-base-buffer-visiting file)))
13930 (org-startup-folded nil)
13931 (org-startup-align-all-tables nil)
13932 (org-goto-start-pos 1)
13933 spos exitcmd level indent reversed)
13934 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13935 (setq file (car org-remember-previous-location)
13936 heading (cdr org-remember-previous-location)
13937 fastp t))
13938 (setq current-prefix-arg nil)
13939 (if (string-match "[ \t\n]+\\'" txt)
13940 (setq txt (replace-match "" t t txt)))
13941 ;; Modify text so that it becomes a nice subtree which can be inserted
13942 ;; into an org tree.
13943 (let* ((lines (split-string txt "\n"))
13944 first)
13945 (setq first (car lines) lines (cdr lines))
13946 (if (string-match "^\\*+ " first)
13947 ;; Is already a headline
13948 (setq indent nil)
13949 ;; We need to add a headline: Use time and first buffer line
13950 (setq lines (cons first lines)
13951 first (concat "* " (current-time-string)
13952 " (" (remember-buffer-desc) ")")
13953 indent " "))
13954 (if (and org-adapt-indentation indent)
13955 (setq lines (mapcar
13956 (lambda (x)
13957 (if (string-match "\\S-" x)
13958 (concat indent x) x))
13959 lines)))
13960 (setq txt (concat first "\n"
13961 (mapconcat 'identity lines "\n"))))
13962 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13963 (setq txt (replace-match "\n\n" t t txt))
13964 (if (string-match "[ \t\n]*\\'" txt)
13965 (setq txt (replace-match "\n" t t txt))))
13966 ;; Put the modified text back into the remember buffer, for refile.
13967 (erase-buffer)
13968 (insert txt)
13969 (goto-char (point-min))
13970 (when (and (eq org-remember-interactive-interface 'refile)
13971 (not fastp))
13972 (org-refile nil (or visiting (find-file-noselect file)))
13973 (throw 'quit t))
13974 ;; Find the file
13975 (if (not visiting) (find-file-noselect file))
13976 (with-current-buffer (or visiting (get-file-buffer file))
13977 (unless (org-mode-p)
13978 (error "Target files for remember notes must be in Org-mode"))
13979 (save-excursion
13980 (save-restriction
13981 (widen)
13982 (and (goto-char (point-min))
13983 (not (re-search-forward "^\\* " nil t))
13984 (insert "\n* " (or heading "Notes") "\n"))
13985 (setq reversed (org-notes-order-reversed-p))
13987 ;; Find the default location
13988 (when (and heading (stringp heading) (string-match "\\S-" heading))
13989 (goto-char (point-min))
13990 (if (re-search-forward
13991 (concat "^\\*+[ \t]+" (regexp-quote heading)
13992 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13993 nil t)
13994 (setq org-goto-start-pos (match-beginning 0))
13995 (when fastp
13996 (goto-char (point-max))
13997 (unless (bolp) (newline))
13998 (insert "* " heading "\n")
13999 (setq org-goto-start-pos (point-at-bol 0)))))
14001 ;; Ask the User for a location, using the appropriate interface
14002 (cond
14003 (fastp (setq spos org-goto-start-pos
14004 exitcmd 'return))
14005 ((eq org-remember-interactive-interface 'outline)
14006 (setq spos (org-get-location (current-buffer)
14007 org-remember-help)
14008 exitcmd (cdr spos)
14009 spos (car spos)))
14010 ((eq org-remember-interactive-interface 'outline-path-completion)
14011 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
14012 (org-refile-use-outline-path t))
14013 (setq spos (org-refile-get-location "Heading: ")
14014 exitcmd 'return
14015 spos (nth 3 spos))))
14016 (t (error "this should not hapen")))
14017 (if (not spos) (throw 'quit nil)) ; return nil to show we did
14018 ; not handle this note
14019 (goto-char spos)
14020 (cond ((org-on-heading-p t)
14021 (org-back-to-heading t)
14022 (setq level (funcall outline-level))
14023 (cond
14024 ((eq exitcmd 'return)
14025 ;; sublevel of current
14026 (setq org-remember-previous-location
14027 (cons (abbreviate-file-name file)
14028 (org-get-heading 'notags)))
14029 (if reversed
14030 (outline-next-heading)
14031 (org-end-of-subtree t)
14032 (if (not (bolp))
14033 (if (looking-at "[ \t]*\n")
14034 (beginning-of-line 2)
14035 (end-of-line 1)
14036 (insert "\n"))))
14037 (bookmark-set "org-remember-last-stored")
14038 (org-paste-subtree (org-get-legal-level level 1) txt))
14039 ((eq exitcmd 'left)
14040 ;; before current
14041 (bookmark-set "org-remember-last-stored")
14042 (org-paste-subtree level txt))
14043 ((eq exitcmd 'right)
14044 ;; after current
14045 (org-end-of-subtree t)
14046 (bookmark-set "org-remember-last-stored")
14047 (org-paste-subtree level txt))
14048 (t (error "This should not happen"))))
14050 ((and (bobp) (not reversed))
14051 ;; Put it at the end, one level below level 1
14052 (save-restriction
14053 (widen)
14054 (goto-char (point-max))
14055 (if (not (bolp)) (newline))
14056 (bookmark-set "org-remember-last-stored")
14057 (org-paste-subtree (org-get-legal-level 1 1) txt)))
14059 ((and (bobp) reversed)
14060 ;; Put it at the start, as level 1
14061 (save-restriction
14062 (widen)
14063 (goto-char (point-min))
14064 (re-search-forward "^\\*+ " nil t)
14065 (beginning-of-line 1)
14066 (bookmark-set "org-remember-last-stored")
14067 (org-paste-subtree 1 txt)))
14069 ;; Put it right there, with automatic level determined by
14070 ;; org-paste-subtree or from prefix arg
14071 (bookmark-set "org-remember-last-stored")
14072 (org-paste-subtree
14073 (if (numberp current-prefix-arg) current-prefix-arg)
14074 txt)))
14075 (when remember-save-after-remembering
14076 (save-buffer)
14077 (if (not visiting) (kill-buffer (current-buffer)))))))))
14079 t) ;; return t to indicate that we took care of this note.
14081 (defun org-get-org-file ()
14082 "Read a filename, with default directory `org-directory'."
14083 (let ((default (or org-default-notes-file remember-data-file)))
14084 (read-file-name (format "File name [%s]: " default)
14085 (file-name-as-directory org-directory)
14086 default)))
14088 (defun org-notes-order-reversed-p ()
14089 "Check if the current file should receive notes in reversed order."
14090 (cond
14091 ((not org-reverse-note-order) nil)
14092 ((eq t org-reverse-note-order) t)
14093 ((not (listp org-reverse-note-order)) nil)
14094 (t (catch 'exit
14095 (let ((all org-reverse-note-order)
14096 entry)
14097 (while (setq entry (pop all))
14098 (if (string-match (car entry) buffer-file-name)
14099 (throw 'exit (cdr entry))))
14100 nil)))))
14102 ;;; Refiling
14104 (defvar org-refile-target-table nil
14105 "The list of refile targets, created by `org-refile'.")
14107 (defvar org-agenda-new-buffers nil
14108 "Buffers created to visit agenda files.")
14110 (defun org-get-refile-targets (&optional default-buffer)
14111 "Produce a table with refile targets."
14112 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
14113 targets txt re files f desc descre)
14114 (with-current-buffer (or default-buffer (current-buffer))
14115 (while (setq entry (pop entries))
14116 (setq files (car entry) desc (cdr entry))
14117 (cond
14118 ((null files) (setq files (list (current-buffer))))
14119 ((eq files 'org-agenda-files)
14120 (setq files (org-agenda-files 'unrestricted)))
14121 ((and (symbolp files) (fboundp files))
14122 (setq files (funcall files)))
14123 ((and (symbolp files) (boundp files))
14124 (setq files (symbol-value files))))
14125 (if (stringp files) (setq files (list files)))
14126 (cond
14127 ((eq (car desc) :tag)
14128 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
14129 ((eq (car desc) :todo)
14130 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
14131 ((eq (car desc) :regexp)
14132 (setq descre (cdr desc)))
14133 ((eq (car desc) :level)
14134 (setq descre (concat "^\\*\\{" (number-to-string
14135 (if org-odd-levels-only
14136 (1- (* 2 (cdr desc)))
14137 (cdr desc)))
14138 "\\}[ \t]")))
14139 ((eq (car desc) :maxlevel)
14140 (setq descre (concat "^\\*\\{1," (number-to-string
14141 (if org-odd-levels-only
14142 (1- (* 2 (cdr desc)))
14143 (cdr desc)))
14144 "\\}[ \t]")))
14145 (t (error "Bad refiling target description %s" desc)))
14146 (while (setq f (pop files))
14147 (save-excursion
14148 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
14149 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
14150 (save-excursion
14151 (save-restriction
14152 (widen)
14153 (goto-char (point-min))
14154 (while (re-search-forward descre nil t)
14155 (goto-char (point-at-bol))
14156 (when (looking-at org-complex-heading-regexp)
14157 (setq txt (match-string 4)
14158 re (concat "^" (regexp-quote
14159 (buffer-substring (match-beginning 1)
14160 (match-end 4)))))
14161 (if (match-end 5) (setq re (concat re "[ \t]+"
14162 (regexp-quote
14163 (match-string 5)))))
14164 (setq re (concat re "[ \t]*$"))
14165 (when org-refile-use-outline-path
14166 (setq txt (mapconcat 'identity
14167 (append
14168 (if (eq org-refile-use-outline-path 'file)
14169 (list (file-name-nondirectory
14170 (buffer-file-name (buffer-base-buffer))))
14171 (if (eq org-refile-use-outline-path 'full-file-path)
14172 (list (buffer-file-name (buffer-base-buffer)))))
14173 (org-get-outline-path)
14174 (list txt))
14175 "/")))
14176 (push (list txt f re (point)) targets))
14177 (goto-char (point-at-eol))))))))
14178 (nreverse targets))))
14180 (defun org-get-outline-path ()
14181 "Return the outline path to the current entry, as a list."
14182 (let (rtn)
14183 (save-excursion
14184 (while (org-up-heading-safe)
14185 (when (looking-at org-complex-heading-regexp)
14186 (push (org-match-string-no-properties 4) rtn)))
14187 rtn)))
14189 (defvar org-refile-history nil
14190 "History for refiling operations.")
14192 (defun org-refile (&optional goto default-buffer)
14193 "Move the entry at point to another heading.
14194 The list of target headings is compiled using the information in
14195 `org-refile-targets', which see. This list is created upon first use, and
14196 you can update it by calling this command with a double prefix (`C-u C-u').
14197 FIXME: Can we find a better way of updating?
14199 At the target location, the entry is filed as a subitem of the target heading.
14200 Depending on `org-reverse-note-order', the new subitem will either be the
14201 first of the last subitem.
14203 With prefix arg GOTO, the command will only visit the target location,
14204 not actually move anything.
14205 With a double prefix `C-c C-c', go to the location where the last refiling
14206 operation has put the subtree.
14208 With a double prefix argument, the command can be used to jump to any
14209 heading in the current buffer."
14210 (interactive "P")
14211 (let* ((cbuf (current-buffer))
14212 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14213 pos it nbuf file re level reversed)
14214 (if (equal goto '(16))
14215 (org-refile-goto-last-stored)
14216 (when (setq it (org-refile-get-location
14217 (if goto "Goto: " "Refile to: ") default-buffer))
14218 (setq file (nth 1 it)
14219 re (nth 2 it)
14220 pos (nth 3 it))
14221 (setq nbuf (or (find-buffer-visiting file)
14222 (find-file-noselect file)))
14223 (if goto
14224 (progn
14225 (switch-to-buffer nbuf)
14226 (goto-char pos)
14227 (org-show-context 'org-goto))
14228 (org-copy-special)
14229 (save-excursion
14230 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14231 (find-file-noselect file))))
14232 (setq reversed (org-notes-order-reversed-p))
14233 (save-excursion
14234 (save-restriction
14235 (widen)
14236 (goto-char pos)
14237 (looking-at outline-regexp)
14238 (setq level (org-get-legal-level (funcall outline-level) 1))
14239 (goto-char
14240 (if reversed
14241 (outline-next-heading)
14242 (or (save-excursion (outline-get-next-sibling))
14243 (org-end-of-subtree t t)
14244 (point-max))))
14245 (bookmark-set "org-refile-last-stored")
14246 (org-paste-subtree level))))
14247 (org-cut-special)
14248 (message "Entry refiled to \"%s\"" (car it)))))))
14250 (defun org-refile-goto-last-stored ()
14251 "Go to the location where the last refile was stored."
14252 (interactive)
14253 (bookmark-jump "org-refile-last-stored")
14254 (message "This is the location of the last refile"))
14256 (defun org-refile-get-location (&optional prompt default-buffer)
14257 "Prompt the user for a refile location, using PROMPT."
14258 (let ((org-refile-targets org-refile-targets)
14259 (org-refile-use-outline-path org-refile-use-outline-path))
14260 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14261 (unless org-refile-target-table
14262 (error "No refile targets"))
14263 (let* ((cbuf (current-buffer))
14264 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14265 (fname (and filename (file-truename filename)))
14266 (tbl (mapcar
14267 (lambda (x)
14268 (if (not (equal fname (file-truename (nth 1 x))))
14269 (cons (concat (car x) " (" (file-name-nondirectory
14270 (nth 1 x)) ")")
14271 (cdr x))
14273 org-refile-target-table))
14274 (completion-ignore-case t))
14275 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14276 tbl)))
14278 ;;;; Dynamic blocks
14280 (defun org-find-dblock (name)
14281 "Find the first dynamic block with name NAME in the buffer.
14282 If not found, stay at current position and return nil."
14283 (let (pos)
14284 (save-excursion
14285 (goto-char (point-min))
14286 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14287 nil t)
14288 (match-beginning 0))))
14289 (if pos (goto-char pos))
14290 pos))
14292 (defconst org-dblock-start-re
14293 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14294 "Matches the startline of a dynamic block, with parameters.")
14296 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14297 "Matches the end of a dyhamic block.")
14299 (defun org-create-dblock (plist)
14300 "Create a dynamic block section, with parameters taken from PLIST.
14301 PLIST must containe a :name entry which is used as name of the block."
14302 (unless (bolp) (newline))
14303 (let ((name (plist-get plist :name)))
14304 (insert "#+BEGIN: " name)
14305 (while plist
14306 (if (eq (car plist) :name)
14307 (setq plist (cddr plist))
14308 (insert " " (prin1-to-string (pop plist)))))
14309 (insert "\n\n#+END:\n")
14310 (beginning-of-line -2)))
14312 (defun org-prepare-dblock ()
14313 "Prepare dynamic block for refresh.
14314 This empties the block, puts the cursor at the insert position and returns
14315 the property list including an extra property :name with the block name."
14316 (unless (looking-at org-dblock-start-re)
14317 (error "Not at a dynamic block"))
14318 (let* ((begdel (1+ (match-end 0)))
14319 (name (org-no-properties (match-string 1)))
14320 (params (append (list :name name)
14321 (read (concat "(" (match-string 3) ")")))))
14322 (unless (re-search-forward org-dblock-end-re nil t)
14323 (error "Dynamic block not terminated"))
14324 (delete-region begdel (match-beginning 0))
14325 (goto-char begdel)
14326 (open-line 1)
14327 params))
14329 (defun org-map-dblocks (&optional command)
14330 "Apply COMMAND to all dynamic blocks in the current buffer.
14331 If COMMAND is not given, use `org-update-dblock'."
14332 (let ((cmd (or command 'org-update-dblock))
14333 pos)
14334 (save-excursion
14335 (goto-char (point-min))
14336 (while (re-search-forward org-dblock-start-re nil t)
14337 (goto-char (setq pos (match-beginning 0)))
14338 (condition-case nil
14339 (funcall cmd)
14340 (error (message "Error during update of dynamic block")))
14341 (goto-char pos)
14342 (unless (re-search-forward org-dblock-end-re nil t)
14343 (error "Dynamic block not terminated"))))))
14345 (defun org-dblock-update (&optional arg)
14346 "User command for updating dynamic blocks.
14347 Update the dynamic block at point. With prefix ARG, update all dynamic
14348 blocks in the buffer."
14349 (interactive "P")
14350 (if arg
14351 (org-update-all-dblocks)
14352 (or (looking-at org-dblock-start-re)
14353 (org-beginning-of-dblock))
14354 (org-update-dblock)))
14356 (defun org-update-dblock ()
14357 "Update the dynamic block at point
14358 This means to empty the block, parse for parameters and then call
14359 the correct writing function."
14360 (save-window-excursion
14361 (let* ((pos (point))
14362 (line (org-current-line))
14363 (params (org-prepare-dblock))
14364 (name (plist-get params :name))
14365 (cmd (intern (concat "org-dblock-write:" name))))
14366 (message "Updating dynamic block `%s' at line %d..." name line)
14367 (funcall cmd params)
14368 (message "Updating dynamic block `%s' at line %d...done" name line)
14369 (goto-char pos))))
14371 (defun org-beginning-of-dblock ()
14372 "Find the beginning of the dynamic block at point.
14373 Error if there is no scuh block at point."
14374 (let ((pos (point))
14375 beg)
14376 (end-of-line 1)
14377 (if (and (re-search-backward org-dblock-start-re nil t)
14378 (setq beg (match-beginning 0))
14379 (re-search-forward org-dblock-end-re nil t)
14380 (> (match-end 0) pos))
14381 (goto-char beg)
14382 (goto-char pos)
14383 (error "Not in a dynamic block"))))
14385 (defun org-update-all-dblocks ()
14386 "Update all dynamic blocks in the buffer.
14387 This function can be used in a hook."
14388 (when (org-mode-p)
14389 (org-map-dblocks 'org-update-dblock)))
14392 ;;;; Completion
14394 (defconst org-additional-option-like-keywords
14395 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14396 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14397 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14399 (defun org-complete (&optional arg)
14400 "Perform completion on word at point.
14401 At the beginning of a headline, this completes TODO keywords as given in
14402 `org-todo-keywords'.
14403 If the current word is preceded by a backslash, completes the TeX symbols
14404 that are supported for HTML support.
14405 If the current word is preceded by \"#+\", completes special words for
14406 setting file options.
14407 In the line after \"#+STARTUP:, complete valid keywords.\"
14408 At all other locations, this simply calls the value of
14409 `org-completion-fallback-command'."
14410 (interactive "P")
14411 (org-without-partial-completion
14412 (catch 'exit
14413 (let* ((end (point))
14414 (beg1 (save-excursion
14415 (skip-chars-backward (org-re "[:alnum:]_@"))
14416 (point)))
14417 (beg (save-excursion
14418 (skip-chars-backward "a-zA-Z0-9_:$")
14419 (point)))
14420 (confirm (lambda (x) (stringp (car x))))
14421 (searchhead (equal (char-before beg) ?*))
14422 (tag (and (equal (char-before beg1) ?:)
14423 (equal (char-after (point-at-bol)) ?*)))
14424 (prop (and (equal (char-before beg1) ?:)
14425 (not (equal (char-after (point-at-bol)) ?*))))
14426 (texp (equal (char-before beg) ?\\))
14427 (link (equal (char-before beg) ?\[))
14428 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14429 beg)
14430 "#+"))
14431 (startup (string-match "^#\\+STARTUP:.*"
14432 (buffer-substring (point-at-bol) (point))))
14433 (completion-ignore-case opt)
14434 (type nil)
14435 (tbl nil)
14436 (table (cond
14437 (opt
14438 (setq type :opt)
14439 (append
14440 (mapcar
14441 (lambda (x)
14442 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14443 (cons (match-string 2 x) (match-string 1 x)))
14444 (org-split-string (org-get-current-options) "\n"))
14445 (mapcar 'list org-additional-option-like-keywords)))
14446 (startup
14447 (setq type :startup)
14448 org-startup-options)
14449 (link (append org-link-abbrev-alist-local
14450 org-link-abbrev-alist))
14451 (texp
14452 (setq type :tex)
14453 org-html-entities)
14454 ((string-match "\\`\\*+[ \t]+\\'"
14455 (buffer-substring (point-at-bol) beg))
14456 (setq type :todo)
14457 (mapcar 'list org-todo-keywords-1))
14458 (searchhead
14459 (setq type :searchhead)
14460 (save-excursion
14461 (goto-char (point-min))
14462 (while (re-search-forward org-todo-line-regexp nil t)
14463 (push (list
14464 (org-make-org-heading-search-string
14465 (match-string 3) t))
14466 tbl)))
14467 tbl)
14468 (tag (setq type :tag beg beg1)
14469 (or org-tag-alist (org-get-buffer-tags)))
14470 (prop (setq type :prop beg beg1)
14471 (mapcar 'list (org-buffer-property-keys nil t t)))
14472 (t (progn
14473 (call-interactively org-completion-fallback-command)
14474 (throw 'exit nil)))))
14475 (pattern (buffer-substring-no-properties beg end))
14476 (completion (try-completion pattern table confirm)))
14477 (cond ((eq completion t)
14478 (if (not (assoc (upcase pattern) table))
14479 (message "Already complete")
14480 (if (equal type :opt)
14481 (insert (substring (cdr (assoc (upcase pattern) table))
14482 (length pattern)))
14483 (if (memq type '(:tag :prop)) (insert ":")))))
14484 ((null completion)
14485 (message "Can't find completion for \"%s\"" pattern)
14486 (ding))
14487 ((not (string= pattern completion))
14488 (delete-region beg end)
14489 (if (string-match " +$" completion)
14490 (setq completion (replace-match "" t t completion)))
14491 (insert completion)
14492 (if (get-buffer-window "*Completions*")
14493 (delete-window (get-buffer-window "*Completions*")))
14494 (if (assoc completion table)
14495 (if (eq type :todo) (insert " ")
14496 (if (memq type '(:tag :prop)) (insert ":"))))
14497 (if (and (equal type :opt) (assoc completion table))
14498 (message "%s" (substitute-command-keys
14499 "Press \\[org-complete] again to insert example settings"))))
14501 (message "Making completion list...")
14502 (let ((list (sort (all-completions pattern table confirm)
14503 'string<)))
14504 (with-output-to-temp-buffer "*Completions*"
14505 (condition-case nil
14506 ;; Protection needed for XEmacs and emacs 21
14507 (display-completion-list list pattern)
14508 (error (display-completion-list list)))))
14509 (message "Making completion list...%s" "done")))))))
14511 ;;;; TODO, DEADLINE, Comments
14513 (defun org-toggle-comment ()
14514 "Change the COMMENT state of an entry."
14515 (interactive)
14516 (save-excursion
14517 (org-back-to-heading)
14518 (let (case-fold-search)
14519 (if (looking-at (concat outline-regexp
14520 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14521 (replace-match "" t t nil 1)
14522 (if (looking-at outline-regexp)
14523 (progn
14524 (goto-char (match-end 0))
14525 (insert org-comment-string " ")))))))
14527 (defvar org-last-todo-state-is-todo nil
14528 "This is non-nil when the last TODO state change led to a TODO state.
14529 If the last change removed the TODO tag or switched to DONE, then
14530 this is nil.")
14532 (defvar org-setting-tags nil) ; dynamically skiped
14534 ;; FIXME: better place
14535 (defun org-property-or-variable-value (var &optional inherit)
14536 "Check if there is a property fixing the value of VAR.
14537 If yes, return this value. If not, return the current value of the variable."
14538 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14539 (if (and prop (stringp prop) (string-match "\\S-" prop))
14540 (read prop)
14541 (symbol-value var))))
14543 (defun org-parse-local-options (string var)
14544 "Parse STRING for startup setting relevant for variable VAR."
14545 (let ((rtn (symbol-value var))
14546 e opts)
14547 (save-match-data
14548 (if (or (not string) (not (string-match "\\S-" string)))
14550 (setq opts (delq nil (mapcar (lambda (x)
14551 (setq e (assoc x org-startup-options))
14552 (if (eq (nth 1 e) var) e nil))
14553 (org-split-string string "[ \t]+"))))
14554 (if (not opts)
14556 (setq rtn nil)
14557 (while (setq e (pop opts))
14558 (if (not (nth 3 e))
14559 (setq rtn (nth 2 e))
14560 (if (not (listp rtn)) (setq rtn nil))
14561 (push (nth 2 e) rtn)))
14562 rtn)))))
14564 (defvar org-blocker-hook nil
14565 "Hook for functions that are allowed to block a state change.
14567 Each function gets as its single argument a property list, see
14568 `org-trigger-hook' for more information about this list.
14570 If any of the functions in this hook returns nil, the state change
14571 is blocked.")
14573 (defvar org-trigger-hook nil
14574 "Hook for functions that are triggered by a state change.
14576 Each function gets as its single argument a property list with at least
14577 the following elements:
14579 (:type type-of-change :position pos-at-entry-start
14580 :from old-state :to new-state)
14582 Depending on the type, more properties may be present.
14584 This mechanism is currently implemented for:
14586 TODO state changes
14587 ------------------
14588 :type todo-state-change
14589 :from previous state (keyword as a string), or nil
14590 :to new state (keyword as a string), or nil")
14593 (defun org-todo (&optional arg)
14594 "Change the TODO state of an item.
14595 The state of an item is given by a keyword at the start of the heading,
14596 like
14597 *** TODO Write paper
14598 *** DONE Call mom
14600 The different keywords are specified in the variable `org-todo-keywords'.
14601 By default the available states are \"TODO\" and \"DONE\".
14602 So for this example: when the item starts with TODO, it is changed to DONE.
14603 When it starts with DONE, the DONE is removed. And when neither TODO nor
14604 DONE are present, add TODO at the beginning of the heading.
14606 With C-u prefix arg, use completion to determine the new state.
14607 With numeric prefix arg, switch to that state.
14609 For calling through lisp, arg is also interpreted in the following way:
14610 'none -> empty state
14611 \"\"(empty string) -> switch to empty state
14612 'done -> switch to DONE
14613 'nextset -> switch to the next set of keywords
14614 'previousset -> switch to the previous set of keywords
14615 \"WAITING\" -> switch to the specified keyword, but only if it
14616 really is a member of `org-todo-keywords'."
14617 (interactive "P")
14618 (save-excursion
14619 (catch 'exit
14620 (org-back-to-heading)
14621 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14622 (or (looking-at (concat " +" org-todo-regexp " *"))
14623 (looking-at " *"))
14624 (let* ((match-data (match-data))
14625 (startpos (point-at-bol))
14626 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14627 (org-log-done org-log-done)
14628 (org-log-repeat org-log-repeat)
14629 (org-todo-log-states org-todo-log-states)
14630 (this (match-string 1))
14631 (hl-pos (match-beginning 0))
14632 (head (org-get-todo-sequence-head this))
14633 (ass (assoc head org-todo-kwd-alist))
14634 (interpret (nth 1 ass))
14635 (done-word (nth 3 ass))
14636 (final-done-word (nth 4 ass))
14637 (last-state (or this ""))
14638 (completion-ignore-case t)
14639 (member (member this org-todo-keywords-1))
14640 (tail (cdr member))
14641 (state (cond
14642 ((and org-todo-key-trigger
14643 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14644 (and (not arg) org-use-fast-todo-selection
14645 (not (eq org-use-fast-todo-selection 'prefix)))))
14646 ;; Use fast selection
14647 (org-fast-todo-selection))
14648 ((and (equal arg '(4))
14649 (or (not org-use-fast-todo-selection)
14650 (not org-todo-key-trigger)))
14651 ;; Read a state with completion
14652 (completing-read "State: " (mapcar (lambda(x) (list x))
14653 org-todo-keywords-1)
14654 nil t))
14655 ((eq arg 'right)
14656 (if this
14657 (if tail (car tail) nil)
14658 (car org-todo-keywords-1)))
14659 ((eq arg 'left)
14660 (if (equal member org-todo-keywords-1)
14662 (if this
14663 (nth (- (length org-todo-keywords-1) (length tail) 2)
14664 org-todo-keywords-1)
14665 (org-last org-todo-keywords-1))))
14666 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14667 (setq arg nil))) ; hack to fall back to cycling
14668 (arg
14669 ;; user or caller requests a specific state
14670 (cond
14671 ((equal arg "") nil)
14672 ((eq arg 'none) nil)
14673 ((eq arg 'done) (or done-word (car org-done-keywords)))
14674 ((eq arg 'nextset)
14675 (or (car (cdr (member head org-todo-heads)))
14676 (car org-todo-heads)))
14677 ((eq arg 'previousset)
14678 (let ((org-todo-heads (reverse org-todo-heads)))
14679 (or (car (cdr (member head org-todo-heads)))
14680 (car org-todo-heads))))
14681 ((car (member arg org-todo-keywords-1)))
14682 ((nth (1- (prefix-numeric-value arg))
14683 org-todo-keywords-1))))
14684 ((null member) (or head (car org-todo-keywords-1)))
14685 ((equal this final-done-word) nil) ;; -> make empty
14686 ((null tail) nil) ;; -> first entry
14687 ((eq interpret 'sequence)
14688 (car tail))
14689 ((memq interpret '(type priority))
14690 (if (eq this-command last-command)
14691 (car tail)
14692 (if (> (length tail) 0)
14693 (or done-word (car org-done-keywords))
14694 nil)))
14695 (t nil)))
14696 (next (if state (concat " " state " ") " "))
14697 (change-plist (list :type 'todo-state-change :from this :to state
14698 :position startpos))
14699 dolog now-done-p)
14700 (when org-blocker-hook
14701 (unless (save-excursion
14702 (save-match-data
14703 (run-hook-with-args-until-failure
14704 'org-blocker-hook change-plist)))
14705 (if (interactive-p)
14706 (error "TODO state change from %s to %s blocked" this state)
14707 ;; fail silently
14708 (message "TODO state change from %s to %s blocked" this state)
14709 (throw 'exit nil))))
14710 (store-match-data match-data)
14711 (replace-match next t t)
14712 (unless (pos-visible-in-window-p hl-pos)
14713 (message "TODO state changed to %s" (org-trim next)))
14714 (unless head
14715 (setq head (org-get-todo-sequence-head state)
14716 ass (assoc head org-todo-kwd-alist)
14717 interpret (nth 1 ass)
14718 done-word (nth 3 ass)
14719 final-done-word (nth 4 ass)))
14720 (when (memq arg '(nextset previousset))
14721 (message "Keyword-Set %d/%d: %s"
14722 (- (length org-todo-sets) -1
14723 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14724 (length org-todo-sets)
14725 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14726 (setq org-last-todo-state-is-todo
14727 (not (member state org-done-keywords)))
14728 (setq now-done-p (and (member state org-done-keywords)
14729 (not (member this org-done-keywords))))
14730 (and logging (org-local-logging logging))
14731 (when (and (or org-todo-log-states org-log-done)
14732 (not (memq arg '(nextset previousset))))
14733 ;; we need to look at recording a time and note
14734 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14735 (nth 2 (assoc this org-todo-log-states))))
14736 (when (and state
14737 (member state org-not-done-keywords)
14738 (not (member this org-not-done-keywords)))
14739 ;; This is now a todo state and was not one before
14740 ;; If there was a CLOSED time stamp, get rid of it.
14741 (org-add-planning-info nil nil 'closed))
14742 (when (and now-done-p org-log-done)
14743 ;; It is now done, and it was not done before
14744 (org-add-planning-info 'closed (org-current-time))
14745 (if (and (not dolog) (eq 'note org-log-done))
14746 (org-add-log-maybe 'done state 'findpos 'note)))
14747 (when (and state dolog)
14748 ;; This is a non-nil state, and we need to log it
14749 (org-add-log-maybe 'state state 'findpos dolog)))
14750 ;; Fixup tag positioning
14751 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14752 (run-hooks 'org-after-todo-state-change-hook)
14753 (if (and arg (not (member state org-done-keywords)))
14754 (setq head (org-get-todo-sequence-head state)))
14755 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14756 ;; Do we need to trigger a repeat?
14757 (when now-done-p (org-auto-repeat-maybe state))
14758 ;; Fixup cursor location if close to the keyword
14759 (if (and (outline-on-heading-p)
14760 (not (bolp))
14761 (save-excursion (beginning-of-line 1)
14762 (looking-at org-todo-line-regexp))
14763 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14764 (progn
14765 (goto-char (or (match-end 2) (match-end 1)))
14766 (just-one-space)))
14767 (when org-trigger-hook
14768 (save-excursion
14769 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14771 (defun org-local-logging (value)
14772 "Get logging settings from a property VALUE."
14773 (let* (words w a)
14774 ;; directly set the variables, they are already local.
14775 (setq org-log-done nil
14776 org-log-repeat nil
14777 org-todo-log-states nil)
14778 (setq words (org-split-string value))
14779 (while (setq w (pop words))
14780 (cond
14781 ((setq a (assoc w org-startup-options))
14782 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14783 (set (nth 1 a) (nth 2 a))))
14784 ((setq a (org-extract-log-state-settings w))
14785 (and (member (car a) org-todo-keywords-1)
14786 (push a org-todo-log-states)))))))
14788 (defun org-get-todo-sequence-head (kwd)
14789 "Return the head of the TODO sequence to which KWD belongs.
14790 If KWD is not set, check if there is a text property remembering the
14791 right sequence."
14792 (let (p)
14793 (cond
14794 ((not kwd)
14795 (or (get-text-property (point-at-bol) 'org-todo-head)
14796 (progn
14797 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14798 nil (point-at-eol)))
14799 (get-text-property p 'org-todo-head))))
14800 ((not (member kwd org-todo-keywords-1))
14801 (car org-todo-keywords-1))
14802 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14804 (defun org-fast-todo-selection ()
14805 "Fast TODO keyword selection with single keys.
14806 Returns the new TODO keyword, or nil if no state change should occur."
14807 (let* ((fulltable org-todo-key-alist)
14808 (done-keywords org-done-keywords) ;; needed for the faces.
14809 (maxlen (apply 'max (mapcar
14810 (lambda (x)
14811 (if (stringp (car x)) (string-width (car x)) 0))
14812 fulltable)))
14813 (expert nil)
14814 (fwidth (+ maxlen 3 1 3))
14815 (ncol (/ (- (window-width) 4) fwidth))
14816 tg cnt e c tbl
14817 groups ingroup)
14818 (save-window-excursion
14819 (if expert
14820 (set-buffer (get-buffer-create " *Org todo*"))
14821 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14822 (erase-buffer)
14823 (org-set-local 'org-done-keywords done-keywords)
14824 (setq tbl fulltable cnt 0)
14825 (while (setq e (pop tbl))
14826 (cond
14827 ((equal e '(:startgroup))
14828 (push '() groups) (setq ingroup t)
14829 (when (not (= cnt 0))
14830 (setq cnt 0)
14831 (insert "\n"))
14832 (insert "{ "))
14833 ((equal e '(:endgroup))
14834 (setq ingroup nil cnt 0)
14835 (insert "}\n"))
14837 (setq tg (car e) c (cdr e))
14838 (if ingroup (push tg (car groups)))
14839 (setq tg (org-add-props tg nil 'face
14840 (org-get-todo-face tg)))
14841 (if (and (= cnt 0) (not ingroup)) (insert " "))
14842 (insert "[" c "] " tg (make-string
14843 (- fwidth 4 (length tg)) ?\ ))
14844 (when (= (setq cnt (1+ cnt)) ncol)
14845 (insert "\n")
14846 (if ingroup (insert " "))
14847 (setq cnt 0)))))
14848 (insert "\n")
14849 (goto-char (point-min))
14850 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14851 (fit-window-to-buffer))
14852 (message "[a-z..]:Set [SPC]:clear")
14853 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14854 (cond
14855 ((or (= c ?\C-g)
14856 (and (= c ?q) (not (rassoc c fulltable))))
14857 (setq quit-flag t))
14858 ((= c ?\ ) nil)
14859 ((setq e (rassoc c fulltable) tg (car e))
14861 (t (setq quit-flag t))))))
14863 (defun org-get-repeat ()
14864 "Check if tere is a deadline/schedule with repeater in this entry."
14865 (save-match-data
14866 (save-excursion
14867 (org-back-to-heading t)
14868 (if (re-search-forward
14869 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14870 (match-string 1)))))
14872 (defvar org-last-changed-timestamp)
14873 (defvar org-log-post-message)
14874 (defvar org-log-note-purpose)
14875 (defun org-auto-repeat-maybe (done-word)
14876 "Check if the current headline contains a repeated deadline/schedule.
14877 If yes, set TODO state back to what it was and change the base date
14878 of repeating deadline/scheduled time stamps to new date.
14879 This function is run automatically after each state change to a DONE state."
14880 ;; last-state is dynamically scoped into this function
14881 (let* ((repeat (org-get-repeat))
14882 (aa (assoc last-state org-todo-kwd-alist))
14883 (interpret (nth 1 aa))
14884 (head (nth 2 aa))
14885 (whata '(("d" . day) ("m" . month) ("y" . year)))
14886 (msg "Entry repeats: ")
14887 (org-log-done nil)
14888 (org-todo-log-states nil)
14889 re type n what ts)
14890 (when repeat
14891 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
14892 (org-todo (if (eq interpret 'type) last-state head))
14893 (when (and org-log-repeat
14894 (or (not (memq 'org-add-log-note
14895 (default-value 'post-command-hook)))
14896 (eq org-log-note-purpose 'done)))
14897 ;; Make sure a note is taken;
14898 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
14899 'findpos org-log-repeat))
14900 (org-back-to-heading t)
14901 (org-add-planning-info nil nil 'closed)
14902 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14903 org-deadline-time-regexp "\\)\\|\\("
14904 org-ts-regexp "\\)"))
14905 (while (re-search-forward
14906 re (save-excursion (outline-next-heading) (point)) t)
14907 (setq type (if (match-end 1) org-scheduled-string
14908 (if (match-end 3) org-deadline-string "Plain:"))
14909 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14910 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14911 (setq n (string-to-number (match-string 1 ts))
14912 what (match-string 2 ts))
14913 (if (equal what "w") (setq n (* n 7) what "d"))
14914 (org-timestamp-change n (cdr (assoc what whata)))
14915 (setq msg (concat msg type org-last-changed-timestamp " "))))
14916 (setq org-log-post-message msg)
14917 (message "%s" msg))))
14919 (defun org-show-todo-tree (arg)
14920 "Make a compact tree which shows all headlines marked with TODO.
14921 The tree will show the lines where the regexp matches, and all higher
14922 headlines above the match.
14923 With a \\[universal-argument] prefix, also show the DONE entries.
14924 With a numeric prefix N, construct a sparse tree for the Nth element
14925 of `org-todo-keywords-1'."
14926 (interactive "P")
14927 (let ((case-fold-search nil)
14928 (kwd-re
14929 (cond ((null arg) org-not-done-regexp)
14930 ((equal arg '(4))
14931 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14932 (mapcar 'list org-todo-keywords-1))))
14933 (concat "\\("
14934 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14935 "\\)\\>")))
14936 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14937 (regexp-quote (nth (1- (prefix-numeric-value arg))
14938 org-todo-keywords-1)))
14939 (t (error "Invalid prefix argument: %s" arg)))))
14940 (message "%d TODO entries found"
14941 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14943 (defun org-deadline (&optional remove)
14944 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14945 With argument REMOVE, remove any deadline from the item."
14946 (interactive "P")
14947 (if remove
14948 (progn
14949 (org-remove-timestamp-with-keyword org-deadline-string)
14950 (message "Item no longer has a deadline."))
14951 (org-add-planning-info 'deadline nil 'closed)))
14953 (defun org-schedule (&optional remove)
14954 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14955 With argument REMOVE, remove any scheduling date from the item."
14956 (interactive "P")
14957 (if remove
14958 (progn
14959 (org-remove-timestamp-with-keyword org-scheduled-string)
14960 (message "Item is no longer scheduled."))
14961 (org-add-planning-info 'scheduled nil 'closed)))
14963 (defun org-remove-timestamp-with-keyword (keyword)
14964 "Remove all time stamps with KEYWORD in the current entry."
14965 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14966 beg)
14967 (save-excursion
14968 (org-back-to-heading t)
14969 (setq beg (point))
14970 (org-end-of-subtree t t)
14971 (while (re-search-backward re beg t)
14972 (replace-match "")
14973 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14974 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14976 (defun org-add-planning-info (what &optional time &rest remove)
14977 "Insert new timestamp with keyword in the line directly after the headline.
14978 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14979 If non is given, the user is prompted for a date.
14980 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14981 be removed."
14982 (interactive)
14983 (let (org-time-was-given org-end-time-was-given)
14984 (when what (setq time (or time (org-read-date nil 'to-time))))
14985 (when (and org-insert-labeled-timestamps-at-point
14986 (member what '(scheduled deadline)))
14987 (insert
14988 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14989 (org-insert-time-stamp time org-time-was-given
14990 nil nil nil (list org-end-time-was-given))
14991 (setq what nil))
14992 (save-excursion
14993 (save-restriction
14994 (let (col list elt ts buffer-invisibility-spec)
14995 (org-back-to-heading t)
14996 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14997 (goto-char (match-end 1))
14998 (setq col (current-column))
14999 (goto-char (match-end 0))
15000 (if (eobp) (insert "\n") (forward-char 1))
15001 (if (and (not (looking-at outline-regexp))
15002 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
15003 "[^\r\n]*"))
15004 (not (equal (match-string 1) org-clock-string)))
15005 (narrow-to-region (match-beginning 0) (match-end 0))
15006 (insert-before-markers "\n")
15007 (backward-char 1)
15008 (narrow-to-region (point) (point))
15009 (indent-to-column col))
15010 ;; Check if we have to remove something.
15011 (setq list (cons what remove))
15012 (while list
15013 (setq elt (pop list))
15014 (goto-char (point-min))
15015 (when (or (and (eq elt 'scheduled)
15016 (re-search-forward org-scheduled-time-regexp nil t))
15017 (and (eq elt 'deadline)
15018 (re-search-forward org-deadline-time-regexp nil t))
15019 (and (eq elt 'closed)
15020 (re-search-forward org-closed-time-regexp nil t)))
15021 (replace-match "")
15022 (if (looking-at "--+<[^>]+>") (replace-match ""))
15023 (if (looking-at " +") (replace-match ""))))
15024 (goto-char (point-max))
15025 (when what
15026 (insert
15027 (if (not (equal (char-before) ?\ )) " " "")
15028 (cond ((eq what 'scheduled) org-scheduled-string)
15029 ((eq what 'deadline) org-deadline-string)
15030 ((eq what 'closed) org-closed-string))
15031 " ")
15032 (setq ts (org-insert-time-stamp
15033 time
15034 (or org-time-was-given
15035 (and (eq what 'closed) org-log-done-with-time))
15036 (eq what 'closed)
15037 nil nil (list org-end-time-was-given)))
15038 (end-of-line 1))
15039 (goto-char (point-min))
15040 (widen)
15041 (if (looking-at "[ \t]+\r?\n")
15042 (replace-match ""))
15043 ts)))))
15045 (defvar org-log-note-marker (make-marker))
15046 (defvar org-log-note-purpose nil)
15047 (defvar org-log-note-state nil)
15048 (defvar org-log-note-how nil)
15049 (defvar org-log-note-window-configuration nil)
15050 (defvar org-log-note-return-to (make-marker))
15051 (defvar org-log-post-message nil
15052 "Message to be displayed after a log note has been stored.
15053 The auto-repeater uses this.")
15055 (defun org-add-log-maybe (&optional purpose state findpos how)
15056 "Set up the post command hook to take a note.
15057 If this is about to TODO state change, the new state is expected in STATE.
15058 When FINDPOS is non-nil, find the correct position for the note in
15059 the current entry. If not, assume that it can be inserted at point."
15060 (save-excursion
15061 (when findpos
15062 (org-back-to-heading t)
15063 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
15064 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
15065 "[^\r\n]*\\)?"))
15066 (goto-char (match-end 0))
15067 (unless org-log-states-order-reversed
15068 (and (= (char-after) ?\n) (forward-char 1))
15069 (org-skip-over-state-notes)
15070 (skip-chars-backward " \t\n\r")))
15071 (move-marker org-log-note-marker (point))
15072 (setq org-log-note-purpose purpose
15073 org-log-note-state state
15074 org-log-note-how how)
15075 (add-hook 'post-command-hook 'org-add-log-note 'append)))
15077 (defun org-skip-over-state-notes ()
15078 "Skip past the list of State notes in an entry."
15079 (if (looking-at "\n[ \t]*- State") (forward-char 1))
15080 (while (looking-at "[ \t]*- State")
15081 (condition-case nil
15082 (org-next-item)
15083 (error (org-end-of-item)))))
15085 (defun org-add-log-note (&optional purpose)
15086 "Pop up a window for taking a note, and add this note later at point."
15087 (remove-hook 'post-command-hook 'org-add-log-note)
15088 (setq org-log-note-window-configuration (current-window-configuration))
15089 (delete-other-windows)
15090 (move-marker org-log-note-return-to (point))
15091 (switch-to-buffer (marker-buffer org-log-note-marker))
15092 (goto-char org-log-note-marker)
15093 (org-switch-to-buffer-other-window "*Org Note*")
15094 (erase-buffer)
15095 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
15096 (org-store-log-note)
15097 (let ((org-inhibit-startup t)) (org-mode))
15098 (insert (format "# Insert note for %s.
15099 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
15100 (cond
15101 ((eq org-log-note-purpose 'clock-out) "stopped clock")
15102 ((eq org-log-note-purpose 'done) "closed todo item")
15103 ((eq org-log-note-purpose 'state)
15104 (format "state change to \"%s\"" org-log-note-state))
15105 (t (error "This should not happen")))))
15106 (org-set-local 'org-finish-function 'org-store-log-note)))
15108 (defun org-store-log-note ()
15109 "Finish taking a log note, and insert it to where it belongs."
15110 (let ((txt (buffer-string))
15111 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
15112 lines ind)
15113 (kill-buffer (current-buffer))
15114 (while (string-match "\\`#.*\n[ \t\n]*" txt)
15115 (setq txt (replace-match "" t t txt)))
15116 (if (string-match "\\s-+\\'" txt)
15117 (setq txt (replace-match "" t t txt)))
15118 (setq lines (org-split-string txt "\n"))
15119 (when (and note (string-match "\\S-" note))
15120 (setq note
15121 (org-replace-escapes
15122 note
15123 (list (cons "%u" (user-login-name))
15124 (cons "%U" user-full-name)
15125 (cons "%t" (format-time-string
15126 (org-time-stamp-format 'long 'inactive)
15127 (current-time)))
15128 (cons "%s" (if org-log-note-state
15129 (concat "\"" org-log-note-state "\"")
15130 "")))))
15131 (if lines (setq note (concat note " \\\\")))
15132 (push note lines))
15133 (when (or current-prefix-arg org-note-abort) (setq lines nil))
15134 (when lines
15135 (save-excursion
15136 (set-buffer (marker-buffer org-log-note-marker))
15137 (save-excursion
15138 (goto-char org-log-note-marker)
15139 (move-marker org-log-note-marker nil)
15140 (end-of-line 1)
15141 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
15142 (indent-relative nil)
15143 (insert "- " (pop lines))
15144 (org-indent-line-function)
15145 (beginning-of-line 1)
15146 (looking-at "[ \t]*")
15147 (setq ind (concat (match-string 0) " "))
15148 (end-of-line 1)
15149 (while lines (insert "\n" ind (pop lines)))))))
15150 (set-window-configuration org-log-note-window-configuration)
15151 (with-current-buffer (marker-buffer org-log-note-return-to)
15152 (goto-char org-log-note-return-to))
15153 (move-marker org-log-note-return-to nil)
15154 (and org-log-post-message (message "%s" org-log-post-message)))
15156 ;; FIXME: what else would be useful?
15157 ;; - priority
15158 ;; - date
15160 (defun org-sparse-tree (&optional arg)
15161 "Create a sparse tree, prompt for the details.
15162 This command can create sparse trees. You first need to select the type
15163 of match used to create the tree:
15165 t Show entries with a specific TODO keyword.
15166 T Show entries selected by a tags match.
15167 p Enter a property name and its value (both with completion on existing
15168 names/values) and show entries with that property.
15169 r Show entries matching a regular expression
15170 d Show deadlines due within `org-deadline-warning-days'."
15171 (interactive "P")
15172 (let (ans kwd value)
15173 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15174 (setq ans (read-char-exclusive))
15175 (cond
15176 ((equal ans ?d)
15177 (call-interactively 'org-check-deadlines))
15178 ((equal ans ?b)
15179 (call-interactively 'org-check-before-date))
15180 ((equal ans ?t)
15181 (org-show-todo-tree '(4)))
15182 ((equal ans ?T)
15183 (call-interactively 'org-tags-sparse-tree))
15184 ((member ans '(?p ?P))
15185 (setq kwd (completing-read "Property: "
15186 (mapcar 'list (org-buffer-property-keys))))
15187 (setq value (completing-read "Value: "
15188 (mapcar 'list (org-property-values kwd))))
15189 (unless (string-match "\\`{.*}\\'" value)
15190 (setq value (concat "\"" value "\"")))
15191 (org-tags-sparse-tree arg (concat kwd "=" value)))
15192 ((member ans '(?r ?R ?/))
15193 (call-interactively 'org-occur))
15194 (t (error "No such sparse tree command \"%c\"" ans)))))
15196 (defvar org-occur-highlights nil)
15197 (make-variable-buffer-local 'org-occur-highlights)
15199 (defun org-occur (regexp &optional keep-previous callback)
15200 "Make a compact tree which shows all matches of REGEXP.
15201 The tree will show the lines where the regexp matches, and all higher
15202 headlines above the match. It will also show the heading after the match,
15203 to make sure editing the matching entry is easy.
15204 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15205 call to `org-occur' will be kept, to allow stacking of calls to this
15206 command.
15207 If CALLBACK is non-nil, it is a function which is called to confirm
15208 that the match should indeed be shown."
15209 (interactive "sRegexp: \nP")
15210 (or keep-previous (org-remove-occur-highlights nil nil t))
15211 (let ((cnt 0))
15212 (save-excursion
15213 (goto-char (point-min))
15214 (if (or (not keep-previous) ; do not want to keep
15215 (not org-occur-highlights)) ; no previous matches
15216 ;; hide everything
15217 (org-overview))
15218 (while (re-search-forward regexp nil t)
15219 (when (or (not callback)
15220 (save-match-data (funcall callback)))
15221 (setq cnt (1+ cnt))
15222 (when org-highlight-sparse-tree-matches
15223 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15224 (org-show-context 'occur-tree))))
15225 (when org-remove-highlights-with-change
15226 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15227 nil 'local))
15228 (unless org-sparse-tree-open-archived-trees
15229 (org-hide-archived-subtrees (point-min) (point-max)))
15230 (run-hooks 'org-occur-hook)
15231 (if (interactive-p)
15232 (message "%d match(es) for regexp %s" cnt regexp))
15233 cnt))
15235 (defun org-show-context (&optional key)
15236 "Make sure point and context and visible.
15237 How much context is shown depends upon the variables
15238 `org-show-hierarchy-above', `org-show-following-heading'. and
15239 `org-show-siblings'."
15240 (let ((heading-p (org-on-heading-p t))
15241 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15242 (following-p (org-get-alist-option org-show-following-heading key))
15243 (entry-p (org-get-alist-option org-show-entry-below key))
15244 (siblings-p (org-get-alist-option org-show-siblings key)))
15245 (catch 'exit
15246 ;; Show heading or entry text
15247 (if (and heading-p (not entry-p))
15248 (org-flag-heading nil) ; only show the heading
15249 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15250 (org-show-hidden-entry))) ; show entire entry
15251 (when following-p
15252 ;; Show next sibling, or heading below text
15253 (save-excursion
15254 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15255 (org-flag-heading nil))))
15256 (when siblings-p (org-show-siblings))
15257 (when hierarchy-p
15258 ;; show all higher headings, possibly with siblings
15259 (save-excursion
15260 (while (and (condition-case nil
15261 (progn (org-up-heading-all 1) t)
15262 (error nil))
15263 (not (bobp)))
15264 (org-flag-heading nil)
15265 (when siblings-p (org-show-siblings))))))))
15267 (defun org-reveal (&optional siblings)
15268 "Show current entry, hierarchy above it, and the following headline.
15269 This can be used to show a consistent set of context around locations
15270 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15271 not t for the search context.
15273 With optional argument SIBLINGS, on each level of the hierarchy all
15274 siblings are shown. This repairs the tree structure to what it would
15275 look like when opened with hierarchical calls to `org-cycle'."
15276 (interactive "P")
15277 (let ((org-show-hierarchy-above t)
15278 (org-show-following-heading t)
15279 (org-show-siblings (if siblings t org-show-siblings)))
15280 (org-show-context nil)))
15282 (defun org-highlight-new-match (beg end)
15283 "Highlight from BEG to END and mark the highlight is an occur headline."
15284 (let ((ov (org-make-overlay beg end)))
15285 (org-overlay-put ov 'face 'secondary-selection)
15286 (push ov org-occur-highlights)))
15288 (defun org-remove-occur-highlights (&optional beg end noremove)
15289 "Remove the occur highlights from the buffer.
15290 BEG and END are ignored. If NOREMOVE is nil, remove this function
15291 from the `before-change-functions' in the current buffer."
15292 (interactive)
15293 (unless org-inhibit-highlight-removal
15294 (mapc 'org-delete-overlay org-occur-highlights)
15295 (setq org-occur-highlights nil)
15296 (unless noremove
15297 (remove-hook 'before-change-functions
15298 'org-remove-occur-highlights 'local))))
15300 ;;;; Priorities
15302 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15303 "Regular expression matching the priority indicator.")
15305 (defvar org-remove-priority-next-time nil)
15307 (defun org-priority-up ()
15308 "Increase the priority of the current item."
15309 (interactive)
15310 (org-priority 'up))
15312 (defun org-priority-down ()
15313 "Decrease the priority of the current item."
15314 (interactive)
15315 (org-priority 'down))
15317 (defun org-priority (&optional action)
15318 "Change the priority of an item by ARG.
15319 ACTION can be `set', `up', `down', or a character."
15320 (interactive)
15321 (setq action (or action 'set))
15322 (let (current new news have remove)
15323 (save-excursion
15324 (org-back-to-heading)
15325 (if (looking-at org-priority-regexp)
15326 (setq current (string-to-char (match-string 2))
15327 have t)
15328 (setq current org-default-priority))
15329 (cond
15330 ((or (eq action 'set) (integerp action))
15331 (if (integerp action)
15332 (setq new action)
15333 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15334 (setq new (read-char-exclusive)))
15335 (if (and (= (upcase org-highest-priority) org-highest-priority)
15336 (= (upcase org-lowest-priority) org-lowest-priority))
15337 (setq new (upcase new)))
15338 (cond ((equal new ?\ ) (setq remove t))
15339 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15340 (error "Priority must be between `%c' and `%c'"
15341 org-highest-priority org-lowest-priority))))
15342 ((eq action 'up)
15343 (if (and (not have) (eq last-command this-command))
15344 (setq new org-lowest-priority)
15345 (setq new (if (and org-priority-start-cycle-with-default (not have))
15346 org-default-priority (1- current)))))
15347 ((eq action 'down)
15348 (if (and (not have) (eq last-command this-command))
15349 (setq new org-highest-priority)
15350 (setq new (if (and org-priority-start-cycle-with-default (not have))
15351 org-default-priority (1+ current)))))
15352 (t (error "Invalid action")))
15353 (if (or (< (upcase new) org-highest-priority)
15354 (> (upcase new) org-lowest-priority))
15355 (setq remove t))
15356 (setq news (format "%c" new))
15357 (if have
15358 (if remove
15359 (replace-match "" t t nil 1)
15360 (replace-match news t t nil 2))
15361 (if remove
15362 (error "No priority cookie found in line")
15363 (looking-at org-todo-line-regexp)
15364 (if (match-end 2)
15365 (progn
15366 (goto-char (match-end 2))
15367 (insert " [#" news "]"))
15368 (goto-char (match-beginning 3))
15369 (insert "[#" news "] ")))))
15370 (org-preserve-lc (org-set-tags nil 'align))
15371 (if remove
15372 (message "Priority removed")
15373 (message "Priority of current item set to %s" news))))
15376 (defun org-get-priority (s)
15377 "Find priority cookie and return priority."
15378 (save-match-data
15379 (if (not (string-match org-priority-regexp s))
15380 (* 1000 (- org-lowest-priority org-default-priority))
15381 (* 1000 (- org-lowest-priority
15382 (string-to-char (match-string 2 s)))))))
15384 ;;;; Tags
15386 (defun org-scan-tags (action matcher &optional todo-only)
15387 "Scan headline tags with inheritance and produce output ACTION.
15388 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15389 evaluated, testing if a given set of tags qualifies a headline for
15390 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15391 are included in the output."
15392 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15393 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15394 (org-re
15395 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15396 (props (list 'face nil
15397 'done-face 'org-done
15398 'undone-face nil
15399 'mouse-face 'highlight
15400 'org-not-done-regexp org-not-done-regexp
15401 'org-todo-regexp org-todo-regexp
15402 'keymap org-agenda-keymap
15403 'help-echo
15404 (format "mouse-2 or RET jump to org file %s"
15405 (abbreviate-file-name
15406 (or (buffer-file-name (buffer-base-buffer))
15407 (buffer-name (buffer-base-buffer)))))))
15408 (case-fold-search nil)
15409 lspos
15410 tags tags-list tags-alist (llast 0) rtn level category i txt
15411 todo marker entry priority)
15412 (save-excursion
15413 (goto-char (point-min))
15414 (when (eq action 'sparse-tree)
15415 (org-overview)
15416 (org-remove-occur-highlights))
15417 (while (re-search-forward re nil t)
15418 (catch :skip
15419 (setq todo (if (match-end 1) (match-string 2))
15420 tags (if (match-end 4) (match-string 4)))
15421 (goto-char (setq lspos (1+ (match-beginning 0))))
15422 (setq level (org-reduced-level (funcall outline-level))
15423 category (org-get-category))
15424 (setq i llast llast level)
15425 ;; remove tag lists from same and sublevels
15426 (while (>= i level)
15427 (when (setq entry (assoc i tags-alist))
15428 (setq tags-alist (delete entry tags-alist)))
15429 (setq i (1- i)))
15430 ;; add the nex tags
15431 (when tags
15432 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15433 tags-alist
15434 (cons (cons level tags) tags-alist)))
15435 ;; compile tags for current headline
15436 (setq tags-list
15437 (if org-use-tag-inheritance
15438 (apply 'append (mapcar 'cdr tags-alist))
15439 tags))
15440 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15441 (eval matcher)
15442 (or (not org-agenda-skip-archived-trees)
15443 (not (member org-archive-tag tags-list))))
15444 (and (eq action 'agenda) (org-agenda-skip))
15445 ;; list this headline
15447 (if (eq action 'sparse-tree)
15448 (progn
15449 (and org-highlight-sparse-tree-matches
15450 (org-get-heading) (match-end 0)
15451 (org-highlight-new-match
15452 (match-beginning 0) (match-beginning 1)))
15453 (org-show-context 'tags-tree))
15454 (setq txt (org-format-agenda-item
15456 (concat
15457 (if org-tags-match-list-sublevels
15458 (make-string (1- level) ?.) "")
15459 (org-get-heading))
15460 category tags-list)
15461 priority (org-get-priority txt))
15462 (goto-char lspos)
15463 (setq marker (org-agenda-new-marker))
15464 (org-add-props txt props
15465 'org-marker marker 'org-hd-marker marker 'org-category category
15466 'priority priority 'type "tagsmatch")
15467 (push txt rtn))
15468 ;; if we are to skip sublevels, jump to end of subtree
15469 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15470 (when (and (eq action 'sparse-tree)
15471 (not org-sparse-tree-open-archived-trees))
15472 (org-hide-archived-subtrees (point-min) (point-max)))
15473 (nreverse rtn)))
15475 (defvar todo-only) ;; dynamically scoped
15477 (defun org-tags-sparse-tree (&optional todo-only match)
15478 "Create a sparse tree according to tags string MATCH.
15479 MATCH can contain positive and negative selection of tags, like
15480 \"+WORK+URGENT-WITHBOSS\".
15481 If optional argument TODO_ONLY is non-nil, only select lines that are
15482 also TODO lines."
15483 (interactive "P")
15484 (org-prepare-agenda-buffers (list (current-buffer)))
15485 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15487 (defvar org-cached-props nil)
15488 (defun org-cached-entry-get (pom property)
15489 (if (or (eq t org-use-property-inheritance)
15490 (member property org-use-property-inheritance))
15491 ;; Caching is not possible, check it directly
15492 (org-entry-get pom property 'inherit)
15493 ;; Get all properties, so that we can do complicated checks easily
15494 (cdr (assoc property (or org-cached-props
15495 (setq org-cached-props
15496 (org-entry-properties pom)))))))
15498 (defun org-global-tags-completion-table (&optional files)
15499 "Return the list of all tags in all agenda buffer/files."
15500 (save-excursion
15501 (org-uniquify
15502 (delq nil
15503 (apply 'append
15504 (mapcar
15505 (lambda (file)
15506 (set-buffer (find-file-noselect file))
15507 (append (org-get-buffer-tags)
15508 (mapcar (lambda (x) (if (stringp (car-safe x))
15509 (list (car-safe x)) nil))
15510 org-tag-alist)))
15511 (if (and files (car files))
15512 files
15513 (org-agenda-files))))))))
15515 (defun org-make-tags-matcher (match)
15516 "Create the TAGS//TODO matcher form for the selection string MATCH."
15517 ;; todo-only is scoped dynamically into this function, and the function
15518 ;; may change it it the matcher asksk for it.
15519 (unless match
15520 ;; Get a new match request, with completion
15521 (let ((org-last-tags-completion-table
15522 (org-global-tags-completion-table)))
15523 (setq match (completing-read
15524 "Match: " 'org-tags-completion-function nil nil nil
15525 'org-tags-history))))
15527 ;; Parse the string and create a lisp form
15528 (let ((match0 match)
15529 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15530 minus tag mm
15531 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15532 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15533 (if (string-match "/+" match)
15534 ;; match contains also a todo-matching request
15535 (progn
15536 (setq tagsmatch (substring match 0 (match-beginning 0))
15537 todomatch (substring match (match-end 0)))
15538 (if (string-match "^!" todomatch)
15539 (setq todo-only t todomatch (substring todomatch 1)))
15540 (if (string-match "^\\s-*$" todomatch)
15541 (setq todomatch nil)))
15542 ;; only matching tags
15543 (setq tagsmatch match todomatch nil))
15545 ;; Make the tags matcher
15546 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15547 (setq tagsmatcher t)
15548 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15549 (while (setq term (pop orterms))
15550 (while (and (equal (substring term -1) "\\") orterms)
15551 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15552 (while (string-match re term)
15553 (setq minus (and (match-end 1)
15554 (equal (match-string 1 term) "-"))
15555 tag (match-string 2 term)
15556 re-p (equal (string-to-char tag) ?{)
15557 level-p (match-end 3)
15558 prop-p (match-end 4)
15559 mm (cond
15560 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15561 (level-p `(= level ,(string-to-number
15562 (match-string 3 term))))
15563 (prop-p
15564 (setq pn (match-string 4 term)
15565 pv (match-string 5 term)
15566 cat-p (equal pn "CATEGORY")
15567 re-p (equal (string-to-char pv) ?{)
15568 pv (substring pv 1 -1))
15569 (if (equal pn "CATEGORY")
15570 (setq gv '(get-text-property (point) 'org-category))
15571 (setq gv `(org-cached-entry-get nil ,pn)))
15572 (if re-p
15573 `(string-match ,pv (or ,gv ""))
15574 `(equal ,pv (or ,gv ""))))
15575 (t `(member ,(downcase tag) tags-list)))
15576 mm (if minus (list 'not mm) mm)
15577 term (substring term (match-end 0)))
15578 (push mm tagsmatcher))
15579 (push (if (> (length tagsmatcher) 1)
15580 (cons 'and tagsmatcher)
15581 (car tagsmatcher))
15582 orlist)
15583 (setq tagsmatcher nil))
15584 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15585 (setq tagsmatcher
15586 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15588 ;; Make the todo matcher
15589 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15590 (setq todomatcher t)
15591 (setq orterms (org-split-string todomatch "|") orlist nil)
15592 (while (setq term (pop orterms))
15593 (while (string-match re term)
15594 (setq minus (and (match-end 1)
15595 (equal (match-string 1 term) "-"))
15596 kwd (match-string 2 term)
15597 re-p (equal (string-to-char kwd) ?{)
15598 term (substring term (match-end 0))
15599 mm (if re-p
15600 `(string-match ,(substring kwd 1 -1) todo)
15601 (list 'equal 'todo kwd))
15602 mm (if minus (list 'not mm) mm))
15603 (push mm todomatcher))
15604 (push (if (> (length todomatcher) 1)
15605 (cons 'and todomatcher)
15606 (car todomatcher))
15607 orlist)
15608 (setq todomatcher nil))
15609 (setq todomatcher (if (> (length orlist) 1)
15610 (cons 'or orlist) (car orlist))))
15612 ;; Return the string and lisp forms of the matcher
15613 (setq matcher (if todomatcher
15614 (list 'and tagsmatcher todomatcher)
15615 tagsmatcher))
15616 (cons match0 matcher)))
15618 (defun org-match-any-p (re list)
15619 "Does re match any element of list?"
15620 (setq list (mapcar (lambda (x) (string-match re x)) list))
15621 (delq nil list))
15623 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15624 (defvar org-tags-overlay (org-make-overlay 1 1))
15625 (org-detach-overlay org-tags-overlay)
15627 (defun org-align-tags-here (to-col)
15628 ;; Assumes that this is a headline
15629 (let ((pos (point)) (col (current-column)) tags)
15630 (beginning-of-line 1)
15631 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15632 (< pos (match-beginning 2)))
15633 (progn
15634 (setq tags (match-string 2))
15635 (goto-char (match-beginning 1))
15636 (insert " ")
15637 (delete-region (point) (1+ (match-end 0)))
15638 (backward-char 1)
15639 (move-to-column
15640 (max (1+ (current-column))
15641 (1+ col)
15642 (if (> to-col 0)
15643 to-col
15644 (- (abs to-col) (length tags))))
15646 (insert tags)
15647 (move-to-column (min (current-column) col) t))
15648 (goto-char pos))))
15650 (defun org-set-tags (&optional arg just-align)
15651 "Set the tags for the current headline.
15652 With prefix ARG, realign all tags in headings in the current buffer."
15653 (interactive "P")
15654 (let* ((re (concat "^" outline-regexp))
15655 (current (org-get-tags-string))
15656 (col (current-column))
15657 (org-setting-tags t)
15658 table current-tags inherited-tags ; computed below when needed
15659 tags p0 c0 c1 rpl)
15660 (if arg
15661 (save-excursion
15662 (goto-char (point-min))
15663 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15664 (while (re-search-forward re nil t)
15665 (org-set-tags nil t)
15666 (end-of-line 1)))
15667 (message "All tags realigned to column %d" org-tags-column))
15668 (if just-align
15669 (setq tags current)
15670 ;; Get a new set of tags from the user
15671 (save-excursion
15672 (setq table (or org-tag-alist (org-get-buffer-tags))
15673 org-last-tags-completion-table table
15674 current-tags (org-split-string current ":")
15675 inherited-tags (nreverse
15676 (nthcdr (length current-tags)
15677 (nreverse (org-get-tags-at))))
15678 tags
15679 (if (or (eq t org-use-fast-tag-selection)
15680 (and org-use-fast-tag-selection
15681 (delq nil (mapcar 'cdr table))))
15682 (org-fast-tag-selection
15683 current-tags inherited-tags table
15684 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15685 (let ((org-add-colon-after-tag-completion t))
15686 (org-trim
15687 (org-without-partial-completion
15688 (completing-read "Tags: " 'org-tags-completion-function
15689 nil nil current 'org-tags-history)))))))
15690 (while (string-match "[-+&]+" tags)
15691 ;; No boolean logic, just a list
15692 (setq tags (replace-match ":" t t tags))))
15694 (if (string-match "\\`[\t ]*\\'" tags)
15695 (setq tags "")
15696 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15697 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15699 ;; Insert new tags at the correct column
15700 (beginning-of-line 1)
15701 (cond
15702 ((and (equal current "") (equal tags "")))
15703 ((re-search-forward
15704 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15705 (point-at-eol) t)
15706 (if (equal tags "")
15707 (setq rpl "")
15708 (goto-char (match-beginning 0))
15709 (setq c0 (current-column) p0 (point)
15710 c1 (max (1+ c0) (if (> org-tags-column 0)
15711 org-tags-column
15712 (- (- org-tags-column) (length tags))))
15713 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15714 (replace-match rpl t t)
15715 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15716 tags)
15717 (t (error "Tags alignment failed")))
15718 (move-to-column col)
15719 (unless just-align
15720 (run-hooks 'org-after-tags-change-hook)))))
15722 (defun org-change-tag-in-region (beg end tag off)
15723 "Add or remove TAG for each entry in the region.
15724 This works in the agenda, and also in an org-mode buffer."
15725 (interactive
15726 (list (region-beginning) (region-end)
15727 (let ((org-last-tags-completion-table
15728 (if (org-mode-p)
15729 (org-get-buffer-tags)
15730 (org-global-tags-completion-table))))
15731 (completing-read
15732 "Tag: " 'org-tags-completion-function nil nil nil
15733 'org-tags-history))
15734 (progn
15735 (message "[s]et or [r]emove? ")
15736 (equal (read-char-exclusive) ?r))))
15737 (if (fboundp 'deactivate-mark) (deactivate-mark))
15738 (let ((agendap (equal major-mode 'org-agenda-mode))
15739 l1 l2 m buf pos newhead (cnt 0))
15740 (goto-char end)
15741 (setq l2 (1- (org-current-line)))
15742 (goto-char beg)
15743 (setq l1 (org-current-line))
15744 (loop for l from l1 to l2 do
15745 (goto-line l)
15746 (setq m (get-text-property (point) 'org-hd-marker))
15747 (when (or (and (org-mode-p) (org-on-heading-p))
15748 (and agendap m))
15749 (setq buf (if agendap (marker-buffer m) (current-buffer))
15750 pos (if agendap m (point)))
15751 (with-current-buffer buf
15752 (save-excursion
15753 (save-restriction
15754 (goto-char pos)
15755 (setq cnt (1+ cnt))
15756 (org-toggle-tag tag (if off 'off 'on))
15757 (setq newhead (org-get-heading)))))
15758 (and agendap (org-agenda-change-all-lines newhead m))))
15759 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15761 (defun org-tags-completion-function (string predicate &optional flag)
15762 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15763 (confirm (lambda (x) (stringp (car x)))))
15764 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15765 (setq s1 (match-string 1 string)
15766 s2 (match-string 2 string))
15767 (setq s1 "" s2 string))
15768 (cond
15769 ((eq flag nil)
15770 ;; try completion
15771 (setq rtn (try-completion s2 ctable confirm))
15772 (if (stringp rtn)
15773 (setq rtn
15774 (concat s1 s2 (substring rtn (length s2))
15775 (if (and org-add-colon-after-tag-completion
15776 (assoc rtn ctable))
15777 ":" ""))))
15778 rtn)
15779 ((eq flag t)
15780 ;; all-completions
15781 (all-completions s2 ctable confirm)
15783 ((eq flag 'lambda)
15784 ;; exact match?
15785 (assoc s2 ctable)))
15788 (defun org-fast-tag-insert (kwd tags face &optional end)
15789 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15790 (insert (format "%-12s" (concat kwd ":"))
15791 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15792 (or end "")))
15794 (defun org-fast-tag-show-exit (flag)
15795 (save-excursion
15796 (goto-line 3)
15797 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15798 (replace-match ""))
15799 (when flag
15800 (end-of-line 1)
15801 (move-to-column (- (window-width) 19) t)
15802 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15804 (defun org-set-current-tags-overlay (current prefix)
15805 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15806 (if (featurep 'xemacs)
15807 (org-overlay-display org-tags-overlay (concat prefix s)
15808 'secondary-selection)
15809 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15810 (org-overlay-display org-tags-overlay (concat prefix s)))))
15812 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15813 "Fast tag selection with single keys.
15814 CURRENT is the current list of tags in the headline, INHERITED is the
15815 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15816 possibly with grouping information. TODO-TABLE is a similar table with
15817 TODO keywords, should these have keys assigned to them.
15818 If the keys are nil, a-z are automatically assigned.
15819 Returns the new tags string, or nil to not change the current settings."
15820 (let* ((fulltable (append table todo-table))
15821 (maxlen (apply 'max (mapcar
15822 (lambda (x)
15823 (if (stringp (car x)) (string-width (car x)) 0))
15824 fulltable)))
15825 (buf (current-buffer))
15826 (expert (eq org-fast-tag-selection-single-key 'expert))
15827 (buffer-tags nil)
15828 (fwidth (+ maxlen 3 1 3))
15829 (ncol (/ (- (window-width) 4) fwidth))
15830 (i-face 'org-done)
15831 (c-face 'org-todo)
15832 tg cnt e c char c1 c2 ntable tbl rtn
15833 ov-start ov-end ov-prefix
15834 (exit-after-next org-fast-tag-selection-single-key)
15835 (done-keywords org-done-keywords)
15836 groups ingroup)
15837 (save-excursion
15838 (beginning-of-line 1)
15839 (if (looking-at
15840 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15841 (setq ov-start (match-beginning 1)
15842 ov-end (match-end 1)
15843 ov-prefix "")
15844 (setq ov-start (1- (point-at-eol))
15845 ov-end (1+ ov-start))
15846 (skip-chars-forward "^\n\r")
15847 (setq ov-prefix
15848 (concat
15849 (buffer-substring (1- (point)) (point))
15850 (if (> (current-column) org-tags-column)
15852 (make-string (- org-tags-column (current-column)) ?\ ))))))
15853 (org-move-overlay org-tags-overlay ov-start ov-end)
15854 (save-window-excursion
15855 (if expert
15856 (set-buffer (get-buffer-create " *Org tags*"))
15857 (delete-other-windows)
15858 (split-window-vertically)
15859 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15860 (erase-buffer)
15861 (org-set-local 'org-done-keywords done-keywords)
15862 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15863 (org-fast-tag-insert "Current" current c-face "\n\n")
15864 (org-fast-tag-show-exit exit-after-next)
15865 (org-set-current-tags-overlay current ov-prefix)
15866 (setq tbl fulltable char ?a cnt 0)
15867 (while (setq e (pop tbl))
15868 (cond
15869 ((equal e '(:startgroup))
15870 (push '() groups) (setq ingroup t)
15871 (when (not (= cnt 0))
15872 (setq cnt 0)
15873 (insert "\n"))
15874 (insert "{ "))
15875 ((equal e '(:endgroup))
15876 (setq ingroup nil cnt 0)
15877 (insert "}\n"))
15879 (setq tg (car e) c2 nil)
15880 (if (cdr e)
15881 (setq c (cdr e))
15882 ;; automatically assign a character.
15883 (setq c1 (string-to-char
15884 (downcase (substring
15885 tg (if (= (string-to-char tg) ?@) 1 0)))))
15886 (if (or (rassoc c1 ntable) (rassoc c1 table))
15887 (while (or (rassoc char ntable) (rassoc char table))
15888 (setq char (1+ char)))
15889 (setq c2 c1))
15890 (setq c (or c2 char)))
15891 (if ingroup (push tg (car groups)))
15892 (setq tg (org-add-props tg nil 'face
15893 (cond
15894 ((not (assoc tg table))
15895 (org-get-todo-face tg))
15896 ((member tg current) c-face)
15897 ((member tg inherited) i-face)
15898 (t nil))))
15899 (if (and (= cnt 0) (not ingroup)) (insert " "))
15900 (insert "[" c "] " tg (make-string
15901 (- fwidth 4 (length tg)) ?\ ))
15902 (push (cons tg c) ntable)
15903 (when (= (setq cnt (1+ cnt)) ncol)
15904 (insert "\n")
15905 (if ingroup (insert " "))
15906 (setq cnt 0)))))
15907 (setq ntable (nreverse ntable))
15908 (insert "\n")
15909 (goto-char (point-min))
15910 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15911 (fit-window-to-buffer))
15912 (setq rtn
15913 (catch 'exit
15914 (while t
15915 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15916 (if groups " [!] no groups" " [!]groups")
15917 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15918 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15919 (cond
15920 ((= c ?\r) (throw 'exit t))
15921 ((= c ?!)
15922 (setq groups (not groups))
15923 (goto-char (point-min))
15924 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15925 ((= c ?\C-c)
15926 (if (not expert)
15927 (org-fast-tag-show-exit
15928 (setq exit-after-next (not exit-after-next)))
15929 (setq expert nil)
15930 (delete-other-windows)
15931 (split-window-vertically)
15932 (org-switch-to-buffer-other-window " *Org tags*")
15933 (and (fboundp 'fit-window-to-buffer)
15934 (fit-window-to-buffer))))
15935 ((or (= c ?\C-g)
15936 (and (= c ?q) (not (rassoc c ntable))))
15937 (org-detach-overlay org-tags-overlay)
15938 (setq quit-flag t))
15939 ((= c ?\ )
15940 (setq current nil)
15941 (if exit-after-next (setq exit-after-next 'now)))
15942 ((= c ?\t)
15943 (condition-case nil
15944 (setq tg (completing-read
15945 "Tag: "
15946 (or buffer-tags
15947 (with-current-buffer buf
15948 (org-get-buffer-tags)))))
15949 (quit (setq tg "")))
15950 (when (string-match "\\S-" tg)
15951 (add-to-list 'buffer-tags (list tg))
15952 (if (member tg current)
15953 (setq current (delete tg current))
15954 (push tg current)))
15955 (if exit-after-next (setq exit-after-next 'now)))
15956 ((setq e (rassoc c todo-table) tg (car e))
15957 (with-current-buffer buf
15958 (save-excursion (org-todo tg)))
15959 (if exit-after-next (setq exit-after-next 'now)))
15960 ((setq e (rassoc c ntable) tg (car e))
15961 (if (member tg current)
15962 (setq current (delete tg current))
15963 (loop for g in groups do
15964 (if (member tg g)
15965 (mapc (lambda (x)
15966 (setq current (delete x current)))
15967 g)))
15968 (push tg current))
15969 (if exit-after-next (setq exit-after-next 'now))))
15971 ;; Create a sorted list
15972 (setq current
15973 (sort current
15974 (lambda (a b)
15975 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15976 (if (eq exit-after-next 'now) (throw 'exit t))
15977 (goto-char (point-min))
15978 (beginning-of-line 2)
15979 (delete-region (point) (point-at-eol))
15980 (org-fast-tag-insert "Current" current c-face)
15981 (org-set-current-tags-overlay current ov-prefix)
15982 (while (re-search-forward
15983 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15984 (setq tg (match-string 1))
15985 (add-text-properties
15986 (match-beginning 1) (match-end 1)
15987 (list 'face
15988 (cond
15989 ((member tg current) c-face)
15990 ((member tg inherited) i-face)
15991 (t (get-text-property (match-beginning 1) 'face))))))
15992 (goto-char (point-min)))))
15993 (org-detach-overlay org-tags-overlay)
15994 (if rtn
15995 (mapconcat 'identity current ":")
15996 nil))))
15998 (defun org-get-tags-string ()
15999 "Get the TAGS string in the current headline."
16000 (unless (org-on-heading-p t)
16001 (error "Not on a heading"))
16002 (save-excursion
16003 (beginning-of-line 1)
16004 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16005 (org-match-string-no-properties 1)
16006 "")))
16008 (defun org-get-tags ()
16009 "Get the list of tags specified in the current headline."
16010 (org-split-string (org-get-tags-string) ":"))
16012 (defun org-get-buffer-tags ()
16013 "Get a table of all tags used in the buffer, for completion."
16014 (let (tags)
16015 (save-excursion
16016 (goto-char (point-min))
16017 (while (re-search-forward
16018 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
16019 (when (equal (char-after (point-at-bol 0)) ?*)
16020 (mapc (lambda (x) (add-to-list 'tags x))
16021 (org-split-string (org-match-string-no-properties 1) ":")))))
16022 (mapcar 'list tags)))
16025 ;;;; Properties
16027 ;;; Setting and retrieving properties
16029 (defconst org-special-properties
16030 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
16031 "TIMESTAMP" "TIMESTAMP_IA")
16032 "The special properties valid in Org-mode.
16034 These are properties that are not defined in the property drawer,
16035 but in some other way.")
16037 (defconst org-default-properties
16038 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
16039 "LOCATION" "LOGGING" "COLUMNS")
16040 "Some properties that are used by Org-mode for various purposes.
16041 Being in this list makes sure that they are offered for completion.")
16043 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
16044 "Regular expression matching the first line of a property drawer.")
16046 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
16047 "Regular expression matching the first line of a property drawer.")
16049 (defun org-property-action ()
16050 "Do an action on properties."
16051 (interactive)
16052 (let (c)
16053 (org-at-property-p)
16054 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
16055 (setq c (read-char-exclusive))
16056 (cond
16057 ((equal c ?s)
16058 (call-interactively 'org-set-property))
16059 ((equal c ?d)
16060 (call-interactively 'org-delete-property))
16061 ((equal c ?D)
16062 (call-interactively 'org-delete-property-globally))
16063 ((equal c ?c)
16064 (call-interactively 'org-compute-property-at-point))
16065 (t (error "No such property action %c" c)))))
16067 (defun org-at-property-p ()
16068 "Is the cursor in a property line?"
16069 ;; FIXME: Does not check if we are actually in the drawer.
16070 ;; FIXME: also returns true on any drawers.....
16071 ;; This is used by C-c C-c for property action.
16072 (save-excursion
16073 (beginning-of-line 1)
16074 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
16076 (defmacro org-with-point-at (pom &rest body)
16077 "Move to buffer and point of point-or-marker POM for the duration of BODY."
16078 (declare (indent 1) (debug t))
16079 `(save-excursion
16080 (if (markerp pom) (set-buffer (marker-buffer pom)))
16081 (save-excursion
16082 (goto-char (or pom (point)))
16083 ,@body)))
16085 (defun org-get-property-block (&optional beg end force)
16086 "Return the (beg . end) range of the body of the property drawer.
16087 BEG and END can be beginning and end of subtree, if not given
16088 they will be found.
16089 If the drawer does not exist and FORCE is non-nil, create the drawer."
16090 (catch 'exit
16091 (save-excursion
16092 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
16093 (end (or end (progn (outline-next-heading) (point)))))
16094 (goto-char beg)
16095 (if (re-search-forward org-property-start-re end t)
16096 (setq beg (1+ (match-end 0)))
16097 (if force
16098 (save-excursion
16099 (org-insert-property-drawer)
16100 (setq end (progn (outline-next-heading) (point))))
16101 (throw 'exit nil))
16102 (goto-char beg)
16103 (if (re-search-forward org-property-start-re end t)
16104 (setq beg (1+ (match-end 0)))))
16105 (if (re-search-forward org-property-end-re end t)
16106 (setq end (match-beginning 0))
16107 (or force (throw 'exit nil))
16108 (goto-char beg)
16109 (setq end beg)
16110 (org-indent-line-function)
16111 (insert ":END:\n"))
16112 (cons beg end)))))
16114 (defun org-entry-properties (&optional pom which)
16115 "Get all properties of the entry at point-or-marker POM.
16116 This includes the TODO keyword, the tags, time strings for deadline,
16117 scheduled, and clocking, and any additional properties defined in the
16118 entry. The return value is an alist, keys may occur multiple times
16119 if the property key was used several times.
16120 POM may also be nil, in which case the current entry is used.
16121 If WHICH is nil or `all', get all properties. If WHICH is
16122 `special' or `standard', only get that subclass."
16123 (setq which (or which 'all))
16124 (org-with-point-at pom
16125 (let ((clockstr (substring org-clock-string 0 -1))
16126 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
16127 beg end range props sum-props key value string clocksum)
16128 (save-excursion
16129 (when (condition-case nil (org-back-to-heading t) (error nil))
16130 (setq beg (point))
16131 (setq sum-props (get-text-property (point) 'org-summaries))
16132 (setq clocksum (get-text-property (point) :org-clock-minutes))
16133 (outline-next-heading)
16134 (setq end (point))
16135 (when (memq which '(all special))
16136 ;; Get the special properties, like TODO and tags
16137 (goto-char beg)
16138 (when (and (looking-at org-todo-line-regexp) (match-end 2))
16139 (push (cons "TODO" (org-match-string-no-properties 2)) props))
16140 (when (looking-at org-priority-regexp)
16141 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16142 (when (and (setq value (org-get-tags-string))
16143 (string-match "\\S-" value))
16144 (push (cons "TAGS" value) props))
16145 (when (setq value (org-get-tags-at))
16146 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16147 props))
16148 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16149 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16150 string (if (equal key clockstr)
16151 (org-no-properties
16152 (org-trim
16153 (buffer-substring
16154 (match-beginning 3) (goto-char (point-at-eol)))))
16155 (substring (org-match-string-no-properties 3) 1 -1)))
16156 (unless key
16157 (if (= (char-after (match-beginning 3)) ?\[)
16158 (setq key "TIMESTAMP_IA")
16159 (setq key "TIMESTAMP")))
16160 (when (or (equal key clockstr) (not (assoc key props)))
16161 (push (cons key string) props)))
16165 (when (memq which '(all standard))
16166 ;; Get the standard properties, like :PORP: ...
16167 (setq range (org-get-property-block beg end))
16168 (when range
16169 (goto-char (car range))
16170 (while (re-search-forward
16171 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16172 (cdr range) t)
16173 (setq key (org-match-string-no-properties 1)
16174 value (org-trim (or (org-match-string-no-properties 2) "")))
16175 (unless (member key excluded)
16176 (push (cons key (or value "")) props)))))
16177 (if clocksum
16178 (push (cons "CLOCKSUM"
16179 (org-column-number-to-string (/ (float clocksum) 60.)
16180 'add_times))
16181 props))
16182 (append sum-props (nreverse props)))))))
16184 (defun org-entry-get (pom property &optional inherit)
16185 "Get value of PROPERTY for entry at point-or-marker POM.
16186 If INHERIT is non-nil and the entry does not have the property,
16187 then also check higher levels of the hierarchy.
16188 If the property is present but empty, the return value is the empty string.
16189 If the property is not present at all, nil is returned."
16190 (org-with-point-at pom
16191 (if inherit
16192 (org-entry-get-with-inheritance property)
16193 (if (member property org-special-properties)
16194 ;; We need a special property. Use brute force, get all properties.
16195 (cdr (assoc property (org-entry-properties nil 'special)))
16196 (let ((range (org-get-property-block)))
16197 (if (and range
16198 (goto-char (car range))
16199 (re-search-forward
16200 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16201 (cdr range) t))
16202 ;; Found the property, return it.
16203 (if (match-end 1)
16204 (org-match-string-no-properties 1)
16205 "")))))))
16207 (defun org-entry-delete (pom property)
16208 "Delete the property PROPERTY from entry at point-or-marker POM."
16209 (org-with-point-at pom
16210 (if (member property org-special-properties)
16211 nil ; cannot delete these properties.
16212 (let ((range (org-get-property-block)))
16213 (if (and range
16214 (goto-char (car range))
16215 (re-search-forward
16216 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16217 (cdr range) t))
16218 (progn
16219 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16221 nil)))))
16223 ;; Multi-values properties are properties that contain multiple values
16224 ;; These values are assumed to be single words, separated by whitespace.
16225 (defun org-entry-add-to-multivalued-property (pom property value)
16226 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16227 (let* ((old (org-entry-get pom property))
16228 (values (and old (org-split-string old "[ \t]"))))
16229 (unless (member value values)
16230 (setq values (cons value values))
16231 (org-entry-put pom property
16232 (mapconcat 'identity values " ")))))
16234 (defun org-entry-remove-from-multivalued-property (pom property value)
16235 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16236 (let* ((old (org-entry-get pom property))
16237 (values (and old (org-split-string old "[ \t]"))))
16238 (when (member value values)
16239 (setq values (delete value values))
16240 (org-entry-put pom property
16241 (mapconcat 'identity values " ")))))
16243 (defun org-entry-member-in-multivalued-property (pom property value)
16244 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16245 (let* ((old (org-entry-get pom property))
16246 (values (and old (org-split-string old "[ \t]"))))
16247 (member value values)))
16249 (defvar org-entry-property-inherited-from (make-marker))
16251 (defun org-entry-get-with-inheritance (property)
16252 "Get entry property, and search higher levels if not present."
16253 (let (tmp)
16254 (save-excursion
16255 (save-restriction
16256 (widen)
16257 (catch 'ex
16258 (while t
16259 (when (setq tmp (org-entry-get nil property))
16260 (org-back-to-heading t)
16261 (move-marker org-entry-property-inherited-from (point))
16262 (throw 'ex tmp))
16263 (or (org-up-heading-safe) (throw 'ex nil)))))
16264 (or tmp (cdr (assoc property org-local-properties))
16265 (cdr (assoc property org-global-properties))))))
16267 (defun org-entry-put (pom property value)
16268 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16269 (org-with-point-at pom
16270 (org-back-to-heading t)
16271 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16272 range)
16273 (cond
16274 ((equal property "TODO")
16275 (when (and (stringp value) (string-match "\\S-" value)
16276 (not (member value org-todo-keywords-1)))
16277 (error "\"%s\" is not a valid TODO state" value))
16278 (if (or (not value)
16279 (not (string-match "\\S-" value)))
16280 (setq value 'none))
16281 (org-todo value)
16282 (org-set-tags nil 'align))
16283 ((equal property "PRIORITY")
16284 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16285 (string-to-char value) ?\ ))
16286 (org-set-tags nil 'align))
16287 ((equal property "SCHEDULED")
16288 (if (re-search-forward org-scheduled-time-regexp end t)
16289 (cond
16290 ((eq value 'earlier) (org-timestamp-change -1 'day))
16291 ((eq value 'later) (org-timestamp-change 1 'day))
16292 (t (call-interactively 'org-schedule)))
16293 (call-interactively 'org-schedule)))
16294 ((equal property "DEADLINE")
16295 (if (re-search-forward org-deadline-time-regexp end t)
16296 (cond
16297 ((eq value 'earlier) (org-timestamp-change -1 'day))
16298 ((eq value 'later) (org-timestamp-change 1 'day))
16299 (t (call-interactively 'org-deadline)))
16300 (call-interactively 'org-deadline)))
16301 ((member property org-special-properties)
16302 (error "The %s property can not yet be set with `org-entry-put'"
16303 property))
16304 (t ; a non-special property
16305 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16306 (setq range (org-get-property-block beg end 'force))
16307 (goto-char (car range))
16308 (if (re-search-forward
16309 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16310 (progn
16311 (delete-region (match-beginning 1) (match-end 1))
16312 (goto-char (match-beginning 1)))
16313 (goto-char (cdr range))
16314 (insert "\n")
16315 (backward-char 1)
16316 (org-indent-line-function)
16317 (insert ":" property ":"))
16318 (and value (insert " " value))
16319 (org-indent-line-function)))))))
16321 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16322 "Get all property keys in the current buffer.
16323 With INCLUDE-SPECIALS, also list the special properties that relect things
16324 like tags and TODO state.
16325 With INCLUDE-DEFAULTS, also include properties that has special meaning
16326 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16327 With INCLUDE-COLUMNS, also include property names given in COLUMN
16328 formats in the current buffer."
16329 (let (rtn range cfmt cols s p)
16330 (save-excursion
16331 (save-restriction
16332 (widen)
16333 (goto-char (point-min))
16334 (while (re-search-forward org-property-start-re nil t)
16335 (setq range (org-get-property-block))
16336 (goto-char (car range))
16337 (while (re-search-forward
16338 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16339 (cdr range) t)
16340 (add-to-list 'rtn (org-match-string-no-properties 1)))
16341 (outline-next-heading))))
16343 (when include-specials
16344 (setq rtn (append org-special-properties rtn)))
16346 (when include-defaults
16347 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16349 (when include-columns
16350 (save-excursion
16351 (save-restriction
16352 (widen)
16353 (goto-char (point-min))
16354 (while (re-search-forward
16355 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16356 nil t)
16357 (setq cfmt (match-string 2) s 0)
16358 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16359 cfmt s)
16360 (setq s (match-end 0)
16361 p (match-string 1 cfmt))
16362 (unless (or (equal p "ITEM")
16363 (member p org-special-properties))
16364 (add-to-list 'rtn (match-string 1 cfmt))))))))
16366 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16368 (defun org-property-values (key)
16369 "Return a list of all values of property KEY."
16370 (save-excursion
16371 (save-restriction
16372 (widen)
16373 (goto-char (point-min))
16374 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16375 values)
16376 (while (re-search-forward re nil t)
16377 (add-to-list 'values (org-trim (match-string 1))))
16378 (delete "" values)))))
16380 (defun org-insert-property-drawer ()
16381 "Insert a property drawer into the current entry."
16382 (interactive)
16383 (org-back-to-heading t)
16384 (looking-at outline-regexp)
16385 (let ((indent (- (match-end 0)(match-beginning 0)))
16386 (beg (point))
16387 (re (concat "^[ \t]*" org-keyword-time-regexp))
16388 end hiddenp)
16389 (outline-next-heading)
16390 (setq end (point))
16391 (goto-char beg)
16392 (while (re-search-forward re end t))
16393 (setq hiddenp (org-invisible-p))
16394 (end-of-line 1)
16395 (and (equal (char-after) ?\n) (forward-char 1))
16396 (org-skip-over-state-notes)
16397 (skip-chars-backward " \t\n\r")
16398 (if (eq (char-before) ?*) (forward-char 1))
16399 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16400 (beginning-of-line 0)
16401 (indent-to-column indent)
16402 (beginning-of-line 2)
16403 (indent-to-column indent)
16404 (beginning-of-line 0)
16405 (if hiddenp
16406 (save-excursion
16407 (org-back-to-heading t)
16408 (hide-entry))
16409 (org-flag-drawer t))))
16411 (defun org-set-property (property value)
16412 "In the current entry, set PROPERTY to VALUE.
16413 When called interactively, this will prompt for a property name, offering
16414 completion on existing and default properties. And then it will prompt
16415 for a value, offering competion either on allowed values (via an inherited
16416 xxx_ALL property) or on existing values in other instances of this property
16417 in the current file."
16418 (interactive
16419 (let* ((prop (completing-read
16420 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16421 (cur (org-entry-get nil prop))
16422 (allowed (org-property-get-allowed-values nil prop 'table))
16423 (existing (mapcar 'list (org-property-values prop)))
16424 (val (if allowed
16425 (completing-read "Value: " allowed nil 'req-match)
16426 (completing-read
16427 (concat "Value" (if (and cur (string-match "\\S-" cur))
16428 (concat "[" cur "]") "")
16429 ": ")
16430 existing nil nil "" nil cur))))
16431 (list prop (if (equal val "") cur val))))
16432 (unless (equal (org-entry-get nil property) value)
16433 (org-entry-put nil property value)))
16435 (defun org-delete-property (property)
16436 "In the current entry, delete PROPERTY."
16437 (interactive
16438 (let* ((prop (completing-read
16439 "Property: " (org-entry-properties nil 'standard))))
16440 (list prop)))
16441 (message "Property %s %s" property
16442 (if (org-entry-delete nil property)
16443 "deleted"
16444 "was not present in the entry")))
16446 (defun org-delete-property-globally (property)
16447 "Remove PROPERTY globally, from all entries."
16448 (interactive
16449 (let* ((prop (completing-read
16450 "Globally remove property: "
16451 (mapcar 'list (org-buffer-property-keys)))))
16452 (list prop)))
16453 (save-excursion
16454 (save-restriction
16455 (widen)
16456 (goto-char (point-min))
16457 (let ((cnt 0))
16458 (while (re-search-forward
16459 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16460 nil t)
16461 (setq cnt (1+ cnt))
16462 (replace-match ""))
16463 (message "Property \"%s\" removed from %d entries" property cnt)))))
16465 (defvar org-columns-current-fmt-compiled) ; defined below
16467 (defun org-compute-property-at-point ()
16468 "Compute the property at point.
16469 This looks for an enclosing column format, extracts the operator and
16470 then applies it to the proerty in the column format's scope."
16471 (interactive)
16472 (unless (org-at-property-p)
16473 (error "Not at a property"))
16474 (let ((prop (org-match-string-no-properties 2)))
16475 (org-columns-get-format-and-top-level)
16476 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16477 (error "No operator defined for property %s" prop))
16478 (org-columns-compute prop)))
16480 (defun org-property-get-allowed-values (pom property &optional table)
16481 "Get allowed values for the property PROPERTY.
16482 When TABLE is non-nil, return an alist that can directly be used for
16483 completion."
16484 (let (vals)
16485 (cond
16486 ((equal property "TODO")
16487 (setq vals (org-with-point-at pom
16488 (append org-todo-keywords-1 '("")))))
16489 ((equal property "PRIORITY")
16490 (let ((n org-lowest-priority))
16491 (while (>= n org-highest-priority)
16492 (push (char-to-string n) vals)
16493 (setq n (1- n)))))
16494 ((member property org-special-properties))
16496 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16498 (when (and vals (string-match "\\S-" vals))
16499 (setq vals (car (read-from-string (concat "(" vals ")"))))
16500 (setq vals (mapcar (lambda (x)
16501 (cond ((stringp x) x)
16502 ((numberp x) (number-to-string x))
16503 ((symbolp x) (symbol-name x))
16504 (t "???")))
16505 vals)))))
16506 (if table (mapcar 'list vals) vals)))
16508 (defun org-property-previous-allowed-value (&optional previous)
16509 "Switch to the next allowed value for this property."
16510 (interactive)
16511 (org-property-next-allowed-value t))
16513 (defun org-property-next-allowed-value (&optional previous)
16514 "Switch to the next allowed value for this property."
16515 (interactive)
16516 (unless (org-at-property-p)
16517 (error "Not at a property"))
16518 (let* ((key (match-string 2))
16519 (value (match-string 3))
16520 (allowed (or (org-property-get-allowed-values (point) key)
16521 (and (member value '("[ ]" "[-]" "[X]"))
16522 '("[ ]" "[X]"))))
16523 nval)
16524 (unless allowed
16525 (error "Allowed values for this property have not been defined"))
16526 (if previous (setq allowed (reverse allowed)))
16527 (if (member value allowed)
16528 (setq nval (car (cdr (member value allowed)))))
16529 (setq nval (or nval (car allowed)))
16530 (if (equal nval value)
16531 (error "Only one allowed value for this property"))
16532 (org-at-property-p)
16533 (replace-match (concat " :" key ": " nval) t t)
16534 (org-indent-line-function)
16535 (beginning-of-line 1)
16536 (skip-chars-forward " \t")))
16538 (defun org-find-entry-with-id (ident)
16539 "Locate the entry that contains the ID property with exact value IDENT.
16540 IDENT can be a string, a symbol or a number, this function will search for
16541 the string representation of it.
16542 Return the position where this entry starts, or nil if there is no such entry."
16543 (let ((id (cond
16544 ((stringp ident) ident)
16545 ((symbol-name ident) (symbol-name ident))
16546 ((numberp ident) (number-to-string ident))
16547 (t (error "IDENT %s must be a string, symbol or number" ident))))
16548 (case-fold-search nil))
16549 (save-excursion
16550 (save-restriction
16551 (widen)
16552 (goto-char (point-min))
16553 (when (re-search-forward
16554 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16555 nil t)
16556 (org-back-to-heading)
16557 (point))))))
16559 ;;; Column View
16561 (defvar org-columns-overlays nil
16562 "Holds the list of current column overlays.")
16564 (defvar org-columns-current-fmt nil
16565 "Local variable, holds the currently active column format.")
16566 (defvar org-columns-current-fmt-compiled nil
16567 "Local variable, holds the currently active column format.
16568 This is the compiled version of the format.")
16569 (defvar org-columns-current-widths nil
16570 "Loval variable, holds the currently widths of fields.")
16571 (defvar org-columns-current-maxwidths nil
16572 "Loval variable, holds the currently active maximum column widths.")
16573 (defvar org-columns-begin-marker (make-marker)
16574 "Points to the position where last a column creation command was called.")
16575 (defvar org-columns-top-level-marker (make-marker)
16576 "Points to the position where current columns region starts.")
16578 (defvar org-columns-map (make-sparse-keymap)
16579 "The keymap valid in column display.")
16581 (defun org-columns-content ()
16582 "Switch to contents view while in columns view."
16583 (interactive)
16584 (org-overview)
16585 (org-content))
16587 (org-defkey org-columns-map "c" 'org-columns-content)
16588 (org-defkey org-columns-map "o" 'org-overview)
16589 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16590 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16591 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16592 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16593 (org-defkey org-columns-map "v" 'org-columns-show-value)
16594 (org-defkey org-columns-map "q" 'org-columns-quit)
16595 (org-defkey org-columns-map "r" 'org-columns-redo)
16596 (org-defkey org-columns-map "g" 'org-columns-redo)
16597 (org-defkey org-columns-map [left] 'backward-char)
16598 (org-defkey org-columns-map "\M-b" 'backward-char)
16599 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16600 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16601 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16602 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16603 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16604 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16605 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16606 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16607 (org-defkey org-columns-map "<" 'org-columns-narrow)
16608 (org-defkey org-columns-map ">" 'org-columns-widen)
16609 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16610 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16611 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16612 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16614 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16615 '("Column"
16616 ["Edit property" org-columns-edit-value t]
16617 ["Next allowed value" org-columns-next-allowed-value t]
16618 ["Previous allowed value" org-columns-previous-allowed-value t]
16619 ["Show full value" org-columns-show-value t]
16620 ["Edit allowed values" org-columns-edit-allowed t]
16621 "--"
16622 ["Edit column attributes" org-columns-edit-attributes t]
16623 ["Increase column width" org-columns-widen t]
16624 ["Decrease column width" org-columns-narrow t]
16625 "--"
16626 ["Move column right" org-columns-move-right t]
16627 ["Move column left" org-columns-move-left t]
16628 ["Add column" org-columns-new t]
16629 ["Delete column" org-columns-delete t]
16630 "--"
16631 ["CONTENTS" org-columns-content t]
16632 ["OVERVIEW" org-overview t]
16633 ["Refresh columns display" org-columns-redo t]
16634 "--"
16635 ["Open link" org-columns-open-link t]
16636 "--"
16637 ["Quit" org-columns-quit t]))
16639 (defun org-columns-new-overlay (beg end &optional string face)
16640 "Create a new column overlay and add it to the list."
16641 (let ((ov (org-make-overlay beg end)))
16642 (org-overlay-put ov 'face (or face 'secondary-selection))
16643 (org-overlay-display ov string face)
16644 (push ov org-columns-overlays)
16645 ov))
16647 (defun org-columns-display-here (&optional props)
16648 "Overlay the current line with column display."
16649 (interactive)
16650 (let* ((fmt org-columns-current-fmt-compiled)
16651 (beg (point-at-bol))
16652 (level-face (save-excursion
16653 (beginning-of-line 1)
16654 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16655 (org-get-level-face 2))))
16656 (color (list :foreground
16657 (face-attribute (or level-face 'default) :foreground)))
16658 props pom property ass width f string ov column val modval)
16659 ;; Check if the entry is in another buffer.
16660 (unless props
16661 (if (eq major-mode 'org-agenda-mode)
16662 (setq pom (or (get-text-property (point) 'org-hd-marker)
16663 (get-text-property (point) 'org-marker))
16664 props (if pom (org-entry-properties pom) nil))
16665 (setq props (org-entry-properties nil))))
16666 ;; Walk the format
16667 (while (setq column (pop fmt))
16668 (setq property (car column)
16669 ass (if (equal property "ITEM")
16670 (cons "ITEM"
16671 (save-match-data
16672 (org-no-properties
16673 (org-remove-tabs
16674 (buffer-substring-no-properties
16675 (point-at-bol) (point-at-eol))))))
16676 (assoc property props))
16677 width (or (cdr (assoc property org-columns-current-maxwidths))
16678 (nth 2 column)
16679 (length property))
16680 f (format "%%-%d.%ds | " width width)
16681 val (or (cdr ass) "")
16682 modval (if (equal property "ITEM")
16683 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16684 string (format f (or modval val)))
16685 ;; Create the overlay
16686 (org-unmodified
16687 (setq ov (org-columns-new-overlay
16688 beg (setq beg (1+ beg)) string
16689 (list color 'org-column)))
16690 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16691 (org-overlay-put ov 'keymap org-columns-map)
16692 (org-overlay-put ov 'org-columns-key property)
16693 (org-overlay-put ov 'org-columns-value (cdr ass))
16694 (org-overlay-put ov 'org-columns-value-modified modval)
16695 (org-overlay-put ov 'org-columns-pom pom)
16696 (org-overlay-put ov 'org-columns-format f))
16697 (if (or (not (char-after beg))
16698 (equal (char-after beg) ?\n))
16699 (let ((inhibit-read-only t))
16700 (save-excursion
16701 (goto-char beg)
16702 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16703 ;; Make the rest of the line disappear.
16704 (org-unmodified
16705 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16706 (org-overlay-put ov 'invisible t)
16707 (org-overlay-put ov 'keymap org-columns-map)
16708 (org-overlay-put ov 'intangible t)
16709 (push ov org-columns-overlays)
16710 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16711 (org-overlay-put ov 'keymap org-columns-map)
16712 (push ov org-columns-overlays)
16713 (let ((inhibit-read-only t))
16714 (put-text-property (max (point-min) (1- (point-at-bol)))
16715 (min (point-max) (1+ (point-at-eol)))
16716 'read-only "Type `e' to edit property")))))
16718 (defvar org-previous-header-line-format nil
16719 "The header line format before column view was turned on.")
16720 (defvar org-columns-inhibit-recalculation nil
16721 "Inhibit recomputing of columns on column view startup.")
16724 (defvar header-line-format)
16725 (defun org-columns-display-here-title ()
16726 "Overlay the newline before the current line with the table title."
16727 (interactive)
16728 (let ((fmt org-columns-current-fmt-compiled)
16729 string (title "")
16730 property width f column str widths)
16731 (while (setq column (pop fmt))
16732 (setq property (car column)
16733 str (or (nth 1 column) property)
16734 width (or (cdr (assoc property org-columns-current-maxwidths))
16735 (nth 2 column)
16736 (length str))
16737 widths (push width widths)
16738 f (format "%%-%d.%ds | " width width)
16739 string (format f str)
16740 title (concat title string)))
16741 (setq title (concat
16742 (org-add-props " " nil 'display '(space :align-to 0))
16743 (org-add-props title nil 'face '(:weight bold :underline t))))
16744 (org-set-local 'org-previous-header-line-format header-line-format)
16745 (org-set-local 'org-columns-current-widths (nreverse widths))
16746 (setq header-line-format title)))
16748 (defun org-columns-remove-overlays ()
16749 "Remove all currently active column overlays."
16750 (interactive)
16751 (when (marker-buffer org-columns-begin-marker)
16752 (with-current-buffer (marker-buffer org-columns-begin-marker)
16753 (when (local-variable-p 'org-previous-header-line-format)
16754 (setq header-line-format org-previous-header-line-format)
16755 (kill-local-variable 'org-previous-header-line-format))
16756 (move-marker org-columns-begin-marker nil)
16757 (move-marker org-columns-top-level-marker nil)
16758 (org-unmodified
16759 (mapc 'org-delete-overlay org-columns-overlays)
16760 (setq org-columns-overlays nil)
16761 (let ((inhibit-read-only t))
16762 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16764 (defun org-columns-cleanup-item (item fmt)
16765 "Remove from ITEM what is a column in the format FMT."
16766 (if (not org-complex-heading-regexp)
16767 item
16768 (when (string-match org-complex-heading-regexp item)
16769 (concat
16770 (org-add-props (concat (match-string 1 item) " ") nil
16771 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16772 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16773 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16774 " " (match-string 4 item)
16775 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16777 (defun org-columns-show-value ()
16778 "Show the full value of the property."
16779 (interactive)
16780 (let ((value (get-char-property (point) 'org-columns-value)))
16781 (message "Value is: %s" (or value ""))))
16783 (defun org-columns-quit ()
16784 "Remove the column overlays and in this way exit column editing."
16785 (interactive)
16786 (org-unmodified
16787 (org-columns-remove-overlays)
16788 (let ((inhibit-read-only t))
16789 (remove-text-properties (point-min) (point-max) '(read-only t))))
16790 (when (eq major-mode 'org-agenda-mode)
16791 (message
16792 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16794 (defun org-columns-check-computed ()
16795 "Check if this column value is computed.
16796 If yes, throw an error indicating that changing it does not make sense."
16797 (let ((val (get-char-property (point) 'org-columns-value)))
16798 (when (and (stringp val)
16799 (get-char-property 0 'org-computed val))
16800 (error "This value is computed from the entry's children"))))
16802 (defun org-columns-todo (&optional arg)
16803 "Change the TODO state during column view."
16804 (interactive "P")
16805 (org-columns-edit-value "TODO"))
16807 (defun org-columns-set-tags-or-toggle (&optional arg)
16808 "Toggle checkbox at point, or set tags for current headline."
16809 (interactive "P")
16810 (if (string-match "\\`\\[[ xX-]\\]\\'"
16811 (get-char-property (point) 'org-columns-value))
16812 (org-columns-next-allowed-value)
16813 (org-columns-edit-value "TAGS")))
16815 (defun org-columns-edit-value (&optional key)
16816 "Edit the value of the property at point in column view.
16817 Where possible, use the standard interface for changing this line."
16818 (interactive)
16819 (org-columns-check-computed)
16820 (let* ((external-key key)
16821 (col (current-column))
16822 (key (or key (get-char-property (point) 'org-columns-key)))
16823 (value (get-char-property (point) 'org-columns-value))
16824 (bol (point-at-bol)) (eol (point-at-eol))
16825 (pom (or (get-text-property bol 'org-hd-marker)
16826 (point))) ; keep despite of compiler waring
16827 (line-overlays
16828 (delq nil (mapcar (lambda (x)
16829 (and (eq (overlay-buffer x) (current-buffer))
16830 (>= (overlay-start x) bol)
16831 (<= (overlay-start x) eol)
16833 org-columns-overlays)))
16834 nval eval allowed)
16835 (cond
16836 ((equal key "CLOCKSUM")
16837 (error "This special column cannot be edited"))
16838 ((equal key "ITEM")
16839 (setq eval '(org-with-point-at pom
16840 (org-edit-headline))))
16841 ((equal key "TODO")
16842 (setq eval '(org-with-point-at pom
16843 (let ((current-prefix-arg
16844 (if external-key current-prefix-arg '(4))))
16845 (call-interactively 'org-todo)))))
16846 ((equal key "PRIORITY")
16847 (setq eval '(org-with-point-at pom
16848 (call-interactively 'org-priority))))
16849 ((equal key "TAGS")
16850 (setq eval '(org-with-point-at pom
16851 (let ((org-fast-tag-selection-single-key
16852 (if (eq org-fast-tag-selection-single-key 'expert)
16853 t org-fast-tag-selection-single-key)))
16854 (call-interactively 'org-set-tags)))))
16855 ((equal key "DEADLINE")
16856 (setq eval '(org-with-point-at pom
16857 (call-interactively 'org-deadline))))
16858 ((equal key "SCHEDULED")
16859 (setq eval '(org-with-point-at pom
16860 (call-interactively 'org-schedule))))
16862 (setq allowed (org-property-get-allowed-values pom key 'table))
16863 (if allowed
16864 (setq nval (completing-read "Value: " allowed nil t))
16865 (setq nval (read-string "Edit: " value)))
16866 (setq nval (org-trim nval))
16867 (when (not (equal nval value))
16868 (setq eval '(org-entry-put pom key nval)))))
16869 (when eval
16870 (let ((inhibit-read-only t))
16871 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16872 (unwind-protect
16873 (progn
16874 (setq org-columns-overlays
16875 (org-delete-all line-overlays org-columns-overlays))
16876 (mapc 'org-delete-overlay line-overlays)
16877 (org-columns-eval eval))
16878 (org-columns-display-here))))
16879 (move-to-column col)
16880 (if (and (org-mode-p)
16881 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16882 (org-columns-update key))))
16884 (defun org-edit-headline () ; FIXME: this is not columns specific
16885 "Edit the current headline, the part without TODO keyword, TAGS."
16886 (org-back-to-heading)
16887 (when (looking-at org-todo-line-regexp)
16888 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16889 (txt (match-string 3))
16890 (post "")
16891 txt2)
16892 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16893 (setq post (match-string 0 txt)
16894 txt (substring txt 0 (match-beginning 0))))
16895 (setq txt2 (read-string "Edit: " txt))
16896 (when (not (equal txt txt2))
16897 (beginning-of-line 1)
16898 (insert pre txt2 post)
16899 (delete-region (point) (point-at-eol))
16900 (org-set-tags nil t)))))
16902 (defun org-columns-edit-allowed ()
16903 "Edit the list of allowed values for the current property."
16904 (interactive)
16905 (let* ((key (get-char-property (point) 'org-columns-key))
16906 (key1 (concat key "_ALL"))
16907 (allowed (org-entry-get (point) key1 t))
16908 nval)
16909 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16910 (setq nval (read-string "Allowed: " allowed))
16911 (org-entry-put
16912 (cond ((marker-position org-entry-property-inherited-from)
16913 org-entry-property-inherited-from)
16914 ((marker-position org-columns-top-level-marker)
16915 org-columns-top-level-marker))
16916 key1 nval)))
16918 (defmacro org-no-warnings (&rest body)
16919 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16921 (defun org-columns-eval (form)
16922 (let (hidep)
16923 (save-excursion
16924 (beginning-of-line 1)
16925 ;; `next-line' is needed here, because it skips invisible line.
16926 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16927 (setq hidep (org-on-heading-p 1)))
16928 (eval form)
16929 (and hidep (hide-entry))))
16931 (defun org-columns-previous-allowed-value ()
16932 "Switch to the previous allowed value for this column."
16933 (interactive)
16934 (org-columns-next-allowed-value t))
16936 (defun org-columns-next-allowed-value (&optional previous)
16937 "Switch to the next allowed value for this column."
16938 (interactive)
16939 (org-columns-check-computed)
16940 (let* ((col (current-column))
16941 (key (get-char-property (point) 'org-columns-key))
16942 (value (get-char-property (point) 'org-columns-value))
16943 (bol (point-at-bol)) (eol (point-at-eol))
16944 (pom (or (get-text-property bol 'org-hd-marker)
16945 (point))) ; keep despite of compiler waring
16946 (line-overlays
16947 (delq nil (mapcar (lambda (x)
16948 (and (eq (overlay-buffer x) (current-buffer))
16949 (>= (overlay-start x) bol)
16950 (<= (overlay-start x) eol)
16952 org-columns-overlays)))
16953 (allowed (or (org-property-get-allowed-values pom key)
16954 (and (memq
16955 (nth 4 (assoc key org-columns-current-fmt-compiled))
16956 '(checkbox checkbox-n-of-m checkbox-percent))
16957 '("[ ]" "[X]"))))
16958 nval)
16959 (when (equal key "ITEM")
16960 (error "Cannot edit item headline from here"))
16961 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16962 (error "Allowed values for this property have not been defined"))
16963 (if (member key '("SCHEDULED" "DEADLINE"))
16964 (setq nval (if previous 'earlier 'later))
16965 (if previous (setq allowed (reverse allowed)))
16966 (if (member value allowed)
16967 (setq nval (car (cdr (member value allowed)))))
16968 (setq nval (or nval (car allowed)))
16969 (if (equal nval value)
16970 (error "Only one allowed value for this property")))
16971 (let ((inhibit-read-only t))
16972 (remove-text-properties (1- bol) eol '(read-only t))
16973 (unwind-protect
16974 (progn
16975 (setq org-columns-overlays
16976 (org-delete-all line-overlays org-columns-overlays))
16977 (mapc 'org-delete-overlay line-overlays)
16978 (org-columns-eval '(org-entry-put pom key nval)))
16979 (org-columns-display-here)))
16980 (move-to-column col)
16981 (if (and (org-mode-p)
16982 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16983 (org-columns-update key))))
16985 (defun org-verify-version (task)
16986 (cond
16987 ((eq task 'columns)
16988 (if (or (featurep 'xemacs)
16989 (< emacs-major-version 22))
16990 (error "Emacs 22 is required for the columns feature")))))
16992 (defun org-columns-open-link (&optional arg)
16993 (interactive "P")
16994 (let ((value (get-char-property (point) 'org-columns-value)))
16995 (org-open-link-from-string value arg)))
16997 (defun org-open-link-from-string (s &optional arg)
16998 "Open a link in the string S, as if it was in Org-mode."
16999 (interactive)
17000 (with-temp-buffer
17001 (let ((org-inhibit-startup t))
17002 (org-mode)
17003 (insert s)
17004 (goto-char (point-min))
17005 (org-open-at-point arg))))
17007 (defun org-columns-get-format-and-top-level ()
17008 (let (fmt)
17009 (when (condition-case nil (org-back-to-heading) (error nil))
17010 (move-marker org-entry-property-inherited-from nil)
17011 (setq fmt (org-entry-get nil "COLUMNS" t)))
17012 (setq fmt (or fmt org-columns-default-format))
17013 (org-set-local 'org-columns-current-fmt fmt)
17014 (org-columns-compile-format fmt)
17015 (if (marker-position org-entry-property-inherited-from)
17016 (move-marker org-columns-top-level-marker
17017 org-entry-property-inherited-from)
17018 (move-marker org-columns-top-level-marker (point)))
17019 fmt))
17021 (defun org-columns ()
17022 "Turn on column view on an org-mode file."
17023 (interactive)
17024 (org-verify-version 'columns)
17025 (org-columns-remove-overlays)
17026 (move-marker org-columns-begin-marker (point))
17027 (let (beg end fmt cache maxwidths)
17028 (setq fmt (org-columns-get-format-and-top-level))
17029 (save-excursion
17030 (goto-char org-columns-top-level-marker)
17031 (setq beg (point))
17032 (unless org-columns-inhibit-recalculation
17033 (org-columns-compute-all))
17034 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
17035 (point-max)))
17036 ;; Get and cache the properties
17037 (goto-char beg)
17038 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
17039 (save-excursion
17040 (save-restriction
17041 (narrow-to-region beg end)
17042 (org-clock-sum))))
17043 (while (re-search-forward (concat "^" outline-regexp) end t)
17044 (push (cons (org-current-line) (org-entry-properties)) cache))
17045 (when cache
17046 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17047 (org-set-local 'org-columns-current-maxwidths maxwidths)
17048 (org-columns-display-here-title)
17049 (mapc (lambda (x)
17050 (goto-line (car x))
17051 (org-columns-display-here (cdr x)))
17052 cache)))))
17054 (defun org-columns-new (&optional prop title width op fmt &rest rest)
17055 "Insert a new column, to the leeft o the current column."
17056 (interactive)
17057 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
17058 cell)
17059 (setq prop (completing-read
17060 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
17061 nil nil prop))
17062 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
17063 (setq width (read-string "Column width: " (if width (number-to-string width))))
17064 (if (string-match "\\S-" width)
17065 (setq width (string-to-number width))
17066 (setq width nil))
17067 (setq fmt (completing-read "Summary [none]: "
17068 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
17069 nil t))
17070 (if (string-match "\\S-" fmt)
17071 (setq fmt (intern fmt))
17072 (setq fmt nil))
17073 (if (eq fmt 'none) (setq fmt nil))
17074 (if editp
17075 (progn
17076 (setcar editp prop)
17077 (setcdr editp (list title width nil fmt)))
17078 (setq cell (nthcdr (1- (current-column))
17079 org-columns-current-fmt-compiled))
17080 (setcdr cell (cons (list prop title width nil fmt)
17081 (cdr cell))))
17082 (org-columns-store-format)
17083 (org-columns-redo)))
17085 (defun org-columns-delete ()
17086 "Delete the column at point from columns view."
17087 (interactive)
17088 (let* ((n (current-column))
17089 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
17090 (when (y-or-n-p
17091 (format "Are you sure you want to remove column \"%s\"? " title))
17092 (setq org-columns-current-fmt-compiled
17093 (delq (nth n org-columns-current-fmt-compiled)
17094 org-columns-current-fmt-compiled))
17095 (org-columns-store-format)
17096 (org-columns-redo)
17097 (if (>= (current-column) (length org-columns-current-fmt-compiled))
17098 (backward-char 1)))))
17100 (defun org-columns-edit-attributes ()
17101 "Edit the attributes of the current column."
17102 (interactive)
17103 (let* ((n (current-column))
17104 (info (nth n org-columns-current-fmt-compiled)))
17105 (apply 'org-columns-new info)))
17107 (defun org-columns-widen (arg)
17108 "Make the column wider by ARG characters."
17109 (interactive "p")
17110 (let* ((n (current-column))
17111 (entry (nth n org-columns-current-fmt-compiled))
17112 (width (or (nth 2 entry)
17113 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
17114 (setq width (max 1 (+ width arg)))
17115 (setcar (nthcdr 2 entry) width)
17116 (org-columns-store-format)
17117 (org-columns-redo)))
17119 (defun org-columns-narrow (arg)
17120 "Make the column nrrower by ARG characters."
17121 (interactive "p")
17122 (org-columns-widen (- arg)))
17124 (defun org-columns-move-right ()
17125 "Swap this column with the one to the right."
17126 (interactive)
17127 (let* ((n (current-column))
17128 (cell (nthcdr n org-columns-current-fmt-compiled))
17130 (when (>= n (1- (length org-columns-current-fmt-compiled)))
17131 (error "Cannot shift this column further to the right"))
17132 (setq e (car cell))
17133 (setcar cell (car (cdr cell)))
17134 (setcdr cell (cons e (cdr (cdr cell))))
17135 (org-columns-store-format)
17136 (org-columns-redo)
17137 (forward-char 1)))
17139 (defun org-columns-move-left ()
17140 "Swap this column with the one to the left."
17141 (interactive)
17142 (let* ((n (current-column)))
17143 (when (= n 0)
17144 (error "Cannot shift this column further to the left"))
17145 (backward-char 1)
17146 (org-columns-move-right)
17147 (backward-char 1)))
17149 (defun org-columns-store-format ()
17150 "Store the text version of the current columns format in appropriate place.
17151 This is either in the COLUMNS property of the node starting the current column
17152 display, or in the #+COLUMNS line of the current buffer."
17153 (let (fmt (cnt 0))
17154 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17155 (org-set-local 'org-columns-current-fmt fmt)
17156 (if (marker-position org-columns-top-level-marker)
17157 (save-excursion
17158 (goto-char org-columns-top-level-marker)
17159 (if (and (org-at-heading-p)
17160 (org-entry-get nil "COLUMNS"))
17161 (org-entry-put nil "COLUMNS" fmt)
17162 (goto-char (point-min))
17163 ;; Overwrite all #+COLUMNS lines....
17164 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17165 (setq cnt (1+ cnt))
17166 (replace-match (concat "#+COLUMNS: " fmt) t t))
17167 (unless (> cnt 0)
17168 (goto-char (point-min))
17169 (or (org-on-heading-p t) (outline-next-heading))
17170 (let ((inhibit-read-only t))
17171 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17172 (org-set-local 'org-columns-default-format fmt))))))
17174 (defvar org-overriding-columns-format nil
17175 "When set, overrides any other definition.")
17176 (defvar org-agenda-view-columns-initially nil
17177 "When set, switch to columns view immediately after creating the agenda.")
17179 (defun org-agenda-columns ()
17180 "Turn on column view in the agenda."
17181 (interactive)
17182 (org-verify-version 'columns)
17183 (org-columns-remove-overlays)
17184 (move-marker org-columns-begin-marker (point))
17185 (let (fmt cache maxwidths m)
17186 (cond
17187 ((and (local-variable-p 'org-overriding-columns-format)
17188 org-overriding-columns-format)
17189 (setq fmt org-overriding-columns-format))
17190 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17191 (setq fmt (org-entry-get m "COLUMNS" t)))
17192 ((and (boundp 'org-columns-current-fmt)
17193 (local-variable-p 'org-columns-current-fmt)
17194 org-columns-current-fmt)
17195 (setq fmt org-columns-current-fmt))
17196 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17197 (setq m (get-text-property m 'org-hd-marker))
17198 (setq fmt (org-entry-get m "COLUMNS" t))))
17199 (setq fmt (or fmt org-columns-default-format))
17200 (org-set-local 'org-columns-current-fmt fmt)
17201 (org-columns-compile-format fmt)
17202 (save-excursion
17203 ;; Get and cache the properties
17204 (goto-char (point-min))
17205 (while (not (eobp))
17206 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17207 (get-text-property (point) 'org-marker)))
17208 (push (cons (org-current-line) (org-entry-properties m)) cache))
17209 (beginning-of-line 2))
17210 (when cache
17211 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17212 (org-set-local 'org-columns-current-maxwidths maxwidths)
17213 (org-columns-display-here-title)
17214 (mapc (lambda (x)
17215 (goto-line (car x))
17216 (org-columns-display-here (cdr x)))
17217 cache)))))
17219 (defun org-columns-get-autowidth-alist (s cache)
17220 "Derive the maximum column widths from the format and the cache."
17221 (let ((start 0) rtn)
17222 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17223 (push (cons (match-string 1 s) 1) rtn)
17224 (setq start (match-end 0)))
17225 (mapc (lambda (x)
17226 (setcdr x (apply 'max
17227 (mapcar
17228 (lambda (y)
17229 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17230 cache))))
17231 rtn)
17232 rtn))
17234 (defun org-columns-compute-all ()
17235 "Compute all columns that have operators defined."
17236 (org-unmodified
17237 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17238 (let ((columns org-columns-current-fmt-compiled) col)
17239 (while (setq col (pop columns))
17240 (when (nth 3 col)
17241 (save-excursion
17242 (org-columns-compute (car col)))))))
17244 (defun org-columns-update (property)
17245 "Recompute PROPERTY, and update the columns display for it."
17246 (org-columns-compute property)
17247 (let (fmt val pos)
17248 (save-excursion
17249 (mapc (lambda (ov)
17250 (when (equal (org-overlay-get ov 'org-columns-key) property)
17251 (setq pos (org-overlay-start ov))
17252 (goto-char pos)
17253 (when (setq val (cdr (assoc property
17254 (get-text-property
17255 (point-at-bol) 'org-summaries))))
17256 (setq fmt (org-overlay-get ov 'org-columns-format))
17257 (org-overlay-put ov 'org-columns-value val)
17258 (org-overlay-put ov 'display (format fmt val)))))
17259 org-columns-overlays))))
17261 (defun org-columns-compute (property)
17262 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17263 (interactive)
17264 (let* ((re (concat "^" outline-regexp))
17265 (lmax 30) ; Does anyone use deeper levels???
17266 (lsum (make-vector lmax 0))
17267 (lflag (make-vector lmax nil))
17268 (level 0)
17269 (ass (assoc property org-columns-current-fmt-compiled))
17270 (format (nth 4 ass))
17271 (printf (nth 5 ass))
17272 (beg org-columns-top-level-marker)
17273 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17274 (save-excursion
17275 ;; Find the region to compute
17276 (goto-char beg)
17277 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17278 (goto-char end)
17279 ;; Walk the tree from the back and do the computations
17280 (while (re-search-backward re beg t)
17281 (setq sumpos (match-beginning 0)
17282 last-level level
17283 level (org-outline-level)
17284 val (org-entry-get nil property)
17285 valflag (and val (string-match "\\S-" val)))
17286 (cond
17287 ((< level last-level)
17288 ;; put the sum of lower levels here as a property
17289 (setq sum (aref lsum last-level) ; current sum
17290 flag (aref lflag last-level) ; any valid entries from children?
17291 str (org-column-number-to-string sum format printf)
17292 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17293 useval (if flag str1 (if valflag val ""))
17294 sum-alist (get-text-property sumpos 'org-summaries))
17295 (if (assoc property sum-alist)
17296 (setcdr (assoc property sum-alist) useval)
17297 (push (cons property useval) sum-alist)
17298 (org-unmodified
17299 (add-text-properties sumpos (1+ sumpos)
17300 (list 'org-summaries sum-alist))))
17301 (when val
17302 (org-entry-put nil property (if flag str val)))
17303 ;; add current to current level accumulator
17304 (when (or flag valflag)
17305 (aset lsum level (+ (aref lsum level)
17306 (if flag sum (org-column-string-to-number
17307 (if flag str val) format))))
17308 (aset lflag level t))
17309 ;; clear accumulators for deeper levels
17310 (loop for l from (1+ level) to (1- lmax) do
17311 (aset lsum l 0)
17312 (aset lflag l nil)))
17313 ((>= level last-level)
17314 ;; add what we have here to the accumulator for this level
17315 (aset lsum level (+ (aref lsum level)
17316 (org-column-string-to-number (or val "0") format)))
17317 (and valflag (aset lflag level t)))
17318 (t (error "This should not happen")))))))
17320 (defun org-columns-redo ()
17321 "Construct the column display again."
17322 (interactive)
17323 (message "Recomputing columns...")
17324 (save-excursion
17325 (if (marker-position org-columns-begin-marker)
17326 (goto-char org-columns-begin-marker))
17327 (org-columns-remove-overlays)
17328 (if (org-mode-p)
17329 (call-interactively 'org-columns)
17330 (call-interactively 'org-agenda-columns)))
17331 (message "Recomputing columns...done"))
17333 (defun org-columns-not-in-agenda ()
17334 (if (eq major-mode 'org-agenda-mode)
17335 (error "This command is only allowed in Org-mode buffers")))
17338 (defun org-string-to-number (s)
17339 "Convert string to number, and interpret hh:mm:ss."
17340 (if (not (string-match ":" s))
17341 (string-to-number s)
17342 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17343 (while l
17344 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17345 sum)))
17347 (defun org-column-number-to-string (n fmt &optional printf)
17348 "Convert a computed column number to a string value, according to FMT."
17349 (cond
17350 ((eq fmt 'add_times)
17351 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17352 (format "%d:%02d" h m)))
17353 ((eq fmt 'checkbox)
17354 (cond ((= n (floor n)) "[X]")
17355 ((> n 1.) "[-]")
17356 (t "[ ]")))
17357 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17358 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17359 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17360 (printf (format printf n))
17361 ((eq fmt 'currency)
17362 (format "%.2f" n))
17363 (t (number-to-string n))))
17365 (defun org-nofm-to-completion (n m &optional percent)
17366 (if (not percent)
17367 (format "[%d/%d]" n m)
17368 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17370 (defun org-column-string-to-number (s fmt)
17371 "Convert a column value to a number that can be used for column computing."
17372 (cond
17373 ((string-match ":" s)
17374 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17375 (while l
17376 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17377 sum))
17378 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17379 (if (equal s "[X]") 1. 0.000001))
17380 (t (string-to-number s))))
17382 (defun org-columns-uncompile-format (cfmt)
17383 "Turn the compiled columns format back into a string representation."
17384 (let ((rtn "") e s prop title op width fmt printf)
17385 (while (setq e (pop cfmt))
17386 (setq prop (car e)
17387 title (nth 1 e)
17388 width (nth 2 e)
17389 op (nth 3 e)
17390 fmt (nth 4 e)
17391 printf (nth 5 e))
17392 (cond
17393 ((eq fmt 'add_times) (setq op ":"))
17394 ((eq fmt 'checkbox) (setq op "X"))
17395 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17396 ((eq fmt 'checkbox-percent) (setq op "X%"))
17397 ((eq fmt 'add_numbers) (setq op "+"))
17398 ((eq fmt 'currency) (setq op "$")))
17399 (if (and op printf) (setq op (concat op ";" printf)))
17400 (if (equal title prop) (setq title nil))
17401 (setq s (concat "%" (if width (number-to-string width))
17402 prop
17403 (if title (concat "(" title ")"))
17404 (if op (concat "{" op "}"))))
17405 (setq rtn (concat rtn " " s)))
17406 (org-trim rtn)))
17408 (defun org-columns-compile-format (fmt)
17409 "Turn a column format string into an alist of specifications.
17410 The alist has one entry for each column in the format. The elements of
17411 that list are:
17412 property the property
17413 title the title field for the columns
17414 width the column width in characters, can be nil for automatic
17415 operator the operator if any
17416 format the output format for computed results, derived from operator
17417 printf a printf format for computed values"
17418 (let ((start 0) width prop title op f printf)
17419 (setq org-columns-current-fmt-compiled nil)
17420 (while (string-match
17421 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17422 fmt start)
17423 (setq start (match-end 0)
17424 width (match-string 1 fmt)
17425 prop (match-string 2 fmt)
17426 title (or (match-string 3 fmt) prop)
17427 op (match-string 4 fmt)
17428 f nil
17429 printf nil)
17430 (if width (setq width (string-to-number width)))
17431 (when (and op (string-match ";" op))
17432 (setq printf (substring op (match-end 0))
17433 op (substring op 0 (match-beginning 0))))
17434 (cond
17435 ((equal op "+") (setq f 'add_numbers))
17436 ((equal op "$") (setq f 'currency))
17437 ((equal op ":") (setq f 'add_times))
17438 ((equal op "X") (setq f 'checkbox))
17439 ((equal op "X/") (setq f 'checkbox-n-of-m))
17440 ((equal op "X%") (setq f 'checkbox-percent))
17442 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17443 (setq org-columns-current-fmt-compiled
17444 (nreverse org-columns-current-fmt-compiled))))
17447 ;;; Dynamic block for Column view
17449 (defun org-columns-capture-view (&optional maxlevel skip-empty-rows)
17450 "Get the column view of the current buffer or subtree.
17451 The first optional argument MAXLEVEL sets the level limit. A
17452 second optional argument SKIP-EMPTY-ROWS tells whether to skip
17453 empty rows, an empty row being one where all the column view
17454 specifiers except ITEM are empty. This function returns a list
17455 containing the title row and all other rows. Each row is a list
17456 of fields."
17457 (save-excursion
17458 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17459 (n (length title)) row tbl)
17460 (goto-char (point-min))
17461 (while (and (re-search-forward "^\\(\\*+\\) " nil t)
17462 (or (null maxlevel)
17463 (>= maxlevel
17464 (if org-odd-levels-only
17465 (/ (1+ (length (match-string 1))) 2)
17466 (length (match-string 1))))))
17467 (when (get-char-property (match-beginning 0) 'org-columns-key)
17468 (setq row nil)
17469 (loop for i from 0 to (1- n) do
17470 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17471 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17473 row))
17474 (setq row (nreverse row))
17475 (unless (and skip-empty-rows
17476 (eq 1 (length (delete "" (delete-dups row)))))
17477 (push row tbl))))
17478 (append (list title 'hline) (nreverse tbl)))))
17480 (defun org-dblock-write:columnview (params)
17481 "Write the column view table.
17482 PARAMS is a property list of parameters:
17484 :width enforce same column widths with <N> specifiers.
17485 :id the :ID: property of the entry where the columns view
17486 should be built, as a string. When `local', call locally.
17487 When `global' call column view with the cursor at the beginning
17488 of the buffer (usually this means that the whole buffer switches
17489 to column view).
17490 :hlines When t, insert a hline before each item. When a number, insert
17491 a hline before each level <= that number.
17492 :vlines When t, make each column a colgroup to enforce vertical lines.
17493 :maxlevel When set to a number, don't capture headlines below this level.
17494 :skip-empty-rows
17495 When t, skip rows where all specifiers other than ITEM are empty."
17496 (let ((pos (move-marker (make-marker) (point)))
17497 (hlines (plist-get params :hlines))
17498 (vlines (plist-get params :vlines))
17499 (maxlevel (plist-get params :maxlevel))
17500 (skip-empty-rows (plist-get params :skip-empty-rows))
17501 tbl id idpos nfields tmp)
17502 (save-excursion
17503 (save-restriction
17504 (when (setq id (plist-get params :id))
17505 (cond ((not id) nil)
17506 ((eq id 'global) (goto-char (point-min)))
17507 ((eq id 'local) nil)
17508 ((setq idpos (org-find-entry-with-id id))
17509 (goto-char idpos))
17510 (t (error "Cannot find entry with :ID: %s" id))))
17511 (org-columns)
17512 (setq tbl (org-columns-capture-view maxlevel skip-empty-rows))
17513 (setq nfields (length (car tbl)))
17514 (org-columns-quit)))
17515 (goto-char pos)
17516 (move-marker pos nil)
17517 (when tbl
17518 (when (plist-get params :hlines)
17519 (setq tmp nil)
17520 (while tbl
17521 (if (eq (car tbl) 'hline)
17522 (push (pop tbl) tmp)
17523 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17524 (if (and (not (eq (car tmp) 'hline))
17525 (or (eq hlines t)
17526 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17527 (push 'hline tmp)))
17528 (push (pop tbl) tmp)))
17529 (setq tbl (nreverse tmp)))
17530 (when vlines
17531 (setq tbl (mapcar (lambda (x)
17532 (if (eq 'hline x) x (cons "" x)))
17533 tbl))
17534 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17535 (setq pos (point))
17536 (insert (org-listtable-to-string tbl))
17537 (when (plist-get params :width)
17538 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17539 org-columns-current-widths "|")))
17540 (goto-char pos)
17541 (org-table-align))))
17543 (defun org-listtable-to-string (tbl)
17544 "Convert a listtable TBL to a string that contains the Org-mode table.
17545 The table still need to be alligned. The resulting string has no leading
17546 and tailing newline characters."
17547 (mapconcat
17548 (lambda (x)
17549 (cond
17550 ((listp x)
17551 (concat "|" (mapconcat 'identity x "|") "|"))
17552 ((eq x 'hline) "|-|")
17553 (t (error "Garbage in listtable: %s" x))))
17554 tbl "\n"))
17556 (defun org-insert-columns-dblock ()
17557 "Create a dynamic block capturing a column view table."
17558 (interactive)
17559 (let ((defaults '(:name "columnview" :hlines 1))
17560 (id (completing-read
17561 "Capture columns (local, global, entry with :ID: property) [local]: "
17562 (append '(("global") ("local"))
17563 (mapcar 'list (org-property-values "ID"))))))
17564 (if (equal id "") (setq id 'local))
17565 (if (equal id "global") (setq id 'global))
17566 (setq defaults (append defaults (list :id id)))
17567 (org-create-dblock defaults)
17568 (org-update-dblock)))
17570 ;;;; Timestamps
17572 (defvar org-last-changed-timestamp nil)
17573 (defvar org-time-was-given) ; dynamically scoped parameter
17574 (defvar org-end-time-was-given) ; dynamically scoped parameter
17575 (defvar org-ts-what) ; dynamically scoped parameter
17577 (defun org-time-stamp (arg)
17578 "Prompt for a date/time and insert a time stamp.
17579 If the user specifies a time like HH:MM, or if this command is called
17580 with a prefix argument, the time stamp will contain date and time.
17581 Otherwise, only the date will be included. All parts of a date not
17582 specified by the user will be filled in from the current date/time.
17583 So if you press just return without typing anything, the time stamp
17584 will represent the current date/time. If there is already a timestamp
17585 at the cursor, it will be modified."
17586 (interactive "P")
17587 (let* ((ts nil)
17588 (default-time
17589 ;; Default time is either today, or, when entering a range,
17590 ;; the range start.
17591 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17592 (save-excursion
17593 (re-search-backward
17594 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17595 (- (point) 20) t)))
17596 (apply 'encode-time (org-parse-time-string (match-string 1)))
17597 (current-time)))
17598 (default-input (and ts (org-get-compact-tod ts)))
17599 org-time-was-given org-end-time-was-given time)
17600 (cond
17601 ((and (org-at-timestamp-p)
17602 (eq last-command 'org-time-stamp)
17603 (eq this-command 'org-time-stamp))
17604 (insert "--")
17605 (setq time (let ((this-command this-command))
17606 (org-read-date arg 'totime nil nil default-time default-input)))
17607 (org-insert-time-stamp time (or org-time-was-given arg)))
17608 ((org-at-timestamp-p)
17609 (setq time (let ((this-command this-command))
17610 (org-read-date arg 'totime nil nil default-time default-input)))
17611 (when (org-at-timestamp-p) ; just to get the match data
17612 (replace-match "")
17613 (setq org-last-changed-timestamp
17614 (org-insert-time-stamp
17615 time (or org-time-was-given arg)
17616 nil nil nil (list org-end-time-was-given))))
17617 (message "Timestamp updated"))
17619 (setq time (let ((this-command this-command))
17620 (org-read-date arg 'totime nil nil default-time default-input)))
17621 (org-insert-time-stamp time (or org-time-was-given arg)
17622 nil nil nil (list org-end-time-was-given))))))
17624 ;; FIXME: can we use this for something else????
17625 ;; like computing time differences?????
17626 (defun org-get-compact-tod (s)
17627 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17628 (let* ((t1 (match-string 1 s))
17629 (h1 (string-to-number (match-string 2 s)))
17630 (m1 (string-to-number (match-string 3 s)))
17631 (t2 (and (match-end 4) (match-string 5 s)))
17632 (h2 (and t2 (string-to-number (match-string 6 s))))
17633 (m2 (and t2 (string-to-number (match-string 7 s))))
17634 dh dm)
17635 (if (not t2)
17637 (setq dh (- h2 h1) dm (- m2 m1))
17638 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17639 (concat t1 "+" (number-to-string dh)
17640 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17642 (defun org-time-stamp-inactive (&optional arg)
17643 "Insert an inactive time stamp.
17644 An inactive time stamp is enclosed in square brackets instead of angle
17645 brackets. It is inactive in the sense that it does not trigger agenda entries,
17646 does not link to the calendar and cannot be changed with the S-cursor keys.
17647 So these are more for recording a certain time/date."
17648 (interactive "P")
17649 (let (org-time-was-given org-end-time-was-given time)
17650 (setq time (org-read-date arg 'totime))
17651 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17652 nil nil (list org-end-time-was-given))))
17654 (defvar org-date-ovl (org-make-overlay 1 1))
17655 (org-overlay-put org-date-ovl 'face 'org-warning)
17656 (org-detach-overlay org-date-ovl)
17658 (defvar org-ans1) ; dynamically scoped parameter
17659 (defvar org-ans2) ; dynamically scoped parameter
17661 (defvar org-plain-time-of-day-regexp) ; defined below
17663 (defvar org-read-date-overlay nil)
17664 (defvar org-dcst nil) ; dynamically scoped
17666 (defun org-read-date (&optional with-time to-time from-string prompt
17667 default-time default-input)
17668 "Read a date, possibly a time, and make things smooth for the user.
17669 The prompt will suggest to enter an ISO date, but you can also enter anything
17670 which will at least partially be understood by `parse-time-string'.
17671 Unrecognized parts of the date will default to the current day, month, year,
17672 hour and minute. If this command is called to replace a timestamp at point,
17673 of to enter the second timestamp of a range, the default time is taken from the
17674 existing stamp. For example,
17675 3-2-5 --> 2003-02-05
17676 feb 15 --> currentyear-02-15
17677 sep 12 9 --> 2009-09-12
17678 12:45 --> today 12:45
17679 22 sept 0:34 --> currentyear-09-22 0:34
17680 12 --> currentyear-currentmonth-12
17681 Fri --> nearest Friday (today or later)
17682 etc.
17684 Furthermore you can specify a relative date by giving, as the *first* thing
17685 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17686 change in days weeks, months, years.
17687 With a single plus or minus, the date is relative to today. With a double
17688 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17689 +4d --> four days from today
17690 +4 --> same as above
17691 +2w --> two weeks from today
17692 ++5 --> five days from default date
17694 The function understands only English month and weekday abbreviations,
17695 but this can be configured with the variables `parse-time-months' and
17696 `parse-time-weekdays'.
17698 While prompting, a calendar is popped up - you can also select the
17699 date with the mouse (button 1). The calendar shows a period of three
17700 months. To scroll it to other months, use the keys `>' and `<'.
17701 If you don't like the calendar, turn it off with
17702 \(setq org-read-date-popup-calendar nil)
17704 With optional argument TO-TIME, the date will immediately be converted
17705 to an internal time.
17706 With an optional argument WITH-TIME, the prompt will suggest to also
17707 insert a time. Note that when WITH-TIME is not set, you can still
17708 enter a time, and this function will inform the calling routine about
17709 this change. The calling routine may then choose to change the format
17710 used to insert the time stamp into the buffer to include the time.
17711 With optional argument FROM-STRING, read from this string instead from
17712 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17713 the time/date that is used for everything that is not specified by the
17714 user."
17715 (require 'parse-time)
17716 (let* ((org-time-stamp-rounding-minutes
17717 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
17718 (org-dcst org-display-custom-times)
17719 (ct (org-current-time))
17720 (def (or default-time ct))
17721 (defdecode (decode-time def))
17722 (dummy (progn
17723 (when (< (nth 2 defdecode) org-extend-today-until)
17724 (setcar (nthcdr 2 defdecode) -1)
17725 (setcar (nthcdr 1 defdecode) 59)
17726 (setq def (apply 'encode-time defdecode)
17727 defdecode (decode-time def)))))
17728 (calendar-move-hook nil)
17729 (view-diary-entries-initially nil)
17730 (view-calendar-holidays-initially nil)
17731 (timestr (format-time-string
17732 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17733 (prompt (concat (if prompt (concat prompt " ") "")
17734 (format "Date+time [%s]: " timestr)))
17735 ans (org-ans0 "") org-ans1 org-ans2 final)
17737 (cond
17738 (from-string (setq ans from-string))
17739 (org-read-date-popup-calendar
17740 (save-excursion
17741 (save-window-excursion
17742 (calendar)
17743 (calendar-forward-day (- (time-to-days def)
17744 (calendar-absolute-from-gregorian
17745 (calendar-current-date))))
17746 (org-eval-in-calendar nil t)
17747 (let* ((old-map (current-local-map))
17748 (map (copy-keymap calendar-mode-map))
17749 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17750 (org-defkey map (kbd "RET") 'org-calendar-select)
17751 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17752 'org-calendar-select-mouse)
17753 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17754 'org-calendar-select-mouse)
17755 (org-defkey minibuffer-local-map [(meta shift left)]
17756 (lambda () (interactive)
17757 (org-eval-in-calendar '(calendar-backward-month 1))))
17758 (org-defkey minibuffer-local-map [(meta shift right)]
17759 (lambda () (interactive)
17760 (org-eval-in-calendar '(calendar-forward-month 1))))
17761 (org-defkey minibuffer-local-map [(meta shift up)]
17762 (lambda () (interactive)
17763 (org-eval-in-calendar '(calendar-backward-year 1))))
17764 (org-defkey minibuffer-local-map [(meta shift down)]
17765 (lambda () (interactive)
17766 (org-eval-in-calendar '(calendar-forward-year 1))))
17767 (org-defkey minibuffer-local-map [(shift up)]
17768 (lambda () (interactive)
17769 (org-eval-in-calendar '(calendar-backward-week 1))))
17770 (org-defkey minibuffer-local-map [(shift down)]
17771 (lambda () (interactive)
17772 (org-eval-in-calendar '(calendar-forward-week 1))))
17773 (org-defkey minibuffer-local-map [(shift left)]
17774 (lambda () (interactive)
17775 (org-eval-in-calendar '(calendar-backward-day 1))))
17776 (org-defkey minibuffer-local-map [(shift right)]
17777 (lambda () (interactive)
17778 (org-eval-in-calendar '(calendar-forward-day 1))))
17779 (org-defkey minibuffer-local-map ">"
17780 (lambda () (interactive)
17781 (org-eval-in-calendar '(scroll-calendar-left 1))))
17782 (org-defkey minibuffer-local-map "<"
17783 (lambda () (interactive)
17784 (org-eval-in-calendar '(scroll-calendar-right 1))))
17785 (unwind-protect
17786 (progn
17787 (use-local-map map)
17788 (add-hook 'post-command-hook 'org-read-date-display)
17789 (setq org-ans0 (read-string prompt default-input nil nil))
17790 ;; org-ans0: from prompt
17791 ;; org-ans1: from mouse click
17792 ;; org-ans2: from calendar motion
17793 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17794 (remove-hook 'post-command-hook 'org-read-date-display)
17795 (use-local-map old-map)
17796 (when org-read-date-overlay
17797 (org-delete-overlay org-read-date-overlay)
17798 (setq org-read-date-overlay nil)))))))
17800 (t ; Naked prompt only
17801 (unwind-protect
17802 (setq ans (read-string prompt default-input nil timestr))
17803 (when org-read-date-overlay
17804 (org-delete-overlay org-read-date-overlay)
17805 (setq org-read-date-overlay nil)))))
17807 (setq final (org-read-date-analyze ans def defdecode))
17809 (if to-time
17810 (apply 'encode-time final)
17811 (if (and (boundp 'org-time-was-given) org-time-was-given)
17812 (format "%04d-%02d-%02d %02d:%02d"
17813 (nth 5 final) (nth 4 final) (nth 3 final)
17814 (nth 2 final) (nth 1 final))
17815 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17816 (defvar def)
17817 (defvar defdecode)
17818 (defvar with-time)
17819 (defun org-read-date-display ()
17820 "Display the currrent date prompt interpretation in the minibuffer."
17821 (when org-read-date-display-live
17822 (when org-read-date-overlay
17823 (org-delete-overlay org-read-date-overlay))
17824 (let ((p (point)))
17825 (end-of-line 1)
17826 (while (not (equal (buffer-substring
17827 (max (point-min) (- (point) 4)) (point))
17828 " "))
17829 (insert " "))
17830 (goto-char p))
17831 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17832 " " (or org-ans1 org-ans2)))
17833 (org-end-time-was-given nil)
17834 (f (org-read-date-analyze ans def defdecode))
17835 (fmts (if org-dcst
17836 org-time-stamp-custom-formats
17837 org-time-stamp-formats))
17838 (fmt (if (or with-time
17839 (and (boundp 'org-time-was-given) org-time-was-given))
17840 (cdr fmts)
17841 (car fmts)))
17842 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17843 (when (and org-end-time-was-given
17844 (string-match org-plain-time-of-day-regexp txt))
17845 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17846 org-end-time-was-given
17847 (substring txt (match-end 0)))))
17848 (setq org-read-date-overlay
17849 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17850 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17852 (defun org-read-date-analyze (ans def defdecode)
17853 "Analyze the combined answer of the date prompt."
17854 ;; FIXME: cleanup and comment
17855 (let (delta deltan deltaw deltadef year month day
17856 hour minute second wday pm h2 m2 tl wday1)
17858 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17859 (setq ans (replace-match "" t t ans)
17860 deltan (car delta)
17861 deltaw (nth 1 delta)
17862 deltadef (nth 2 delta)))
17864 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17865 (when (string-match
17866 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17867 (setq year (if (match-end 2)
17868 (string-to-number (match-string 2 ans))
17869 (string-to-number (format-time-string "%Y")))
17870 month (string-to-number (match-string 3 ans))
17871 day (string-to-number (match-string 4 ans)))
17872 (if (< year 100) (setq year (+ 2000 year)))
17873 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17874 t nil ans)))
17875 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17876 ;; If there is a time with am/pm, and *no* time without it, we convert
17877 ;; so that matching will be successful.
17878 (loop for i from 1 to 2 do ; twice, for end time as well
17879 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17880 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17881 (setq hour (string-to-number (match-string 1 ans))
17882 minute (if (match-end 3)
17883 (string-to-number (match-string 3 ans))
17885 pm (equal ?p
17886 (string-to-char (downcase (match-string 4 ans)))))
17887 (if (and (= hour 12) (not pm))
17888 (setq hour 0)
17889 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17890 (setq ans (replace-match (format "%02d:%02d" hour minute)
17891 t t ans))))
17893 ;; Check if a time range is given as a duration
17894 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17895 (setq hour (string-to-number (match-string 1 ans))
17896 h2 (+ hour (string-to-number (match-string 3 ans)))
17897 minute (string-to-number (match-string 2 ans))
17898 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17899 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17900 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17902 ;; Check if there is a time range
17903 (when (boundp 'org-end-time-was-given)
17904 (setq org-time-was-given nil)
17905 (when (and (string-match org-plain-time-of-day-regexp ans)
17906 (match-end 8))
17907 (setq org-end-time-was-given (match-string 8 ans))
17908 (setq ans (concat (substring ans 0 (match-beginning 7))
17909 (substring ans (match-end 7))))))
17911 (setq tl (parse-time-string ans)
17912 day (or (nth 3 tl) (nth 3 defdecode))
17913 month (or (nth 4 tl)
17914 (if (and org-read-date-prefer-future
17915 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17916 (1+ (nth 4 defdecode))
17917 (nth 4 defdecode)))
17918 year (or (nth 5 tl)
17919 (if (and org-read-date-prefer-future
17920 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17921 (1+ (nth 5 defdecode))
17922 (nth 5 defdecode)))
17923 hour (or (nth 2 tl) (nth 2 defdecode))
17924 minute (or (nth 1 tl) (nth 1 defdecode))
17925 second (or (nth 0 tl) 0)
17926 wday (nth 6 tl))
17927 (when deltan
17928 (unless deltadef
17929 (let ((now (decode-time (current-time))))
17930 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17931 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17932 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17933 ((equal deltaw "m") (setq month (+ month deltan)))
17934 ((equal deltaw "y") (setq year (+ year deltan)))))
17935 (when (and wday (not (nth 3 tl)))
17936 ;; Weekday was given, but no day, so pick that day in the week
17937 ;; on or after the derived date.
17938 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17939 (unless (equal wday wday1)
17940 (setq day (+ day (% (- wday wday1 -7) 7)))))
17941 (if (and (boundp 'org-time-was-given)
17942 (nth 2 tl))
17943 (setq org-time-was-given t))
17944 (if (< year 100) (setq year (+ 2000 year)))
17945 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17946 (list second minute hour day month year)))
17948 (defvar parse-time-weekdays)
17950 (defun org-read-date-get-relative (s today default)
17951 "Check string S for special relative date string.
17952 TODAY and DEFAULT are internal times, for today and for a default.
17953 Return shift list (N what def-flag)
17954 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17955 N is the number of WHATs to shift.
17956 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17957 the DEFAULT date rather than TODAY."
17958 (when (string-match
17959 (concat
17960 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17961 "\\([0-9]+\\)?"
17962 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17963 "\\([ \t]\\|$\\)") s)
17964 (let* ((dir (if (match-end 1)
17965 (string-to-char (substring (match-string 1 s) -1))
17966 ?+))
17967 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17968 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17969 (what (if (match-end 3) (match-string 3 s) "d"))
17970 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17971 (date (if rel default today))
17972 (wday (nth 6 (decode-time date)))
17973 delta)
17974 (if wday1
17975 (progn
17976 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17977 (if (= dir ?-) (setq delta (- delta 7)))
17978 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17979 (list delta "d" rel))
17980 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17982 (defun org-eval-in-calendar (form &optional keepdate)
17983 "Eval FORM in the calendar window and return to current window.
17984 Also, store the cursor date in variable org-ans2."
17985 (let ((sw (selected-window)))
17986 (select-window (get-buffer-window "*Calendar*"))
17987 (eval form)
17988 (when (and (not keepdate) (calendar-cursor-to-date))
17989 (let* ((date (calendar-cursor-to-date))
17990 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17991 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17992 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17993 (select-window sw)))
17995 ; ;; Update the prompt to show new default date
17996 ; (save-excursion
17997 ; (goto-char (point-min))
17998 ; (when (and org-ans2
17999 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
18000 ; (get-text-property (match-end 0) 'field))
18001 ; (let ((inhibit-read-only t))
18002 ; (replace-match (concat "[" org-ans2 "]") t t)
18003 ; (add-text-properties (point-min) (1+ (match-end 0))
18004 ; (text-properties-at (1+ (point-min)))))))))
18006 (defun org-calendar-select ()
18007 "Return to `org-read-date' with the date currently selected.
18008 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18009 (interactive)
18010 (when (calendar-cursor-to-date)
18011 (let* ((date (calendar-cursor-to-date))
18012 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18013 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18014 (if (active-minibuffer-window) (exit-minibuffer))))
18016 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
18017 "Insert a date stamp for the date given by the internal TIME.
18018 WITH-HM means, use the stamp format that includes the time of the day.
18019 INACTIVE means use square brackets instead of angular ones, so that the
18020 stamp will not contribute to the agenda.
18021 PRE and POST are optional strings to be inserted before and after the
18022 stamp.
18023 The command returns the inserted time stamp."
18024 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
18025 stamp)
18026 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
18027 (insert-before-markers (or pre ""))
18028 (insert-before-markers (setq stamp (format-time-string fmt time)))
18029 (when (listp extra)
18030 (setq extra (car extra))
18031 (if (and (stringp extra)
18032 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
18033 (setq extra (format "-%02d:%02d"
18034 (string-to-number (match-string 1 extra))
18035 (string-to-number (match-string 2 extra))))
18036 (setq extra nil)))
18037 (when extra
18038 (backward-char 1)
18039 (insert-before-markers extra)
18040 (forward-char 1))
18041 (insert-before-markers (or post ""))
18042 stamp))
18044 (defun org-toggle-time-stamp-overlays ()
18045 "Toggle the use of custom time stamp formats."
18046 (interactive)
18047 (setq org-display-custom-times (not org-display-custom-times))
18048 (unless org-display-custom-times
18049 (let ((p (point-min)) (bmp (buffer-modified-p)))
18050 (while (setq p (next-single-property-change p 'display))
18051 (if (and (get-text-property p 'display)
18052 (eq (get-text-property p 'face) 'org-date))
18053 (remove-text-properties
18054 p (setq p (next-single-property-change p 'display))
18055 '(display t))))
18056 (set-buffer-modified-p bmp)))
18057 (if (featurep 'xemacs)
18058 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
18059 (org-restart-font-lock)
18060 (setq org-table-may-need-update t)
18061 (if org-display-custom-times
18062 (message "Time stamps are overlayed with custom format")
18063 (message "Time stamp overlays removed")))
18065 (defun org-display-custom-time (beg end)
18066 "Overlay modified time stamp format over timestamp between BED and END."
18067 (let* ((ts (buffer-substring beg end))
18068 t1 w1 with-hm tf time str w2 (off 0))
18069 (save-match-data
18070 (setq t1 (org-parse-time-string ts t))
18071 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
18072 (setq off (- (match-end 0) (match-beginning 0)))))
18073 (setq end (- end off))
18074 (setq w1 (- end beg)
18075 with-hm (and (nth 1 t1) (nth 2 t1))
18076 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
18077 time (org-fix-decoded-time t1)
18078 str (org-add-props
18079 (format-time-string
18080 (substring tf 1 -1) (apply 'encode-time time))
18081 nil 'mouse-face 'highlight)
18082 w2 (length str))
18083 (if (not (= w2 w1))
18084 (add-text-properties (1+ beg) (+ 2 beg)
18085 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
18086 (if (featurep 'xemacs)
18087 (progn
18088 (put-text-property beg end 'invisible t)
18089 (put-text-property beg end 'end-glyph (make-glyph str)))
18090 (put-text-property beg end 'display str))))
18092 (defun org-translate-time (string)
18093 "Translate all timestamps in STRING to custom format.
18094 But do this only if the variable `org-display-custom-times' is set."
18095 (when org-display-custom-times
18096 (save-match-data
18097 (let* ((start 0)
18098 (re org-ts-regexp-both)
18099 t1 with-hm inactive tf time str beg end)
18100 (while (setq start (string-match re string start))
18101 (setq beg (match-beginning 0)
18102 end (match-end 0)
18103 t1 (save-match-data
18104 (org-parse-time-string (substring string beg end) t))
18105 with-hm (and (nth 1 t1) (nth 2 t1))
18106 inactive (equal (substring string beg (1+ beg)) "[")
18107 tf (funcall (if with-hm 'cdr 'car)
18108 org-time-stamp-custom-formats)
18109 time (org-fix-decoded-time t1)
18110 str (format-time-string
18111 (concat
18112 (if inactive "[" "<") (substring tf 1 -1)
18113 (if inactive "]" ">"))
18114 (apply 'encode-time time))
18115 string (replace-match str t t string)
18116 start (+ start (length str)))))))
18117 string)
18119 (defun org-fix-decoded-time (time)
18120 "Set 0 instead of nil for the first 6 elements of time.
18121 Don't touch the rest."
18122 (let ((n 0))
18123 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
18125 (defun org-days-to-time (timestamp-string)
18126 "Difference between TIMESTAMP-STRING and now in days."
18127 (- (time-to-days (org-time-string-to-time timestamp-string))
18128 (time-to-days (current-time))))
18130 (defun org-deadline-close (timestamp-string &optional ndays)
18131 "Is the time in TIMESTAMP-STRING close to the current date?"
18132 (setq ndays (or ndays (org-get-wdays timestamp-string)))
18133 (and (< (org-days-to-time timestamp-string) ndays)
18134 (not (org-entry-is-done-p))))
18136 (defun org-get-wdays (ts)
18137 "Get the deadline lead time appropriate for timestring TS."
18138 (cond
18139 ((<= org-deadline-warning-days 0)
18140 ;; 0 or negative, enforce this value no matter what
18141 (- org-deadline-warning-days))
18142 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
18143 ;; lead time is specified.
18144 (floor (* (string-to-number (match-string 1 ts))
18145 (cdr (assoc (match-string 2 ts)
18146 '(("d" . 1) ("w" . 7)
18147 ("m" . 30.4) ("y" . 365.25)))))))
18148 ;; go for the default.
18149 (t org-deadline-warning-days)))
18151 (defun org-calendar-select-mouse (ev)
18152 "Return to `org-read-date' with the date currently selected.
18153 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18154 (interactive "e")
18155 (mouse-set-point ev)
18156 (when (calendar-cursor-to-date)
18157 (let* ((date (calendar-cursor-to-date))
18158 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18159 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18160 (if (active-minibuffer-window) (exit-minibuffer))))
18162 (defun org-check-deadlines (ndays)
18163 "Check if there are any deadlines due or past due.
18164 A deadline is considered due if it happens within `org-deadline-warning-days'
18165 days from today's date. If the deadline appears in an entry marked DONE,
18166 it is not shown. The prefix arg NDAYS can be used to test that many
18167 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18168 (interactive "P")
18169 (let* ((org-warn-days
18170 (cond
18171 ((equal ndays '(4)) 100000)
18172 (ndays (prefix-numeric-value ndays))
18173 (t (abs org-deadline-warning-days))))
18174 (case-fold-search nil)
18175 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18176 (callback
18177 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18179 (message "%d deadlines past-due or due within %d days"
18180 (org-occur regexp nil callback)
18181 org-warn-days)))
18183 (defun org-check-before-date (date)
18184 "Check if there are deadlines or scheduled entries before DATE."
18185 (interactive (list (org-read-date)))
18186 (let ((case-fold-search nil)
18187 (regexp (concat "\\<\\(" org-deadline-string
18188 "\\|" org-scheduled-string
18189 "\\) *<\\([^>]+\\)>"))
18190 (callback
18191 (lambda () (time-less-p
18192 (org-time-string-to-time (match-string 2))
18193 (org-time-string-to-time date)))))
18194 (message "%d entries before %s"
18195 (org-occur regexp nil callback) date)))
18197 (defun org-evaluate-time-range (&optional to-buffer)
18198 "Evaluate a time range by computing the difference between start and end.
18199 Normally the result is just printed in the echo area, but with prefix arg
18200 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18201 If the time range is actually in a table, the result is inserted into the
18202 next column.
18203 For time difference computation, a year is assumed to be exactly 365
18204 days in order to avoid rounding problems."
18205 (interactive "P")
18207 (org-clock-update-time-maybe)
18208 (save-excursion
18209 (unless (org-at-date-range-p t)
18210 (goto-char (point-at-bol))
18211 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18212 (if (not (org-at-date-range-p t))
18213 (error "Not at a time-stamp range, and none found in current line")))
18214 (let* ((ts1 (match-string 1))
18215 (ts2 (match-string 2))
18216 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18217 (match-end (match-end 0))
18218 (time1 (org-time-string-to-time ts1))
18219 (time2 (org-time-string-to-time ts2))
18220 (t1 (time-to-seconds time1))
18221 (t2 (time-to-seconds time2))
18222 (diff (abs (- t2 t1)))
18223 (negative (< (- t2 t1) 0))
18224 ;; (ys (floor (* 365 24 60 60)))
18225 (ds (* 24 60 60))
18226 (hs (* 60 60))
18227 (fy "%dy %dd %02d:%02d")
18228 (fy1 "%dy %dd")
18229 (fd "%dd %02d:%02d")
18230 (fd1 "%dd")
18231 (fh "%02d:%02d")
18232 y d h m align)
18233 (if havetime
18234 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18236 d (floor (/ diff ds)) diff (mod diff ds)
18237 h (floor (/ diff hs)) diff (mod diff hs)
18238 m (floor (/ diff 60)))
18239 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18241 d (floor (+ (/ diff ds) 0.5))
18242 h 0 m 0))
18243 (if (not to-buffer)
18244 (message "%s" (org-make-tdiff-string y d h m))
18245 (if (org-at-table-p)
18246 (progn
18247 (goto-char match-end)
18248 (setq align t)
18249 (and (looking-at " *|") (goto-char (match-end 0))))
18250 (goto-char match-end))
18251 (if (looking-at
18252 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18253 (replace-match ""))
18254 (if negative (insert " -"))
18255 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18256 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18257 (insert " " (format fh h m))))
18258 (if align (org-table-align))
18259 (message "Time difference inserted")))))
18261 (defun org-make-tdiff-string (y d h m)
18262 (let ((fmt "")
18263 (l nil))
18264 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18265 l (push y l)))
18266 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18267 l (push d l)))
18268 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18269 l (push h l)))
18270 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18271 l (push m l)))
18272 (apply 'format fmt (nreverse l))))
18274 (defun org-time-string-to-time (s)
18275 (apply 'encode-time (org-parse-time-string s)))
18277 (defun org-time-string-to-absolute (s &optional daynr prefer)
18278 "Convert a time stamp to an absolute day number.
18279 If there is a specifyer for a cyclic time stamp, get the closest date to
18280 DAYNR."
18281 (cond
18282 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18283 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18284 daynr
18285 (+ daynr 1000)))
18286 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18287 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18288 (time-to-days (current-time))) (match-string 0 s)
18289 prefer))
18290 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18292 (defun org-time-from-absolute (d)
18293 "Return the time corresponding to date D.
18294 D may be an absolute day number, or a calendar-type list (month day year)."
18295 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18296 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18298 (defun org-calendar-holiday ()
18299 "List of holidays, for Diary display in Org-mode."
18300 (require 'holidays)
18301 (let ((hl (funcall
18302 (if (fboundp 'calendar-check-holidays)
18303 'calendar-check-holidays 'check-calendar-holidays) date)))
18304 (if hl (mapconcat 'identity hl "; "))))
18306 (defun org-diary-sexp-entry (sexp entry date)
18307 "Process a SEXP diary ENTRY for DATE."
18308 (require 'diary-lib)
18309 (let ((result (if calendar-debug-sexp
18310 (let ((stack-trace-on-error t))
18311 (eval (car (read-from-string sexp))))
18312 (condition-case nil
18313 (eval (car (read-from-string sexp)))
18314 (error
18315 (beep)
18316 (message "Bad sexp at line %d in %s: %s"
18317 (org-current-line)
18318 (buffer-file-name) sexp)
18319 (sleep-for 2))))))
18320 (cond ((stringp result) result)
18321 ((and (consp result)
18322 (stringp (cdr result))) (cdr result))
18323 (result entry)
18324 (t nil))))
18326 (defun org-diary-to-ical-string (frombuf)
18327 "Get iCalendar entries from diary entries in buffer FROMBUF.
18328 This uses the icalendar.el library."
18329 (let* ((tmpdir (if (featurep 'xemacs)
18330 (temp-directory)
18331 temporary-file-directory))
18332 (tmpfile (make-temp-name
18333 (expand-file-name "orgics" tmpdir)))
18334 buf rtn b e)
18335 (save-excursion
18336 (set-buffer frombuf)
18337 (icalendar-export-region (point-min) (point-max) tmpfile)
18338 (setq buf (find-buffer-visiting tmpfile))
18339 (set-buffer buf)
18340 (goto-char (point-min))
18341 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18342 (setq b (match-beginning 0)))
18343 (goto-char (point-max))
18344 (if (re-search-backward "^END:VEVENT" nil t)
18345 (setq e (match-end 0)))
18346 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18347 (kill-buffer buf)
18348 (kill-buffer frombuf)
18349 (delete-file tmpfile)
18350 rtn))
18352 (defun org-closest-date (start current change prefer)
18353 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18354 When PREFER is `past' return a date that is either CURRENT or past.
18355 When PREFER is `future', return a date that is either CURRENT or future."
18356 ;; Make the proper lists from the dates
18357 (catch 'exit
18358 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18359 dn dw sday cday n1 n2
18360 d m y y1 y2 date1 date2 nmonths nm ny m2)
18362 (setq start (org-date-to-gregorian start)
18363 current (org-date-to-gregorian
18364 (if org-agenda-repeating-timestamp-show-all
18365 current
18366 (time-to-days (current-time))))
18367 sday (calendar-absolute-from-gregorian start)
18368 cday (calendar-absolute-from-gregorian current))
18370 (if (<= cday sday) (throw 'exit sday))
18372 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18373 (setq dn (string-to-number (match-string 1 change))
18374 dw (cdr (assoc (match-string 2 change) a1)))
18375 (error "Invalid change specifyer: %s" change))
18376 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18377 (cond
18378 ((eq dw 'day)
18379 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18380 n2 (+ n1 dn)))
18381 ((eq dw 'year)
18382 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18383 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18384 (setq date1 (list m d y1)
18385 n1 (calendar-absolute-from-gregorian date1)
18386 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18387 n2 (calendar-absolute-from-gregorian date2)))
18388 ((eq dw 'month)
18389 ;; approx number of month between the tow dates
18390 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18391 ;; How often does dn fit in there?
18392 (setq d (nth 1 start) m (car start) y (nth 2 start)
18393 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18394 m (+ m nm)
18395 ny (floor (/ m 12))
18396 y (+ y ny)
18397 m (- m (* ny 12)))
18398 (while (> m 12) (setq m (- m 12) y (1+ y)))
18399 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18400 (setq m2 (+ m dn) y2 y)
18401 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18402 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18403 (while (< n2 cday)
18404 (setq n1 n2 m m2 y y2)
18405 (setq m2 (+ m dn) y2 y)
18406 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18407 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18409 (if org-agenda-repeating-timestamp-show-all
18410 (cond
18411 ((eq prefer 'past) n1)
18412 ((eq prefer 'future) (if (= cday n1) n1 n2))
18413 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18414 (cond
18415 ((eq prefer 'past) n1)
18416 ((eq prefer 'future) (if (= cday n1) n1 n2))
18417 (t (if (= cday n1) n1 n2)))))))
18419 (defun org-date-to-gregorian (date)
18420 "Turn any specification of DATE into a gregorian date for the calendar."
18421 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18422 ((and (listp date) (= (length date) 3)) date)
18423 ((stringp date)
18424 (setq date (org-parse-time-string date))
18425 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18426 ((listp date)
18427 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18429 (defun org-parse-time-string (s &optional nodefault)
18430 "Parse the standard Org-mode time string.
18431 This should be a lot faster than the normal `parse-time-string'.
18432 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18433 hour and minute fields will be nil if not given."
18434 (if (string-match org-ts-regexp0 s)
18435 (list 0
18436 (if (or (match-beginning 8) (not nodefault))
18437 (string-to-number (or (match-string 8 s) "0")))
18438 (if (or (match-beginning 7) (not nodefault))
18439 (string-to-number (or (match-string 7 s) "0")))
18440 (string-to-number (match-string 4 s))
18441 (string-to-number (match-string 3 s))
18442 (string-to-number (match-string 2 s))
18443 nil nil nil)
18444 (make-list 9 0)))
18446 (defun org-timestamp-up (&optional arg)
18447 "Increase the date item at the cursor by one.
18448 If the cursor is on the year, change the year. If it is on the month or
18449 the day, change that.
18450 With prefix ARG, change by that many units."
18451 (interactive "p")
18452 (org-timestamp-change (prefix-numeric-value arg)))
18454 (defun org-timestamp-down (&optional arg)
18455 "Decrease the date item at the cursor by one.
18456 If the cursor is on the year, change the year. If it is on the month or
18457 the day, change that.
18458 With prefix ARG, change by that many units."
18459 (interactive "p")
18460 (org-timestamp-change (- (prefix-numeric-value arg))))
18462 (defun org-timestamp-up-day (&optional arg)
18463 "Increase the date in the time stamp by one day.
18464 With prefix ARG, change that many days."
18465 (interactive "p")
18466 (if (and (not (org-at-timestamp-p t))
18467 (org-on-heading-p))
18468 (org-todo 'up)
18469 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18471 (defun org-timestamp-down-day (&optional arg)
18472 "Decrease the date in the time stamp by one day.
18473 With prefix ARG, change that many days."
18474 (interactive "p")
18475 (if (and (not (org-at-timestamp-p t))
18476 (org-on-heading-p))
18477 (org-todo 'down)
18478 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18480 (defsubst org-pos-in-match-range (pos n)
18481 (and (match-beginning n)
18482 (<= (match-beginning n) pos)
18483 (>= (match-end n) pos)))
18485 (defun org-at-timestamp-p (&optional inactive-ok)
18486 "Determine if the cursor is in or at a timestamp."
18487 (interactive)
18488 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18489 (pos (point))
18490 (ans (or (looking-at tsr)
18491 (save-excursion
18492 (skip-chars-backward "^[<\n\r\t")
18493 (if (> (point) (point-min)) (backward-char 1))
18494 (and (looking-at tsr)
18495 (> (- (match-end 0) pos) -1))))))
18496 (and ans
18497 (boundp 'org-ts-what)
18498 (setq org-ts-what
18499 (cond
18500 ((= pos (match-beginning 0)) 'bracket)
18501 ((= pos (1- (match-end 0))) 'bracket)
18502 ((org-pos-in-match-range pos 2) 'year)
18503 ((org-pos-in-match-range pos 3) 'month)
18504 ((org-pos-in-match-range pos 7) 'hour)
18505 ((org-pos-in-match-range pos 8) 'minute)
18506 ((or (org-pos-in-match-range pos 4)
18507 (org-pos-in-match-range pos 5)) 'day)
18508 ((and (> pos (or (match-end 8) (match-end 5)))
18509 (< pos (match-end 0)))
18510 (- pos (or (match-end 8) (match-end 5))))
18511 (t 'day))))
18512 ans))
18514 (defun org-toggle-timestamp-type ()
18515 "Toggle the type (<active> or [inactive]) of a time stamp."
18516 (interactive)
18517 (when (org-at-timestamp-p t)
18518 (save-excursion
18519 (goto-char (match-beginning 0))
18520 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18521 (goto-char (1- (match-end 0)))
18522 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18523 (message "Timestamp is now %sactive"
18524 (if (equal (char-before) ?>) "in" ""))))
18526 (defun org-timestamp-change (n &optional what)
18527 "Change the date in the time stamp at point.
18528 The date will be changed by N times WHAT. WHAT can be `day', `month',
18529 `year', `minute', `second'. If WHAT is not given, the cursor position
18530 in the timestamp determines what will be changed."
18531 (let ((pos (point))
18532 with-hm inactive
18533 (dm (max (nth 1 org-time-stamp-rounding-minutes-when-changing) 1))
18534 org-ts-what
18535 extra rem
18536 ts time time0)
18537 (if (not (org-at-timestamp-p t))
18538 (error "Not at a timestamp"))
18539 (if (and (not what) (eq org-ts-what 'bracket))
18540 (org-toggle-timestamp-type)
18541 (if (and (not what) (not (eq org-ts-what 'day))
18542 org-display-custom-times
18543 (get-text-property (point) 'display)
18544 (not (get-text-property (1- (point)) 'display)))
18545 (setq org-ts-what 'day))
18546 (setq org-ts-what (or what org-ts-what)
18547 inactive (= (char-after (match-beginning 0)) ?\[)
18548 ts (match-string 0))
18549 (replace-match "")
18550 (if (string-match
18551 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18553 (setq extra (match-string 1 ts)))
18554 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18555 (setq with-hm t))
18556 (setq time0 (org-parse-time-string ts))
18557 (when (and (eq org-ts-what 'minute)
18558 (eq current-prefix-arg nil))
18559 (setq n (* dm (signum n)))
18560 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
18561 (setcar (cdr time0) (+ (nth 1 time0)
18562 (if (> n 0) (- rem) (- dm rem))))))
18563 (setq time
18564 (encode-time (or (car time0) 0)
18565 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18566 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18567 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18568 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18569 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18570 (nthcdr 6 time0)))
18571 (when (integerp org-ts-what)
18572 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18573 (if (eq what 'calendar)
18574 (let ((cal-date (org-get-date-from-calendar)))
18575 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18576 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18577 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18578 (setcar time0 (or (car time0) 0))
18579 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18580 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18581 (setq time (apply 'encode-time time0))))
18582 (setq org-last-changed-timestamp
18583 (org-insert-time-stamp time with-hm inactive nil nil extra))
18584 (org-clock-update-time-maybe)
18585 (goto-char pos)
18586 ;; Try to recenter the calendar window, if any
18587 (if (and org-calendar-follow-timestamp-change
18588 (get-buffer-window "*Calendar*" t)
18589 (memq org-ts-what '(day month year)))
18590 (org-recenter-calendar (time-to-days time))))))
18592 ;; FIXME: does not yet work for lead times
18593 (defun org-modify-ts-extra (s pos n)
18594 "Change the different parts of the lead-time and repeat fields in timestamp."
18595 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18596 ng h m new)
18597 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18598 (cond
18599 ((or (org-pos-in-match-range pos 2)
18600 (org-pos-in-match-range pos 3))
18601 (setq m (string-to-number (match-string 3 s))
18602 h (string-to-number (match-string 2 s)))
18603 (if (org-pos-in-match-range pos 2)
18604 (setq h (+ h n))
18605 (setq m (+ m n)))
18606 (if (< m 0) (setq m (+ m 60) h (1- h)))
18607 (if (> m 59) (setq m (- m 60) h (1+ h)))
18608 (setq h (min 24 (max 0 h)))
18609 (setq ng 1 new (format "-%02d:%02d" h m)))
18610 ((org-pos-in-match-range pos 6)
18611 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18612 ((org-pos-in-match-range pos 5)
18613 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18615 (when ng
18616 (setq s (concat
18617 (substring s 0 (match-beginning ng))
18619 (substring s (match-end ng))))))
18622 (defun org-recenter-calendar (date)
18623 "If the calendar is visible, recenter it to DATE."
18624 (let* ((win (selected-window))
18625 (cwin (get-buffer-window "*Calendar*" t))
18626 (calendar-move-hook nil))
18627 (when cwin
18628 (select-window cwin)
18629 (calendar-goto-date (if (listp date) date
18630 (calendar-gregorian-from-absolute date)))
18631 (select-window win))))
18633 (defun org-goto-calendar (&optional arg)
18634 "Go to the Emacs calendar at the current date.
18635 If there is a time stamp in the current line, go to that date.
18636 A prefix ARG can be used to force the current date."
18637 (interactive "P")
18638 (let ((tsr org-ts-regexp) diff
18639 (calendar-move-hook nil)
18640 (view-calendar-holidays-initially nil)
18641 (view-diary-entries-initially nil))
18642 (if (or (org-at-timestamp-p)
18643 (save-excursion
18644 (beginning-of-line 1)
18645 (looking-at (concat ".*" tsr))))
18646 (let ((d1 (time-to-days (current-time)))
18647 (d2 (time-to-days
18648 (org-time-string-to-time (match-string 1)))))
18649 (setq diff (- d2 d1))))
18650 (calendar)
18651 (calendar-goto-today)
18652 (if (and diff (not arg)) (calendar-forward-day diff))))
18654 (defun org-get-date-from-calendar ()
18655 "Return a list (month day year) of date at point in calendar."
18656 (with-current-buffer "*Calendar*"
18657 (save-match-data
18658 (calendar-cursor-to-date))))
18660 (defun org-date-from-calendar ()
18661 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18662 If there is already a time stamp at the cursor position, update it."
18663 (interactive)
18664 (if (org-at-timestamp-p t)
18665 (org-timestamp-change 0 'calendar)
18666 (let ((cal-date (org-get-date-from-calendar)))
18667 (org-insert-time-stamp
18668 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18670 (defvar appt-time-msg-list)
18672 ;;;###autoload
18673 (defun org-agenda-to-appt (&optional refresh filter)
18674 "Activate appointments found in `org-agenda-files'.
18675 With a \\[universal-argument] prefix, refresh the list of
18676 appointements.
18678 If FILTER is t, interactively prompt the user for a regular
18679 expression, and filter out entries that don't match it.
18681 If FILTER is a string, use this string as a regular expression
18682 for filtering entries out.
18684 FILTER can also be an alist with the car of each cell being
18685 either 'headline or 'category. For example:
18687 '((headline \"IMPORTANT\")
18688 (category \"Work\"))
18690 will only add headlines containing IMPORTANT or headlines
18691 belonging to the \"Work\" category."
18692 (interactive "P")
18693 (require 'calendar)
18694 (if refresh (setq appt-time-msg-list nil))
18695 (if (eq filter t)
18696 (setq filter (read-from-minibuffer "Regexp filter: ")))
18697 (let* ((cnt 0) ; count added events
18698 (org-agenda-new-buffers nil)
18699 (org-deadline-warning-days 0)
18700 (today (org-date-to-gregorian
18701 (time-to-days (current-time))))
18702 (files (org-agenda-files)) entries file)
18703 ;; Get all entries which may contain an appt
18704 (while (setq file (pop files))
18705 (setq entries
18706 (append entries
18707 (org-agenda-get-day-entries
18708 file today :timestamp :scheduled :deadline))))
18709 (setq entries (delq nil entries))
18710 ;; Map thru entries and find if we should filter them out
18711 (mapc
18712 (lambda(x)
18713 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18714 (cat (get-text-property 1 'org-category x))
18715 (tod (get-text-property 1 'time-of-day x))
18716 (ok (or (null filter)
18717 (and (stringp filter) (string-match filter evt))
18718 (and (listp filter)
18719 (or (string-match
18720 (cadr (assoc 'category filter)) cat)
18721 (string-match
18722 (cadr (assoc 'headline filter)) evt))))))
18723 ;; FIXME: Shall we remove text-properties for the appt text?
18724 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18725 (when (and ok tod)
18726 (setq tod (number-to-string tod)
18727 tod (when (string-match
18728 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18729 (concat (match-string 1 tod) ":"
18730 (match-string 2 tod))))
18731 (appt-add tod evt)
18732 (setq cnt (1+ cnt))))) entries)
18733 (org-release-buffers org-agenda-new-buffers)
18734 (if (eq cnt 0)
18735 (message "No event to add")
18736 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18738 ;;; The clock for measuring work time.
18740 (defvar org-mode-line-string "")
18741 (put 'org-mode-line-string 'risky-local-variable t)
18743 (defvar org-mode-line-timer nil)
18744 (defvar org-clock-heading "")
18745 (defvar org-clock-start-time "")
18747 (defun org-update-mode-line ()
18748 (let* ((delta (- (time-to-seconds (current-time))
18749 (time-to-seconds org-clock-start-time)))
18750 (h (floor delta 3600))
18751 (m (floor (- delta (* 3600 h)) 60)))
18752 (setq org-mode-line-string
18753 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18754 'help-echo "Org-mode clock is running"))
18755 (force-mode-line-update)))
18757 (defvar org-clock-marker (make-marker)
18758 "Marker recording the last clock-in.")
18759 (defvar org-clock-mode-line-entry nil
18760 "Information for the modeline about the running clock.")
18762 (defun org-clock-in ()
18763 "Start the clock on the current item.
18764 If necessary, clock-out of the currently active clock."
18765 (interactive)
18766 (org-clock-out t)
18767 (let (ts)
18768 (save-excursion
18769 (org-back-to-heading t)
18770 (when (and org-clock-in-switch-to-state
18771 (not (looking-at (concat outline-regexp "[ \t]*"
18772 org-clock-in-switch-to-state
18773 "\\>"))))
18774 (org-todo org-clock-in-switch-to-state))
18775 (if (and org-clock-heading-function
18776 (functionp org-clock-heading-function))
18777 (setq org-clock-heading (funcall org-clock-heading-function))
18778 (if (looking-at org-complex-heading-regexp)
18779 (setq org-clock-heading (match-string 4))
18780 (setq org-clock-heading "???")))
18781 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18782 (org-clock-find-position)
18784 (insert "\n") (backward-char 1)
18785 (indent-relative)
18786 (insert org-clock-string " ")
18787 (setq org-clock-start-time (current-time))
18788 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18789 (move-marker org-clock-marker (point) (buffer-base-buffer))
18790 (or global-mode-string (setq global-mode-string '("")))
18791 (or (memq 'org-mode-line-string global-mode-string)
18792 (setq global-mode-string
18793 (append global-mode-string '(org-mode-line-string))))
18794 (org-update-mode-line)
18795 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18796 (message "Clock started at %s" ts))))
18798 (defun org-clock-find-position ()
18799 "Find the location where the next clock line should be inserted."
18800 (org-back-to-heading t)
18801 (catch 'exit
18802 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18803 (re (concat "^[ \t]*" org-clock-string))
18804 (cnt 0)
18805 first last)
18806 (goto-char beg)
18807 (when (eobp) (newline) (setq end (max (point) end)))
18808 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18809 ;; we seem to have a CLOCK drawer, so go there.
18810 (beginning-of-line 2)
18811 (throw 'exit t))
18812 ;; Lets count the CLOCK lines
18813 (goto-char beg)
18814 (while (re-search-forward re end t)
18815 (setq first (or first (match-beginning 0))
18816 last (match-beginning 0)
18817 cnt (1+ cnt)))
18818 (when (and (integerp org-clock-into-drawer)
18819 (>= (1+ cnt) org-clock-into-drawer))
18820 ;; Wrap current entries into a new drawer
18821 (goto-char last)
18822 (beginning-of-line 2)
18823 (if (org-at-item-p) (org-end-of-item))
18824 (insert ":END:\n")
18825 (beginning-of-line 0)
18826 (org-indent-line-function)
18827 (goto-char first)
18828 (insert ":CLOCK:\n")
18829 (beginning-of-line 0)
18830 (org-indent-line-function)
18831 (org-flag-drawer t)
18832 (beginning-of-line 2)
18833 (throw 'exit nil))
18835 (goto-char beg)
18836 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18837 (not (equal (match-string 1) org-clock-string)))
18838 ;; Planning info, skip to after it
18839 (beginning-of-line 2)
18840 (or (bolp) (newline)))
18841 (when (eq t org-clock-into-drawer)
18842 (insert ":CLOCK:\n:END:\n")
18843 (beginning-of-line -1)
18844 (org-indent-line-function)
18845 (org-flag-drawer t)
18846 (beginning-of-line 2)
18847 (org-indent-line-function)))))
18849 (defun org-clock-out (&optional fail-quietly)
18850 "Stop the currently running clock.
18851 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18852 (interactive)
18853 (catch 'exit
18854 (if (not (marker-buffer org-clock-marker))
18855 (if fail-quietly (throw 'exit t) (error "No active clock")))
18856 (let (ts te s h m)
18857 (save-excursion
18858 (set-buffer (marker-buffer org-clock-marker))
18859 (goto-char org-clock-marker)
18860 (beginning-of-line 1)
18861 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18862 (equal (match-string 1) org-clock-string))
18863 (setq ts (match-string 2))
18864 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18865 (goto-char (match-end 0))
18866 (delete-region (point) (point-at-eol))
18867 (insert "--")
18868 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18869 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18870 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18871 h (floor (/ s 3600))
18872 s (- s (* 3600 h))
18873 m (floor (/ s 60))
18874 s (- s (* 60 s)))
18875 (insert " => " (format "%2d:%02d" h m))
18876 (move-marker org-clock-marker nil)
18877 (when org-log-note-clock-out
18878 (org-add-log-maybe 'clock-out))
18879 (when org-mode-line-timer
18880 (cancel-timer org-mode-line-timer)
18881 (setq org-mode-line-timer nil))
18882 (setq global-mode-string
18883 (delq 'org-mode-line-string global-mode-string))
18884 (force-mode-line-update)
18885 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18887 (defun org-clock-cancel ()
18888 "Cancel the running clock be removing the start timestamp."
18889 (interactive)
18890 (if (not (marker-buffer org-clock-marker))
18891 (error "No active clock"))
18892 (save-excursion
18893 (set-buffer (marker-buffer org-clock-marker))
18894 (goto-char org-clock-marker)
18895 (delete-region (1- (point-at-bol)) (point-at-eol)))
18896 (setq global-mode-string
18897 (delq 'org-mode-line-string global-mode-string))
18898 (force-mode-line-update)
18899 (message "Clock canceled"))
18901 (defun org-clock-goto (&optional delete-windows)
18902 "Go to the currently clocked-in entry."
18903 (interactive "P")
18904 (if (not (marker-buffer org-clock-marker))
18905 (error "No active clock"))
18906 (switch-to-buffer-other-window
18907 (marker-buffer org-clock-marker))
18908 (if delete-windows (delete-other-windows))
18909 (goto-char org-clock-marker)
18910 (org-show-entry)
18911 (org-back-to-heading)
18912 (recenter))
18914 (defvar org-clock-file-total-minutes nil
18915 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18916 (make-variable-buffer-local 'org-clock-file-total-minutes)
18918 (defun org-clock-sum (&optional tstart tend)
18919 "Sum the times for each subtree.
18920 Puts the resulting times in minutes as a text property on each headline."
18921 (interactive)
18922 (let* ((bmp (buffer-modified-p))
18923 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18924 org-clock-string
18925 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18926 (lmax 30)
18927 (ltimes (make-vector lmax 0))
18928 (t1 0)
18929 (level 0)
18930 ts te dt
18931 time)
18932 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18933 (save-excursion
18934 (goto-char (point-max))
18935 (while (re-search-backward re nil t)
18936 (cond
18937 ((match-end 2)
18938 ;; Two time stamps
18939 (setq ts (match-string 2)
18940 te (match-string 3)
18941 ts (time-to-seconds
18942 (apply 'encode-time (org-parse-time-string ts)))
18943 te (time-to-seconds
18944 (apply 'encode-time (org-parse-time-string te)))
18945 ts (if tstart (max ts tstart) ts)
18946 te (if tend (min te tend) te)
18947 dt (- te ts)
18948 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18949 ((match-end 4)
18950 ;; A naket time
18951 (setq t1 (+ t1 (string-to-number (match-string 5))
18952 (* 60 (string-to-number (match-string 4))))))
18953 (t ;; A headline
18954 (setq level (- (match-end 1) (match-beginning 1)))
18955 (when (or (> t1 0) (> (aref ltimes level) 0))
18956 (loop for l from 0 to level do
18957 (aset ltimes l (+ (aref ltimes l) t1)))
18958 (setq t1 0 time (aref ltimes level))
18959 (loop for l from level to (1- lmax) do
18960 (aset ltimes l 0))
18961 (goto-char (match-beginning 0))
18962 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18963 (setq org-clock-file-total-minutes (aref ltimes 0)))
18964 (set-buffer-modified-p bmp)))
18966 (defun org-clock-display (&optional total-only)
18967 "Show subtree times in the entire buffer.
18968 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18969 in the echo area."
18970 (interactive)
18971 (org-remove-clock-overlays)
18972 (let (time h m p)
18973 (org-clock-sum)
18974 (unless total-only
18975 (save-excursion
18976 (goto-char (point-min))
18977 (while (or (and (equal (setq p (point)) (point-min))
18978 (get-text-property p :org-clock-minutes))
18979 (setq p (next-single-property-change
18980 (point) :org-clock-minutes)))
18981 (goto-char p)
18982 (when (setq time (get-text-property p :org-clock-minutes))
18983 (org-put-clock-overlay time (funcall outline-level))))
18984 (setq h (/ org-clock-file-total-minutes 60)
18985 m (- org-clock-file-total-minutes (* 60 h)))
18986 ;; Arrange to remove the overlays upon next change.
18987 (when org-remove-highlights-with-change
18988 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18989 nil 'local))))
18990 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18992 (defvar org-clock-overlays nil)
18993 (make-variable-buffer-local 'org-clock-overlays)
18995 (defun org-put-clock-overlay (time &optional level)
18996 "Put an overlays on the current line, displaying TIME.
18997 If LEVEL is given, prefix time with a corresponding number of stars.
18998 This creates a new overlay and stores it in `org-clock-overlays', so that it
18999 will be easy to remove."
19000 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
19001 (l (if level (org-get-legal-level level 0) 0))
19002 (off 0)
19003 ov tx)
19004 (move-to-column c)
19005 (unless (eolp) (skip-chars-backward "^ \t"))
19006 (skip-chars-backward " \t")
19007 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
19008 tx (concat (buffer-substring (1- (point)) (point))
19009 (make-string (+ off (max 0 (- c (current-column)))) ?.)
19010 (org-add-props (format "%s %2d:%02d%s"
19011 (make-string l ?*) h m
19012 (make-string (- 16 l) ?\ ))
19013 '(face secondary-selection))
19014 ""))
19015 (if (not (featurep 'xemacs))
19016 (org-overlay-put ov 'display tx)
19017 (org-overlay-put ov 'invisible t)
19018 (org-overlay-put ov 'end-glyph (make-glyph tx)))
19019 (push ov org-clock-overlays)))
19021 (defun org-remove-clock-overlays (&optional beg end noremove)
19022 "Remove the occur highlights from the buffer.
19023 BEG and END are ignored. If NOREMOVE is nil, remove this function
19024 from the `before-change-functions' in the current buffer."
19025 (interactive)
19026 (unless org-inhibit-highlight-removal
19027 (mapc 'org-delete-overlay org-clock-overlays)
19028 (setq org-clock-overlays nil)
19029 (unless noremove
19030 (remove-hook 'before-change-functions
19031 'org-remove-clock-overlays 'local))))
19033 (defun org-clock-out-if-current ()
19034 "Clock out if the current entry contains the running clock.
19035 This is used to stop the clock after a TODO entry is marked DONE,
19036 and is only done if the variable `org-clock-out-when-done' is not nil."
19037 (when (and org-clock-out-when-done
19038 (member state org-done-keywords)
19039 (equal (marker-buffer org-clock-marker) (current-buffer))
19040 (< (point) org-clock-marker)
19041 (> (save-excursion (outline-next-heading) (point))
19042 org-clock-marker))
19043 ;; Clock out, but don't accept a logging message for this.
19044 (let ((org-log-note-clock-out nil))
19045 (org-clock-out))))
19047 (add-hook 'org-after-todo-state-change-hook
19048 'org-clock-out-if-current)
19050 (defun org-check-running-clock ()
19051 "Check if the current buffer contains the running clock.
19052 If yes, offer to stop it and to save the buffer with the changes."
19053 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
19054 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
19055 (buffer-name))))
19056 (org-clock-out)
19057 (when (y-or-n-p "Save changed buffer?")
19058 (save-buffer))))
19060 (defun org-clock-report (&optional arg)
19061 "Create a table containing a report about clocked time.
19062 If the cursor is inside an existing clocktable block, then the table
19063 will be updated. If not, a new clocktable will be inserted.
19064 When called with a prefix argument, move to the first clock table in the
19065 buffer and update it."
19066 (interactive "P")
19067 (org-remove-clock-overlays)
19068 (when arg
19069 (org-find-dblock "clocktable")
19070 (org-show-entry))
19071 (if (org-in-clocktable-p)
19072 (goto-char (org-in-clocktable-p))
19073 (org-create-dblock (list :name "clocktable"
19074 :maxlevel 2 :scope 'file)))
19075 (org-update-dblock))
19077 (defun org-in-clocktable-p ()
19078 "Check if the cursor is in a clocktable."
19079 (let ((pos (point)) start)
19080 (save-excursion
19081 (end-of-line 1)
19082 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
19083 (setq start (match-beginning 0))
19084 (re-search-forward "^#\\+END:.*" nil t)
19085 (>= (match-end 0) pos)
19086 start))))
19088 (defun org-clock-update-time-maybe ()
19089 "If this is a CLOCK line, update it and return t.
19090 Otherwise, return nil."
19091 (interactive)
19092 (save-excursion
19093 (beginning-of-line 1)
19094 (skip-chars-forward " \t")
19095 (when (looking-at org-clock-string)
19096 (let ((re (concat "[ \t]*" org-clock-string
19097 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
19098 "\\([ \t]*=>.*\\)?"))
19099 ts te h m s)
19100 (if (not (looking-at re))
19102 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
19103 (end-of-line 1)
19104 (setq ts (match-string 1)
19105 te (match-string 2))
19106 (setq s (- (time-to-seconds
19107 (apply 'encode-time (org-parse-time-string te)))
19108 (time-to-seconds
19109 (apply 'encode-time (org-parse-time-string ts))))
19110 h (floor (/ s 3600))
19111 s (- s (* 3600 h))
19112 m (floor (/ s 60))
19113 s (- s (* 60 s)))
19114 (insert " => " (format "%2d:%02d" h m))
19115 t)))))
19117 (defun org-clock-special-range (key &optional time as-strings)
19118 "Return two times bordering a special time range.
19119 Key is a symbol specifying the range and can be one of `today', `yesterday',
19120 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
19121 A week starts Monday 0:00 and ends Sunday 24:00.
19122 The range is determined relative to TIME. TIME defaults to the current time.
19123 The return value is a cons cell with two internal times like the ones
19124 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
19125 the returned times will be formatted strings."
19126 (let* ((tm (decode-time (or time (current-time))))
19127 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
19128 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
19129 (dow (nth 6 tm))
19130 s1 m1 h1 d1 month1 y1 diff ts te fm)
19131 (cond
19132 ((eq key 'today)
19133 (setq h 0 m 0 h1 24 m1 0))
19134 ((eq key 'yesterday)
19135 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19136 ((eq key 'thisweek)
19137 (setq diff (if (= dow 0) 6 (1- dow))
19138 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19139 ((eq key 'lastweek)
19140 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19141 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19142 ((eq key 'thismonth)
19143 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19144 ((eq key 'lastmonth)
19145 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19146 ((eq key 'thisyear)
19147 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19148 ((eq key 'lastyear)
19149 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19150 (t (error "No such time block %s" key)))
19151 (setq ts (encode-time s m h d month y)
19152 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19153 (or d1 d) (or month1 month) (or y1 y)))
19154 (setq fm (cdr org-time-stamp-formats))
19155 (if as-strings
19156 (cons (format-time-string fm ts) (format-time-string fm te))
19157 (cons ts te))))
19159 (defun org-dblock-write:clocktable (params)
19160 "Write the standard clocktable."
19161 (catch 'exit
19162 (let* ((hlchars '((1 . "*") (2 . "/")))
19163 (ins (make-marker))
19164 (total-time nil)
19165 (scope (plist-get params :scope))
19166 (tostring (plist-get params :tostring))
19167 (multifile (plist-get params :multifile))
19168 (header (plist-get params :header))
19169 (maxlevel (or (plist-get params :maxlevel) 3))
19170 (step (plist-get params :step))
19171 (emph (plist-get params :emphasize))
19172 (ts (plist-get params :tstart))
19173 (te (plist-get params :tend))
19174 (block (plist-get params :block))
19175 ipos time h m p level hlc hdl
19176 cc beg end pos tbl)
19177 (when step
19178 (org-clocktable-steps params)
19179 (throw 'exit nil))
19180 (when block
19181 (setq cc (org-clock-special-range block nil t)
19182 ts (car cc) te (cdr cc)))
19183 (if ts (setq ts (time-to-seconds
19184 (apply 'encode-time (org-parse-time-string ts)))))
19185 (if te (setq te (time-to-seconds
19186 (apply 'encode-time (org-parse-time-string te)))))
19187 (move-marker ins (point))
19188 (setq ipos (point))
19190 ;; Get the right scope
19191 (setq pos (point))
19192 (save-restriction
19193 (cond
19194 ((not scope))
19195 ((eq scope 'file) (widen))
19196 ((eq scope 'subtree) (org-narrow-to-subtree))
19197 ((eq scope 'tree)
19198 (while (org-up-heading-safe))
19199 (org-narrow-to-subtree))
19200 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19201 (symbol-name scope)))
19202 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19203 (catch 'exit
19204 (while (org-up-heading-safe)
19205 (looking-at outline-regexp)
19206 (if (<= (org-reduced-level (funcall outline-level)) level)
19207 (throw 'exit nil))))
19208 (org-narrow-to-subtree))
19209 ((or (listp scope) (eq scope 'agenda))
19210 (let* ((files (if (listp scope) scope (org-agenda-files)))
19211 (scope 'agenda)
19212 (p1 (copy-sequence params))
19213 file)
19214 (plist-put p1 :tostring t)
19215 (plist-put p1 :multifile t)
19216 (plist-put p1 :scope 'file)
19217 (org-prepare-agenda-buffers files)
19218 (while (setq file (pop files))
19219 (with-current-buffer (find-buffer-visiting file)
19220 (push (org-clocktable-add-file
19221 file (org-dblock-write:clocktable p1)) tbl)
19222 (setq total-time (+ (or total-time 0)
19223 org-clock-file-total-minutes)))))))
19224 (goto-char pos)
19226 (unless (eq scope 'agenda)
19227 (org-clock-sum ts te)
19228 (goto-char (point-min))
19229 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19230 (goto-char p)
19231 (when (setq time (get-text-property p :org-clock-minutes))
19232 (save-excursion
19233 (beginning-of-line 1)
19234 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19235 (setq level (org-reduced-level
19236 (- (match-end 1) (match-beginning 1))))
19237 (<= level maxlevel))
19238 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19239 hdl (match-string 2)
19240 h (/ time 60)
19241 m (- time (* 60 h)))
19242 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19243 (push (concat
19244 "| " (int-to-string level) "|" hlc hdl hlc " |"
19245 (make-string (1- level) ?|)
19246 hlc (format "%d:%02d" h m) hlc
19247 " |") tbl))))))
19248 (setq tbl (nreverse tbl))
19249 (if tostring
19250 (if tbl (mapconcat 'identity tbl "\n") nil)
19251 (goto-char ins)
19252 (insert-before-markers
19253 (or header
19254 (concat
19255 "Clock summary at ["
19256 (substring
19257 (format-time-string (cdr org-time-stamp-formats))
19258 1 -1)
19259 "]."
19260 (if block
19261 (format " Considered range is /%s/." block)
19263 "\n\n"))
19264 (if (eq scope 'agenda) "|File" "")
19265 "|L|Headline|Time|\n")
19266 (setq total-time (or total-time org-clock-file-total-minutes)
19267 h (/ total-time 60)
19268 m (- total-time (* 60 h)))
19269 (insert-before-markers
19270 "|-\n|"
19271 (if (eq scope 'agenda) "|" "")
19273 "*Total time*| "
19274 (format "*%d:%02d*" h m)
19275 "|\n|-\n")
19276 (setq tbl (delq nil tbl))
19277 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19278 (equal (substring (car tbl) 0 2) "|-"))
19279 (pop tbl))
19280 (insert-before-markers (mapconcat
19281 'identity (delq nil tbl)
19282 (if (eq scope 'agenda) "\n|-\n" "\n")))
19283 (backward-delete-char 1)
19284 (goto-char ipos)
19285 (skip-chars-forward "^|")
19286 (org-table-align))))))
19288 (defun org-clocktable-steps (params)
19289 (let* ((p1 (copy-sequence params))
19290 (ts (plist-get p1 :tstart))
19291 (te (plist-get p1 :tend))
19292 (step0 (plist-get p1 :step))
19293 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19294 (block (plist-get p1 :block))
19296 (when block
19297 (setq cc (org-clock-special-range block nil t)
19298 ts (car cc) te (cdr cc)))
19299 (if ts (setq ts (time-to-seconds
19300 (apply 'encode-time (org-parse-time-string ts)))))
19301 (if te (setq te (time-to-seconds
19302 (apply 'encode-time (org-parse-time-string te)))))
19303 (plist-put p1 :header "")
19304 (plist-put p1 :step nil)
19305 (plist-put p1 :block nil)
19306 (while (< ts te)
19307 (or (bolp) (insert "\n"))
19308 (plist-put p1 :tstart (format-time-string
19309 (car org-time-stamp-formats)
19310 (seconds-to-time ts)))
19311 (plist-put p1 :tend (format-time-string
19312 (car org-time-stamp-formats)
19313 (seconds-to-time (setq ts (+ ts step)))))
19314 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19315 (plist-get p1 :tstart) "\n")
19316 (org-dblock-write:clocktable p1)
19317 (re-search-forward "#\\+END:")
19318 (end-of-line 0))))
19321 (defun org-clocktable-add-file (file table)
19322 (if table
19323 (let ((lines (org-split-string table "\n"))
19324 (ff (file-name-nondirectory file)))
19325 (mapconcat 'identity
19326 (mapcar (lambda (x)
19327 (if (string-match org-table-dataline-regexp x)
19328 (concat "|" ff x)
19330 lines)
19331 "\n"))))
19333 ;; FIXME: I don't think anybody uses this, ask David
19334 (defun org-collect-clock-time-entries ()
19335 "Return an internal list with clocking information.
19336 This list has one entry for each CLOCK interval.
19337 FIXME: describe the elements."
19338 (interactive)
19339 (let ((re (concat "^[ \t]*" org-clock-string
19340 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19341 rtn beg end next cont level title total closedp leafp
19342 clockpos titlepos h m donep)
19343 (save-excursion
19344 (org-clock-sum)
19345 (goto-char (point-min))
19346 (while (re-search-forward re nil t)
19347 (setq clockpos (match-beginning 0)
19348 beg (match-string 1) end (match-string 2)
19349 cont (match-end 0))
19350 (setq beg (apply 'encode-time (org-parse-time-string beg))
19351 end (apply 'encode-time (org-parse-time-string end)))
19352 (org-back-to-heading t)
19353 (setq donep (org-entry-is-done-p))
19354 (setq titlepos (point)
19355 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19356 h (/ total 60) m (- total (* 60 h))
19357 total (cons h m))
19358 (looking-at "\\(\\*+\\) +\\(.*\\)")
19359 (setq level (- (match-end 1) (match-beginning 1))
19360 title (org-match-string-no-properties 2))
19361 (save-excursion (outline-next-heading) (setq next (point)))
19362 (setq closedp (re-search-forward org-closed-time-regexp next t))
19363 (goto-char next)
19364 (setq leafp (and (looking-at "^\\*+ ")
19365 (<= (- (match-end 0) (point)) level)))
19366 (push (list beg end clockpos closedp donep
19367 total title titlepos level leafp)
19368 rtn)
19369 (goto-char cont)))
19370 (nreverse rtn)))
19372 ;;;; Agenda, and Diary Integration
19374 ;;; Define the Org-agenda-mode
19376 (defvar org-agenda-mode-map (make-sparse-keymap)
19377 "Keymap for `org-agenda-mode'.")
19379 (defvar org-agenda-menu) ; defined later in this file.
19380 (defvar org-agenda-follow-mode nil)
19381 (defvar org-agenda-show-log nil)
19382 (defvar org-agenda-redo-command nil)
19383 (defvar org-agenda-query-string nil)
19384 (defvar org-agenda-mode-hook nil)
19385 (defvar org-agenda-type nil)
19386 (defvar org-agenda-force-single-file nil)
19388 (defun org-agenda-mode ()
19389 "Mode for time-sorted view on action items in Org-mode files.
19391 The following commands are available:
19393 \\{org-agenda-mode-map}"
19394 (interactive)
19395 (kill-all-local-variables)
19396 (setq org-agenda-undo-list nil
19397 org-agenda-pending-undo-list nil)
19398 (setq major-mode 'org-agenda-mode)
19399 ;; Keep global-font-lock-mode from turning on font-lock-mode
19400 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19401 (setq mode-name "Org-Agenda")
19402 (use-local-map org-agenda-mode-map)
19403 (easy-menu-add org-agenda-menu)
19404 (if org-startup-truncated (setq truncate-lines t))
19405 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19406 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19407 ;; Make sure properties are removed when copying text
19408 (when (boundp 'buffer-substring-filters)
19409 (org-set-local 'buffer-substring-filters
19410 (cons (lambda (x)
19411 (set-text-properties 0 (length x) nil x) x)
19412 buffer-substring-filters)))
19413 (unless org-agenda-keep-modes
19414 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19415 org-agenda-show-log nil))
19416 (easy-menu-change
19417 '("Agenda") "Agenda Files"
19418 (append
19419 (list
19420 (vector
19421 (if (get 'org-agenda-files 'org-restrict)
19422 "Restricted to single file"
19423 "Edit File List")
19424 '(org-edit-agenda-file-list)
19425 (not (get 'org-agenda-files 'org-restrict)))
19426 "--")
19427 (mapcar 'org-file-menu-entry (org-agenda-files))))
19428 (org-agenda-set-mode-name)
19429 (apply
19430 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19431 (list 'org-agenda-mode-hook)))
19433 (substitute-key-definition 'undo 'org-agenda-undo
19434 org-agenda-mode-map global-map)
19435 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19436 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19437 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19438 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19439 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19440 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19441 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19442 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19443 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19444 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19445 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19446 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19447 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19448 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19449 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19450 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19451 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19452 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19453 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19454 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19455 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19456 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19457 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19458 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19459 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19460 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19461 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19462 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19463 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19465 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19466 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19467 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19468 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19469 (while l (org-defkey org-agenda-mode-map
19470 (int-to-string (pop l)) 'digit-argument)))
19472 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19473 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19474 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19475 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19476 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19477 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19478 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19479 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19480 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19481 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19482 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19483 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19484 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19485 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19486 (org-defkey org-agenda-mode-map "n" 'next-line)
19487 (org-defkey org-agenda-mode-map "p" 'previous-line)
19488 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19489 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19490 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19491 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19492 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19493 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19494 (eval-after-load "calendar"
19495 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19496 'org-calendar-goto-agenda))
19497 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19498 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19499 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19500 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19501 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19502 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19503 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19504 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19505 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19506 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19507 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19508 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19509 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19510 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19511 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19512 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19513 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19514 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19515 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19516 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19517 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19518 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19520 (org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add)
19521 (org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract)
19522 (org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re)
19523 (org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re)
19525 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19526 "Local keymap for agenda entries from Org-mode.")
19528 (org-defkey org-agenda-keymap
19529 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19530 (org-defkey org-agenda-keymap
19531 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19532 (when org-agenda-mouse-1-follows-link
19533 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19534 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19535 '("Agenda"
19536 ("Agenda Files")
19537 "--"
19538 ["Show" org-agenda-show t]
19539 ["Go To (other window)" org-agenda-goto t]
19540 ["Go To (this window)" org-agenda-switch-to t]
19541 ["Follow Mode" org-agenda-follow-mode
19542 :style toggle :selected org-agenda-follow-mode :active t]
19543 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19544 "--"
19545 ["Cycle TODO" org-agenda-todo t]
19546 ["Archive subtree" org-agenda-archive t]
19547 ["Delete subtree" org-agenda-kill t]
19548 "--"
19549 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19550 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19551 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19552 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19553 "--"
19554 ("Tags and Properties"
19555 ["Show all Tags" org-agenda-show-tags t]
19556 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19557 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19558 "--"
19559 ["Column View" org-columns t])
19560 ("Date/Schedule"
19561 ["Schedule" org-agenda-schedule t]
19562 ["Set Deadline" org-agenda-deadline t]
19563 "--"
19564 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19565 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19566 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19567 ("Clock"
19568 ["Clock in" org-agenda-clock-in t]
19569 ["Clock out" org-agenda-clock-out t]
19570 ["Clock cancel" org-agenda-clock-cancel t]
19571 ["Goto running clock" org-clock-goto t])
19572 ("Priority"
19573 ["Set Priority" org-agenda-priority t]
19574 ["Increase Priority" org-agenda-priority-up t]
19575 ["Decrease Priority" org-agenda-priority-down t]
19576 ["Show Priority" org-agenda-show-priority t])
19577 ("Calendar/Diary"
19578 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19579 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19580 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19581 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19582 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19583 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19584 "--"
19585 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19586 "--"
19587 ("View"
19588 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19589 :style radio :selected (equal org-agenda-ndays 1)]
19590 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19591 :style radio :selected (equal org-agenda-ndays 7)]
19592 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19593 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19594 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19595 :style radio :selected (member org-agenda-ndays '(365 366))]
19596 "--"
19597 ["Show Logbook entries" org-agenda-log-mode
19598 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19599 ["Include Diary" org-agenda-toggle-diary
19600 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19601 ["Use Time Grid" org-agenda-toggle-time-grid
19602 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19603 ["Write view to file" org-write-agenda t]
19604 ["Rebuild buffer" org-agenda-redo t]
19605 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19606 "--"
19607 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19608 "--"
19609 ["Quit" org-agenda-quit t]
19610 ["Exit and Release Buffers" org-agenda-exit t]
19613 ;;; Agenda undo
19615 (defvar org-agenda-allow-remote-undo t
19616 "Non-nil means, allow remote undo from the agenda buffer.")
19617 (defvar org-agenda-undo-list nil
19618 "List of undoable operations in the agenda since last refresh.")
19619 (defvar org-agenda-undo-has-started-in nil
19620 "Buffers that have already seen `undo-start' in the current undo sequence.")
19621 (defvar org-agenda-pending-undo-list nil
19622 "In a series of undo commands, this is the list of remaning undo items.")
19624 (defmacro org-if-unprotected (&rest body)
19625 "Execute BODY if there is no `org-protected' text property at point."
19626 (declare (debug t))
19627 `(unless (get-text-property (point) 'org-protected)
19628 ,@body))
19630 (defmacro org-with-remote-undo (_buffer &rest _body)
19631 "Execute BODY while recording undo information in two buffers."
19632 (declare (indent 1) (debug t))
19633 `(let ((_cline (org-current-line))
19634 (_cmd this-command)
19635 (_buf1 (current-buffer))
19636 (_buf2 ,_buffer)
19637 (_undo1 buffer-undo-list)
19638 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19639 _c1 _c2)
19640 ,@_body
19641 (when org-agenda-allow-remote-undo
19642 (setq _c1 (org-verify-change-for-undo
19643 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19644 _c2 (org-verify-change-for-undo
19645 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19646 (when (or _c1 _c2)
19647 ;; make sure there are undo boundaries
19648 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19649 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19650 ;; remember which buffer to undo
19651 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19652 org-agenda-undo-list)))))
19654 (defun org-agenda-undo ()
19655 "Undo a remote editing step in the agenda.
19656 This undoes changes both in the agenda buffer and in the remote buffer
19657 that have been changed along."
19658 (interactive)
19659 (or org-agenda-allow-remote-undo
19660 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19661 (if (not (eq this-command last-command))
19662 (setq org-agenda-undo-has-started-in nil
19663 org-agenda-pending-undo-list org-agenda-undo-list))
19664 (if (not org-agenda-pending-undo-list)
19665 (error "No further undo information"))
19666 (let* ((entry (pop org-agenda-pending-undo-list))
19667 buf line cmd rembuf)
19668 (setq cmd (pop entry) line (pop entry))
19669 (setq rembuf (nth 2 entry))
19670 (org-with-remote-undo rembuf
19671 (while (bufferp (setq buf (pop entry)))
19672 (if (pop entry)
19673 (with-current-buffer buf
19674 (let ((last-undo-buffer buf)
19675 (inhibit-read-only t))
19676 (unless (memq buf org-agenda-undo-has-started-in)
19677 (push buf org-agenda-undo-has-started-in)
19678 (make-local-variable 'pending-undo-list)
19679 (undo-start))
19680 (while (and pending-undo-list
19681 (listp pending-undo-list)
19682 (not (car pending-undo-list)))
19683 (pop pending-undo-list))
19684 (undo-more 1))))))
19685 (goto-line line)
19686 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19688 (defun org-verify-change-for-undo (l1 l2)
19689 "Verify that a real change occurred between the undo lists L1 and L2."
19690 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19691 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19692 (not (eq l1 l2)))
19694 ;;; Agenda dispatch
19696 (defvar org-agenda-restrict nil)
19697 (defvar org-agenda-restrict-begin (make-marker))
19698 (defvar org-agenda-restrict-end (make-marker))
19699 (defvar org-agenda-last-dispatch-buffer nil)
19700 (defvar org-agenda-overriding-restriction nil)
19702 ;;;###autoload
19703 (defun org-agenda (arg &optional keys restriction)
19704 "Dispatch agenda commands to collect entries to the agenda buffer.
19705 Prompts for a command to execute. Any prefix arg will be passed
19706 on to the selected command. The default selections are:
19708 a Call `org-agenda-list' to display the agenda for current day or week.
19709 t Call `org-todo-list' to display the global todo list.
19710 T Call `org-todo-list' to display the global todo list, select only
19711 entries with a specific TODO keyword (the user gets a prompt).
19712 m Call `org-tags-view' to display headlines with tags matching
19713 a condition (the user is prompted for the condition).
19714 M Like `m', but select only TODO entries, no ordinary headlines.
19715 L Create a timeline for the current buffer.
19716 e Export views to associated files.
19718 More commands can be added by configuring the variable
19719 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19720 searches can be pre-defined in this way.
19722 If the current buffer is in Org-mode and visiting a file, you can also
19723 first press `<' once to indicate that the agenda should be temporarily
19724 \(until the next use of \\[org-agenda]) restricted to the current file.
19725 Pressing `<' twice means to restrict to the current subtree or region
19726 \(if active)."
19727 (interactive "P")
19728 (catch 'exit
19729 (let* ((prefix-descriptions nil)
19730 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19731 (org-agenda-custom-commands
19732 ;; normalize different versions
19733 (delq nil
19734 (mapcar
19735 (lambda (x)
19736 (cond ((stringp (cdr x))
19737 (push x prefix-descriptions)
19738 nil)
19739 ((stringp (nth 1 x)) x)
19740 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19741 (t (cons (car x) (cons "" (cdr x))))))
19742 org-agenda-custom-commands)))
19743 (buf (current-buffer))
19744 (bfn (buffer-file-name (buffer-base-buffer)))
19745 entry key type match lprops ans)
19746 ;; Turn off restriction unless there is an overriding one
19747 (unless org-agenda-overriding-restriction
19748 (put 'org-agenda-files 'org-restrict nil)
19749 (setq org-agenda-restrict nil)
19750 (move-marker org-agenda-restrict-begin nil)
19751 (move-marker org-agenda-restrict-end nil))
19752 ;; Delete old local properties
19753 (put 'org-agenda-redo-command 'org-lprops nil)
19754 ;; Remember where this call originated
19755 (setq org-agenda-last-dispatch-buffer (current-buffer))
19756 (unless keys
19757 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19758 keys (car ans)
19759 restriction (cdr ans)))
19760 ;; Estabish the restriction, if any
19761 (when (and (not org-agenda-overriding-restriction) restriction)
19762 (put 'org-agenda-files 'org-restrict (list bfn))
19763 (cond
19764 ((eq restriction 'region)
19765 (setq org-agenda-restrict t)
19766 (move-marker org-agenda-restrict-begin (region-beginning))
19767 (move-marker org-agenda-restrict-end (region-end)))
19768 ((eq restriction 'subtree)
19769 (save-excursion
19770 (setq org-agenda-restrict t)
19771 (org-back-to-heading t)
19772 (move-marker org-agenda-restrict-begin (point))
19773 (move-marker org-agenda-restrict-end
19774 (progn (org-end-of-subtree t)))))))
19776 (require 'calendar) ; FIXME: can we avoid this for some commands?
19777 ;; For example the todo list should not need it (but does...)
19778 (cond
19779 ((setq entry (assoc keys org-agenda-custom-commands))
19780 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19781 (progn
19782 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19783 (put 'org-agenda-redo-command 'org-lprops lprops)
19784 (cond
19785 ((eq type 'agenda)
19786 (org-let lprops '(org-agenda-list current-prefix-arg)))
19787 ((eq type 'alltodo)
19788 (org-let lprops '(org-todo-list current-prefix-arg)))
19789 ((eq type 'search)
19790 (org-let lprops '(org-search-view current-prefix-arg match)))
19791 ((eq type 'stuck)
19792 (org-let lprops '(org-agenda-list-stuck-projects
19793 current-prefix-arg)))
19794 ((eq type 'tags)
19795 (org-let lprops '(org-tags-view current-prefix-arg match)))
19796 ((eq type 'tags-todo)
19797 (org-let lprops '(org-tags-view '(4) match)))
19798 ((eq type 'todo)
19799 (org-let lprops '(org-todo-list match)))
19800 ((eq type 'tags-tree)
19801 (org-check-for-org-mode)
19802 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19803 ((eq type 'todo-tree)
19804 (org-check-for-org-mode)
19805 (org-let lprops
19806 '(org-occur (concat "^" outline-regexp "[ \t]*"
19807 (regexp-quote match) "\\>"))))
19808 ((eq type 'occur-tree)
19809 (org-check-for-org-mode)
19810 (org-let lprops '(org-occur match)))
19811 ((functionp type)
19812 (org-let lprops '(funcall type match)))
19813 ((fboundp type)
19814 (org-let lprops '(funcall type match)))
19815 (t (error "Invalid custom agenda command type %s" type))))
19816 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19817 ((equal keys "C")
19818 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19819 (customize-variable 'org-agenda-custom-commands))
19820 ((equal keys "a") (call-interactively 'org-agenda-list))
19821 ((equal keys "s") (call-interactively 'org-search-view))
19822 ((equal keys "t") (call-interactively 'org-todo-list))
19823 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19824 ((equal keys "m") (call-interactively 'org-tags-view))
19825 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19826 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19827 ((equal keys "L")
19828 (unless (org-mode-p)
19829 (error "This is not an Org-mode file"))
19830 (unless restriction
19831 (put 'org-agenda-files 'org-restrict (list bfn))
19832 (org-call-with-arg 'org-timeline arg)))
19833 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19834 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19835 ((equal keys "!") (customize-variable 'org-stuck-projects))
19836 (t (error "Invalid agenda key"))))))
19838 (defun org-agenda-normalize-custom-commands (cmds)
19839 (delq nil
19840 (mapcar
19841 (lambda (x)
19842 (cond ((stringp (cdr x)) nil)
19843 ((stringp (nth 1 x)) x)
19844 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19845 (t (cons (car x) (cons "" (cdr x))))))
19846 cmds)))
19848 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19849 "The user interface for selecting an agenda command."
19850 (catch 'exit
19851 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19852 (restrict-ok (and bfn (org-mode-p)))
19853 (region-p (org-region-active-p))
19854 (custom org-agenda-custom-commands)
19855 (selstring "")
19856 restriction second-time
19857 c entry key type match prefixes rmheader header-end custom1 desc)
19858 (save-window-excursion
19859 (delete-other-windows)
19860 (org-switch-to-buffer-other-window " *Agenda Commands*")
19861 (erase-buffer)
19862 (insert (eval-when-compile
19863 (let ((header
19865 Press key for an agenda command: < Buffer,subtree/region restriction
19866 -------------------------------- > Remove restriction
19867 a Agenda for current week or day e Export agenda views
19868 t List of all TODO entries T Entries with special TODO kwd
19869 m Match a TAGS query M Like m, but only TODO entries
19870 L Timeline for current buffer # List stuck projects (!=configure)
19871 s Search for keywords C Configure custom agenda commands
19872 / Multi-occur
19874 (start 0))
19875 (while (string-match
19876 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19877 header start)
19878 (setq start (match-end 0))
19879 (add-text-properties (match-beginning 2) (match-end 2)
19880 '(face bold) header))
19881 header)))
19882 (setq header-end (move-marker (make-marker) (point)))
19883 (while t
19884 (setq custom1 custom)
19885 (when (eq rmheader t)
19886 (goto-line 1)
19887 (re-search-forward ":" nil t)
19888 (delete-region (match-end 0) (point-at-eol))
19889 (forward-char 1)
19890 (looking-at "-+")
19891 (delete-region (match-end 0) (point-at-eol))
19892 (move-marker header-end (match-end 0)))
19893 (goto-char header-end)
19894 (delete-region (point) (point-max))
19895 (while (setq entry (pop custom1))
19896 (setq key (car entry) desc (nth 1 entry)
19897 type (nth 2 entry) match (nth 3 entry))
19898 (if (> (length key) 1)
19899 (add-to-list 'prefixes (string-to-char key))
19900 (insert
19901 (format
19902 "\n%-4s%-14s: %s"
19903 (org-add-props (copy-sequence key)
19904 '(face bold))
19905 (cond
19906 ((string-match "\\S-" desc) desc)
19907 ((eq type 'agenda) "Agenda for current week or day")
19908 ((eq type 'alltodo) "List of all TODO entries")
19909 ((eq type 'search) "Word search")
19910 ((eq type 'stuck) "List of stuck projects")
19911 ((eq type 'todo) "TODO keyword")
19912 ((eq type 'tags) "Tags query")
19913 ((eq type 'tags-todo) "Tags (TODO)")
19914 ((eq type 'tags-tree) "Tags tree")
19915 ((eq type 'todo-tree) "TODO kwd tree")
19916 ((eq type 'occur-tree) "Occur tree")
19917 ((functionp type) (if (symbolp type)
19918 (symbol-name type)
19919 "Lambda expression"))
19920 (t "???"))
19921 (cond
19922 ((stringp match)
19923 (org-add-props match nil 'face 'org-warning))
19924 (match
19925 (format "set of %d commands" (length match)))
19926 (t ""))))))
19927 (when prefixes
19928 (mapc (lambda (x)
19929 (insert
19930 (format "\n%s %s"
19931 (org-add-props (char-to-string x)
19932 nil 'face 'bold)
19933 (or (cdr (assoc (concat selstring (char-to-string x))
19934 prefix-descriptions))
19935 "Prefix key"))))
19936 prefixes))
19937 (goto-char (point-min))
19938 (when (fboundp 'fit-window-to-buffer)
19939 (if second-time
19940 (if (not (pos-visible-in-window-p (point-max)))
19941 (fit-window-to-buffer))
19942 (setq second-time t)
19943 (fit-window-to-buffer)))
19944 (message "Press key for agenda command%s:"
19945 (if (or restrict-ok org-agenda-overriding-restriction)
19946 (if org-agenda-overriding-restriction
19947 " (restriction lock active)"
19948 (if restriction
19949 (format " (restricted to %s)" restriction)
19950 " (unrestricted)"))
19951 ""))
19952 (setq c (read-char-exclusive))
19953 (message "")
19954 (cond
19955 ((assoc (char-to-string c) custom)
19956 (setq selstring (concat selstring (char-to-string c)))
19957 (throw 'exit (cons selstring restriction)))
19958 ((memq c prefixes)
19959 (setq selstring (concat selstring (char-to-string c))
19960 prefixes nil
19961 rmheader (or rmheader t)
19962 custom (delq nil (mapcar
19963 (lambda (x)
19964 (if (or (= (length (car x)) 1)
19965 (/= (string-to-char (car x)) c))
19967 (cons (substring (car x) 1) (cdr x))))
19968 custom))))
19969 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19970 (message "Restriction is only possible in Org-mode buffers")
19971 (ding) (sit-for 1))
19972 ((eq c ?1)
19973 (org-agenda-remove-restriction-lock 'noupdate)
19974 (setq restriction 'buffer))
19975 ((eq c ?0)
19976 (org-agenda-remove-restriction-lock 'noupdate)
19977 (setq restriction (if region-p 'region 'subtree)))
19978 ((eq c ?<)
19979 (org-agenda-remove-restriction-lock 'noupdate)
19980 (setq restriction
19981 (cond
19982 ((eq restriction 'buffer)
19983 (if region-p 'region 'subtree))
19984 ((memq restriction '(subtree region))
19985 nil)
19986 (t 'buffer))))
19987 ((eq c ?>)
19988 (org-agenda-remove-restriction-lock 'noupdate)
19989 (setq restriction nil))
19990 ((and (equal selstring "") (memq c '(?s ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19991 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19992 ((and (> (length selstring) 0) (eq c ?\d))
19993 (delete-window)
19994 (org-agenda-get-restriction-and-command prefix-descriptions))
19996 ((equal c ?q) (error "Abort"))
19997 (t (error "Invalid key %c" c))))))))
19999 (defun org-run-agenda-series (name series)
20000 (org-prepare-agenda name)
20001 (let* ((org-agenda-multi t)
20002 (redo (list 'org-run-agenda-series name (list 'quote series)))
20003 (cmds (car series))
20004 (gprops (nth 1 series))
20005 match ;; The byte compiler incorrectly complains about this. Keep it!
20006 cmd type lprops)
20007 (while (setq cmd (pop cmds))
20008 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
20009 (cond
20010 ((eq type 'agenda)
20011 (org-let2 gprops lprops
20012 '(call-interactively 'org-agenda-list)))
20013 ((eq type 'alltodo)
20014 (org-let2 gprops lprops
20015 '(call-interactively 'org-todo-list)))
20016 ((eq type 'search)
20017 (org-let2 gprops lprops
20018 '(org-search-view current-prefix-arg match)))
20019 ((eq type 'stuck)
20020 (org-let2 gprops lprops
20021 '(call-interactively 'org-agenda-list-stuck-projects)))
20022 ((eq type 'tags)
20023 (org-let2 gprops lprops
20024 '(org-tags-view current-prefix-arg match)))
20025 ((eq type 'tags-todo)
20026 (org-let2 gprops lprops
20027 '(org-tags-view '(4) match)))
20028 ((eq type 'todo)
20029 (org-let2 gprops lprops
20030 '(org-todo-list match)))
20031 ((fboundp type)
20032 (org-let2 gprops lprops
20033 '(funcall type match)))
20034 (t (error "Invalid type in command series"))))
20035 (widen)
20036 (setq org-agenda-redo-command redo)
20037 (goto-char (point-min)))
20038 (org-finalize-agenda))
20040 ;;;###autoload
20041 (defmacro org-batch-agenda (cmd-key &rest parameters)
20042 "Run an agenda command in batch mode and send the result to STDOUT.
20043 If CMD-KEY is a string of length 1, it is used as a key in
20044 `org-agenda-custom-commands' and triggers this command. If it is a
20045 longer string it is used as a tags/todo match string.
20046 Paramters are alternating variable names and values that will be bound
20047 before running the agenda command."
20048 (let (pars)
20049 (while parameters
20050 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20051 (if (> (length cmd-key) 2)
20052 (eval (list 'let (nreverse pars)
20053 (list 'org-tags-view nil cmd-key)))
20054 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20055 (set-buffer org-agenda-buffer-name)
20056 (princ (org-encode-for-stdout (buffer-string)))))
20058 (defun org-encode-for-stdout (string)
20059 (if (fboundp 'encode-coding-string)
20060 (encode-coding-string string buffer-file-coding-system)
20061 string))
20063 (defvar org-agenda-info nil)
20065 ;;;###autoload
20066 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
20067 "Run an agenda command in batch mode and send the result to STDOUT.
20068 If CMD-KEY is a string of length 1, it is used as a key in
20069 `org-agenda-custom-commands' and triggers this command. If it is a
20070 longer string it is used as a tags/todo match string.
20071 Paramters are alternating variable names and values that will be bound
20072 before running the agenda command.
20074 The output gives a line for each selected agenda item. Each
20075 item is a list of comma-separated values, like this:
20077 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
20079 category The category of the item
20080 head The headline, without TODO kwd, TAGS and PRIORITY
20081 type The type of the agenda entry, can be
20082 todo selected in TODO match
20083 tagsmatch selected in tags match
20084 diary imported from diary
20085 deadline a deadline on given date
20086 scheduled scheduled on given date
20087 timestamp entry has timestamp on given date
20088 closed entry was closed on given date
20089 upcoming-deadline warning about deadline
20090 past-scheduled forwarded scheduled item
20091 block entry has date block including g. date
20092 todo The todo keyword, if any
20093 tags All tags including inherited ones, separated by colons
20094 date The relevant date, like 2007-2-14
20095 time The time, like 15:00-16:50
20096 extra Sting with extra planning info
20097 priority-l The priority letter if any was given
20098 priority-n The computed numerical priority
20099 agenda-day The day in the agenda where this is listed"
20101 (let (pars)
20102 (while parameters
20103 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20104 (push (list 'org-agenda-remove-tags t) pars)
20105 (if (> (length cmd-key) 2)
20106 (eval (list 'let (nreverse pars)
20107 (list 'org-tags-view nil cmd-key)))
20108 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20109 (set-buffer org-agenda-buffer-name)
20110 (let* ((lines (org-split-string (buffer-string) "\n"))
20111 line)
20112 (while (setq line (pop lines))
20113 (catch 'next
20114 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
20115 (setq org-agenda-info
20116 (org-fix-agenda-info (text-properties-at 0 line)))
20117 (princ
20118 (org-encode-for-stdout
20119 (mapconcat 'org-agenda-export-csv-mapper
20120 '(org-category txt type todo tags date time-of-day extra
20121 priority-letter priority agenda-day)
20122 ",")))
20123 (princ "\n"))))))
20125 (defun org-fix-agenda-info (props)
20126 "Make sure all properties on an agenda item have a canonical form,
20127 so the export commands can easily use it."
20128 (let (tmp re)
20129 (when (setq tmp (plist-get props 'tags))
20130 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20131 (when (setq tmp (plist-get props 'date))
20132 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20133 (let ((calendar-date-display-form '(year "-" month "-" day)))
20134 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20136 (setq tmp (calendar-date-string tmp)))
20137 (setq props (plist-put props 'date tmp)))
20138 (when (setq tmp (plist-get props 'day))
20139 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20140 (let ((calendar-date-display-form '(year "-" month "-" day)))
20141 (setq tmp (calendar-date-string tmp)))
20142 (setq props (plist-put props 'day tmp))
20143 (setq props (plist-put props 'agenda-day tmp)))
20144 (when (setq tmp (plist-get props 'txt))
20145 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20146 (plist-put props 'priority-letter (match-string 1 tmp))
20147 (setq tmp (replace-match "" t t tmp)))
20148 (when (and (setq re (plist-get props 'org-todo-regexp))
20149 (setq re (concat "\\`\\.*" re " ?"))
20150 (string-match re tmp))
20151 (plist-put props 'todo (match-string 1 tmp))
20152 (setq tmp (replace-match "" t t tmp)))
20153 (plist-put props 'txt tmp)))
20154 props)
20156 (defun org-agenda-export-csv-mapper (prop)
20157 (let ((res (plist-get org-agenda-info prop)))
20158 (setq res
20159 (cond
20160 ((not res) "")
20161 ((stringp res) res)
20162 (t (prin1-to-string res))))
20163 (while (string-match "," res)
20164 (setq res (replace-match ";" t t res)))
20165 (org-trim res)))
20168 ;;;###autoload
20169 (defun org-store-agenda-views (&rest parameters)
20170 (interactive)
20171 (eval (list 'org-batch-store-agenda-views)))
20173 ;; FIXME, why is this a macro?????
20174 ;;;###autoload
20175 (defmacro org-batch-store-agenda-views (&rest parameters)
20176 "Run all custom agenda commands that have a file argument."
20177 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20178 (pop-up-frames nil)
20179 (dir default-directory)
20180 pars cmd thiscmdkey files opts)
20181 (while parameters
20182 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20183 (setq pars (reverse pars))
20184 (save-window-excursion
20185 (while cmds
20186 (setq cmd (pop cmds)
20187 thiscmdkey (car cmd)
20188 opts (nth 4 cmd)
20189 files (nth 5 cmd))
20190 (if (stringp files) (setq files (list files)))
20191 (when files
20192 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20193 (list 'org-agenda nil thiscmdkey)))
20194 (set-buffer org-agenda-buffer-name)
20195 (while files
20196 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20197 (list 'org-write-agenda
20198 (expand-file-name (pop files) dir) t))))
20199 (and (get-buffer org-agenda-buffer-name)
20200 (kill-buffer org-agenda-buffer-name)))))))
20202 (defun org-write-agenda (file &optional nosettings)
20203 "Write the current buffer (an agenda view) as a file.
20204 Depending on the extension of the file name, plain text (.txt),
20205 HTML (.html or .htm) or Postscript (.ps) is produced.
20206 If NOSETTINGS is given, do not scope the settings of
20207 `org-agenda-exporter-settings' into the export commands. This is used when
20208 the settings have already been scoped and we do not wish to overrule other,
20209 higher priority settings."
20210 (interactive "FWrite agenda to file: ")
20211 (if (not (file-writable-p file))
20212 (error "Cannot write agenda to file %s" file))
20213 (cond
20214 ((string-match "\\.html?\\'" file) (require 'htmlize))
20215 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20216 (org-let (if nosettings nil org-agenda-exporter-settings)
20217 '(save-excursion
20218 (save-window-excursion
20219 (cond
20220 ((string-match "\\.html?\\'" file)
20221 (set-buffer (htmlize-buffer (current-buffer)))
20223 (when (and org-agenda-export-html-style
20224 (string-match "<style>" org-agenda-export-html-style))
20225 ;; replace <style> section with org-agenda-export-html-style
20226 (goto-char (point-min))
20227 (kill-region (- (search-forward "<style") 6)
20228 (search-forward "</style>"))
20229 (insert org-agenda-export-html-style))
20230 (write-file file)
20231 (kill-buffer (current-buffer))
20232 (message "HTML written to %s" file))
20233 ((string-match "\\.ps\\'" file)
20234 (ps-print-buffer-with-faces file)
20235 (message "Postscript written to %s" file))
20237 (let ((bs (buffer-string)))
20238 (find-file file)
20239 (insert bs)
20240 (save-buffer 0)
20241 (kill-buffer (current-buffer))
20242 (message "Plain text written to %s" file))))))
20243 (set-buffer org-agenda-buffer-name)))
20245 (defmacro org-no-read-only (&rest body)
20246 "Inhibit read-only for BODY."
20247 `(let ((inhibit-read-only t)) ,@body))
20249 (defun org-check-for-org-mode ()
20250 "Make sure current buffer is in org-mode. Error if not."
20251 (or (org-mode-p)
20252 (error "Cannot execute org-mode agenda command on buffer in %s."
20253 major-mode)))
20255 (defun org-fit-agenda-window ()
20256 "Fit the window to the buffer size."
20257 (and (memq org-agenda-window-setup '(reorganize-frame))
20258 (fboundp 'fit-window-to-buffer)
20259 (fit-window-to-buffer
20261 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20262 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20264 ;;; Agenda file list
20266 (defun org-agenda-files (&optional unrestricted)
20267 "Get the list of agenda files.
20268 Optional UNRESTRICTED means return the full list even if a restriction
20269 is currently in place."
20270 (let ((files
20271 (cond
20272 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20273 ((stringp org-agenda-files) (org-read-agenda-file-list))
20274 ((listp org-agenda-files) org-agenda-files)
20275 (t (error "Invalid value of `org-agenda-files'")))))
20276 (setq files (apply 'append
20277 (mapcar (lambda (f)
20278 (if (file-directory-p f)
20279 (directory-files f t
20280 org-agenda-file-regexp)
20281 (list f)))
20282 files)))
20283 (if org-agenda-skip-unavailable-files
20284 (delq nil
20285 (mapcar (function
20286 (lambda (file)
20287 (and (file-readable-p file) file)))
20288 files))
20289 files))) ; `org-check-agenda-file' will remove them from the list
20291 (defun org-edit-agenda-file-list ()
20292 "Edit the list of agenda files.
20293 Depending on setup, this either uses customize to edit the variable
20294 `org-agenda-files', or it visits the file that is holding the list. In the
20295 latter case, the buffer is set up in a way that saving it automatically kills
20296 the buffer and restores the previous window configuration."
20297 (interactive)
20298 (if (stringp org-agenda-files)
20299 (let ((cw (current-window-configuration)))
20300 (find-file org-agenda-files)
20301 (org-set-local 'org-window-configuration cw)
20302 (org-add-hook 'after-save-hook
20303 (lambda ()
20304 (set-window-configuration
20305 (prog1 org-window-configuration
20306 (kill-buffer (current-buffer))))
20307 (org-install-agenda-files-menu)
20308 (message "New agenda file list installed"))
20309 nil 'local)
20310 (message "%s" (substitute-command-keys
20311 "Edit list and finish with \\[save-buffer]")))
20312 (customize-variable 'org-agenda-files)))
20314 (defun org-store-new-agenda-file-list (list)
20315 "Set new value for the agenda file list and save it correcly."
20316 (if (stringp org-agenda-files)
20317 (let ((f org-agenda-files) b)
20318 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20319 (with-temp-file f
20320 (insert (mapconcat 'identity list "\n") "\n")))
20321 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20322 (setq org-agenda-files list)
20323 (customize-save-variable 'org-agenda-files org-agenda-files))))
20325 (defun org-read-agenda-file-list ()
20326 "Read the list of agenda files from a file."
20327 (when (stringp org-agenda-files)
20328 (with-temp-buffer
20329 (insert-file-contents org-agenda-files)
20330 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20333 ;;;###autoload
20334 (defun org-cycle-agenda-files ()
20335 "Cycle through the files in `org-agenda-files'.
20336 If the current buffer visits an agenda file, find the next one in the list.
20337 If the current buffer does not, find the first agenda file."
20338 (interactive)
20339 (let* ((fs (org-agenda-files t))
20340 (files (append fs (list (car fs))))
20341 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20342 file)
20343 (unless files (error "No agenda files"))
20344 (catch 'exit
20345 (while (setq file (pop files))
20346 (if (equal (file-truename file) tcf)
20347 (when (car files)
20348 (find-file (car files))
20349 (throw 'exit t))))
20350 (find-file (car fs)))
20351 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20353 (defun org-agenda-file-to-front (&optional to-end)
20354 "Move/add the current file to the top of the agenda file list.
20355 If the file is not present in the list, it is added to the front. If it is
20356 present, it is moved there. With optional argument TO-END, add/move to the
20357 end of the list."
20358 (interactive "P")
20359 (let ((org-agenda-skip-unavailable-files nil)
20360 (file-alist (mapcar (lambda (x)
20361 (cons (file-truename x) x))
20362 (org-agenda-files t)))
20363 (ctf (file-truename buffer-file-name))
20364 x had)
20365 (setq x (assoc ctf file-alist) had x)
20367 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20368 (if to-end
20369 (setq file-alist (append (delq x file-alist) (list x)))
20370 (setq file-alist (cons x (delq x file-alist))))
20371 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20372 (org-install-agenda-files-menu)
20373 (message "File %s to %s of agenda file list"
20374 (if had "moved" "added") (if to-end "end" "front"))))
20376 (defun org-remove-file (&optional file)
20377 "Remove current file from the list of files in variable `org-agenda-files'.
20378 These are the files which are being checked for agenda entries.
20379 Optional argument FILE means, use this file instead of the current."
20380 (interactive)
20381 (let* ((org-agenda-skip-unavailable-files nil)
20382 (file (or file buffer-file-name))
20383 (true-file (file-truename file))
20384 (afile (abbreviate-file-name file))
20385 (files (delq nil (mapcar
20386 (lambda (x)
20387 (if (equal true-file
20388 (file-truename x))
20389 nil x))
20390 (org-agenda-files t)))))
20391 (if (not (= (length files) (length (org-agenda-files t))))
20392 (progn
20393 (org-store-new-agenda-file-list files)
20394 (org-install-agenda-files-menu)
20395 (message "Removed file: %s" afile))
20396 (message "File was not in list: %s (not removed)" afile))))
20398 (defun org-file-menu-entry (file)
20399 (vector file (list 'find-file file) t))
20401 (defun org-check-agenda-file (file)
20402 "Make sure FILE exists. If not, ask user what to do."
20403 (when (not (file-exists-p file))
20404 (message "non-existent file %s. [R]emove from list or [A]bort?"
20405 (abbreviate-file-name file))
20406 (let ((r (downcase (read-char-exclusive))))
20407 (cond
20408 ((equal r ?r)
20409 (org-remove-file file)
20410 (throw 'nextfile t))
20411 (t (error "Abort"))))))
20413 ;;; Agenda prepare and finalize
20415 (defvar org-agenda-multi nil) ; dynammically scoped
20416 (defvar org-agenda-buffer-name "*Org Agenda*")
20417 (defvar org-pre-agenda-window-conf nil)
20418 (defvar org-agenda-name nil)
20419 (defun org-prepare-agenda (&optional name)
20420 (setq org-todo-keywords-for-agenda nil)
20421 (setq org-done-keywords-for-agenda nil)
20422 (if org-agenda-multi
20423 (progn
20424 (setq buffer-read-only nil)
20425 (goto-char (point-max))
20426 (unless (or (bobp) org-agenda-compact-blocks)
20427 (insert "\n" (make-string (window-width) ?=) "\n"))
20428 (narrow-to-region (point) (point-max)))
20429 (org-agenda-reset-markers)
20430 (org-prepare-agenda-buffers (org-agenda-files))
20431 (setq org-todo-keywords-for-agenda
20432 (org-uniquify org-todo-keywords-for-agenda))
20433 (setq org-done-keywords-for-agenda
20434 (org-uniquify org-done-keywords-for-agenda))
20435 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20436 (awin (get-buffer-window abuf)))
20437 (cond
20438 ((equal (current-buffer) abuf) nil)
20439 (awin (select-window awin))
20440 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20441 ((equal org-agenda-window-setup 'current-window)
20442 (switch-to-buffer abuf))
20443 ((equal org-agenda-window-setup 'other-window)
20444 (org-switch-to-buffer-other-window abuf))
20445 ((equal org-agenda-window-setup 'other-frame)
20446 (switch-to-buffer-other-frame abuf))
20447 ((equal org-agenda-window-setup 'reorganize-frame)
20448 (delete-other-windows)
20449 (org-switch-to-buffer-other-window abuf))))
20450 (setq buffer-read-only nil)
20451 (erase-buffer)
20452 (org-agenda-mode)
20453 (and name (not org-agenda-name)
20454 (org-set-local 'org-agenda-name name)))
20455 (setq buffer-read-only nil))
20457 (defun org-finalize-agenda ()
20458 "Finishing touch for the agenda buffer, called just before displaying it."
20459 (unless org-agenda-multi
20460 (save-excursion
20461 (let ((inhibit-read-only t))
20462 (goto-char (point-min))
20463 (while (org-activate-bracket-links (point-max))
20464 (add-text-properties (match-beginning 0) (match-end 0)
20465 '(face org-link)))
20466 (org-agenda-align-tags)
20467 (unless org-agenda-with-colors
20468 (remove-text-properties (point-min) (point-max) '(face nil))))
20469 (if (and (boundp 'org-overriding-columns-format)
20470 org-overriding-columns-format)
20471 (org-set-local 'org-overriding-columns-format
20472 org-overriding-columns-format))
20473 (if (and (boundp 'org-agenda-view-columns-initially)
20474 org-agenda-view-columns-initially)
20475 (org-agenda-columns))
20476 (when org-agenda-fontify-priorities
20477 (org-fontify-priorities))
20478 (run-hooks 'org-finalize-agenda-hook)
20479 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20482 (defun org-fontify-priorities ()
20483 "Make highest priority lines bold, and lowest italic."
20484 (interactive)
20485 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20486 (org-delete-overlay o)))
20487 (org-overlays-in (point-min) (point-max)))
20488 (save-excursion
20489 (let ((inhibit-read-only t)
20490 b e p ov h l)
20491 (goto-char (point-min))
20492 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20493 (setq h (or (get-char-property (point) 'org-highest-priority)
20494 org-highest-priority)
20495 l (or (get-char-property (point) 'org-lowest-priority)
20496 org-lowest-priority)
20497 p (string-to-char (match-string 1))
20498 b (match-beginning 0) e (point-at-eol)
20499 ov (org-make-overlay b e))
20500 (org-overlay-put
20501 ov 'face
20502 (cond ((listp org-agenda-fontify-priorities)
20503 (cdr (assoc p org-agenda-fontify-priorities)))
20504 ((equal p l) 'italic)
20505 ((equal p h) 'bold)))
20506 (org-overlay-put ov 'org-type 'org-priority)))))
20508 (defun org-prepare-agenda-buffers (files)
20509 "Create buffers for all agenda files, protect archived trees and comments."
20510 (interactive)
20511 (let ((pa '(:org-archived t))
20512 (pc '(:org-comment t))
20513 (pall '(:org-archived t :org-comment t))
20514 (inhibit-read-only t)
20515 (rea (concat ":" org-archive-tag ":"))
20516 bmp file re)
20517 (save-excursion
20518 (save-restriction
20519 (while (setq file (pop files))
20520 (if (bufferp file)
20521 (set-buffer file)
20522 (org-check-agenda-file file)
20523 (set-buffer (org-get-agenda-file-buffer file)))
20524 (widen)
20525 (setq bmp (buffer-modified-p))
20526 (org-refresh-category-properties)
20527 (setq org-todo-keywords-for-agenda
20528 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20529 (setq org-done-keywords-for-agenda
20530 (append org-done-keywords-for-agenda org-done-keywords))
20531 (save-excursion
20532 (remove-text-properties (point-min) (point-max) pall)
20533 (when org-agenda-skip-archived-trees
20534 (goto-char (point-min))
20535 (while (re-search-forward rea nil t)
20536 (if (org-on-heading-p t)
20537 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20538 (goto-char (point-min))
20539 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20540 (while (re-search-forward re nil t)
20541 (add-text-properties
20542 (match-beginning 0) (org-end-of-subtree t) pc)))
20543 (set-buffer-modified-p bmp))))))
20545 (defvar org-agenda-skip-function nil
20546 "Function to be called at each match during agenda construction.
20547 If this function returns nil, the current match should not be skipped.
20548 Otherwise, the function must return a position from where the search
20549 should be continued.
20550 This may also be a Lisp form, it will be evaluated.
20551 Never set this variable using `setq' or so, because then it will apply
20552 to all future agenda commands. Instead, bind it with `let' to scope
20553 it dynamically into the agenda-constructing command. A good way to set
20554 it is through options in org-agenda-custom-commands.")
20556 (defun org-agenda-skip ()
20557 "Throw to `:skip' in places that should be skipped.
20558 Also moves point to the end of the skipped region, so that search can
20559 continue from there."
20560 (let ((p (point-at-bol)) to fp)
20561 (and org-agenda-skip-archived-trees
20562 (get-text-property p :org-archived)
20563 (org-end-of-subtree t)
20564 (throw :skip t))
20565 (and (get-text-property p :org-comment)
20566 (org-end-of-subtree t)
20567 (throw :skip t))
20568 (if (equal (char-after p) ?#) (throw :skip t))
20569 (when (and (or (setq fp (functionp org-agenda-skip-function))
20570 (consp org-agenda-skip-function))
20571 (setq to (save-excursion
20572 (save-match-data
20573 (if fp
20574 (funcall org-agenda-skip-function)
20575 (eval org-agenda-skip-function))))))
20576 (goto-char to)
20577 (throw :skip t))))
20579 (defvar org-agenda-markers nil
20580 "List of all currently active markers created by `org-agenda'.")
20581 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20582 "Creation time of the last agenda marker.")
20584 (defun org-agenda-new-marker (&optional pos)
20585 "Return a new agenda marker.
20586 Org-mode keeps a list of these markers and resets them when they are
20587 no longer in use."
20588 (let ((m (copy-marker (or pos (point)))))
20589 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20590 (push m org-agenda-markers)
20593 (defun org-agenda-reset-markers ()
20594 "Reset markers created by `org-agenda'."
20595 (while org-agenda-markers
20596 (move-marker (pop org-agenda-markers) nil)))
20598 (defun org-get-agenda-file-buffer (file)
20599 "Get a buffer visiting FILE. If the buffer needs to be created, add
20600 it to the list of buffers which might be released later."
20601 (let ((buf (org-find-base-buffer-visiting file)))
20602 (if buf
20603 buf ; just return it
20604 ;; Make a new buffer and remember it
20605 (setq buf (find-file-noselect file))
20606 (if buf (push buf org-agenda-new-buffers))
20607 buf)))
20609 (defun org-release-buffers (blist)
20610 "Release all buffers in list, asking the user for confirmation when needed.
20611 When a buffer is unmodified, it is just killed. When modified, it is saved
20612 \(if the user agrees) and then killed."
20613 (let (buf file)
20614 (while (setq buf (pop blist))
20615 (setq file (buffer-file-name buf))
20616 (when (and (buffer-modified-p buf)
20617 file
20618 (y-or-n-p (format "Save file %s? " file)))
20619 (with-current-buffer buf (save-buffer)))
20620 (kill-buffer buf))))
20622 (defun org-get-category (&optional pos)
20623 "Get the category applying to position POS."
20624 (get-text-property (or pos (point)) 'org-category))
20626 ;;; Agenda timeline
20628 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20630 (defun org-timeline (&optional include-all)
20631 "Show a time-sorted view of the entries in the current org file.
20632 Only entries with a time stamp of today or later will be listed. With
20633 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20634 under the current date.
20635 If the buffer contains an active region, only check the region for
20636 dates."
20637 (interactive "P")
20638 (require 'calendar)
20639 (org-compile-prefix-format 'timeline)
20640 (org-set-sorting-strategy 'timeline)
20641 (let* ((dopast t)
20642 (dotodo include-all)
20643 (doclosed org-agenda-show-log)
20644 (entry buffer-file-name)
20645 (date (calendar-current-date))
20646 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20647 (end (if (org-region-active-p) (region-end) (point-max)))
20648 (day-numbers (org-get-all-dates beg end 'no-ranges
20649 t doclosed ; always include today
20650 org-timeline-show-empty-dates))
20651 (org-deadline-warning-days 0)
20652 (org-agenda-only-exact-dates t)
20653 (today (time-to-days (current-time)))
20654 (past t)
20655 args
20656 s e rtn d emptyp)
20657 (setq org-agenda-redo-command
20658 (list 'progn
20659 (list 'org-switch-to-buffer-other-window (current-buffer))
20660 (list 'org-timeline (list 'quote include-all))))
20661 (if (not dopast)
20662 ;; Remove past dates from the list of dates.
20663 (setq day-numbers (delq nil (mapcar (lambda(x)
20664 (if (>= x today) x nil))
20665 day-numbers))))
20666 (org-prepare-agenda (concat "Timeline "
20667 (file-name-nondirectory buffer-file-name)))
20668 (if doclosed (push :closed args))
20669 (push :timestamp args)
20670 (push :deadline args)
20671 (push :scheduled args)
20672 (push :sexp args)
20673 (if dotodo (push :todo args))
20674 (while (setq d (pop day-numbers))
20675 (if (and (listp d) (eq (car d) :omitted))
20676 (progn
20677 (setq s (point))
20678 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20679 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20680 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20681 (if (and (>= d today)
20682 dopast
20683 past)
20684 (progn
20685 (setq past nil)
20686 (insert (make-string 79 ?-) "\n")))
20687 (setq date (calendar-gregorian-from-absolute d))
20688 (setq s (point))
20689 (setq rtn (and (not emptyp)
20690 (apply 'org-agenda-get-day-entries entry
20691 date args)))
20692 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20693 (progn
20694 (insert
20695 (if (stringp org-agenda-format-date)
20696 (format-time-string org-agenda-format-date
20697 (org-time-from-absolute date))
20698 (funcall org-agenda-format-date date))
20699 "\n")
20700 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20701 (put-text-property s (1- (point)) 'org-date-line t)
20702 (if (equal d today)
20703 (put-text-property s (1- (point)) 'org-today t))
20704 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20705 (put-text-property s (1- (point)) 'day d)))))
20706 (goto-char (point-min))
20707 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20708 (point-min)))
20709 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20710 (org-finalize-agenda)
20711 (setq buffer-read-only t)))
20713 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20714 "Return a list of all relevant day numbers from BEG to END buffer positions.
20715 If NO-RANGES is non-nil, include only the start and end dates of a range,
20716 not every single day in the range. If FORCE-TODAY is non-nil, make
20717 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20718 inactive time stamps (those in square brackets) are included.
20719 When EMPTY is non-nil, also include days without any entries."
20720 (let ((re (concat
20721 (if pre-re pre-re "")
20722 (if inactive org-ts-regexp-both org-ts-regexp)))
20723 dates dates1 date day day1 day2 ts1 ts2)
20724 (if force-today
20725 (setq dates (list (time-to-days (current-time)))))
20726 (save-excursion
20727 (goto-char beg)
20728 (while (re-search-forward re end t)
20729 (setq day (time-to-days (org-time-string-to-time
20730 (substring (match-string 1) 0 10))))
20731 (or (memq day dates) (push day dates)))
20732 (unless no-ranges
20733 (goto-char beg)
20734 (while (re-search-forward org-tr-regexp end t)
20735 (setq ts1 (substring (match-string 1) 0 10)
20736 ts2 (substring (match-string 2) 0 10)
20737 day1 (time-to-days (org-time-string-to-time ts1))
20738 day2 (time-to-days (org-time-string-to-time ts2)))
20739 (while (< (setq day1 (1+ day1)) day2)
20740 (or (memq day1 dates) (push day1 dates)))))
20741 (setq dates (sort dates '<))
20742 (when empty
20743 (while (setq day (pop dates))
20744 (setq day2 (car dates))
20745 (push day dates1)
20746 (when (and day2 empty)
20747 (if (or (eq empty t)
20748 (and (numberp empty) (<= (- day2 day) empty)))
20749 (while (< (setq day (1+ day)) day2)
20750 (push (list day) dates1))
20751 (push (cons :omitted (- day2 day)) dates1))))
20752 (setq dates (nreverse dates1)))
20753 dates)))
20755 ;;; Agenda Daily/Weekly
20757 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20758 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20759 (defvar org-agenda-last-arguments nil
20760 "The arguments of the previous call to org-agenda")
20761 (defvar org-starting-day nil) ; local variable in the agenda buffer
20762 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20763 (defvar org-include-all-loc nil) ; local variable
20764 (defvar org-agenda-remove-date nil) ; dynamically scoped
20766 ;;;###autoload
20767 (defun org-agenda-list (&optional include-all start-day ndays)
20768 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20769 The view will be for the current day or week, but from the overview buffer
20770 you will be able to go to other days/weeks.
20772 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20773 all unfinished TODO items will also be shown, before the agenda.
20774 This feature is considered obsolete, please use the TODO list or a block
20775 agenda instead.
20777 With a numeric prefix argument in an interactive call, the agenda will
20778 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20779 the number of days. NDAYS defaults to `org-agenda-ndays'.
20781 START-DAY defaults to TODAY, or to the most recent match for the weekday
20782 given in `org-agenda-start-on-weekday'."
20783 (interactive "P")
20784 (if (and (integerp include-all) (> include-all 0))
20785 (setq ndays include-all include-all nil))
20786 (setq ndays (or ndays org-agenda-ndays)
20787 start-day (or start-day org-agenda-start-day))
20788 (if org-agenda-overriding-arguments
20789 (setq include-all (car org-agenda-overriding-arguments)
20790 start-day (nth 1 org-agenda-overriding-arguments)
20791 ndays (nth 2 org-agenda-overriding-arguments)))
20792 (if (stringp start-day)
20793 ;; Convert to an absolute day number
20794 (setq start-day (time-to-days (org-read-date nil t start-day))))
20795 (setq org-agenda-last-arguments (list include-all start-day ndays))
20796 (org-compile-prefix-format 'agenda)
20797 (org-set-sorting-strategy 'agenda)
20798 (require 'calendar)
20799 (let* ((org-agenda-start-on-weekday
20800 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20801 org-agenda-start-on-weekday nil))
20802 (thefiles (org-agenda-files))
20803 (files thefiles)
20804 (today (time-to-days
20805 (time-subtract (current-time)
20806 (list 0 (* 3600 org-extend-today-until) 0))))
20807 (sd (or start-day today))
20808 (start (if (or (null org-agenda-start-on-weekday)
20809 (< org-agenda-ndays 7))
20811 (let* ((nt (calendar-day-of-week
20812 (calendar-gregorian-from-absolute sd)))
20813 (n1 org-agenda-start-on-weekday)
20814 (d (- nt n1)))
20815 (- sd (+ (if (< d 0) 7 0) d)))))
20816 (day-numbers (list start))
20817 (day-cnt 0)
20818 (inhibit-redisplay (not debug-on-error))
20819 s e rtn rtnall file date d start-pos end-pos todayp nd)
20820 (setq org-agenda-redo-command
20821 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20822 ;; Make the list of days
20823 (setq ndays (or ndays org-agenda-ndays)
20824 nd ndays)
20825 (while (> ndays 1)
20826 (push (1+ (car day-numbers)) day-numbers)
20827 (setq ndays (1- ndays)))
20828 (setq day-numbers (nreverse day-numbers))
20829 (org-prepare-agenda "Day/Week")
20830 (org-set-local 'org-starting-day (car day-numbers))
20831 (org-set-local 'org-include-all-loc include-all)
20832 (org-set-local 'org-agenda-span
20833 (org-agenda-ndays-to-span nd))
20834 (when (and (or include-all org-agenda-include-all-todo)
20835 (member today day-numbers))
20836 (setq files thefiles
20837 rtnall nil)
20838 (while (setq file (pop files))
20839 (catch 'nextfile
20840 (org-check-agenda-file file)
20841 (setq date (calendar-gregorian-from-absolute today)
20842 rtn (org-agenda-get-day-entries
20843 file date :todo))
20844 (setq rtnall (append rtnall rtn))))
20845 (when rtnall
20846 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20847 (add-text-properties (point-min) (1- (point))
20848 (list 'face 'org-agenda-structure))
20849 (insert (org-finalize-agenda-entries rtnall) "\n")))
20850 (unless org-agenda-compact-blocks
20851 (setq s (point))
20852 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20853 "-agenda:\n")
20854 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20855 'org-date-line t)))
20856 (while (setq d (pop day-numbers))
20857 (setq date (calendar-gregorian-from-absolute d)
20858 s (point))
20859 (if (or (setq todayp (= d today))
20860 (and (not start-pos) (= d sd)))
20861 (setq start-pos (point))
20862 (if (and start-pos (not end-pos))
20863 (setq end-pos (point))))
20864 (setq files thefiles
20865 rtnall nil)
20866 (while (setq file (pop files))
20867 (catch 'nextfile
20868 (org-check-agenda-file file)
20869 (if org-agenda-show-log
20870 (setq rtn (org-agenda-get-day-entries
20871 file date
20872 :deadline :scheduled :timestamp :sexp :closed))
20873 (setq rtn (org-agenda-get-day-entries
20874 file date
20875 :deadline :scheduled :sexp :timestamp)))
20876 (setq rtnall (append rtnall rtn))))
20877 (if org-agenda-include-diary
20878 (progn
20879 (require 'diary-lib)
20880 (setq rtn (org-get-entries-from-diary date))
20881 (setq rtnall (append rtnall rtn))))
20882 (if (or rtnall org-agenda-show-all-dates)
20883 (progn
20884 (setq day-cnt (1+ day-cnt))
20885 (insert
20886 (if (stringp org-agenda-format-date)
20887 (format-time-string org-agenda-format-date
20888 (org-time-from-absolute date))
20889 (funcall org-agenda-format-date date))
20890 "\n")
20891 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20892 (put-text-property s (1- (point)) 'org-date-line t)
20893 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20894 (if todayp (put-text-property s (1- (point)) 'org-today t))
20895 (if rtnall (insert
20896 (org-finalize-agenda-entries
20897 (org-agenda-add-time-grid-maybe
20898 rtnall nd todayp))
20899 "\n"))
20900 (put-text-property s (1- (point)) 'day d)
20901 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20902 (goto-char (point-min))
20903 (org-fit-agenda-window)
20904 (unless (and (pos-visible-in-window-p (point-min))
20905 (pos-visible-in-window-p (point-max)))
20906 (goto-char (1- (point-max)))
20907 (recenter -1)
20908 (if (not (pos-visible-in-window-p (or start-pos 1)))
20909 (progn
20910 (goto-char (or start-pos 1))
20911 (recenter 1))))
20912 (goto-char (or start-pos 1))
20913 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20914 (org-finalize-agenda)
20915 (setq buffer-read-only t)
20916 (message "")))
20918 (defun org-agenda-ndays-to-span (n)
20919 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20921 ;;; Agenda word search
20923 (defvar org-agenda-search-history nil)
20925 ;;;###autoload
20926 (defun org-search-view (&optional arg string)
20927 "Show all entries that contain words or regular expressions.
20928 If the first character of the search string is an asterisks,
20929 search only the headlines.
20931 The search string is broken into \"words\" by splitting at whitespace.
20932 The individual words are then interpreted as a boolean expression with
20933 logical AND. Words prefixed with a minus must not occur in the entry.
20934 Words without a prefix or prefixed with a plus must occur in the entry.
20935 Matching is case-insensitive and the words are enclosed by word delimiters.
20937 Words enclosed by curly braces are interpreted as regular expressions
20938 that must or must not match in the entry.
20940 This command searches the agenda files, and in addition the files listed
20941 in `org-agenda-text-search-extra-files'."
20942 (interactive "P")
20943 (org-compile-prefix-format 'search)
20944 (org-set-sorting-strategy 'search)
20945 (org-prepare-agenda "SEARCH")
20946 (let* ((props (list 'face nil
20947 'done-face 'org-done
20948 'org-not-done-regexp org-not-done-regexp
20949 'org-todo-regexp org-todo-regexp
20950 'mouse-face 'highlight
20951 'keymap org-agenda-keymap
20952 'help-echo (format "mouse-2 or RET jump to location")))
20953 regexp rtn rtnall files file pos
20954 marker priority category tags c neg re
20955 ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
20956 (unless (and (not arg)
20957 (stringp string)
20958 (string-match "\\S-" string))
20959 (setq string (read-string "[+-]Word/{Regexp} ...: "
20960 (cond
20961 ((integerp arg) (cons string arg))
20962 (arg string))
20963 'org-agenda-search-history)))
20964 (setq org-agenda-redo-command
20965 (list 'org-search-view 'current-prefix-arg string))
20966 (setq org-agenda-query-string string)
20968 (if (equal (string-to-char string) ?*)
20969 (setq hdl-only t
20970 words (substring string 1))
20971 (setq words string))
20972 (setq words (org-split-string words))
20973 (mapc (lambda (w)
20974 (setq c (string-to-char w))
20975 (if (equal c ?-)
20976 (setq neg t w (substring w 1))
20977 (if (equal c ?+)
20978 (setq neg nil w (substring w 1))
20979 (setq neg nil)))
20980 (if (string-match "\\`{.*}\\'" w)
20981 (setq re (substring w 1 -1))
20982 (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>")))
20983 (if neg (push re regexps-) (push re regexps+)))
20984 words)
20985 (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b)))))
20986 (if (not regexps+)
20987 (setq regexp (concat "^" org-outline-regexp))
20988 (setq regexp (pop regexps+))
20989 (if hdl-only (setq regexp (concat "^" org-outline-regexp ".*?"
20990 regexp))))
20991 (setq files (append (org-agenda-files) org-agenda-text-search-extra-files)
20992 rtnall nil)
20993 (while (setq file (pop files))
20994 (setq ee nil)
20995 (catch 'nextfile
20996 (org-check-agenda-file file)
20997 (setq buffer (if (file-exists-p file)
20998 (org-get-agenda-file-buffer file)
20999 (error "No such file %s" file)))
21000 (if (not buffer)
21001 ;; If file does not exist, make sure an error message is sent
21002 (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s"
21003 file))))
21004 (with-current-buffer buffer
21005 (unless (org-mode-p)
21006 (error "Agenda file %s is not in `org-mode'" file))
21007 (let ((case-fold-search t))
21008 (save-excursion
21009 (save-restriction
21010 (if org-agenda-restrict
21011 (narrow-to-region org-agenda-restrict-begin
21012 org-agenda-restrict-end)
21013 (widen))
21014 (goto-char (point-min))
21015 (unless (or (org-on-heading-p)
21016 (outline-next-heading))
21017 (throw 'nextfile t))
21018 (goto-char (max (point-min) (1- (point))))
21019 (while (re-search-forward regexp nil t)
21020 (org-back-to-heading t)
21021 (skip-chars-forward "* ")
21022 (setq beg (point-at-bol)
21023 beg1 (point)
21024 end (progn (outline-next-heading) (point)))
21025 (catch :skip
21026 (goto-char beg)
21027 (org-agenda-skip)
21028 (setq str (buffer-substring-no-properties
21029 (point-at-bol)
21030 (if hdl-only (point-at-eol) end)))
21031 (mapc (lambda (wr) (when (string-match wr str)
21032 (goto-char (1- end))
21033 (throw :skip t)))
21034 regexps-)
21035 (mapc (lambda (wr) (unless (string-match wr str)
21036 (goto-char (1- end))
21037 (throw :skip t)))
21038 regexps+)
21039 (goto-char beg)
21040 (setq marker (org-agenda-new-marker (point))
21041 category (org-get-category)
21042 tags (org-get-tags-at (point))
21043 txt (org-format-agenda-item
21045 (buffer-substring-no-properties
21046 beg1 (point-at-eol))
21047 category tags))
21048 (org-add-props txt props
21049 'org-marker marker 'org-hd-marker marker
21050 'priority 1000 'org-category category
21051 'type "search")
21052 (push txt ee)
21053 (goto-char (1- end)))))))))
21054 (setq rtn (nreverse ee))
21055 (setq rtnall (append rtnall rtn)))
21056 (if org-agenda-overriding-header
21057 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21058 nil 'face 'org-agenda-structure) "\n")
21059 (insert "Search words: ")
21060 (add-text-properties (point-min) (1- (point))
21061 (list 'face 'org-agenda-structure))
21062 (setq pos (point))
21063 (insert string "\n")
21064 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21065 (setq pos (point))
21066 (unless org-agenda-multi
21067 (insert "Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit\n")
21068 (add-text-properties pos (1- (point))
21069 (list 'face 'org-agenda-structure))))
21070 (when rtnall
21071 (insert (org-finalize-agenda-entries rtnall) "\n"))
21072 (goto-char (point-min))
21073 (org-fit-agenda-window)
21074 (add-text-properties (point-min) (point-max) '(org-agenda-type search))
21075 (org-finalize-agenda)
21076 (setq buffer-read-only t)))
21078 ;;; Agenda TODO list
21080 (defvar org-select-this-todo-keyword nil)
21081 (defvar org-last-arg nil)
21083 ;;;###autoload
21084 (defun org-todo-list (arg)
21085 "Show all TODO entries from all agenda file in a single list.
21086 The prefix arg can be used to select a specific TODO keyword and limit
21087 the list to these. When using \\[universal-argument], you will be prompted
21088 for a keyword. A numeric prefix directly selects the Nth keyword in
21089 `org-todo-keywords-1'."
21090 (interactive "P")
21091 (require 'calendar)
21092 (org-compile-prefix-format 'todo)
21093 (org-set-sorting-strategy 'todo)
21094 (org-prepare-agenda "TODO")
21095 (let* ((today (time-to-days (current-time)))
21096 (date (calendar-gregorian-from-absolute today))
21097 (kwds org-todo-keywords-for-agenda)
21098 (completion-ignore-case t)
21099 (org-select-this-todo-keyword
21100 (if (stringp arg) arg
21101 (and arg (integerp arg) (> arg 0)
21102 (nth (1- arg) kwds))))
21103 rtn rtnall files file pos)
21104 (when (equal arg '(4))
21105 (setq org-select-this-todo-keyword
21106 (completing-read "Keyword (or KWD1|K2D2|...): "
21107 (mapcar 'list kwds) nil nil)))
21108 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
21109 (org-set-local 'org-last-arg arg)
21110 (setq org-agenda-redo-command
21111 '(org-todo-list (or current-prefix-arg org-last-arg)))
21112 (setq files (org-agenda-files)
21113 rtnall nil)
21114 (while (setq file (pop files))
21115 (catch 'nextfile
21116 (org-check-agenda-file file)
21117 (setq rtn (org-agenda-get-day-entries file date :todo))
21118 (setq rtnall (append rtnall rtn))))
21119 (if org-agenda-overriding-header
21120 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21121 nil 'face 'org-agenda-structure) "\n")
21122 (insert "Global list of TODO items of type: ")
21123 (add-text-properties (point-min) (1- (point))
21124 (list 'face 'org-agenda-structure))
21125 (setq pos (point))
21126 (insert (or org-select-this-todo-keyword "ALL") "\n")
21127 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21128 (setq pos (point))
21129 (unless org-agenda-multi
21130 (insert "Available with `N r': (0)ALL")
21131 (let ((n 0) s)
21132 (mapc (lambda (x)
21133 (setq s (format "(%d)%s" (setq n (1+ n)) x))
21134 (if (> (+ (current-column) (string-width s) 1) (frame-width))
21135 (insert "\n "))
21136 (insert " " s))
21137 kwds))
21138 (insert "\n"))
21139 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21140 (when rtnall
21141 (insert (org-finalize-agenda-entries rtnall) "\n"))
21142 (goto-char (point-min))
21143 (org-fit-agenda-window)
21144 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
21145 (org-finalize-agenda)
21146 (setq buffer-read-only t)))
21148 ;;; Agenda tags match
21150 ;;;###autoload
21151 (defun org-tags-view (&optional todo-only match)
21152 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
21153 The prefix arg TODO-ONLY limits the search to TODO entries."
21154 (interactive "P")
21155 (org-compile-prefix-format 'tags)
21156 (org-set-sorting-strategy 'tags)
21157 (let* ((org-tags-match-list-sublevels
21158 (if todo-only t org-tags-match-list-sublevels))
21159 (completion-ignore-case t)
21160 rtn rtnall files file pos matcher
21161 buffer)
21162 (setq matcher (org-make-tags-matcher match)
21163 match (car matcher) matcher (cdr matcher))
21164 (org-prepare-agenda (concat "TAGS " match))
21165 (setq org-agenda-redo-command
21166 (list 'org-tags-view (list 'quote todo-only)
21167 (list 'if 'current-prefix-arg nil match)))
21168 (setq files (org-agenda-files)
21169 rtnall nil)
21170 (while (setq file (pop files))
21171 (catch 'nextfile
21172 (org-check-agenda-file file)
21173 (setq buffer (if (file-exists-p file)
21174 (org-get-agenda-file-buffer file)
21175 (error "No such file %s" file)))
21176 (if (not buffer)
21177 ;; If file does not exist, merror message to agenda
21178 (setq rtn (list
21179 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21180 rtnall (append rtnall rtn))
21181 (with-current-buffer buffer
21182 (unless (org-mode-p)
21183 (error "Agenda file %s is not in `org-mode'" file))
21184 (save-excursion
21185 (save-restriction
21186 (if org-agenda-restrict
21187 (narrow-to-region org-agenda-restrict-begin
21188 org-agenda-restrict-end)
21189 (widen))
21190 (setq rtn (org-scan-tags 'agenda matcher todo-only))
21191 (setq rtnall (append rtnall rtn))))))))
21192 (if org-agenda-overriding-header
21193 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21194 nil 'face 'org-agenda-structure) "\n")
21195 (insert "Headlines with TAGS match: ")
21196 (add-text-properties (point-min) (1- (point))
21197 (list 'face 'org-agenda-structure))
21198 (setq pos (point))
21199 (insert match "\n")
21200 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21201 (setq pos (point))
21202 (unless org-agenda-multi
21203 (insert "Press `C-u r' to search again with new search string\n"))
21204 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21205 (when rtnall
21206 (insert (org-finalize-agenda-entries rtnall) "\n"))
21207 (goto-char (point-min))
21208 (org-fit-agenda-window)
21209 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
21210 (org-finalize-agenda)
21211 (setq buffer-read-only t)))
21213 ;;; Agenda Finding stuck projects
21215 (defvar org-agenda-skip-regexp nil
21216 "Regular expression used in skipping subtrees for the agenda.
21217 This is basically a temporary global variable that can be set and then
21218 used by user-defined selections using `org-agenda-skip-function'.")
21220 (defvar org-agenda-overriding-header nil
21221 "When this is set during todo and tags searches, will replace header.")
21223 (defun org-agenda-skip-subtree-when-regexp-matches ()
21224 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
21225 If yes, it returns the end position of this tree, causing agenda commands
21226 to skip this subtree. This is a function that can be put into
21227 `org-agenda-skip-function' for the duration of a command."
21228 (let ((end (save-excursion (org-end-of-subtree t)))
21229 skip)
21230 (save-excursion
21231 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
21232 (and skip end)))
21234 (defun org-agenda-skip-entry-if (&rest conditions)
21235 "Skip entry if any of CONDITIONS is true.
21236 See `org-agenda-skip-if' for details."
21237 (org-agenda-skip-if nil conditions))
21239 (defun org-agenda-skip-subtree-if (&rest conditions)
21240 "Skip entry if any of CONDITIONS is true.
21241 See `org-agenda-skip-if' for details."
21242 (org-agenda-skip-if t conditions))
21244 (defun org-agenda-skip-if (subtree conditions)
21245 "Checks current entity for CONDITIONS.
21246 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21247 the entry, i.e. the text before the next heading is checked.
21249 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21250 from different tests. Valid conditions are:
21252 scheduled Check if there is a scheduled cookie
21253 notscheduled Check if there is no scheduled cookie
21254 deadline Check if there is a deadline
21255 notdeadline Check if there is no deadline
21256 regexp Check if regexp matches
21257 notregexp Check if regexp does not match.
21259 The regexp is taken from the conditions list, it must come right after
21260 the `regexp' or `notregexp' element.
21262 If any of these conditions is met, this function returns the end point of
21263 the entity, causing the search to continue from there. This is a function
21264 that can be put into `org-agenda-skip-function' for the duration of a command."
21265 (let (beg end m)
21266 (org-back-to-heading t)
21267 (setq beg (point)
21268 end (if subtree
21269 (progn (org-end-of-subtree t) (point))
21270 (progn (outline-next-heading) (1- (point)))))
21271 (goto-char beg)
21272 (and
21274 (and (memq 'scheduled conditions)
21275 (re-search-forward org-scheduled-time-regexp end t))
21276 (and (memq 'notscheduled conditions)
21277 (not (re-search-forward org-scheduled-time-regexp end t)))
21278 (and (memq 'deadline conditions)
21279 (re-search-forward org-deadline-time-regexp end t))
21280 (and (memq 'notdeadline conditions)
21281 (not (re-search-forward org-deadline-time-regexp end t)))
21282 (and (setq m (memq 'regexp conditions))
21283 (stringp (nth 1 m))
21284 (re-search-forward (nth 1 m) end t))
21285 (and (setq m (memq 'notregexp conditions))
21286 (stringp (nth 1 m))
21287 (not (re-search-forward (nth 1 m) end t))))
21288 end)))
21290 ;;;###autoload
21291 (defun org-agenda-list-stuck-projects (&rest ignore)
21292 "Create agenda view for projects that are stuck.
21293 Stuck projects are project that have no next actions. For the definitions
21294 of what a project is and how to check if it stuck, customize the variable
21295 `org-stuck-projects'.
21296 MATCH is being ignored."
21297 (interactive)
21298 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21299 ;; FIXME: we could have used org-agenda-skip-if here.
21300 (org-agenda-overriding-header "List of stuck projects: ")
21301 (matcher (nth 0 org-stuck-projects))
21302 (todo (nth 1 org-stuck-projects))
21303 (todo-wds (if (member "*" todo)
21304 (progn
21305 (org-prepare-agenda-buffers (org-agenda-files))
21306 (org-delete-all
21307 org-done-keywords-for-agenda
21308 (copy-sequence org-todo-keywords-for-agenda)))
21309 todo))
21310 (todo-re (concat "^\\*+[ \t]+\\("
21311 (mapconcat 'identity todo-wds "\\|")
21312 "\\)\\>"))
21313 (tags (nth 2 org-stuck-projects))
21314 (tags-re (if (member "*" tags)
21315 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21316 (concat "^\\*+ .*:\\("
21317 (mapconcat 'identity tags "\\|")
21318 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21319 (gen-re (nth 3 org-stuck-projects))
21320 (re-list
21321 (delq nil
21322 (list
21323 (if todo todo-re)
21324 (if tags tags-re)
21325 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21326 gen-re)))))
21327 (setq org-agenda-skip-regexp
21328 (if re-list
21329 (mapconcat 'identity re-list "\\|")
21330 (error "No information how to identify unstuck projects")))
21331 (org-tags-view nil matcher)
21332 (with-current-buffer org-agenda-buffer-name
21333 (setq org-agenda-redo-command
21334 '(org-agenda-list-stuck-projects
21335 (or current-prefix-arg org-last-arg))))))
21337 ;;; Diary integration
21339 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21341 (defun org-get-entries-from-diary (date)
21342 "Get the (Emacs Calendar) diary entries for DATE."
21343 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21344 (diary-display-hook '(fancy-diary-display))
21345 (pop-up-frames nil)
21346 (list-diary-entries-hook
21347 (cons 'org-diary-default-entry list-diary-entries-hook))
21348 (diary-file-name-prefix-function nil) ; turn this feature off
21349 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21350 entries
21351 (org-disable-agenda-to-diary t))
21352 (save-excursion
21353 (save-window-excursion
21354 (funcall (if (fboundp 'diary-list-entries)
21355 'diary-list-entries 'list-diary-entries)
21356 date 1)))
21357 (if (not (get-buffer fancy-diary-buffer))
21358 (setq entries nil)
21359 (with-current-buffer fancy-diary-buffer
21360 (setq buffer-read-only nil)
21361 (if (zerop (buffer-size))
21362 ;; No entries
21363 (setq entries nil)
21364 ;; Omit the date and other unnecessary stuff
21365 (org-agenda-cleanup-fancy-diary)
21366 ;; Add prefix to each line and extend the text properties
21367 (if (zerop (buffer-size))
21368 (setq entries nil)
21369 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21370 (set-buffer-modified-p nil)
21371 (kill-buffer fancy-diary-buffer)))
21372 (when entries
21373 (setq entries (org-split-string entries "\n"))
21374 (setq entries
21375 (mapcar
21376 (lambda (x)
21377 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21378 ;; Extend the text properties to the beginning of the line
21379 (org-add-props x (text-properties-at (1- (length x)) x)
21380 'type "diary" 'date date))
21381 entries)))))
21383 (defun org-agenda-cleanup-fancy-diary ()
21384 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21385 This gets rid of the date, the underline under the date, and
21386 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21387 date. It also removes lines that contain only whitespace."
21388 (goto-char (point-min))
21389 (if (looking-at ".*?:[ \t]*")
21390 (progn
21391 (replace-match "")
21392 (re-search-forward "\n=+$" nil t)
21393 (replace-match "")
21394 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21395 (re-search-forward "\n=+$" nil t)
21396 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21397 (goto-char (point-min))
21398 (while (re-search-forward "^ +\n" nil t)
21399 (replace-match ""))
21400 (goto-char (point-min))
21401 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21402 (replace-match "")))
21404 ;; Make sure entries from the diary have the right text properties.
21405 (eval-after-load "diary-lib"
21406 '(if (boundp 'diary-modify-entry-list-string-function)
21407 ;; We can rely on the hook, nothing to do
21409 ;; Hook not avaiable, must use advice to make this work
21410 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21411 "Make the position visible."
21412 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21413 (stringp string)
21414 buffer-file-name)
21415 (setq string (org-modify-diary-entry-string string))))))
21417 (defun org-modify-diary-entry-string (string)
21418 "Add text properties to string, allowing org-mode to act on it."
21419 (org-add-props string nil
21420 'mouse-face 'highlight
21421 'keymap org-agenda-keymap
21422 'help-echo (if buffer-file-name
21423 (format "mouse-2 or RET jump to diary file %s"
21424 (abbreviate-file-name buffer-file-name))
21426 'org-agenda-diary-link t
21427 'org-marker (org-agenda-new-marker (point-at-bol))))
21429 (defun org-diary-default-entry ()
21430 "Add a dummy entry to the diary.
21431 Needed to avoid empty dates which mess up holiday display."
21432 ;; Catch the error if dealing with the new add-to-diary-alist
21433 (when org-disable-agenda-to-diary
21434 (condition-case nil
21435 (add-to-diary-list original-date "Org-mode dummy" "")
21436 (error
21437 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21439 ;;;###autoload
21440 (defun org-diary (&rest args)
21441 "Return diary information from org-files.
21442 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21443 It accesses org files and extracts information from those files to be
21444 listed in the diary. The function accepts arguments specifying what
21445 items should be listed. The following arguments are allowed:
21447 :timestamp List the headlines of items containing a date stamp or
21448 date range matching the selected date. Deadlines will
21449 also be listed, on the expiration day.
21451 :sexp List entries resulting from diary-like sexps.
21453 :deadline List any deadlines past due, or due within
21454 `org-deadline-warning-days'. The listing occurs only
21455 in the diary for *today*, not at any other date. If
21456 an entry is marked DONE, it is no longer listed.
21458 :scheduled List all items which are scheduled for the given date.
21459 The diary for *today* also contains items which were
21460 scheduled earlier and are not yet marked DONE.
21462 :todo List all TODO items from the org-file. This may be a
21463 long list - so this is not turned on by default.
21464 Like deadlines, these entries only show up in the
21465 diary for *today*, not at any other date.
21467 The call in the diary file should look like this:
21469 &%%(org-diary) ~/path/to/some/orgfile.org
21471 Use a separate line for each org file to check. Or, if you omit the file name,
21472 all files listed in `org-agenda-files' will be checked automatically:
21474 &%%(org-diary)
21476 If you don't give any arguments (as in the example above), the default
21477 arguments (:deadline :scheduled :timestamp :sexp) are used.
21478 So the example above may also be written as
21480 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21482 The function expects the lisp variables `entry' and `date' to be provided
21483 by the caller, because this is how the calendar works. Don't use this
21484 function from a program - use `org-agenda-get-day-entries' instead."
21485 (when (> (- (time-to-seconds (current-time))
21486 org-agenda-last-marker-time)
21488 (org-agenda-reset-markers))
21489 (org-compile-prefix-format 'agenda)
21490 (org-set-sorting-strategy 'agenda)
21491 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21492 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21493 (list entry)
21494 (org-agenda-files t)))
21495 file rtn results)
21496 (org-prepare-agenda-buffers files)
21497 ;; If this is called during org-agenda, don't return any entries to
21498 ;; the calendar. Org Agenda will list these entries itself.
21499 (if org-disable-agenda-to-diary (setq files nil))
21500 (while (setq file (pop files))
21501 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21502 (setq results (append results rtn)))
21503 (if results
21504 (concat (org-finalize-agenda-entries results) "\n"))))
21506 ;;; Agenda entry finders
21508 (defun org-agenda-get-day-entries (file date &rest args)
21509 "Does the work for `org-diary' and `org-agenda'.
21510 FILE is the path to a file to be checked for entries. DATE is date like
21511 the one returned by `calendar-current-date'. ARGS are symbols indicating
21512 which kind of entries should be extracted. For details about these, see
21513 the documentation of `org-diary'."
21514 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21515 (let* ((org-startup-folded nil)
21516 (org-startup-align-all-tables nil)
21517 (buffer (if (file-exists-p file)
21518 (org-get-agenda-file-buffer file)
21519 (error "No such file %s" file)))
21520 arg results rtn)
21521 (if (not buffer)
21522 ;; If file does not exist, make sure an error message ends up in diary
21523 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21524 (with-current-buffer buffer
21525 (unless (org-mode-p)
21526 (error "Agenda file %s is not in `org-mode'" file))
21527 (let ((case-fold-search nil))
21528 (save-excursion
21529 (save-restriction
21530 (if org-agenda-restrict
21531 (narrow-to-region org-agenda-restrict-begin
21532 org-agenda-restrict-end)
21533 (widen))
21534 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21535 (while (setq arg (pop args))
21536 (cond
21537 ((and (eq arg :todo)
21538 (equal date (calendar-current-date)))
21539 (setq rtn (org-agenda-get-todos))
21540 (setq results (append results rtn)))
21541 ((eq arg :timestamp)
21542 (setq rtn (org-agenda-get-blocks))
21543 (setq results (append results rtn))
21544 (setq rtn (org-agenda-get-timestamps))
21545 (setq results (append results rtn)))
21546 ((eq arg :sexp)
21547 (setq rtn (org-agenda-get-sexps))
21548 (setq results (append results rtn)))
21549 ((eq arg :scheduled)
21550 (setq rtn (org-agenda-get-scheduled))
21551 (setq results (append results rtn)))
21552 ((eq arg :closed)
21553 (setq rtn (org-agenda-get-closed))
21554 (setq results (append results rtn)))
21555 ((eq arg :deadline)
21556 (setq rtn (org-agenda-get-deadlines))
21557 (setq results (append results rtn))))))))
21558 results))))
21560 (defun org-entry-is-todo-p ()
21561 (member (org-get-todo-state) org-not-done-keywords))
21563 (defun org-entry-is-done-p ()
21564 (member (org-get-todo-state) org-done-keywords))
21566 (defun org-get-todo-state ()
21567 (save-excursion
21568 (org-back-to-heading t)
21569 (and (looking-at org-todo-line-regexp)
21570 (match-end 2)
21571 (match-string 2))))
21573 (defun org-at-date-range-p (&optional inactive-ok)
21574 "Is the cursor inside a date range?"
21575 (interactive)
21576 (save-excursion
21577 (catch 'exit
21578 (let ((pos (point)))
21579 (skip-chars-backward "^[<\r\n")
21580 (skip-chars-backward "<[")
21581 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21582 (>= (match-end 0) pos)
21583 (throw 'exit t))
21584 (skip-chars-backward "^<[\r\n")
21585 (skip-chars-backward "<[")
21586 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21587 (>= (match-end 0) pos)
21588 (throw 'exit t)))
21589 nil)))
21591 (defun org-agenda-get-todos ()
21592 "Return the TODO information for agenda display."
21593 (let* ((props (list 'face nil
21594 'done-face 'org-done
21595 'org-not-done-regexp org-not-done-regexp
21596 'org-todo-regexp org-todo-regexp
21597 'mouse-face 'highlight
21598 'keymap org-agenda-keymap
21599 'help-echo
21600 (format "mouse-2 or RET jump to org file %s"
21601 (abbreviate-file-name buffer-file-name))))
21602 ;; FIXME: get rid of the \n at some point but watch out
21603 (regexp (concat "^\\*+[ \t]+\\("
21604 (if org-select-this-todo-keyword
21605 (if (equal org-select-this-todo-keyword "*")
21606 org-todo-regexp
21607 (concat "\\<\\("
21608 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21609 "\\)\\>"))
21610 org-not-done-regexp)
21611 "[^\n\r]*\\)"))
21612 marker priority category tags
21613 ee txt beg end)
21614 (goto-char (point-min))
21615 (while (re-search-forward regexp nil t)
21616 (catch :skip
21617 (save-match-data
21618 (beginning-of-line)
21619 (setq beg (point) end (progn (outline-next-heading) (point)))
21620 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21621 (re-search-forward org-ts-regexp end t))
21622 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21623 (re-search-forward org-scheduled-time-regexp end t))
21624 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21625 (re-search-forward org-deadline-time-regexp end t)
21626 (org-deadline-close (match-string 1))))
21627 (goto-char (1+ beg))
21628 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21629 (throw :skip nil)))
21630 (goto-char beg)
21631 (org-agenda-skip)
21632 (goto-char (match-beginning 1))
21633 (setq marker (org-agenda-new-marker (match-beginning 0))
21634 category (org-get-category)
21635 tags (org-get-tags-at (point))
21636 txt (org-format-agenda-item "" (match-string 1) category tags)
21637 priority (1+ (org-get-priority txt)))
21638 (org-add-props txt props
21639 'org-marker marker 'org-hd-marker marker
21640 'priority priority 'org-category category
21641 'type "todo")
21642 (push txt ee)
21643 (if org-agenda-todo-list-sublevels
21644 (goto-char (match-end 1))
21645 (org-end-of-subtree 'invisible))))
21646 (nreverse ee)))
21648 (defconst org-agenda-no-heading-message
21649 "No heading for this item in buffer or region.")
21651 (defun org-agenda-get-timestamps ()
21652 "Return the date stamp information for agenda display."
21653 (let* ((props (list 'face nil
21654 'org-not-done-regexp org-not-done-regexp
21655 'org-todo-regexp org-todo-regexp
21656 'mouse-face 'highlight
21657 'keymap org-agenda-keymap
21658 'help-echo
21659 (format "mouse-2 or RET jump to org file %s"
21660 (abbreviate-file-name buffer-file-name))))
21661 (d1 (calendar-absolute-from-gregorian date))
21662 (remove-re
21663 (concat
21664 (regexp-quote
21665 (format-time-string
21666 "<%Y-%m-%d"
21667 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21668 ".*?>"))
21669 (regexp
21670 (concat
21671 (regexp-quote
21672 (substring
21673 (format-time-string
21674 (car org-time-stamp-formats)
21675 (apply 'encode-time ; DATE bound by calendar
21676 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21677 0 11))
21678 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21679 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21680 marker hdmarker deadlinep scheduledp donep tmp priority category
21681 ee txt timestr tags b0 b3 e3 head)
21682 (goto-char (point-min))
21683 (while (re-search-forward regexp nil t)
21684 (setq b0 (match-beginning 0)
21685 b3 (match-beginning 3) e3 (match-end 3))
21686 (catch :skip
21687 (and (org-at-date-range-p) (throw :skip nil))
21688 (org-agenda-skip)
21689 (if (and (match-end 1)
21690 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21691 (throw :skip nil))
21692 (if (and e3
21693 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21694 (throw :skip nil))
21695 (setq marker (org-agenda-new-marker b0)
21696 category (org-get-category b0)
21697 tmp (buffer-substring (max (point-min)
21698 (- b0 org-ds-keyword-length))
21700 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21701 deadlinep (string-match org-deadline-regexp tmp)
21702 scheduledp (string-match org-scheduled-regexp tmp)
21703 donep (org-entry-is-done-p))
21704 (if (or scheduledp deadlinep) (throw :skip t))
21705 (if (string-match ">" timestr)
21706 ;; substring should only run to end of time stamp
21707 (setq timestr (substring timestr 0 (match-end 0))))
21708 (save-excursion
21709 (if (re-search-backward "^\\*+ " nil t)
21710 (progn
21711 (goto-char (match-beginning 0))
21712 (setq hdmarker (org-agenda-new-marker)
21713 tags (org-get-tags-at))
21714 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21715 (setq head (match-string 1))
21716 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21717 (setq txt (org-format-agenda-item
21718 nil head category tags timestr nil
21719 remove-re)))
21720 (setq txt org-agenda-no-heading-message))
21721 (setq priority (org-get-priority txt))
21722 (org-add-props txt props
21723 'org-marker marker 'org-hd-marker hdmarker)
21724 (org-add-props txt nil 'priority priority
21725 'org-category category 'date date
21726 'type "timestamp")
21727 (push txt ee))
21728 (outline-next-heading)))
21729 (nreverse ee)))
21731 (defun org-agenda-get-sexps ()
21732 "Return the sexp information for agenda display."
21733 (require 'diary-lib)
21734 (let* ((props (list 'face nil
21735 'mouse-face 'highlight
21736 'keymap org-agenda-keymap
21737 'help-echo
21738 (format "mouse-2 or RET jump to org file %s"
21739 (abbreviate-file-name buffer-file-name))))
21740 (regexp "^&?%%(")
21741 marker category ee txt tags entry result beg b sexp sexp-entry)
21742 (goto-char (point-min))
21743 (while (re-search-forward regexp nil t)
21744 (catch :skip
21745 (org-agenda-skip)
21746 (setq beg (match-beginning 0))
21747 (goto-char (1- (match-end 0)))
21748 (setq b (point))
21749 (forward-sexp 1)
21750 (setq sexp (buffer-substring b (point)))
21751 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21752 (org-trim (match-string 1))
21753 ""))
21754 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21755 (when result
21756 (setq marker (org-agenda-new-marker beg)
21757 category (org-get-category beg))
21759 (if (string-match "\\S-" result)
21760 (setq txt result)
21761 (setq txt "SEXP entry returned empty string"))
21763 (setq txt (org-format-agenda-item
21764 "" txt category tags 'time))
21765 (org-add-props txt props 'org-marker marker)
21766 (org-add-props txt nil
21767 'org-category category 'date date
21768 'type "sexp")
21769 (push txt ee))))
21770 (nreverse ee)))
21772 (defun org-agenda-get-closed ()
21773 "Return the logged TODO entries for agenda display."
21774 (let* ((props (list 'mouse-face 'highlight
21775 'org-not-done-regexp org-not-done-regexp
21776 'org-todo-regexp org-todo-regexp
21777 'keymap org-agenda-keymap
21778 'help-echo
21779 (format "mouse-2 or RET jump to org file %s"
21780 (abbreviate-file-name buffer-file-name))))
21781 (regexp (concat
21782 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21783 (regexp-quote
21784 (substring
21785 (format-time-string
21786 (car org-time-stamp-formats)
21787 (apply 'encode-time ; DATE bound by calendar
21788 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21789 1 11))))
21790 marker hdmarker priority category tags closedp
21791 ee txt timestr)
21792 (goto-char (point-min))
21793 (while (re-search-forward regexp nil t)
21794 (catch :skip
21795 (org-agenda-skip)
21796 (setq marker (org-agenda-new-marker (match-beginning 0))
21797 closedp (equal (match-string 1) org-closed-string)
21798 category (org-get-category (match-beginning 0))
21799 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21800 ;; donep (org-entry-is-done-p)
21802 (if (string-match "\\]" timestr)
21803 ;; substring should only run to end of time stamp
21804 (setq timestr (substring timestr 0 (match-end 0))))
21805 (save-excursion
21806 (if (re-search-backward "^\\*+ " nil t)
21807 (progn
21808 (goto-char (match-beginning 0))
21809 (setq hdmarker (org-agenda-new-marker)
21810 tags (org-get-tags-at))
21811 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21812 (setq txt (org-format-agenda-item
21813 (if closedp "Closed: " "Clocked: ")
21814 (match-string 1) category tags timestr)))
21815 (setq txt org-agenda-no-heading-message))
21816 (setq priority 100000)
21817 (org-add-props txt props
21818 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21819 'priority priority 'org-category category
21820 'type "closed" 'date date
21821 'undone-face 'org-warning 'done-face 'org-done)
21822 (push txt ee))
21823 (goto-char (point-at-eol))))
21824 (nreverse ee)))
21826 (defun org-agenda-get-deadlines ()
21827 "Return the deadline information for agenda display."
21828 (let* ((props (list 'mouse-face 'highlight
21829 'org-not-done-regexp org-not-done-regexp
21830 'org-todo-regexp org-todo-regexp
21831 'keymap org-agenda-keymap
21832 'help-echo
21833 (format "mouse-2 or RET jump to org file %s"
21834 (abbreviate-file-name buffer-file-name))))
21835 (regexp org-deadline-time-regexp)
21836 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21837 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21838 d2 diff dfrac wdays pos pos1 category tags
21839 ee txt head face s upcomingp donep timestr)
21840 (goto-char (point-min))
21841 (while (re-search-forward regexp nil t)
21842 (catch :skip
21843 (org-agenda-skip)
21844 (setq s (match-string 1)
21845 pos (1- (match-beginning 1))
21846 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21847 diff (- d2 d1)
21848 wdays (org-get-wdays s)
21849 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21850 upcomingp (and todayp (> diff 0)))
21851 ;; When to show a deadline in the calendar:
21852 ;; If the expiration is within wdays warning time.
21853 ;; Past-due deadlines are only shown on the current date
21854 (if (or (and (<= diff wdays)
21855 (and todayp (not org-agenda-only-exact-dates)))
21856 (= diff 0))
21857 (save-excursion
21858 (setq category (org-get-category))
21859 (if (re-search-backward "^\\*+[ \t]+" nil t)
21860 (progn
21861 (goto-char (match-end 0))
21862 (setq pos1 (match-beginning 0))
21863 (setq tags (org-get-tags-at pos1))
21864 (setq head (buffer-substring-no-properties
21865 (point)
21866 (progn (skip-chars-forward "^\r\n")
21867 (point))))
21868 (setq donep (string-match org-looking-at-done-regexp head))
21869 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21870 (setq timestr
21871 (concat (substring s (match-beginning 1)) " "))
21872 (setq timestr 'time))
21873 (if (and donep
21874 (or org-agenda-skip-deadline-if-done
21875 (not (= diff 0))))
21876 (setq txt nil)
21877 (setq txt (org-format-agenda-item
21878 (if (= diff 0)
21879 (car org-agenda-deadline-leaders)
21880 (format (nth 1 org-agenda-deadline-leaders)
21881 diff))
21882 head category tags timestr))))
21883 (setq txt org-agenda-no-heading-message))
21884 (when txt
21885 (setq face (org-agenda-deadline-face dfrac wdays))
21886 (org-add-props txt props
21887 'org-marker (org-agenda-new-marker pos)
21888 'org-hd-marker (org-agenda-new-marker pos1)
21889 'priority (+ (- diff)
21890 (org-get-priority txt))
21891 'org-category category
21892 'type (if upcomingp "upcoming-deadline" "deadline")
21893 'date (if upcomingp date d2)
21894 'face (if donep 'org-done face)
21895 'undone-face face 'done-face 'org-done)
21896 (push txt ee))))))
21897 (nreverse ee)))
21899 (defun org-agenda-deadline-face (fraction &optional wdays)
21900 "Return the face to displaying a deadline item.
21901 FRACTION is what fraction of the head-warning time has passed."
21902 (if (equal wdays 0) (setq fraction 1.))
21903 (let ((faces org-agenda-deadline-faces) f)
21904 (catch 'exit
21905 (while (setq f (pop faces))
21906 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21908 (defun org-agenda-get-scheduled ()
21909 "Return the scheduled information for agenda display."
21910 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21911 'org-todo-regexp org-todo-regexp
21912 'done-face 'org-done
21913 'mouse-face 'highlight
21914 'keymap org-agenda-keymap
21915 'help-echo
21916 (format "mouse-2 or RET jump to org file %s"
21917 (abbreviate-file-name buffer-file-name))))
21918 (regexp org-scheduled-time-regexp)
21919 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21920 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21921 d2 diff pos pos1 category tags
21922 ee txt head pastschedp donep face timestr s)
21923 (goto-char (point-min))
21924 (while (re-search-forward regexp nil t)
21925 (catch :skip
21926 (org-agenda-skip)
21927 (setq s (match-string 1)
21928 pos (1- (match-beginning 1))
21929 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21930 ;;; is this right?
21931 ;;; do we need to do this for deadleine too????
21932 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21933 diff (- d2 d1))
21934 (setq pastschedp (and todayp (< diff 0)))
21935 ;; When to show a scheduled item in the calendar:
21936 ;; If it is on or past the date.
21937 (if (or (and (< diff 0)
21938 (and todayp (not org-agenda-only-exact-dates)))
21939 (= diff 0))
21940 (save-excursion
21941 (setq category (org-get-category))
21942 (if (re-search-backward "^\\*+[ \t]+" nil t)
21943 (progn
21944 (goto-char (match-end 0))
21945 (setq pos1 (match-beginning 0))
21946 (setq tags (org-get-tags-at))
21947 (setq head (buffer-substring-no-properties
21948 (point)
21949 (progn (skip-chars-forward "^\r\n") (point))))
21950 (setq donep (string-match org-looking-at-done-regexp head))
21951 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21952 (setq timestr
21953 (concat (substring s (match-beginning 1)) " "))
21954 (setq timestr 'time))
21955 (if (and donep
21956 (or org-agenda-skip-scheduled-if-done
21957 (not (= diff 0))))
21958 (setq txt nil)
21959 (setq txt (org-format-agenda-item
21960 (if (= diff 0)
21961 (car org-agenda-scheduled-leaders)
21962 (format (nth 1 org-agenda-scheduled-leaders)
21963 (- 1 diff)))
21964 head category tags timestr))))
21965 (setq txt org-agenda-no-heading-message))
21966 (when txt
21967 (setq face (if pastschedp
21968 'org-scheduled-previously
21969 'org-scheduled-today))
21970 (org-add-props txt props
21971 'undone-face face
21972 'face (if donep 'org-done face)
21973 'org-marker (org-agenda-new-marker pos)
21974 'org-hd-marker (org-agenda-new-marker pos1)
21975 'type (if pastschedp "past-scheduled" "scheduled")
21976 'date (if pastschedp d2 date)
21977 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21978 'org-category category)
21979 (push txt ee))))))
21980 (nreverse ee)))
21982 (defun org-agenda-get-blocks ()
21983 "Return the date-range information for agenda display."
21984 (let* ((props (list 'face nil
21985 'org-not-done-regexp org-not-done-regexp
21986 'org-todo-regexp org-todo-regexp
21987 'mouse-face 'highlight
21988 'keymap org-agenda-keymap
21989 'help-echo
21990 (format "mouse-2 or RET jump to org file %s"
21991 (abbreviate-file-name buffer-file-name))))
21992 (regexp org-tr-regexp)
21993 (d0 (calendar-absolute-from-gregorian date))
21994 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21995 donep head)
21996 (goto-char (point-min))
21997 (while (re-search-forward regexp nil t)
21998 (catch :skip
21999 (org-agenda-skip)
22000 (setq pos (point))
22001 (setq timestr (match-string 0)
22002 s1 (match-string 1)
22003 s2 (match-string 2)
22004 d1 (time-to-days (org-time-string-to-time s1))
22005 d2 (time-to-days (org-time-string-to-time s2)))
22006 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
22007 ;; Only allow days between the limits, because the normal
22008 ;; date stamps will catch the limits.
22009 (save-excursion
22010 (setq marker (org-agenda-new-marker (point)))
22011 (setq category (org-get-category))
22012 (if (re-search-backward "^\\*+ " nil t)
22013 (progn
22014 (goto-char (match-beginning 0))
22015 (setq hdmarker (org-agenda-new-marker (point)))
22016 (setq tags (org-get-tags-at))
22017 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
22018 (setq head (match-string 1))
22019 (and org-agenda-skip-timestamp-if-done
22020 (org-entry-is-done-p)
22021 (throw :skip t))
22022 (setq txt (org-format-agenda-item
22023 (format (if (= d1 d2) "" "(%d/%d): ")
22024 (1+ (- d0 d1)) (1+ (- d2 d1)))
22025 head category tags
22026 (if (= d0 d1) timestr))))
22027 (setq txt org-agenda-no-heading-message))
22028 (org-add-props txt props
22029 'org-marker marker 'org-hd-marker hdmarker
22030 'type "block" 'date date
22031 'priority (org-get-priority txt) 'org-category category)
22032 (push txt ee)))
22033 (goto-char pos)))
22034 ;; Sort the entries by expiration date.
22035 (nreverse ee)))
22037 ;;; Agenda presentation and sorting
22039 (defconst org-plain-time-of-day-regexp
22040 (concat
22041 "\\(\\<[012]?[0-9]"
22042 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22043 "\\(--?"
22044 "\\(\\<[012]?[0-9]"
22045 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22046 "\\)?")
22047 "Regular expression to match a plain time or time range.
22048 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22049 groups carry important information:
22050 0 the full match
22051 1 the first time, range or not
22052 8 the second time, if it is a range.")
22054 (defconst org-plain-time-extension-regexp
22055 (concat
22056 "\\(\\<[012]?[0-9]"
22057 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22058 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
22059 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
22060 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22061 groups carry important information:
22062 0 the full match
22063 7 hours of duration
22064 9 minutes of duration")
22066 (defconst org-stamp-time-of-day-regexp
22067 (concat
22068 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
22069 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
22070 "\\(--?"
22071 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
22072 "Regular expression to match a timestamp time or time range.
22073 After a match, the following groups carry important information:
22074 0 the full match
22075 1 date plus weekday, for backreferencing to make sure both times on same day
22076 2 the first time, range or not
22077 4 the second time, if it is a range.")
22079 (defvar org-prefix-has-time nil
22080 "A flag, set by `org-compile-prefix-format'.
22081 The flag is set if the currently compiled format contains a `%t'.")
22082 (defvar org-prefix-has-tag nil
22083 "A flag, set by `org-compile-prefix-format'.
22084 The flag is set if the currently compiled format contains a `%T'.")
22086 (defun org-format-agenda-item (extra txt &optional category tags dotime
22087 noprefix remove-re)
22088 "Format TXT to be inserted into the agenda buffer.
22089 In particular, it adds the prefix and corresponding text properties. EXTRA
22090 must be a string and replaces the `%s' specifier in the prefix format.
22091 CATEGORY (string, symbol or nil) may be used to overrule the default
22092 category taken from local variable or file name. It will replace the `%c'
22093 specifier in the format. DOTIME, when non-nil, indicates that a
22094 time-of-day should be extracted from TXT for sorting of this entry, and for
22095 the `%t' specifier in the format. When DOTIME is a string, this string is
22096 searched for a time before TXT is. NOPREFIX is a flag and indicates that
22097 only the correctly processes TXT should be returned - this is used by
22098 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
22099 Any match of REMOVE-RE will be removed from TXT."
22100 (save-match-data
22101 ;; Diary entries sometimes have extra whitespace at the beginning
22102 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
22103 (let* ((category (or category
22104 org-category
22105 (if buffer-file-name
22106 (file-name-sans-extension
22107 (file-name-nondirectory buffer-file-name))
22108 "")))
22109 (tag (if tags (nth (1- (length tags)) tags) ""))
22110 time ; time and tag are needed for the eval of the prefix format
22111 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
22112 (time-of-day (and dotime (org-get-time-of-day ts)))
22113 stamp plain s0 s1 s2 rtn srp)
22114 (when (and dotime time-of-day org-prefix-has-time)
22115 ;; Extract starting and ending time and move them to prefix
22116 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
22117 (setq plain (string-match org-plain-time-of-day-regexp ts)))
22118 (setq s0 (match-string 0 ts)
22119 srp (and stamp (match-end 3))
22120 s1 (match-string (if plain 1 2) ts)
22121 s2 (match-string (if plain 8 (if srp 4 6)) ts))
22123 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
22124 ;; them, we might want to remove them there to avoid duplication.
22125 ;; The user can turn this off with a variable.
22126 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
22127 (string-match (concat (regexp-quote s0) " *") txt)
22128 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
22129 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
22130 (= (match-beginning 0) 0)
22132 (setq txt (replace-match "" nil nil txt))))
22133 ;; Normalize the time(s) to 24 hour
22134 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
22135 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
22137 (when (and s1 (not s2) org-agenda-default-appointment-duration
22138 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
22139 (let ((m (+ (string-to-number (match-string 2 s1))
22140 (* 60 (string-to-number (match-string 1 s1)))
22141 org-agenda-default-appointment-duration))
22143 (setq h (/ m 60) m (- m (* h 60)))
22144 (setq s2 (format "%02d:%02d" h m))))
22146 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22147 txt)
22148 ;; Tags are in the string
22149 (if (or (eq org-agenda-remove-tags t)
22150 (and org-agenda-remove-tags
22151 org-prefix-has-tag))
22152 (setq txt (replace-match "" t t txt))
22153 (setq txt (replace-match
22154 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
22155 (match-string 2 txt))
22156 t t txt))))
22158 (when remove-re
22159 (while (string-match remove-re txt)
22160 (setq txt (replace-match "" t t txt))))
22162 ;; Create the final string
22163 (if noprefix
22164 (setq rtn txt)
22165 ;; Prepare the variables needed in the eval of the compiled format
22166 (setq time (cond (s2 (concat s1 "-" s2))
22167 (s1 (concat s1 "......"))
22168 (t ""))
22169 extra (or extra "")
22170 category (if (symbolp category) (symbol-name category) category))
22171 ;; Evaluate the compiled format
22172 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
22174 ;; And finally add the text properties
22175 (org-add-props rtn nil
22176 'org-category (downcase category) 'tags tags
22177 'org-highest-priority org-highest-priority
22178 'org-lowest-priority org-lowest-priority
22179 'prefix-length (- (length rtn) (length txt))
22180 'time-of-day time-of-day
22181 'txt txt
22182 'time time
22183 'extra extra
22184 'dotime dotime))))
22186 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
22187 (defvar org-agenda-sorting-strategy-selected nil)
22189 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
22190 (catch 'exit
22191 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
22192 ((and todayp (member 'today (car org-agenda-time-grid))))
22193 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
22194 ((member 'weekly (car org-agenda-time-grid)))
22195 (t (throw 'exit list)))
22196 (let* ((have (delq nil (mapcar
22197 (lambda (x) (get-text-property 1 'time-of-day x))
22198 list)))
22199 (string (nth 1 org-agenda-time-grid))
22200 (gridtimes (nth 2 org-agenda-time-grid))
22201 (req (car org-agenda-time-grid))
22202 (remove (member 'remove-match req))
22203 new time)
22204 (if (and (member 'require-timed req) (not have))
22205 ;; don't show empty grid
22206 (throw 'exit list))
22207 (while (setq time (pop gridtimes))
22208 (unless (and remove (member time have))
22209 (setq time (int-to-string time))
22210 (push (org-format-agenda-item
22211 nil string "" nil
22212 (concat (substring time 0 -2) ":" (substring time -2)))
22213 new)
22214 (put-text-property
22215 1 (length (car new)) 'face 'org-time-grid (car new))))
22216 (if (member 'time-up org-agenda-sorting-strategy-selected)
22217 (append new list)
22218 (append list new)))))
22220 (defun org-compile-prefix-format (key)
22221 "Compile the prefix format into a Lisp form that can be evaluated.
22222 The resulting form is returned and stored in the variable
22223 `org-prefix-format-compiled'."
22224 (setq org-prefix-has-time nil org-prefix-has-tag nil)
22225 (let ((s (cond
22226 ((stringp org-agenda-prefix-format)
22227 org-agenda-prefix-format)
22228 ((assq key org-agenda-prefix-format)
22229 (cdr (assq key org-agenda-prefix-format)))
22230 (t " %-12:c%?-12t% s")))
22231 (start 0)
22232 varform vars var e c f opt)
22233 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
22234 s start)
22235 (setq var (cdr (assoc (match-string 4 s)
22236 '(("c" . category) ("t" . time) ("s" . extra)
22237 ("T" . tag))))
22238 c (or (match-string 3 s) "")
22239 opt (match-beginning 1)
22240 start (1+ (match-beginning 0)))
22241 (if (equal var 'time) (setq org-prefix-has-time t))
22242 (if (equal var 'tag) (setq org-prefix-has-tag t))
22243 (setq f (concat "%" (match-string 2 s) "s"))
22244 (if opt
22245 (setq varform
22246 `(if (equal "" ,var)
22248 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22249 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22250 (setq s (replace-match "%s" t nil s))
22251 (push varform vars))
22252 (setq vars (nreverse vars))
22253 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22255 (defun org-set-sorting-strategy (key)
22256 (if (symbolp (car org-agenda-sorting-strategy))
22257 ;; the old format
22258 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22259 (setq org-agenda-sorting-strategy-selected
22260 (or (cdr (assq key org-agenda-sorting-strategy))
22261 (cdr (assq 'agenda org-agenda-sorting-strategy))
22262 '(time-up category-keep priority-down)))))
22264 (defun org-get-time-of-day (s &optional string mod24)
22265 "Check string S for a time of day.
22266 If found, return it as a military time number between 0 and 2400.
22267 If not found, return nil.
22268 The optional STRING argument forces conversion into a 5 character wide string
22269 HH:MM."
22270 (save-match-data
22271 (when
22272 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22273 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22274 (let* ((h (string-to-number (match-string 1 s)))
22275 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22276 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22277 (am-p (equal ampm "am"))
22278 (h1 (cond ((not ampm) h)
22279 ((= h 12) (if am-p 0 12))
22280 (t (+ h (if am-p 0 12)))))
22281 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22282 (mod h1 24) h1))
22283 (t0 (+ (* 100 h2) m))
22284 (t1 (concat (if (>= h1 24) "+" " ")
22285 (if (< t0 100) "0" "")
22286 (if (< t0 10) "0" "")
22287 (int-to-string t0))))
22288 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22290 (defun org-finalize-agenda-entries (list &optional nosort)
22291 "Sort and concatenate the agenda items."
22292 (setq list (mapcar 'org-agenda-highlight-todo list))
22293 (if nosort
22294 list
22295 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22297 (defun org-agenda-highlight-todo (x)
22298 (let (re pl)
22299 (if (eq x 'line)
22300 (save-excursion
22301 (beginning-of-line 1)
22302 (setq re (get-text-property (point) 'org-todo-regexp))
22303 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22304 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22305 (add-text-properties (match-beginning 0) (match-end 0)
22306 (list 'face (org-get-todo-face 0)))
22307 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22308 (delete-region (match-beginning 1) (1- (match-end 0)))
22309 (goto-char (match-beginning 1))
22310 (insert (format org-agenda-todo-keyword-format s)))))
22311 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22312 pl (get-text-property 0 'prefix-length x))
22313 (when (and re
22314 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22315 x (or pl 0)) pl))
22316 (add-text-properties
22317 (or (match-end 1) (match-end 0)) (match-end 0)
22318 (list 'face (org-get-todo-face (match-string 2 x)))
22320 (setq x (concat (substring x 0 (match-end 1))
22321 (format org-agenda-todo-keyword-format
22322 (match-string 2 x))
22324 (substring x (match-end 3)))))
22325 x)))
22327 (defsubst org-cmp-priority (a b)
22328 "Compare the priorities of string A and B."
22329 (let ((pa (or (get-text-property 1 'priority a) 0))
22330 (pb (or (get-text-property 1 'priority b) 0)))
22331 (cond ((> pa pb) +1)
22332 ((< pa pb) -1)
22333 (t nil))))
22335 (defsubst org-cmp-category (a b)
22336 "Compare the string values of categories of strings A and B."
22337 (let ((ca (or (get-text-property 1 'org-category a) ""))
22338 (cb (or (get-text-property 1 'org-category b) "")))
22339 (cond ((string-lessp ca cb) -1)
22340 ((string-lessp cb ca) +1)
22341 (t nil))))
22343 (defsubst org-cmp-tag (a b)
22344 "Compare the string values of categories of strings A and B."
22345 (let ((ta (car (last (get-text-property 1 'tags a))))
22346 (tb (car (last (get-text-property 1 'tags b)))))
22347 (cond ((not ta) +1)
22348 ((not tb) -1)
22349 ((string-lessp ta tb) -1)
22350 ((string-lessp tb ta) +1)
22351 (t nil))))
22353 (defsubst org-cmp-time (a b)
22354 "Compare the time-of-day values of strings A and B."
22355 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22356 (ta (or (get-text-property 1 'time-of-day a) def))
22357 (tb (or (get-text-property 1 'time-of-day b) def)))
22358 (cond ((< ta tb) -1)
22359 ((< tb ta) +1)
22360 (t nil))))
22362 (defun org-entries-lessp (a b)
22363 "Predicate for sorting agenda entries."
22364 ;; The following variables will be used when the form is evaluated.
22365 ;; So even though the compiler complains, keep them.
22366 (let* ((time-up (org-cmp-time a b))
22367 (time-down (if time-up (- time-up) nil))
22368 (priority-up (org-cmp-priority a b))
22369 (priority-down (if priority-up (- priority-up) nil))
22370 (category-up (org-cmp-category a b))
22371 (category-down (if category-up (- category-up) nil))
22372 (category-keep (if category-up +1 nil))
22373 (tag-up (org-cmp-tag a b))
22374 (tag-down (if tag-up (- tag-up) nil)))
22375 (cdr (assoc
22376 (eval (cons 'or org-agenda-sorting-strategy-selected))
22377 '((-1 . t) (1 . nil) (nil . nil))))))
22379 ;;; Agenda restriction lock
22381 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22382 "Overlay to mark the headline to which arenda commands are restricted.")
22383 (org-overlay-put org-agenda-restriction-lock-overlay
22384 'face 'org-agenda-restriction-lock)
22385 (org-overlay-put org-agenda-restriction-lock-overlay
22386 'help-echo "Agendas are currently limited to this subtree.")
22387 (org-detach-overlay org-agenda-restriction-lock-overlay)
22388 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22389 "Overlay marking the agenda restriction line in speedbar.")
22390 (org-overlay-put org-speedbar-restriction-lock-overlay
22391 'face 'org-agenda-restriction-lock)
22392 (org-overlay-put org-speedbar-restriction-lock-overlay
22393 'help-echo "Agendas are currently limited to this item.")
22394 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22396 (defun org-agenda-set-restriction-lock (&optional type)
22397 "Set restriction lock for agenda, to current subtree or file.
22398 Restriction will be the file if TYPE is `file', or if type is the
22399 universal prefix '(4), or if the cursor is before the first headline
22400 in the file. Otherwise, restriction will be to the current subtree."
22401 (interactive "P")
22402 (and (equal type '(4)) (setq type 'file))
22403 (setq type (cond
22404 (type type)
22405 ((org-at-heading-p) 'subtree)
22406 ((condition-case nil (org-back-to-heading t) (error nil))
22407 'subtree)
22408 (t 'file)))
22409 (if (eq type 'subtree)
22410 (progn
22411 (setq org-agenda-restrict t)
22412 (setq org-agenda-overriding-restriction 'subtree)
22413 (put 'org-agenda-files 'org-restrict
22414 (list (buffer-file-name (buffer-base-buffer))))
22415 (org-back-to-heading t)
22416 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22417 (move-marker org-agenda-restrict-begin (point))
22418 (move-marker org-agenda-restrict-end
22419 (save-excursion (org-end-of-subtree t)))
22420 (message "Locking agenda restriction to subtree"))
22421 (put 'org-agenda-files 'org-restrict
22422 (list (buffer-file-name (buffer-base-buffer))))
22423 (setq org-agenda-restrict nil)
22424 (setq org-agenda-overriding-restriction 'file)
22425 (move-marker org-agenda-restrict-begin nil)
22426 (move-marker org-agenda-restrict-end nil)
22427 (message "Locking agenda restriction to file"))
22428 (setq current-prefix-arg nil)
22429 (org-agenda-maybe-redo))
22431 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22432 "Remove the agenda restriction lock."
22433 (interactive "P")
22434 (org-detach-overlay org-agenda-restriction-lock-overlay)
22435 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22436 (setq org-agenda-overriding-restriction nil)
22437 (setq org-agenda-restrict nil)
22438 (put 'org-agenda-files 'org-restrict nil)
22439 (move-marker org-agenda-restrict-begin nil)
22440 (move-marker org-agenda-restrict-end nil)
22441 (setq current-prefix-arg nil)
22442 (message "Agenda restriction lock removed")
22443 (or noupdate (org-agenda-maybe-redo)))
22445 (defun org-agenda-maybe-redo ()
22446 "If there is any window showing the agenda view, update it."
22447 (let ((w (get-buffer-window org-agenda-buffer-name t))
22448 (w0 (selected-window)))
22449 (when w
22450 (select-window w)
22451 (org-agenda-redo)
22452 (select-window w0)
22453 (if org-agenda-overriding-restriction
22454 (message "Agenda view shifted to new %s restriction"
22455 org-agenda-overriding-restriction)
22456 (message "Agenda restriction lock removed")))))
22458 ;;; Agenda commands
22460 (defun org-agenda-check-type (error &rest types)
22461 "Check if agenda buffer is of allowed type.
22462 If ERROR is non-nil, throw an error, otherwise just return nil."
22463 (if (memq org-agenda-type types)
22465 (if error
22466 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22467 nil)))
22469 (defun org-agenda-quit ()
22470 "Exit agenda by removing the window or the buffer."
22471 (interactive)
22472 (let ((buf (current-buffer)))
22473 (if (not (one-window-p)) (delete-window))
22474 (kill-buffer buf)
22475 (org-agenda-reset-markers)
22476 (org-columns-remove-overlays))
22477 ;; Maybe restore the pre-agenda window configuration.
22478 (and org-agenda-restore-windows-after-quit
22479 (not (eq org-agenda-window-setup 'other-frame))
22480 org-pre-agenda-window-conf
22481 (set-window-configuration org-pre-agenda-window-conf)))
22483 (defun org-agenda-exit ()
22484 "Exit agenda by removing the window or the buffer.
22485 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22486 Org-mode buffers visited directly by the user will not be touched."
22487 (interactive)
22488 (org-release-buffers org-agenda-new-buffers)
22489 (setq org-agenda-new-buffers nil)
22490 (org-agenda-quit))
22492 (defun org-agenda-execute (arg)
22493 "Execute another agenda command, keeping same window.\\<global-map>
22494 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22495 (interactive "P")
22496 (let ((org-agenda-window-setup 'current-window))
22497 (org-agenda arg)))
22499 (defun org-save-all-org-buffers ()
22500 "Save all Org-mode buffers without user confirmation."
22501 (interactive)
22502 (message "Saving all Org-mode buffers...")
22503 (save-some-buffers t 'org-mode-p)
22504 (message "Saving all Org-mode buffers... done"))
22506 (defun org-agenda-redo ()
22507 "Rebuild Agenda.
22508 When this is the global TODO list, a prefix argument will be interpreted."
22509 (interactive)
22510 (let* ((org-agenda-keep-modes t)
22511 (line (org-current-line))
22512 (window-line (- line (org-current-line (window-start))))
22513 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22514 (message "Rebuilding agenda buffer...")
22515 (org-let lprops '(eval org-agenda-redo-command))
22516 (setq org-agenda-undo-list nil
22517 org-agenda-pending-undo-list nil)
22518 (message "Rebuilding agenda buffer...done")
22519 (goto-line line)
22520 (recenter window-line)))
22522 (defun org-agenda-manipulate-query-add ()
22523 "Manipulate the query by adding a search term with positive selection.
22524 Positive selection means, the term must be matched for selection of an entry."
22525 (interactive)
22526 (org-agenda-manipulate-query ?\[))
22527 (defun org-agenda-manipulate-query-subtract ()
22528 "Manipulate the query by adding a search term with negative selection.
22529 Negative selection means, term must not be matched for selection of an entry."
22530 (interactive)
22531 (org-agenda-manipulate-query ?\]))
22532 (defun org-agenda-manipulate-query-add-re ()
22533 "Manipulate the query by adding a search regexp with positive selection.
22534 Positive selection means, the regexp must match for selection of an entry."
22535 (interactive)
22536 (org-agenda-manipulate-query ?\{))
22537 (defun org-agenda-manipulate-query-subtract-re ()
22538 "Manipulate the query by adding a search regexp with negative selection.
22539 Negative selection means, regexp must not match for selection of an entry."
22540 (interactive)
22541 (org-agenda-manipulate-query ?\}))
22542 (defun org-agenda-manipulate-query (char)
22543 (cond
22544 ((eq org-agenda-type 'search)
22545 (org-add-to-string
22546 'org-agenda-query-string
22547 (cdr (assoc char '((?\[ . " +") (?\] . " -")
22548 (?\{ . " +{}") (?\} . " -{}")))))
22549 (setq org-agenda-redo-command
22550 (list 'org-search-view
22551 (+ (length org-agenda-query-string)
22552 (if (member char '(?\{ ?\})) 0 1))
22553 org-agenda-query-string))
22554 (set-register org-agenda-query-register org-agenda-query-string)
22555 (org-agenda-redo))
22556 (t (error "Canot manipulate query for %s-type agenda buffers"
22557 org-agenda-type))))
22559 (defun org-add-to-string (var string)
22560 (set var (concat (symbol-value var) string)))
22562 (defun org-agenda-goto-date (date)
22563 "Jump to DATE in agenda."
22564 (interactive (list (org-read-date)))
22565 (org-agenda-list nil date))
22567 (defun org-agenda-goto-today ()
22568 "Go to today."
22569 (interactive)
22570 (org-agenda-check-type t 'timeline 'agenda)
22571 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22572 (cond
22573 (tdpos (goto-char tdpos))
22574 ((eq org-agenda-type 'agenda)
22575 (let* ((sd (time-to-days
22576 (time-subtract (current-time)
22577 (list 0 (* 3600 org-extend-today-until) 0))))
22578 (comp (org-agenda-compute-time-span sd org-agenda-span))
22579 (org-agenda-overriding-arguments org-agenda-last-arguments))
22580 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22581 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22582 (org-agenda-redo)
22583 (org-agenda-find-same-or-today-or-agenda)))
22584 (t (error "Cannot find today")))))
22586 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22587 (goto-char
22588 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22589 (text-property-any (point-min) (point-max) 'org-today t)
22590 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22591 (point-min))))
22593 (defun org-agenda-later (arg)
22594 "Go forward in time by thee current span.
22595 With prefix ARG, go forward that many times the current span."
22596 (interactive "p")
22597 (org-agenda-check-type t 'agenda)
22598 (let* ((span org-agenda-span)
22599 (sd org-starting-day)
22600 (greg (calendar-gregorian-from-absolute sd))
22601 (cnt (get-text-property (point) 'org-day-cnt))
22602 greg2 nd)
22603 (cond
22604 ((eq span 'day)
22605 (setq sd (+ arg sd) nd 1))
22606 ((eq span 'week)
22607 (setq sd (+ (* 7 arg) sd) nd 7))
22608 ((eq span 'month)
22609 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22610 sd (calendar-absolute-from-gregorian greg2))
22611 (setcar greg2 (1+ (car greg2)))
22612 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22613 ((eq span 'year)
22614 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22615 sd (calendar-absolute-from-gregorian greg2))
22616 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22617 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22618 (let ((org-agenda-overriding-arguments
22619 (list (car org-agenda-last-arguments) sd nd t)))
22620 (org-agenda-redo)
22621 (org-agenda-find-same-or-today-or-agenda cnt))))
22623 (defun org-agenda-earlier (arg)
22624 "Go backward in time by the current span.
22625 With prefix ARG, go backward that many times the current span."
22626 (interactive "p")
22627 (org-agenda-later (- arg)))
22629 (defun org-agenda-day-view ()
22630 "Switch to daily view for agenda."
22631 (interactive)
22632 (setq org-agenda-ndays 1)
22633 (org-agenda-change-time-span 'day))
22634 (defun org-agenda-week-view ()
22635 "Switch to daily view for agenda."
22636 (interactive)
22637 (setq org-agenda-ndays 7)
22638 (org-agenda-change-time-span 'week))
22639 (defun org-agenda-month-view ()
22640 "Switch to daily view for agenda."
22641 (interactive)
22642 (org-agenda-change-time-span 'month))
22643 (defun org-agenda-year-view ()
22644 "Switch to daily view for agenda."
22645 (interactive)
22646 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22647 (org-agenda-change-time-span 'year)
22648 (error "Abort")))
22650 (defun org-agenda-change-time-span (span)
22651 "Change the agenda view to SPAN.
22652 SPAN may be `day', `week', `month', `year'."
22653 (org-agenda-check-type t 'agenda)
22654 (if (equal org-agenda-span span)
22655 (error "Viewing span is already \"%s\"" span))
22656 (let* ((sd (or (get-text-property (point) 'day)
22657 org-starting-day))
22658 (computed (org-agenda-compute-time-span sd span))
22659 (org-agenda-overriding-arguments
22660 (list (car org-agenda-last-arguments)
22661 (car computed) (cdr computed) t)))
22662 (org-agenda-redo)
22663 (org-agenda-find-same-or-today-or-agenda))
22664 (org-agenda-set-mode-name)
22665 (message "Switched to %s view" span))
22667 (defun org-agenda-compute-time-span (sd span)
22668 "Compute starting date and number of days for agenda.
22669 SPAN may be `day', `week', `month', `year'. The return value
22670 is a cons cell with the starting date and the number of days,
22671 so that the date SD will be in that range."
22672 (let* ((greg (calendar-gregorian-from-absolute sd))
22674 (cond
22675 ((eq span 'day)
22676 (setq nd 1))
22677 ((eq span 'week)
22678 (let* ((nt (calendar-day-of-week
22679 (calendar-gregorian-from-absolute sd)))
22680 (d (if org-agenda-start-on-weekday
22681 (- nt org-agenda-start-on-weekday)
22682 0)))
22683 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22684 (setq nd 7)))
22685 ((eq span 'month)
22686 (setq sd (calendar-absolute-from-gregorian
22687 (list (car greg) 1 (nth 2 greg)))
22688 nd (- (calendar-absolute-from-gregorian
22689 (list (1+ (car greg)) 1 (nth 2 greg)))
22690 sd)))
22691 ((eq span 'year)
22692 (setq sd (calendar-absolute-from-gregorian
22693 (list 1 1 (nth 2 greg)))
22694 nd (- (calendar-absolute-from-gregorian
22695 (list 1 1 (1+ (nth 2 greg))))
22696 sd))))
22697 (cons sd nd)))
22699 ;; FIXME: does not work if user makes date format that starts with a blank
22700 (defun org-agenda-next-date-line (&optional arg)
22701 "Jump to the next line indicating a date in agenda buffer."
22702 (interactive "p")
22703 (org-agenda-check-type t 'agenda 'timeline)
22704 (beginning-of-line 1)
22705 (if (looking-at "^\\S-") (forward-char 1))
22706 (if (not (re-search-forward "^\\S-" nil t arg))
22707 (progn
22708 (backward-char 1)
22709 (error "No next date after this line in this buffer")))
22710 (goto-char (match-beginning 0)))
22712 (defun org-agenda-previous-date-line (&optional arg)
22713 "Jump to the previous line indicating a date in agenda buffer."
22714 (interactive "p")
22715 (org-agenda-check-type t 'agenda 'timeline)
22716 (beginning-of-line 1)
22717 (if (not (re-search-backward "^\\S-" nil t arg))
22718 (error "No previous date before this line in this buffer")))
22720 ;; Initialize the highlight
22721 (defvar org-hl (org-make-overlay 1 1))
22722 (org-overlay-put org-hl 'face 'highlight)
22724 (defun org-highlight (begin end &optional buffer)
22725 "Highlight a region with overlay."
22726 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22727 org-hl begin end (or buffer (current-buffer))))
22729 (defun org-unhighlight ()
22730 "Detach overlay INDEX."
22731 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22733 ;; FIXME this is currently not used.
22734 (defun org-highlight-until-next-command (beg end &optional buffer)
22735 (org-highlight beg end buffer)
22736 (add-hook 'pre-command-hook 'org-unhighlight-once))
22737 (defun org-unhighlight-once ()
22738 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22739 (org-unhighlight))
22741 (defun org-agenda-follow-mode ()
22742 "Toggle follow mode in an agenda buffer."
22743 (interactive)
22744 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22745 (org-agenda-set-mode-name)
22746 (message "Follow mode is %s"
22747 (if org-agenda-follow-mode "on" "off")))
22749 (defun org-agenda-log-mode ()
22750 "Toggle log mode in an agenda buffer."
22751 (interactive)
22752 (org-agenda-check-type t 'agenda 'timeline)
22753 (setq org-agenda-show-log (not org-agenda-show-log))
22754 (org-agenda-set-mode-name)
22755 (org-agenda-redo)
22756 (message "Log mode is %s"
22757 (if org-agenda-show-log "on" "off")))
22759 (defun org-agenda-toggle-diary ()
22760 "Toggle diary inclusion in an agenda buffer."
22761 (interactive)
22762 (org-agenda-check-type t 'agenda)
22763 (setq org-agenda-include-diary (not org-agenda-include-diary))
22764 (org-agenda-redo)
22765 (org-agenda-set-mode-name)
22766 (message "Diary inclusion turned %s"
22767 (if org-agenda-include-diary "on" "off")))
22769 (defun org-agenda-toggle-time-grid ()
22770 "Toggle time grid in an agenda buffer."
22771 (interactive)
22772 (org-agenda-check-type t 'agenda)
22773 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22774 (org-agenda-redo)
22775 (org-agenda-set-mode-name)
22776 (message "Time-grid turned %s"
22777 (if org-agenda-use-time-grid "on" "off")))
22779 (defun org-agenda-set-mode-name ()
22780 "Set the mode name to indicate all the small mode settings."
22781 (setq mode-name
22782 (concat "Org-Agenda"
22783 (if (equal org-agenda-ndays 1) " Day" "")
22784 (if (equal org-agenda-ndays 7) " Week" "")
22785 (if org-agenda-follow-mode " Follow" "")
22786 (if org-agenda-include-diary " Diary" "")
22787 (if org-agenda-use-time-grid " Grid" "")
22788 (if org-agenda-show-log " Log" "")))
22789 (force-mode-line-update))
22791 (defun org-agenda-post-command-hook ()
22792 (and (eolp) (not (bolp)) (backward-char 1))
22793 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22794 (if (and org-agenda-follow-mode
22795 (get-text-property (point) 'org-marker))
22796 (org-agenda-show)))
22798 (defun org-agenda-show-priority ()
22799 "Show the priority of the current item.
22800 This priority is composed of the main priority given with the [#A] cookies,
22801 and by additional input from the age of a schedules or deadline entry."
22802 (interactive)
22803 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22804 (message "Priority is %d" (if pri pri -1000))))
22806 (defun org-agenda-show-tags ()
22807 "Show the tags applicable to the current item."
22808 (interactive)
22809 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22810 (if tags
22811 (message "Tags are :%s:"
22812 (org-no-properties (mapconcat 'identity tags ":")))
22813 (message "No tags associated with this line"))))
22815 (defun org-agenda-goto (&optional highlight)
22816 "Go to the Org-mode file which contains the item at point."
22817 (interactive)
22818 (let* ((marker (or (get-text-property (point) 'org-marker)
22819 (org-agenda-error)))
22820 (buffer (marker-buffer marker))
22821 (pos (marker-position marker)))
22822 (switch-to-buffer-other-window buffer)
22823 (widen)
22824 (goto-char pos)
22825 (when (org-mode-p)
22826 (org-show-context 'agenda)
22827 (save-excursion
22828 (and (outline-next-heading)
22829 (org-flag-heading nil)))) ; show the next heading
22830 (recenter (/ (window-height) 2))
22831 (run-hooks 'org-agenda-after-show-hook)
22832 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22834 (defvar org-agenda-after-show-hook nil
22835 "Normal hook run after an item has been shown from the agenda.
22836 Point is in the buffer where the item originated.")
22838 (defun org-agenda-kill ()
22839 "Kill the entry or subtree belonging to the current agenda entry."
22840 (interactive)
22841 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22842 (let* ((marker (or (get-text-property (point) 'org-marker)
22843 (org-agenda-error)))
22844 (buffer (marker-buffer marker))
22845 (pos (marker-position marker))
22846 (type (get-text-property (point) 'type))
22847 dbeg dend (n 0) conf)
22848 (org-with-remote-undo buffer
22849 (with-current-buffer buffer
22850 (save-excursion
22851 (goto-char pos)
22852 (if (and (org-mode-p) (not (member type '("sexp"))))
22853 (setq dbeg (progn (org-back-to-heading t) (point))
22854 dend (org-end-of-subtree t t))
22855 (setq dbeg (point-at-bol)
22856 dend (min (point-max) (1+ (point-at-eol)))))
22857 (goto-char dbeg)
22858 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22859 (setq conf (or (eq t org-agenda-confirm-kill)
22860 (and (numberp org-agenda-confirm-kill)
22861 (> n org-agenda-confirm-kill))))
22862 (and conf
22863 (not (y-or-n-p
22864 (format "Delete entry with %d lines in buffer \"%s\"? "
22865 n (buffer-name buffer))))
22866 (error "Abort"))
22867 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22868 (with-current-buffer buffer (delete-region dbeg dend))
22869 (message "Agenda item and source killed"))))
22871 (defun org-agenda-archive ()
22872 "Kill the entry or subtree belonging to the current agenda entry."
22873 (interactive)
22874 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22875 (let* ((marker (or (get-text-property (point) 'org-marker)
22876 (org-agenda-error)))
22877 (buffer (marker-buffer marker))
22878 (pos (marker-position marker)))
22879 (org-with-remote-undo buffer
22880 (with-current-buffer buffer
22881 (if (org-mode-p)
22882 (save-excursion
22883 (goto-char pos)
22884 (org-remove-subtree-entries-from-agenda)
22885 (org-back-to-heading t)
22886 (org-archive-subtree))
22887 (error "Archiving works only in Org-mode files"))))))
22889 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22890 "Remove all lines in the agenda that correspond to a given subtree.
22891 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22892 If this information is not given, the function uses the tree at point."
22893 (let ((buf (or buf (current-buffer))) m p)
22894 (save-excursion
22895 (unless (and beg end)
22896 (org-back-to-heading t)
22897 (setq beg (point))
22898 (org-end-of-subtree t)
22899 (setq end (point)))
22900 (set-buffer (get-buffer org-agenda-buffer-name))
22901 (save-excursion
22902 (goto-char (point-max))
22903 (beginning-of-line 1)
22904 (while (not (bobp))
22905 (when (and (setq m (get-text-property (point) 'org-marker))
22906 (equal buf (marker-buffer m))
22907 (setq p (marker-position m))
22908 (>= p beg)
22909 (<= p end))
22910 (let ((inhibit-read-only t))
22911 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22912 (beginning-of-line 0))))))
22914 (defun org-agenda-open-link ()
22915 "Follow the link in the current line, if any."
22916 (interactive)
22917 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22918 (save-excursion
22919 (save-restriction
22920 (narrow-to-region (point-at-bol) (point-at-eol))
22921 (org-open-at-point))))
22923 (defun org-agenda-copy-local-variable (var)
22924 "Get a variable from a referenced buffer and install it here."
22925 (let ((m (get-text-property (point) 'org-marker)))
22926 (when (and m (buffer-live-p (marker-buffer m)))
22927 (org-set-local var (with-current-buffer (marker-buffer m)
22928 (symbol-value var))))))
22930 (defun org-agenda-switch-to (&optional delete-other-windows)
22931 "Go to the Org-mode file which contains the item at point."
22932 (interactive)
22933 (let* ((marker (or (get-text-property (point) 'org-marker)
22934 (org-agenda-error)))
22935 (buffer (marker-buffer marker))
22936 (pos (marker-position marker)))
22937 (switch-to-buffer buffer)
22938 (and delete-other-windows (delete-other-windows))
22939 (widen)
22940 (goto-char pos)
22941 (when (org-mode-p)
22942 (org-show-context 'agenda)
22943 (save-excursion
22944 (and (outline-next-heading)
22945 (org-flag-heading nil)))))) ; show the next heading
22947 (defun org-agenda-goto-mouse (ev)
22948 "Go to the Org-mode file which contains the item at the mouse click."
22949 (interactive "e")
22950 (mouse-set-point ev)
22951 (org-agenda-goto))
22953 (defun org-agenda-show ()
22954 "Display the Org-mode file which contains the item at point."
22955 (interactive)
22956 (let ((win (selected-window)))
22957 (org-agenda-goto t)
22958 (select-window win)))
22960 (defun org-agenda-recenter (arg)
22961 "Display the Org-mode file which contains the item at point and recenter."
22962 (interactive "P")
22963 (let ((win (selected-window)))
22964 (org-agenda-goto t)
22965 (recenter arg)
22966 (select-window win)))
22968 (defun org-agenda-show-mouse (ev)
22969 "Display the Org-mode file which contains the item at the mouse click."
22970 (interactive "e")
22971 (mouse-set-point ev)
22972 (org-agenda-show))
22974 (defun org-agenda-check-no-diary ()
22975 "Check if the entry is a diary link and abort if yes."
22976 (if (get-text-property (point) 'org-agenda-diary-link)
22977 (org-agenda-error)))
22979 (defun org-agenda-error ()
22980 (error "Command not allowed in this line"))
22982 (defun org-agenda-tree-to-indirect-buffer ()
22983 "Show the subtree corresponding to the current entry in an indirect buffer.
22984 This calls the command `org-tree-to-indirect-buffer' from the original
22985 Org-mode buffer.
22986 With numerical prefix arg ARG, go up to this level and then take that tree.
22987 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22988 dedicated frame)."
22989 (interactive)
22990 (org-agenda-check-no-diary)
22991 (let* ((marker (or (get-text-property (point) 'org-marker)
22992 (org-agenda-error)))
22993 (buffer (marker-buffer marker))
22994 (pos (marker-position marker)))
22995 (with-current-buffer buffer
22996 (save-excursion
22997 (goto-char pos)
22998 (call-interactively 'org-tree-to-indirect-buffer)))))
23000 (defvar org-last-heading-marker (make-marker)
23001 "Marker pointing to the headline that last changed its TODO state
23002 by a remote command from the agenda.")
23004 (defun org-agenda-todo-nextset ()
23005 "Switch TODO entry to next sequence."
23006 (interactive)
23007 (org-agenda-todo 'nextset))
23009 (defun org-agenda-todo-previousset ()
23010 "Switch TODO entry to previous sequence."
23011 (interactive)
23012 (org-agenda-todo 'previousset))
23014 (defun org-agenda-todo (&optional arg)
23015 "Cycle TODO state of line at point, also in Org-mode file.
23016 This changes the line at point, all other lines in the agenda referring to
23017 the same tree node, and the headline of the tree node in the Org-mode file."
23018 (interactive "P")
23019 (org-agenda-check-no-diary)
23020 (let* ((col (current-column))
23021 (marker (or (get-text-property (point) 'org-marker)
23022 (org-agenda-error)))
23023 (buffer (marker-buffer marker))
23024 (pos (marker-position marker))
23025 (hdmarker (get-text-property (point) 'org-hd-marker))
23026 (inhibit-read-only t)
23027 newhead)
23028 (org-with-remote-undo buffer
23029 (with-current-buffer buffer
23030 (widen)
23031 (goto-char pos)
23032 (org-show-context 'agenda)
23033 (save-excursion
23034 (and (outline-next-heading)
23035 (org-flag-heading nil))) ; show the next heading
23036 (org-todo arg)
23037 (and (bolp) (forward-char 1))
23038 (setq newhead (org-get-heading))
23039 (save-excursion
23040 (org-back-to-heading)
23041 (move-marker org-last-heading-marker (point))))
23042 (beginning-of-line 1)
23043 (save-excursion
23044 (org-agenda-change-all-lines newhead hdmarker 'fixface))
23045 (move-to-column col))))
23047 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
23048 "Change all lines in the agenda buffer which match HDMARKER.
23049 The new content of the line will be NEWHEAD (as modified by
23050 `org-format-agenda-item'). HDMARKER is checked with
23051 `equal' against all `org-hd-marker' text properties in the file.
23052 If FIXFACE is non-nil, the face of each item is modified acording to
23053 the new TODO state."
23054 (let* ((inhibit-read-only t)
23055 props m pl undone-face done-face finish new dotime cat tags)
23056 (save-excursion
23057 (goto-char (point-max))
23058 (beginning-of-line 1)
23059 (while (not finish)
23060 (setq finish (bobp))
23061 (when (and (setq m (get-text-property (point) 'org-hd-marker))
23062 (equal m hdmarker))
23063 (setq props (text-properties-at (point))
23064 dotime (get-text-property (point) 'dotime)
23065 cat (get-text-property (point) 'org-category)
23066 tags (get-text-property (point) 'tags)
23067 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
23068 pl (get-text-property (point) 'prefix-length)
23069 undone-face (get-text-property (point) 'undone-face)
23070 done-face (get-text-property (point) 'done-face))
23071 (move-to-column pl)
23072 (cond
23073 ((equal new "")
23074 (beginning-of-line 1)
23075 (and (looking-at ".*\n?") (replace-match "")))
23076 ((looking-at ".*")
23077 (replace-match new t t)
23078 (beginning-of-line 1)
23079 (add-text-properties (point-at-bol) (point-at-eol) props)
23080 (when fixface
23081 (add-text-properties
23082 (point-at-bol) (point-at-eol)
23083 (list 'face
23084 (if org-last-todo-state-is-todo
23085 undone-face done-face))))
23086 (org-agenda-highlight-todo 'line)
23087 (beginning-of-line 1))
23088 (t (error "Line update did not work"))))
23089 (beginning-of-line 0)))
23090 (org-finalize-agenda)))
23092 (defun org-agenda-align-tags (&optional line)
23093 "Align all tags in agenda items to `org-agenda-tags-column'."
23094 (let ((inhibit-read-only t) l c)
23095 (save-excursion
23096 (goto-char (if line (point-at-bol) (point-min)))
23097 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
23098 (if line (point-at-eol) nil) t)
23099 (add-text-properties
23100 (match-beginning 2) (match-end 2)
23101 (list 'face (delq nil (list 'org-tag (get-text-property
23102 (match-beginning 2) 'face)))))
23103 (setq l (- (match-end 2) (match-beginning 2))
23104 c (if (< org-agenda-tags-column 0)
23105 (- (abs org-agenda-tags-column) l)
23106 org-agenda-tags-column))
23107 (delete-region (match-beginning 1) (match-end 1))
23108 (goto-char (match-beginning 1))
23109 (insert (org-add-props
23110 (make-string (max 1 (- c (current-column))) ?\ )
23111 (text-properties-at (point))))))))
23113 (defun org-agenda-priority-up ()
23114 "Increase the priority of line at point, also in Org-mode file."
23115 (interactive)
23116 (org-agenda-priority 'up))
23118 (defun org-agenda-priority-down ()
23119 "Decrease the priority of line at point, also in Org-mode file."
23120 (interactive)
23121 (org-agenda-priority 'down))
23123 (defun org-agenda-priority (&optional force-direction)
23124 "Set the priority of line at point, also in Org-mode file.
23125 This changes the line at point, all other lines in the agenda referring to
23126 the same tree node, and the headline of the tree node in the Org-mode file."
23127 (interactive)
23128 (org-agenda-check-no-diary)
23129 (let* ((marker (or (get-text-property (point) 'org-marker)
23130 (org-agenda-error)))
23131 (hdmarker (get-text-property (point) 'org-hd-marker))
23132 (buffer (marker-buffer hdmarker))
23133 (pos (marker-position hdmarker))
23134 (inhibit-read-only t)
23135 newhead)
23136 (org-with-remote-undo buffer
23137 (with-current-buffer buffer
23138 (widen)
23139 (goto-char pos)
23140 (org-show-context 'agenda)
23141 (save-excursion
23142 (and (outline-next-heading)
23143 (org-flag-heading nil))) ; show the next heading
23144 (funcall 'org-priority force-direction)
23145 (end-of-line 1)
23146 (setq newhead (org-get-heading)))
23147 (org-agenda-change-all-lines newhead hdmarker)
23148 (beginning-of-line 1))))
23150 (defun org-get-tags-at (&optional pos)
23151 "Get a list of all headline tags applicable at POS.
23152 POS defaults to point. If tags are inherited, the list contains
23153 the targets in the same sequence as the headlines appear, i.e.
23154 the tags of the current headline come last."
23155 (interactive)
23156 (let (tags lastpos)
23157 (save-excursion
23158 (save-restriction
23159 (widen)
23160 (goto-char (or pos (point)))
23161 (save-match-data
23162 (org-back-to-heading t)
23163 (condition-case nil
23164 (while (not (equal lastpos (point)))
23165 (setq lastpos (point))
23166 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
23167 (setq tags (append (org-split-string
23168 (org-match-string-no-properties 1) ":")
23169 tags)))
23170 (or org-use-tag-inheritance (error ""))
23171 (org-up-heading-all 1))
23172 (error nil))))
23173 tags)))
23175 ;; FIXME: should fix the tags property of the agenda line.
23176 (defun org-agenda-set-tags ()
23177 "Set tags for the current headline."
23178 (interactive)
23179 (org-agenda-check-no-diary)
23180 (if (and (org-region-active-p) (interactive-p))
23181 (call-interactively 'org-change-tag-in-region)
23182 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23183 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23184 (org-agenda-error)))
23185 (buffer (marker-buffer hdmarker))
23186 (pos (marker-position hdmarker))
23187 (inhibit-read-only t)
23188 newhead)
23189 (org-with-remote-undo buffer
23190 (with-current-buffer buffer
23191 (widen)
23192 (goto-char pos)
23193 (save-excursion
23194 (org-show-context 'agenda))
23195 (save-excursion
23196 (and (outline-next-heading)
23197 (org-flag-heading nil))) ; show the next heading
23198 (goto-char pos)
23199 (call-interactively 'org-set-tags)
23200 (end-of-line 1)
23201 (setq newhead (org-get-heading)))
23202 (org-agenda-change-all-lines newhead hdmarker)
23203 (beginning-of-line 1)))))
23205 (defun org-agenda-toggle-archive-tag ()
23206 "Toggle the archive tag for the current entry."
23207 (interactive)
23208 (org-agenda-check-no-diary)
23209 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23210 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23211 (org-agenda-error)))
23212 (buffer (marker-buffer hdmarker))
23213 (pos (marker-position hdmarker))
23214 (inhibit-read-only t)
23215 newhead)
23216 (org-with-remote-undo buffer
23217 (with-current-buffer buffer
23218 (widen)
23219 (goto-char pos)
23220 (org-show-context 'agenda)
23221 (save-excursion
23222 (and (outline-next-heading)
23223 (org-flag-heading nil))) ; show the next heading
23224 (call-interactively 'org-toggle-archive-tag)
23225 (end-of-line 1)
23226 (setq newhead (org-get-heading)))
23227 (org-agenda-change-all-lines newhead hdmarker)
23228 (beginning-of-line 1))))
23230 (defun org-agenda-date-later (arg &optional what)
23231 "Change the date of this item to one day later."
23232 (interactive "p")
23233 (org-agenda-check-type t 'agenda 'timeline)
23234 (org-agenda-check-no-diary)
23235 (let* ((marker (or (get-text-property (point) 'org-marker)
23236 (org-agenda-error)))
23237 (buffer (marker-buffer marker))
23238 (pos (marker-position marker)))
23239 (org-with-remote-undo buffer
23240 (with-current-buffer buffer
23241 (widen)
23242 (goto-char pos)
23243 (if (not (org-at-timestamp-p))
23244 (error "Cannot find time stamp"))
23245 (org-timestamp-change arg (or what 'day)))
23246 (org-agenda-show-new-time marker org-last-changed-timestamp))
23247 (message "Time stamp changed to %s" org-last-changed-timestamp)))
23249 (defun org-agenda-date-earlier (arg &optional what)
23250 "Change the date of this item to one day earlier."
23251 (interactive "p")
23252 (org-agenda-date-later (- arg) what))
23254 (defun org-agenda-show-new-time (marker stamp &optional prefix)
23255 "Show new date stamp via text properties."
23256 ;; We use text properties to make this undoable
23257 (let ((inhibit-read-only t))
23258 (setq stamp (concat " " prefix " => " stamp))
23259 (save-excursion
23260 (goto-char (point-max))
23261 (while (not (bobp))
23262 (when (equal marker (get-text-property (point) 'org-marker))
23263 (move-to-column (- (window-width) (length stamp)) t)
23264 (if (featurep 'xemacs)
23265 ;; Use `duplicable' property to trigger undo recording
23266 (let ((ex (make-extent nil nil))
23267 (gl (make-glyph stamp)))
23268 (set-glyph-face gl 'secondary-selection)
23269 (set-extent-properties
23270 ex (list 'invisible t 'end-glyph gl 'duplicable t))
23271 (insert-extent ex (1- (point)) (point-at-eol)))
23272 (add-text-properties
23273 (1- (point)) (point-at-eol)
23274 (list 'display (org-add-props stamp nil
23275 'face 'secondary-selection))))
23276 (beginning-of-line 1))
23277 (beginning-of-line 0)))))
23279 (defun org-agenda-date-prompt (arg)
23280 "Change the date of this item. Date is prompted for, with default today.
23281 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23282 be used to request time specification in the time stamp."
23283 (interactive "P")
23284 (org-agenda-check-type t 'agenda 'timeline)
23285 (org-agenda-check-no-diary)
23286 (let* ((marker (or (get-text-property (point) 'org-marker)
23287 (org-agenda-error)))
23288 (buffer (marker-buffer marker))
23289 (pos (marker-position marker)))
23290 (org-with-remote-undo buffer
23291 (with-current-buffer buffer
23292 (widen)
23293 (goto-char pos)
23294 (if (not (org-at-timestamp-p))
23295 (error "Cannot find time stamp"))
23296 (org-time-stamp arg)
23297 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23299 (defun org-agenda-schedule (arg)
23300 "Schedule the item at point."
23301 (interactive "P")
23302 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23303 (org-agenda-check-no-diary)
23304 (let* ((marker (or (get-text-property (point) 'org-marker)
23305 (org-agenda-error)))
23306 (buffer (marker-buffer marker))
23307 (pos (marker-position marker))
23308 (org-insert-labeled-timestamps-at-point nil)
23310 (message "%s" (marker-insertion-type marker)) (sit-for 3)
23311 (set-marker-insertion-type marker t)
23312 (org-with-remote-undo buffer
23313 (with-current-buffer buffer
23314 (widen)
23315 (goto-char pos)
23316 (setq ts (org-schedule arg)))
23317 (org-agenda-show-new-time marker ts "S"))
23318 (message "Item scheduled for %s" ts)))
23320 (defun org-agenda-deadline (arg)
23321 "Schedule the item at point."
23322 (interactive "P")
23323 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23324 (org-agenda-check-no-diary)
23325 (let* ((marker (or (get-text-property (point) 'org-marker)
23326 (org-agenda-error)))
23327 (buffer (marker-buffer marker))
23328 (pos (marker-position marker))
23329 (org-insert-labeled-timestamps-at-point nil)
23331 (org-with-remote-undo buffer
23332 (with-current-buffer buffer
23333 (widen)
23334 (goto-char pos)
23335 (setq ts (org-deadline arg)))
23336 (org-agenda-show-new-time marker ts "S"))
23337 (message "Deadline for this item set to %s" ts)))
23339 (defun org-get-heading (&optional no-tags)
23340 "Return the heading of the current entry, without the stars."
23341 (save-excursion
23342 (org-back-to-heading t)
23343 (if (looking-at
23344 (if no-tags
23345 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23346 "\\*+[ \t]+\\([^\r\n]*\\)"))
23347 (match-string 1) "")))
23349 (defun org-agenda-clock-in (&optional arg)
23350 "Start the clock on the currently selected item."
23351 (interactive "P")
23352 (org-agenda-check-no-diary)
23353 (let* ((marker (or (get-text-property (point) 'org-marker)
23354 (org-agenda-error)))
23355 (pos (marker-position marker)))
23356 (org-with-remote-undo (marker-buffer marker)
23357 (with-current-buffer (marker-buffer marker)
23358 (widen)
23359 (goto-char pos)
23360 (org-clock-in)))))
23362 (defun org-agenda-clock-out (&optional arg)
23363 "Stop the currently running clock."
23364 (interactive "P")
23365 (unless (marker-buffer org-clock-marker)
23366 (error "No running clock"))
23367 (org-with-remote-undo (marker-buffer org-clock-marker)
23368 (org-clock-out)))
23370 (defun org-agenda-clock-cancel (&optional arg)
23371 "Cancel the currently running clock."
23372 (interactive "P")
23373 (unless (marker-buffer org-clock-marker)
23374 (error "No running clock"))
23375 (org-with-remote-undo (marker-buffer org-clock-marker)
23376 (org-clock-cancel)))
23378 (defun org-agenda-diary-entry ()
23379 "Make a diary entry, like the `i' command from the calendar.
23380 All the standard commands work: block, weekly etc."
23381 (interactive)
23382 (org-agenda-check-type t 'agenda 'timeline)
23383 (require 'diary-lib)
23384 (let* ((char (progn
23385 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23386 (read-char-exclusive)))
23387 (cmd (cdr (assoc char
23388 '((?d . insert-diary-entry)
23389 (?w . insert-weekly-diary-entry)
23390 (?m . insert-monthly-diary-entry)
23391 (?y . insert-yearly-diary-entry)
23392 (?a . insert-anniversary-diary-entry)
23393 (?b . insert-block-diary-entry)
23394 (?c . insert-cyclic-diary-entry)))))
23395 (oldf (symbol-function 'calendar-cursor-to-date))
23396 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23397 (point (point))
23398 (mark (or (mark t) (point))))
23399 (unless cmd
23400 (error "No command associated with <%c>" char))
23401 (unless (and (get-text-property point 'day)
23402 (or (not (equal ?b char))
23403 (get-text-property mark 'day)))
23404 (error "Don't know which date to use for diary entry"))
23405 ;; We implement this by hacking the `calendar-cursor-to-date' function
23406 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23407 (let ((calendar-mark-ring
23408 (list (calendar-gregorian-from-absolute
23409 (or (get-text-property mark 'day)
23410 (get-text-property point 'day))))))
23411 (unwind-protect
23412 (progn
23413 (fset 'calendar-cursor-to-date
23414 (lambda (&optional error)
23415 (calendar-gregorian-from-absolute
23416 (get-text-property point 'day))))
23417 (call-interactively cmd))
23418 (fset 'calendar-cursor-to-date oldf)))))
23421 (defun org-agenda-execute-calendar-command (cmd)
23422 "Execute a calendar command from the agenda, with the date associated to
23423 the cursor position."
23424 (org-agenda-check-type t 'agenda 'timeline)
23425 (require 'diary-lib)
23426 (unless (get-text-property (point) 'day)
23427 (error "Don't know which date to use for calendar command"))
23428 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23429 (point (point))
23430 (date (calendar-gregorian-from-absolute
23431 (get-text-property point 'day)))
23432 ;; the following 3 vars are needed in the calendar
23433 (displayed-day (extract-calendar-day date))
23434 (displayed-month (extract-calendar-month date))
23435 (displayed-year (extract-calendar-year date)))
23436 (unwind-protect
23437 (progn
23438 (fset 'calendar-cursor-to-date
23439 (lambda (&optional error)
23440 (calendar-gregorian-from-absolute
23441 (get-text-property point 'day))))
23442 (call-interactively cmd))
23443 (fset 'calendar-cursor-to-date oldf))))
23445 (defun org-agenda-phases-of-moon ()
23446 "Display the phases of the moon for the 3 months around the cursor date."
23447 (interactive)
23448 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23450 (defun org-agenda-holidays ()
23451 "Display the holidays for the 3 months around the cursor date."
23452 (interactive)
23453 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23455 (defun org-agenda-sunrise-sunset (arg)
23456 "Display sunrise and sunset for the cursor date.
23457 Latitude and longitude can be specified with the variables
23458 `calendar-latitude' and `calendar-longitude'. When called with prefix
23459 argument, latitude and longitude will be prompted for."
23460 (interactive "P")
23461 (let ((calendar-longitude (if arg nil calendar-longitude))
23462 (calendar-latitude (if arg nil calendar-latitude))
23463 (calendar-location-name
23464 (if arg "the given coordinates" calendar-location-name)))
23465 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23467 (defun org-agenda-goto-calendar ()
23468 "Open the Emacs calendar with the date at the cursor."
23469 (interactive)
23470 (org-agenda-check-type t 'agenda 'timeline)
23471 (let* ((day (or (get-text-property (point) 'day)
23472 (error "Don't know which date to open in calendar")))
23473 (date (calendar-gregorian-from-absolute day))
23474 (calendar-move-hook nil)
23475 (view-calendar-holidays-initially nil)
23476 (view-diary-entries-initially nil))
23477 (calendar)
23478 (calendar-goto-date date)))
23480 (defun org-calendar-goto-agenda ()
23481 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23482 This is a command that has to be installed in `calendar-mode-map'."
23483 (interactive)
23484 (org-agenda-list nil (calendar-absolute-from-gregorian
23485 (calendar-cursor-to-date))
23486 nil))
23488 (defun org-agenda-convert-date ()
23489 (interactive)
23490 (org-agenda-check-type t 'agenda 'timeline)
23491 (let ((day (get-text-property (point) 'day))
23492 date s)
23493 (unless day
23494 (error "Don't know which date to convert"))
23495 (setq date (calendar-gregorian-from-absolute day))
23496 (setq s (concat
23497 "Gregorian: " (calendar-date-string date) "\n"
23498 "ISO: " (calendar-iso-date-string date) "\n"
23499 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23500 "Julian: " (calendar-julian-date-string date) "\n"
23501 "Astron. JD: " (calendar-astro-date-string date)
23502 " (Julian date number at noon UTC)\n"
23503 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23504 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23505 "French: " (calendar-french-date-string date) "\n"
23506 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23507 "Mayan: " (calendar-mayan-date-string date) "\n"
23508 "Coptic: " (calendar-coptic-date-string date) "\n"
23509 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23510 "Persian: " (calendar-persian-date-string date) "\n"
23511 "Chinese: " (calendar-chinese-date-string date) "\n"))
23512 (with-output-to-temp-buffer "*Dates*"
23513 (princ s))
23514 (if (fboundp 'fit-window-to-buffer)
23515 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23518 ;;;; Embedded LaTeX
23520 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23521 "Keymap for the minor `org-cdlatex-mode'.")
23523 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23524 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23525 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23526 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23527 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23529 (defvar org-cdlatex-texmathp-advice-is-done nil
23530 "Flag remembering if we have applied the advice to texmathp already.")
23532 (define-minor-mode org-cdlatex-mode
23533 "Toggle the minor `org-cdlatex-mode'.
23534 This mode supports entering LaTeX environment and math in LaTeX fragments
23535 in Org-mode.
23536 \\{org-cdlatex-mode-map}"
23537 nil " OCDL" nil
23538 (when org-cdlatex-mode (require 'cdlatex))
23539 (unless org-cdlatex-texmathp-advice-is-done
23540 (setq org-cdlatex-texmathp-advice-is-done t)
23541 (defadvice texmathp (around org-math-always-on activate)
23542 "Always return t in org-mode buffers.
23543 This is because we want to insert math symbols without dollars even outside
23544 the LaTeX math segments. If Orgmode thinks that point is actually inside
23545 en embedded LaTeX fragement, let texmathp do its job.
23546 \\[org-cdlatex-mode-map]"
23547 (interactive)
23548 (let (p)
23549 (cond
23550 ((not (org-mode-p)) ad-do-it)
23551 ((eq this-command 'cdlatex-math-symbol)
23552 (setq ad-return-value t
23553 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23555 (let ((p (org-inside-LaTeX-fragment-p)))
23556 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23557 (setq ad-return-value t
23558 texmathp-why '("Org-mode embedded math" . 0))
23559 (if p ad-do-it)))))))))
23561 (defun turn-on-org-cdlatex ()
23562 "Unconditionally turn on `org-cdlatex-mode'."
23563 (org-cdlatex-mode 1))
23565 (defun org-inside-LaTeX-fragment-p ()
23566 "Test if point is inside a LaTeX fragment.
23567 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23568 sequence appearing also before point.
23569 Even though the matchers for math are configurable, this function assumes
23570 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23571 delimiters are skipped when they have been removed by customization.
23572 The return value is nil, or a cons cell with the delimiter and
23573 and the position of this delimiter.
23575 This function does a reasonably good job, but can locally be fooled by
23576 for example currency specifications. For example it will assume being in
23577 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23578 fragments that are properly closed, but during editing, we have to live
23579 with the uncertainty caused by missing closing delimiters. This function
23580 looks only before point, not after."
23581 (catch 'exit
23582 (let ((pos (point))
23583 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23584 (lim (progn
23585 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23586 (point)))
23587 dd-on str (start 0) m re)
23588 (goto-char pos)
23589 (when dodollar
23590 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23591 re (nth 1 (assoc "$" org-latex-regexps)))
23592 (while (string-match re str start)
23593 (cond
23594 ((= (match-end 0) (length str))
23595 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23596 ((= (match-end 0) (- (length str) 5))
23597 (throw 'exit nil))
23598 (t (setq start (match-end 0))))))
23599 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23600 (goto-char pos)
23601 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23602 (and (match-beginning 2) (throw 'exit nil))
23603 ;; count $$
23604 (while (re-search-backward "\\$\\$" lim t)
23605 (setq dd-on (not dd-on)))
23606 (goto-char pos)
23607 (if dd-on (cons "$$" m))))))
23610 (defun org-try-cdlatex-tab ()
23611 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23612 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23613 - inside a LaTeX fragment, or
23614 - after the first word in a line, where an abbreviation expansion could
23615 insert a LaTeX environment."
23616 (when org-cdlatex-mode
23617 (cond
23618 ((save-excursion
23619 (skip-chars-backward "a-zA-Z0-9*")
23620 (skip-chars-backward " \t")
23621 (bolp))
23622 (cdlatex-tab) t)
23623 ((org-inside-LaTeX-fragment-p)
23624 (cdlatex-tab) t)
23625 (t nil))))
23627 (defun org-cdlatex-underscore-caret (&optional arg)
23628 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23629 Revert to the normal definition outside of these fragments."
23630 (interactive "P")
23631 (if (org-inside-LaTeX-fragment-p)
23632 (call-interactively 'cdlatex-sub-superscript)
23633 (let (org-cdlatex-mode)
23634 (call-interactively (key-binding (vector last-input-event))))))
23636 (defun org-cdlatex-math-modify (&optional arg)
23637 "Execute `cdlatex-math-modify' in LaTeX fragments.
23638 Revert to the normal definition outside of these fragments."
23639 (interactive "P")
23640 (if (org-inside-LaTeX-fragment-p)
23641 (call-interactively 'cdlatex-math-modify)
23642 (let (org-cdlatex-mode)
23643 (call-interactively (key-binding (vector last-input-event))))))
23645 (defvar org-latex-fragment-image-overlays nil
23646 "List of overlays carrying the images of latex fragments.")
23647 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23649 (defun org-remove-latex-fragment-image-overlays ()
23650 "Remove all overlays with LaTeX fragment images in current buffer."
23651 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23652 (setq org-latex-fragment-image-overlays nil))
23654 (defun org-preview-latex-fragment (&optional subtree)
23655 "Preview the LaTeX fragment at point, or all locally or globally.
23656 If the cursor is in a LaTeX fragment, create the image and overlay
23657 it over the source code. If there is no fragment at point, display
23658 all fragments in the current text, from one headline to the next. With
23659 prefix SUBTREE, display all fragments in the current subtree. With a
23660 double prefix `C-u C-u', or when the cursor is before the first headline,
23661 display all fragments in the buffer.
23662 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23663 (interactive "P")
23664 (org-remove-latex-fragment-image-overlays)
23665 (save-excursion
23666 (save-restriction
23667 (let (beg end at msg)
23668 (cond
23669 ((or (equal subtree '(16))
23670 (not (save-excursion
23671 (re-search-backward (concat "^" outline-regexp) nil t))))
23672 (setq beg (point-min) end (point-max)
23673 msg "Creating images for buffer...%s"))
23674 ((equal subtree '(4))
23675 (org-back-to-heading)
23676 (setq beg (point) end (org-end-of-subtree t)
23677 msg "Creating images for subtree...%s"))
23679 (if (setq at (org-inside-LaTeX-fragment-p))
23680 (goto-char (max (point-min) (- (cdr at) 2)))
23681 (org-back-to-heading))
23682 (setq beg (point) end (progn (outline-next-heading) (point))
23683 msg (if at "Creating image...%s"
23684 "Creating images for entry...%s"))))
23685 (message msg "")
23686 (narrow-to-region beg end)
23687 (goto-char beg)
23688 (org-format-latex
23689 (concat "ltxpng/" (file-name-sans-extension
23690 (file-name-nondirectory
23691 buffer-file-name)))
23692 default-directory 'overlays msg at 'forbuffer)
23693 (message msg "done. Use `C-c C-c' to remove images.")))))
23695 (defvar org-latex-regexps
23696 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23697 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23698 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23699 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23700 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23701 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23702 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23703 "Regular expressions for matching embedded LaTeX.")
23705 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23706 "Replace LaTeX fragments with links to an image, and produce images."
23707 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23708 (let* ((prefixnodir (file-name-nondirectory prefix))
23709 (absprefix (expand-file-name prefix dir))
23710 (todir (file-name-directory absprefix))
23711 (opt org-format-latex-options)
23712 (matchers (plist-get opt :matchers))
23713 (re-list org-latex-regexps)
23714 (cnt 0) txt link beg end re e checkdir
23715 m n block linkfile movefile ov)
23716 ;; Check if there are old images files with this prefix, and remove them
23717 (when (file-directory-p todir)
23718 (mapc 'delete-file
23719 (directory-files
23720 todir 'full
23721 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23722 ;; Check the different regular expressions
23723 (while (setq e (pop re-list))
23724 (setq m (car e) re (nth 1 e) n (nth 2 e)
23725 block (if (nth 3 e) "\n\n" ""))
23726 (when (member m matchers)
23727 (goto-char (point-min))
23728 (while (re-search-forward re nil t)
23729 (when (or (not at) (equal (cdr at) (match-beginning n)))
23730 (setq txt (match-string n)
23731 beg (match-beginning n) end (match-end n)
23732 cnt (1+ cnt)
23733 linkfile (format "%s_%04d.png" prefix cnt)
23734 movefile (format "%s_%04d.png" absprefix cnt)
23735 link (concat block "[[file:" linkfile "]]" block))
23736 (if msg (message msg cnt))
23737 (goto-char beg)
23738 (unless checkdir ; make sure the directory exists
23739 (setq checkdir t)
23740 (or (file-directory-p todir) (make-directory todir)))
23741 (org-create-formula-image
23742 txt movefile opt forbuffer)
23743 (if overlays
23744 (progn
23745 (setq ov (org-make-overlay beg end))
23746 (if (featurep 'xemacs)
23747 (progn
23748 (org-overlay-put ov 'invisible t)
23749 (org-overlay-put
23750 ov 'end-glyph
23751 (make-glyph (vector 'png :file movefile))))
23752 (org-overlay-put
23753 ov 'display
23754 (list 'image :type 'png :file movefile :ascent 'center)))
23755 (push ov org-latex-fragment-image-overlays)
23756 (goto-char end))
23757 (delete-region beg end)
23758 (insert link))))))))
23760 ;; This function borrows from Ganesh Swami's latex2png.el
23761 (defun org-create-formula-image (string tofile options buffer)
23762 (let* ((tmpdir (if (featurep 'xemacs)
23763 (temp-directory)
23764 temporary-file-directory))
23765 (texfilebase (make-temp-name
23766 (expand-file-name "orgtex" tmpdir)))
23767 (texfile (concat texfilebase ".tex"))
23768 (dvifile (concat texfilebase ".dvi"))
23769 (pngfile (concat texfilebase ".png"))
23770 (fnh (face-attribute 'default :height nil))
23771 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23772 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23773 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23774 "Black"))
23775 (bg (or (plist-get options (if buffer :background :html-background))
23776 "Transparent")))
23777 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23778 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23779 (with-temp-file texfile
23780 (insert org-format-latex-header
23781 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23782 (let ((dir default-directory))
23783 (condition-case nil
23784 (progn
23785 (cd tmpdir)
23786 (call-process "latex" nil nil nil texfile))
23787 (error nil))
23788 (cd dir))
23789 (if (not (file-exists-p dvifile))
23790 (progn (message "Failed to create dvi file from %s" texfile) nil)
23791 (call-process "dvipng" nil nil nil
23792 "-E" "-fg" fg "-bg" bg
23793 "-D" dpi
23794 ;;"-x" scale "-y" scale
23795 "-T" "tight"
23796 "-o" pngfile
23797 dvifile)
23798 (if (not (file-exists-p pngfile))
23799 (progn (message "Failed to create png file from %s" texfile) nil)
23800 ;; Use the requested file name and clean up
23801 (copy-file pngfile tofile 'replace)
23802 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23803 (delete-file (concat texfilebase e)))
23804 pngfile))))
23806 (defun org-dvipng-color (attr)
23807 "Return an rgb color specification for dvipng."
23808 (apply 'format "rgb %s %s %s"
23809 (mapcar 'org-normalize-color
23810 (color-values (face-attribute 'default attr nil)))))
23812 (defun org-normalize-color (value)
23813 "Return string to be used as color value for an RGB component."
23814 (format "%g" (/ value 65535.0)))
23816 ;;;; Exporting
23818 ;;; Variables, constants, and parameter plists
23820 (defconst org-level-max 20)
23822 (defvar org-export-html-preamble nil
23823 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23824 (defvar org-export-html-postamble nil
23825 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23826 (defvar org-export-html-auto-preamble t
23827 "Should default preamble be inserted? Set by publishing functions.")
23828 (defvar org-export-html-auto-postamble t
23829 "Should default postamble be inserted? Set by publishing functions.")
23830 (defvar org-current-export-file nil) ; dynamically scoped parameter
23831 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23834 (defconst org-export-plist-vars
23835 '((:language . org-export-default-language)
23836 (:customtime . org-display-custom-times)
23837 (:headline-levels . org-export-headline-levels)
23838 (:section-numbers . org-export-with-section-numbers)
23839 (:table-of-contents . org-export-with-toc)
23840 (:preserve-breaks . org-export-preserve-breaks)
23841 (:archived-trees . org-export-with-archived-trees)
23842 (:emphasize . org-export-with-emphasize)
23843 (:sub-superscript . org-export-with-sub-superscripts)
23844 (:special-strings . org-export-with-special-strings)
23845 (:footnotes . org-export-with-footnotes)
23846 (:drawers . org-export-with-drawers)
23847 (:tags . org-export-with-tags)
23848 (:TeX-macros . org-export-with-TeX-macros)
23849 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23850 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23851 (:fixed-width . org-export-with-fixed-width)
23852 (:timestamps . org-export-with-timestamps)
23853 (:author-info . org-export-author-info)
23854 (:time-stamp-file . org-export-time-stamp-file)
23855 (:tables . org-export-with-tables)
23856 (:table-auto-headline . org-export-highlight-first-table-line)
23857 (:style . org-export-html-style)
23858 (:agenda-style . org-agenda-export-html-style)
23859 (:convert-org-links . org-export-html-link-org-files-as-html)
23860 (:inline-images . org-export-html-inline-images)
23861 (:html-extension . org-export-html-extension)
23862 (:html-table-tag . org-export-html-table-tag)
23863 (:expand-quoted-html . org-export-html-expand)
23864 (:timestamp . org-export-html-with-timestamp)
23865 (:publishing-directory . org-export-publishing-directory)
23866 (:preamble . org-export-html-preamble)
23867 (:postamble . org-export-html-postamble)
23868 (:auto-preamble . org-export-html-auto-preamble)
23869 (:auto-postamble . org-export-html-auto-postamble)
23870 (:author . user-full-name)
23871 (:email . user-mail-address)))
23873 (defun org-default-export-plist ()
23874 "Return the property list with default settings for the export variables."
23875 (let ((l org-export-plist-vars) rtn e)
23876 (while (setq e (pop l))
23877 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23878 rtn))
23880 (defun org-infile-export-plist ()
23881 "Return the property list with file-local settings for export."
23882 (save-excursion
23883 (save-restriction
23884 (widen)
23885 (goto-char 0)
23886 (let ((re (org-make-options-regexp
23887 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23888 p key val text options)
23889 (while (re-search-forward re nil t)
23890 (setq key (org-match-string-no-properties 1)
23891 val (org-match-string-no-properties 2))
23892 (cond
23893 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23894 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23895 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23896 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23897 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23898 ((string-equal key "TEXT")
23899 (setq text (if text (concat text "\n" val) val)))
23900 ((string-equal key "OPTIONS") (setq options val))))
23901 (setq p (plist-put p :text text))
23902 (when options
23903 (let ((op '(("H" . :headline-levels)
23904 ("num" . :section-numbers)
23905 ("toc" . :table-of-contents)
23906 ("\\n" . :preserve-breaks)
23907 ("@" . :expand-quoted-html)
23908 (":" . :fixed-width)
23909 ("|" . :tables)
23910 ("^" . :sub-superscript)
23911 ("-" . :special-strings)
23912 ("f" . :footnotes)
23913 ("d" . :drawers)
23914 ("tags" . :tags)
23915 ("*" . :emphasize)
23916 ("TeX" . :TeX-macros)
23917 ("LaTeX" . :LaTeX-fragments)
23918 ("skip" . :skip-before-1st-heading)
23919 ("author" . :author-info)
23920 ("timestamp" . :time-stamp-file)))
23922 (while (setq o (pop op))
23923 (if (string-match (concat (regexp-quote (car o))
23924 ":\\([^ \t\n\r;,.]*\\)")
23925 options)
23926 (setq p (plist-put p (cdr o)
23927 (car (read-from-string
23928 (match-string 1 options)))))))))
23929 p))))
23931 (defun org-export-directory (type plist)
23932 (let* ((val (plist-get plist :publishing-directory))
23933 (dir (if (listp val)
23934 (or (cdr (assoc type val)) ".")
23935 val)))
23936 dir))
23938 (defun org-skip-comments (lines)
23939 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23940 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23941 (re2 "^\\(\\*+\\)[ \t\n\r]")
23942 (case-fold-search nil)
23943 rtn line level)
23944 (while (setq line (pop lines))
23945 (cond
23946 ((and (string-match re1 line)
23947 (setq level (- (match-end 1) (match-beginning 1))))
23948 ;; Beginning of a COMMENT subtree. Skip it.
23949 (while (and (setq line (pop lines))
23950 (or (not (string-match re2 line))
23951 (> (- (match-end 1) (match-beginning 1)) level))))
23952 (setq lines (cons line lines)))
23953 ((string-match "^#" line)
23954 ;; an ordinary comment line
23956 ((and org-export-table-remove-special-lines
23957 (string-match "^[ \t]*|" line)
23958 (or (string-match "^[ \t]*| *[!_^] *|" line)
23959 (and (string-match "| *<[0-9]+> *|" line)
23960 (not (string-match "| *[^ <|]" line)))))
23961 ;; a special table line that should be removed
23963 (t (setq rtn (cons line rtn)))))
23964 (nreverse rtn)))
23966 (defun org-export (&optional arg)
23967 (interactive)
23968 (let ((help "[t] insert the export option template
23969 \[v] limit export to visible part of outline tree
23971 \[a] export as ASCII
23973 \[h] export as HTML
23974 \[H] export as HTML to temporary buffer
23975 \[R] export region as HTML
23976 \[b] export as HTML and browse immediately
23977 \[x] export as XOXO
23979 \[l] export as LaTeX
23980 \[L] export as LaTeX to temporary buffer
23982 \[i] export current file as iCalendar file
23983 \[I] export all agenda files as iCalendar files
23984 \[c] export agenda files into combined iCalendar file
23986 \[F] publish current file
23987 \[P] publish current project
23988 \[X] publish... (project will be prompted for)
23989 \[A] publish all projects")
23990 (cmds
23991 '((?t . org-insert-export-options-template)
23992 (?v . org-export-visible)
23993 (?a . org-export-as-ascii)
23994 (?h . org-export-as-html)
23995 (?b . org-export-as-html-and-open)
23996 (?H . org-export-as-html-to-buffer)
23997 (?R . org-export-region-as-html)
23998 (?x . org-export-as-xoxo)
23999 (?l . org-export-as-latex)
24000 (?L . org-export-as-latex-to-buffer)
24001 (?i . org-export-icalendar-this-file)
24002 (?I . org-export-icalendar-all-agenda-files)
24003 (?c . org-export-icalendar-combine-agenda-files)
24004 (?F . org-publish-current-file)
24005 (?P . org-publish-current-project)
24006 (?X . org-publish)
24007 (?A . org-publish-all)))
24008 r1 r2 ass)
24009 (save-window-excursion
24010 (delete-other-windows)
24011 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
24012 (princ help))
24013 (message "Select command: ")
24014 (setq r1 (read-char-exclusive)))
24015 (setq r2 (if (< r1 27) (+ r1 96) r1))
24016 (if (setq ass (assq r2 cmds))
24017 (call-interactively (cdr ass))
24018 (error "No command associated with key %c" r1))))
24020 (defconst org-html-entities
24021 '(("nbsp")
24022 ("iexcl")
24023 ("cent")
24024 ("pound")
24025 ("curren")
24026 ("yen")
24027 ("brvbar")
24028 ("vert" . "&#124;")
24029 ("sect")
24030 ("uml")
24031 ("copy")
24032 ("ordf")
24033 ("laquo")
24034 ("not")
24035 ("shy")
24036 ("reg")
24037 ("macr")
24038 ("deg")
24039 ("plusmn")
24040 ("sup2")
24041 ("sup3")
24042 ("acute")
24043 ("micro")
24044 ("para")
24045 ("middot")
24046 ("odot"."o")
24047 ("star"."*")
24048 ("cedil")
24049 ("sup1")
24050 ("ordm")
24051 ("raquo")
24052 ("frac14")
24053 ("frac12")
24054 ("frac34")
24055 ("iquest")
24056 ("Agrave")
24057 ("Aacute")
24058 ("Acirc")
24059 ("Atilde")
24060 ("Auml")
24061 ("Aring") ("AA"."&Aring;")
24062 ("AElig")
24063 ("Ccedil")
24064 ("Egrave")
24065 ("Eacute")
24066 ("Ecirc")
24067 ("Euml")
24068 ("Igrave")
24069 ("Iacute")
24070 ("Icirc")
24071 ("Iuml")
24072 ("ETH")
24073 ("Ntilde")
24074 ("Ograve")
24075 ("Oacute")
24076 ("Ocirc")
24077 ("Otilde")
24078 ("Ouml")
24079 ("times")
24080 ("Oslash")
24081 ("Ugrave")
24082 ("Uacute")
24083 ("Ucirc")
24084 ("Uuml")
24085 ("Yacute")
24086 ("THORN")
24087 ("szlig")
24088 ("agrave")
24089 ("aacute")
24090 ("acirc")
24091 ("atilde")
24092 ("auml")
24093 ("aring")
24094 ("aelig")
24095 ("ccedil")
24096 ("egrave")
24097 ("eacute")
24098 ("ecirc")
24099 ("euml")
24100 ("igrave")
24101 ("iacute")
24102 ("icirc")
24103 ("iuml")
24104 ("eth")
24105 ("ntilde")
24106 ("ograve")
24107 ("oacute")
24108 ("ocirc")
24109 ("otilde")
24110 ("ouml")
24111 ("divide")
24112 ("oslash")
24113 ("ugrave")
24114 ("uacute")
24115 ("ucirc")
24116 ("uuml")
24117 ("yacute")
24118 ("thorn")
24119 ("yuml")
24120 ("fnof")
24121 ("Alpha")
24122 ("Beta")
24123 ("Gamma")
24124 ("Delta")
24125 ("Epsilon")
24126 ("Zeta")
24127 ("Eta")
24128 ("Theta")
24129 ("Iota")
24130 ("Kappa")
24131 ("Lambda")
24132 ("Mu")
24133 ("Nu")
24134 ("Xi")
24135 ("Omicron")
24136 ("Pi")
24137 ("Rho")
24138 ("Sigma")
24139 ("Tau")
24140 ("Upsilon")
24141 ("Phi")
24142 ("Chi")
24143 ("Psi")
24144 ("Omega")
24145 ("alpha")
24146 ("beta")
24147 ("gamma")
24148 ("delta")
24149 ("epsilon")
24150 ("varepsilon"."&epsilon;")
24151 ("zeta")
24152 ("eta")
24153 ("theta")
24154 ("iota")
24155 ("kappa")
24156 ("lambda")
24157 ("mu")
24158 ("nu")
24159 ("xi")
24160 ("omicron")
24161 ("pi")
24162 ("rho")
24163 ("sigmaf") ("varsigma"."&sigmaf;")
24164 ("sigma")
24165 ("tau")
24166 ("upsilon")
24167 ("phi")
24168 ("chi")
24169 ("psi")
24170 ("omega")
24171 ("thetasym") ("vartheta"."&thetasym;")
24172 ("upsih")
24173 ("piv")
24174 ("bull") ("bullet"."&bull;")
24175 ("hellip") ("dots"."&hellip;")
24176 ("prime")
24177 ("Prime")
24178 ("oline")
24179 ("frasl")
24180 ("weierp")
24181 ("image")
24182 ("real")
24183 ("trade")
24184 ("alefsym")
24185 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
24186 ("uarr") ("uparrow"."&uarr;")
24187 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
24188 ("darr")("downarrow"."&darr;")
24189 ("harr") ("leftrightarrow"."&harr;")
24190 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
24191 ("lArr") ("Leftarrow"."&lArr;")
24192 ("uArr") ("Uparrow"."&uArr;")
24193 ("rArr") ("Rightarrow"."&rArr;")
24194 ("dArr") ("Downarrow"."&dArr;")
24195 ("hArr") ("Leftrightarrow"."&hArr;")
24196 ("forall")
24197 ("part") ("partial"."&part;")
24198 ("exist") ("exists"."&exist;")
24199 ("empty") ("emptyset"."&empty;")
24200 ("nabla")
24201 ("isin") ("in"."&isin;")
24202 ("notin")
24203 ("ni")
24204 ("prod")
24205 ("sum")
24206 ("minus")
24207 ("lowast") ("ast"."&lowast;")
24208 ("radic")
24209 ("prop") ("proptp"."&prop;")
24210 ("infin") ("infty"."&infin;")
24211 ("ang") ("angle"."&ang;")
24212 ("and") ("wedge"."&and;")
24213 ("or") ("vee"."&or;")
24214 ("cap")
24215 ("cup")
24216 ("int")
24217 ("there4")
24218 ("sim")
24219 ("cong") ("simeq"."&cong;")
24220 ("asymp")("approx"."&asymp;")
24221 ("ne") ("neq"."&ne;")
24222 ("equiv")
24223 ("le")
24224 ("ge")
24225 ("sub") ("subset"."&sub;")
24226 ("sup") ("supset"."&sup;")
24227 ("nsub")
24228 ("sube")
24229 ("supe")
24230 ("oplus")
24231 ("otimes")
24232 ("perp")
24233 ("sdot") ("cdot"."&sdot;")
24234 ("lceil")
24235 ("rceil")
24236 ("lfloor")
24237 ("rfloor")
24238 ("lang")
24239 ("rang")
24240 ("loz") ("Diamond"."&loz;")
24241 ("spades") ("spadesuit"."&spades;")
24242 ("clubs") ("clubsuit"."&clubs;")
24243 ("hearts") ("diamondsuit"."&hearts;")
24244 ("diams") ("diamondsuit"."&diams;")
24245 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
24246 ("quot")
24247 ("amp")
24248 ("lt")
24249 ("gt")
24250 ("OElig")
24251 ("oelig")
24252 ("Scaron")
24253 ("scaron")
24254 ("Yuml")
24255 ("circ")
24256 ("tilde")
24257 ("ensp")
24258 ("emsp")
24259 ("thinsp")
24260 ("zwnj")
24261 ("zwj")
24262 ("lrm")
24263 ("rlm")
24264 ("ndash")
24265 ("mdash")
24266 ("lsquo")
24267 ("rsquo")
24268 ("sbquo")
24269 ("ldquo")
24270 ("rdquo")
24271 ("bdquo")
24272 ("dagger")
24273 ("Dagger")
24274 ("permil")
24275 ("lsaquo")
24276 ("rsaquo")
24277 ("euro")
24279 ("arccos"."arccos")
24280 ("arcsin"."arcsin")
24281 ("arctan"."arctan")
24282 ("arg"."arg")
24283 ("cos"."cos")
24284 ("cosh"."cosh")
24285 ("cot"."cot")
24286 ("coth"."coth")
24287 ("csc"."csc")
24288 ("deg"."deg")
24289 ("det"."det")
24290 ("dim"."dim")
24291 ("exp"."exp")
24292 ("gcd"."gcd")
24293 ("hom"."hom")
24294 ("inf"."inf")
24295 ("ker"."ker")
24296 ("lg"."lg")
24297 ("lim"."lim")
24298 ("liminf"."liminf")
24299 ("limsup"."limsup")
24300 ("ln"."ln")
24301 ("log"."log")
24302 ("max"."max")
24303 ("min"."min")
24304 ("Pr"."Pr")
24305 ("sec"."sec")
24306 ("sin"."sin")
24307 ("sinh"."sinh")
24308 ("sup"."sup")
24309 ("tan"."tan")
24310 ("tanh"."tanh")
24312 "Entities for TeX->HTML translation.
24313 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24314 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24315 In that case, \"\\ent\" will be translated to \"&other;\".
24316 The list contains HTML entities for Latin-1, Greek and other symbols.
24317 It is supplemented by a number of commonly used TeX macros with appropriate
24318 translations. There is currently no way for users to extend this.")
24320 ;;; General functions for all backends
24322 (defun org-cleaned-string-for-export (string &rest parameters)
24323 "Cleanup a buffer STRING so that links can be created safely."
24324 (interactive)
24325 (let* ((re-radio (and org-target-link-regexp
24326 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24327 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24328 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24329 (re-archive (concat ":" org-archive-tag ":"))
24330 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24331 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24332 (htmlp (plist-get parameters :for-html))
24333 (asciip (plist-get parameters :for-ascii))
24334 (latexp (plist-get parameters :for-LaTeX))
24335 (commentsp (plist-get parameters :comments))
24336 (archived-trees (plist-get parameters :archived-trees))
24337 (inhibit-read-only t)
24338 (drawers org-drawers)
24339 (exp-drawers (plist-get parameters :drawers))
24340 (outline-regexp "\\*+ ")
24341 a b xx
24342 rtn p)
24343 (with-current-buffer (get-buffer-create " org-mode-tmp")
24344 (erase-buffer)
24345 (insert string)
24346 ;; Remove license-to-kill stuff
24347 (while (setq p (text-property-any (point-min) (point-max)
24348 :org-license-to-kill t))
24349 (delete-region p (next-single-property-change p :org-license-to-kill)))
24351 (let ((org-inhibit-startup t)) (org-mode))
24352 (untabify (point-min) (point-max))
24354 ;; Get rid of drawers
24355 (unless (eq t exp-drawers)
24356 (goto-char (point-min))
24357 (let ((re (concat "^[ \t]*:\\("
24358 (mapconcat
24359 'identity
24360 (org-delete-all exp-drawers
24361 (copy-sequence drawers))
24362 "\\|")
24363 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24364 (while (re-search-forward re nil t)
24365 (replace-match ""))))
24367 ;; Get the correct stuff before the first headline
24368 (when (plist-get parameters :skip-before-1st-heading)
24369 (goto-char (point-min))
24370 (when (re-search-forward "^\\*+[ \t]" nil t)
24371 (delete-region (point-min) (match-beginning 0))
24372 (goto-char (point-min))
24373 (insert "\n")))
24374 (when (plist-get parameters :add-text)
24375 (goto-char (point-min))
24376 (insert (plist-get parameters :add-text) "\n"))
24378 ;; Get rid of archived trees
24379 (when (not (eq archived-trees t))
24380 (goto-char (point-min))
24381 (while (re-search-forward re-archive nil t)
24382 (if (not (org-on-heading-p t))
24383 (org-end-of-subtree t)
24384 (beginning-of-line 1)
24385 (setq a (if archived-trees
24386 (1+ (point-at-eol)) (point))
24387 b (org-end-of-subtree t))
24388 (if (> b a) (delete-region a b)))))
24390 ;; Find targets in comments and move them out of comments,
24391 ;; but mark them as targets that should be invisible
24392 (goto-char (point-min))
24393 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24394 (replace-match "\\1(INVISIBLE)"))
24396 ;; Protect backend specific stuff, throw away the others.
24397 (let ((formatters
24398 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24399 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24400 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24401 fmt)
24402 (goto-char (point-min))
24403 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24404 (goto-char (match-end 0))
24405 (while (not (looking-at "#\\+END_EXAMPLE"))
24406 (insert ": ")
24407 (beginning-of-line 2)))
24408 (goto-char (point-min))
24409 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24410 (add-text-properties (match-beginning 0) (match-end 0)
24411 '(org-protected t)))
24412 (while formatters
24413 (setq fmt (pop formatters))
24414 (when (car fmt)
24415 (goto-char (point-min))
24416 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24417 ":[ \t]*\\(.*\\)") nil t)
24418 (replace-match "\\1" t)
24419 (add-text-properties
24420 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24421 '(org-protected t))))
24422 (goto-char (point-min))
24423 (while (re-search-forward
24424 (concat "^#\\+"
24425 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24426 (cadddr fmt) "\\>.*\n?") nil t)
24427 (if (car fmt)
24428 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24429 '(org-protected t))
24430 (delete-region (match-beginning 0) (match-end 0))))))
24432 ;; Protect quoted subtrees
24433 (goto-char (point-min))
24434 (while (re-search-forward re-quote nil t)
24435 (goto-char (match-beginning 0))
24436 (end-of-line 1)
24437 (add-text-properties (point) (org-end-of-subtree t)
24438 '(org-protected t)))
24440 ;; Protect verbatim elements
24441 (goto-char (point-min))
24442 (while (re-search-forward org-verbatim-re nil t)
24443 (add-text-properties (match-beginning 4) (match-end 4)
24444 '(org-protected t))
24445 (goto-char (1+ (match-end 4))))
24447 ;; Remove subtrees that are commented
24448 (goto-char (point-min))
24449 (while (re-search-forward re-commented nil t)
24450 (goto-char (match-beginning 0))
24451 (delete-region (point) (org-end-of-subtree t)))
24453 ;; Remove special table lines
24454 (when org-export-table-remove-special-lines
24455 (goto-char (point-min))
24456 (while (re-search-forward "^[ \t]*|" nil t)
24457 (beginning-of-line 1)
24458 (if (or (looking-at "[ \t]*| *[!_^] *|")
24459 (and (looking-at ".*?| *<[0-9]+> *|")
24460 (not (looking-at ".*?| *[^ <|]"))))
24461 (delete-region (max (point-min) (1- (point-at-bol)))
24462 (point-at-eol))
24463 (end-of-line 1))))
24465 ;; Specific LaTeX stuff
24466 (when latexp
24467 (require 'org-export-latex nil)
24468 (org-export-latex-cleaned-string))
24470 (when asciip
24471 (org-export-ascii-clean-string))
24473 ;; Specific HTML stuff
24474 (when htmlp
24475 ;; Convert LaTeX fragments to images
24476 (when (plist-get parameters :LaTeX-fragments)
24477 (org-format-latex
24478 (concat "ltxpng/" (file-name-sans-extension
24479 (file-name-nondirectory
24480 org-current-export-file)))
24481 org-current-export-dir nil "Creating LaTeX image %s"))
24482 (message "Exporting..."))
24484 ;; Remove or replace comments
24485 (goto-char (point-min))
24486 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24487 (if commentsp
24488 (progn (add-text-properties
24489 (match-beginning 0) (match-end 0) '(org-protected t))
24490 (replace-match (format commentsp (match-string 1)) t t))
24491 (replace-match "")))
24493 ;; Find matches for radio targets and turn them into internal links
24494 (goto-char (point-min))
24495 (when re-radio
24496 (while (re-search-forward re-radio nil t)
24497 (org-if-unprotected
24498 (replace-match "\\1[[\\2]]"))))
24500 ;; Find all links that contain a newline and put them into a single line
24501 (goto-char (point-min))
24502 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24503 (org-if-unprotected
24504 (replace-match "\\1 \\3")
24505 (goto-char (match-beginning 0))))
24508 ;; Normalize links: Convert angle and plain links into bracket links
24509 ;; Expand link abbreviations
24510 (goto-char (point-min))
24511 (while (re-search-forward re-plain-link nil t)
24512 (goto-char (1- (match-end 0)))
24513 (org-if-unprotected
24514 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24515 ":" (match-string 3) "]]")))
24516 ;; added 'org-link face to links
24517 (put-text-property 0 (length s) 'face 'org-link s)
24518 (replace-match s t t))))
24519 (goto-char (point-min))
24520 (while (re-search-forward re-angle-link nil t)
24521 (goto-char (1- (match-end 0)))
24522 (org-if-unprotected
24523 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24524 ":" (match-string 3) "]]")))
24525 (put-text-property 0 (length s) 'face 'org-link s)
24526 (replace-match s t t))))
24527 (goto-char (point-min))
24528 (while (re-search-forward org-bracket-link-regexp nil t)
24529 (org-if-unprotected
24530 (let* ((s (concat "[[" (setq xx (save-match-data
24531 (org-link-expand-abbrev (match-string 1))))
24533 (if (match-end 3)
24534 (match-string 2)
24535 (concat "[" xx "]"))
24536 "]")))
24537 (put-text-property 0 (length s) 'face 'org-link s)
24538 (replace-match s t t))))
24540 ;; Find multiline emphasis and put them into single line
24541 (when (plist-get parameters :emph-multiline)
24542 (goto-char (point-min))
24543 (while (re-search-forward org-emph-re nil t)
24544 (if (not (= (char-after (match-beginning 3))
24545 (char-after (match-beginning 4))))
24546 (org-if-unprotected
24547 (subst-char-in-region (match-beginning 0) (match-end 0)
24548 ?\n ?\ t)
24549 (goto-char (1- (match-end 0))))
24550 (goto-char (1+ (match-beginning 0))))))
24552 (setq rtn (buffer-string)))
24553 (kill-buffer " org-mode-tmp")
24554 rtn))
24556 (defun org-export-grab-title-from-buffer ()
24557 "Get a title for the current document, from looking at the buffer."
24558 (let ((inhibit-read-only t))
24559 (save-excursion
24560 (goto-char (point-min))
24561 (let ((end (save-excursion (outline-next-heading) (point))))
24562 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24563 ;; Mark the line so that it will not be exported as normal text.
24564 (org-unmodified
24565 (add-text-properties (match-beginning 0) (match-end 0)
24566 (list :org-license-to-kill t)))
24567 ;; Return the title string
24568 (org-trim (match-string 0)))))))
24570 (defun org-export-get-title-from-subtree ()
24571 "Return subtree title and exclude it from export."
24572 (let (title (m (mark)))
24573 (save-excursion
24574 (goto-char (region-beginning))
24575 (when (and (org-at-heading-p)
24576 (>= (org-end-of-subtree t t) (region-end)))
24577 ;; This is a subtree, we take the title from the first heading
24578 (goto-char (region-beginning))
24579 (looking-at org-todo-line-regexp)
24580 (setq title (match-string 3))
24581 (org-unmodified
24582 (add-text-properties (point) (1+ (point-at-eol))
24583 (list :org-license-to-kill t)))))
24584 title))
24586 (defun org-solidify-link-text (s &optional alist)
24587 "Take link text and make a safe target out of it."
24588 (save-match-data
24589 (let* ((rtn
24590 (mapconcat
24591 'identity
24592 (org-split-string s "[ \t\r\n]+") "--"))
24593 (a (assoc rtn alist)))
24594 (or (cdr a) rtn))))
24596 (defun org-get-min-level (lines)
24597 "Get the minimum level in LINES."
24598 (let ((re "^\\(\\*+\\) ") l min)
24599 (catch 'exit
24600 (while (setq l (pop lines))
24601 (if (string-match re l)
24602 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24603 1)))
24605 ;; Variable holding the vector with section numbers
24606 (defvar org-section-numbers (make-vector org-level-max 0))
24608 (defun org-init-section-numbers ()
24609 "Initialize the vector for the section numbers."
24610 (let* ((level -1)
24611 (numbers (nreverse (org-split-string "" "\\.")))
24612 (depth (1- (length org-section-numbers)))
24613 (i depth) number-string)
24614 (while (>= i 0)
24615 (if (> i level)
24616 (aset org-section-numbers i 0)
24617 (setq number-string (or (car numbers) "0"))
24618 (if (string-match "\\`[A-Z]\\'" number-string)
24619 (aset org-section-numbers i
24620 (- (string-to-char number-string) ?A -1))
24621 (aset org-section-numbers i (string-to-number number-string)))
24622 (pop numbers))
24623 (setq i (1- i)))))
24625 (defun org-section-number (&optional level)
24626 "Return a string with the current section number.
24627 When LEVEL is non-nil, increase section numbers on that level."
24628 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24629 (when level
24630 (when (> level -1)
24631 (aset org-section-numbers
24632 level (1+ (aref org-section-numbers level))))
24633 (setq idx (1+ level))
24634 (while (<= idx depth)
24635 (if (not (= idx 1))
24636 (aset org-section-numbers idx 0))
24637 (setq idx (1+ idx))))
24638 (setq idx 0)
24639 (while (<= idx depth)
24640 (setq n (aref org-section-numbers idx))
24641 (setq string (concat string (if (not (string= string "")) "." "")
24642 (int-to-string n)))
24643 (setq idx (1+ idx)))
24644 (save-match-data
24645 (if (string-match "\\`\\([@0]\\.\\)+" string)
24646 (setq string (replace-match "" t nil string)))
24647 (if (string-match "\\(\\.0\\)+\\'" string)
24648 (setq string (replace-match "" t nil string))))
24649 string))
24651 ;;; ASCII export
24653 (defvar org-last-level nil) ; dynamically scoped variable
24654 (defvar org-min-level nil) ; dynamically scoped variable
24655 (defvar org-levels-open nil) ; dynamically scoped parameter
24656 (defvar org-ascii-current-indentation nil) ; For communication
24658 (defun org-export-as-ascii (arg)
24659 "Export the outline as a pretty ASCII file.
24660 If there is an active region, export only the region.
24661 The prefix ARG specifies how many levels of the outline should become
24662 underlined headlines. The default is 3."
24663 (interactive "P")
24664 (setq-default org-todo-line-regexp org-todo-line-regexp)
24665 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24666 (org-infile-export-plist)))
24667 (region-p (org-region-active-p))
24668 (subtree-p
24669 (when region-p
24670 (save-excursion
24671 (goto-char (region-beginning))
24672 (and (org-at-heading-p)
24673 (>= (org-end-of-subtree t t) (region-end))))))
24674 (custom-times org-display-custom-times)
24675 (org-ascii-current-indentation '(0 . 0))
24676 (level 0) line txt
24677 (umax nil)
24678 (umax-toc nil)
24679 (case-fold-search nil)
24680 (filename (concat (file-name-as-directory
24681 (org-export-directory :ascii opt-plist))
24682 (file-name-sans-extension
24683 (or (and subtree-p
24684 (org-entry-get (region-beginning)
24685 "EXPORT_FILE_NAME" t))
24686 (file-name-nondirectory buffer-file-name)))
24687 ".txt"))
24688 (filename (if (equal (file-truename filename)
24689 (file-truename buffer-file-name))
24690 (concat filename ".txt")
24691 filename))
24692 (buffer (find-file-noselect filename))
24693 (org-levels-open (make-vector org-level-max nil))
24694 (odd org-odd-levels-only)
24695 (date (plist-get opt-plist :date))
24696 (author (plist-get opt-plist :author))
24697 (title (or (and subtree-p (org-export-get-title-from-subtree))
24698 (plist-get opt-plist :title)
24699 (and (not
24700 (plist-get opt-plist :skip-before-1st-heading))
24701 (org-export-grab-title-from-buffer))
24702 (file-name-sans-extension
24703 (file-name-nondirectory buffer-file-name))))
24704 (email (plist-get opt-plist :email))
24705 (language (plist-get opt-plist :language))
24706 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24707 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24708 (todo nil)
24709 (lang-words nil)
24710 (region
24711 (buffer-substring
24712 (if (org-region-active-p) (region-beginning) (point-min))
24713 (if (org-region-active-p) (region-end) (point-max))))
24714 (lines (org-split-string
24715 (org-cleaned-string-for-export
24716 region
24717 :for-ascii t
24718 :skip-before-1st-heading
24719 (plist-get opt-plist :skip-before-1st-heading)
24720 :drawers (plist-get opt-plist :drawers)
24721 :verbatim-multiline t
24722 :archived-trees
24723 (plist-get opt-plist :archived-trees)
24724 :add-text (plist-get opt-plist :text))
24725 "\n"))
24726 thetoc have-headings first-heading-pos
24727 table-open table-buffer)
24729 (let ((inhibit-read-only t))
24730 (org-unmodified
24731 (remove-text-properties (point-min) (point-max)
24732 '(:org-license-to-kill t))))
24734 (setq org-min-level (org-get-min-level lines))
24735 (setq org-last-level org-min-level)
24736 (org-init-section-numbers)
24738 (find-file-noselect filename)
24740 (setq lang-words (or (assoc language org-export-language-setup)
24741 (assoc "en" org-export-language-setup)))
24742 (switch-to-buffer-other-window buffer)
24743 (erase-buffer)
24744 (fundamental-mode)
24745 ;; create local variables for all options, to make sure all called
24746 ;; functions get the correct information
24747 (mapc (lambda (x)
24748 (set (make-local-variable (cdr x))
24749 (plist-get opt-plist (car x))))
24750 org-export-plist-vars)
24751 (org-set-local 'org-odd-levels-only odd)
24752 (setq umax (if arg (prefix-numeric-value arg)
24753 org-export-headline-levels))
24754 (setq umax-toc (if (integerp org-export-with-toc)
24755 (min org-export-with-toc umax)
24756 umax))
24758 ;; File header
24759 (if title (org-insert-centered title ?=))
24760 (insert "\n")
24761 (if (and (or author email)
24762 org-export-author-info)
24763 (insert (concat (nth 1 lang-words) ": " (or author "")
24764 (if email (concat " <" email ">") "")
24765 "\n")))
24767 (cond
24768 ((and date (string-match "%" date))
24769 (setq date (format-time-string date (current-time))))
24770 (date)
24771 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24773 (if (and date org-export-time-stamp-file)
24774 (insert (concat (nth 2 lang-words) ": " date"\n")))
24776 (insert "\n\n")
24778 (if org-export-with-toc
24779 (progn
24780 (push (concat (nth 3 lang-words) "\n") thetoc)
24781 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24782 (mapc '(lambda (line)
24783 (if (string-match org-todo-line-regexp
24784 line)
24785 ;; This is a headline
24786 (progn
24787 (setq have-headings t)
24788 (setq level (- (match-end 1) (match-beginning 1))
24789 level (org-tr-level level)
24790 txt (match-string 3 line)
24791 todo
24792 (or (and org-export-mark-todo-in-toc
24793 (match-beginning 2)
24794 (not (member (match-string 2 line)
24795 org-done-keywords)))
24796 ; TODO, not DONE
24797 (and org-export-mark-todo-in-toc
24798 (= level umax-toc)
24799 (org-search-todo-below
24800 line lines level))))
24801 (setq txt (org-html-expand-for-ascii txt))
24803 (while (string-match org-bracket-link-regexp txt)
24804 (setq txt
24805 (replace-match
24806 (match-string (if (match-end 2) 3 1) txt)
24807 t t txt)))
24809 (if (and (memq org-export-with-tags '(not-in-toc nil))
24810 (string-match
24811 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24812 txt))
24813 (setq txt (replace-match "" t t txt)))
24814 (if (string-match quote-re0 txt)
24815 (setq txt (replace-match "" t t txt)))
24817 (if org-export-with-section-numbers
24818 (setq txt (concat (org-section-number level)
24819 " " txt)))
24820 (if (<= level umax-toc)
24821 (progn
24822 (push
24823 (concat
24824 (make-string
24825 (* (max 0 (- level org-min-level)) 4) ?\ )
24826 (format (if todo "%s (*)\n" "%s\n") txt))
24827 thetoc)
24828 (setq org-last-level level))
24829 ))))
24830 lines)
24831 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24833 (org-init-section-numbers)
24834 (while (setq line (pop lines))
24835 ;; Remove the quoted HTML tags.
24836 (setq line (org-html-expand-for-ascii line))
24837 ;; Remove targets
24838 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24839 (setq line (replace-match "" t t line)))
24840 ;; Replace internal links
24841 (while (string-match org-bracket-link-regexp line)
24842 (setq line (replace-match
24843 (if (match-end 3) "[\\3]" "[\\1]")
24844 t nil line)))
24845 (when custom-times
24846 (setq line (org-translate-time line)))
24847 (cond
24848 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24849 ;; a Headline
24850 (setq first-heading-pos (or first-heading-pos (point)))
24851 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24852 txt (match-string 2 line))
24853 (org-ascii-level-start level txt umax lines))
24855 ((and org-export-with-tables
24856 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24857 (if (not table-open)
24858 ;; New table starts
24859 (setq table-open t table-buffer nil))
24860 ;; Accumulate lines
24861 (setq table-buffer (cons line table-buffer))
24862 (when (or (not lines)
24863 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24864 (car lines))))
24865 (setq table-open nil
24866 table-buffer (nreverse table-buffer))
24867 (insert (mapconcat
24868 (lambda (x)
24869 (org-fix-indentation x org-ascii-current-indentation))
24870 (org-format-table-ascii table-buffer)
24871 "\n") "\n")))
24873 (setq line (org-fix-indentation line org-ascii-current-indentation))
24874 (if (and org-export-with-fixed-width
24875 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24876 (setq line (replace-match "\\1" nil nil line)))
24877 (insert line "\n"))))
24879 (normal-mode)
24881 ;; insert the table of contents
24882 (when thetoc
24883 (goto-char (point-min))
24884 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24885 (progn
24886 (goto-char (match-beginning 0))
24887 (replace-match ""))
24888 (goto-char first-heading-pos))
24889 (mapc 'insert thetoc)
24890 (or (looking-at "[ \t]*\n[ \t]*\n")
24891 (insert "\n\n")))
24893 ;; Convert whitespace place holders
24894 (goto-char (point-min))
24895 (let (beg end)
24896 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24897 (setq end (next-single-property-change beg 'org-whitespace))
24898 (goto-char beg)
24899 (delete-region beg end)
24900 (insert (make-string (- end beg) ?\ ))))
24902 (save-buffer)
24903 ;; remove display and invisible chars
24904 (let (beg end)
24905 (goto-char (point-min))
24906 (while (setq beg (next-single-property-change (point) 'display))
24907 (setq end (next-single-property-change beg 'display))
24908 (delete-region beg end)
24909 (goto-char beg)
24910 (insert "=>"))
24911 (goto-char (point-min))
24912 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24913 (setq end (next-single-property-change beg 'org-cwidth))
24914 (delete-region beg end)
24915 (goto-char beg)))
24916 (goto-char (point-min))))
24918 (defun org-export-ascii-clean-string ()
24919 "Do extra work for ASCII export"
24920 (goto-char (point-min))
24921 (while (re-search-forward org-verbatim-re nil t)
24922 (goto-char (match-end 2))
24923 (backward-delete-char 1) (insert "'")
24924 (goto-char (match-beginning 2))
24925 (delete-char 1) (insert "`")
24926 (goto-char (match-end 2))))
24928 (defun org-search-todo-below (line lines level)
24929 "Search the subtree below LINE for any TODO entries."
24930 (let ((rest (cdr (memq line lines)))
24931 (re org-todo-line-regexp)
24932 line lv todo)
24933 (catch 'exit
24934 (while (setq line (pop rest))
24935 (if (string-match re line)
24936 (progn
24937 (setq lv (- (match-end 1) (match-beginning 1))
24938 todo (and (match-beginning 2)
24939 (not (member (match-string 2 line)
24940 org-done-keywords))))
24941 ; TODO, not DONE
24942 (if (<= lv level) (throw 'exit nil))
24943 (if todo (throw 'exit t))))))))
24945 (defun org-html-expand-for-ascii (line)
24946 "Handle quoted HTML for ASCII export."
24947 (if org-export-html-expand
24948 (while (string-match "@<[^<>\n]*>" line)
24949 ;; We just remove the tags for now.
24950 (setq line (replace-match "" nil nil line))))
24951 line)
24953 (defun org-insert-centered (s &optional underline)
24954 "Insert the string S centered and underline it with character UNDERLINE."
24955 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24956 (insert (make-string ind ?\ ) s "\n")
24957 (if underline
24958 (insert (make-string ind ?\ )
24959 (make-string (string-width s) underline)
24960 "\n"))))
24962 (defun org-ascii-level-start (level title umax &optional lines)
24963 "Insert a new level in ASCII export."
24964 (let (char (n (- level umax 1)) (ind 0))
24965 (if (> level umax)
24966 (progn
24967 (insert (make-string (* 2 n) ?\ )
24968 (char-to-string (nth (% n (length org-export-ascii-bullets))
24969 org-export-ascii-bullets))
24970 " " title "\n")
24971 ;; find the indentation of the next non-empty line
24972 (catch 'stop
24973 (while lines
24974 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24975 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24976 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24977 (pop lines)))
24978 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24979 (if (or (not (equal (char-before) ?\n))
24980 (not (equal (char-before (1- (point))) ?\n)))
24981 (insert "\n"))
24982 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24983 (unless org-export-with-tags
24984 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24985 (setq title (replace-match "" t t title))))
24986 (if org-export-with-section-numbers
24987 (setq title (concat (org-section-number level) " " title)))
24988 (insert title "\n" (make-string (string-width title) char) "\n")
24989 (setq org-ascii-current-indentation '(0 . 0)))))
24991 (defun org-export-visible (type arg)
24992 "Create a copy of the visible part of the current buffer, and export it.
24993 The copy is created in a temporary buffer and removed after use.
24994 TYPE is the final key (as a string) that also select the export command in
24995 the `C-c C-e' export dispatcher.
24996 As a special case, if the you type SPC at the prompt, the temporary
24997 org-mode file will not be removed but presented to you so that you can
24998 continue to use it. The prefix arg ARG is passed through to the exporting
24999 command."
25000 (interactive
25001 (list (progn
25002 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
25003 (read-char-exclusive))
25004 current-prefix-arg))
25005 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
25006 (error "Invalid export key"))
25007 (let* ((binding (cdr (assoc type
25008 '((?a . org-export-as-ascii)
25009 (?\C-a . org-export-as-ascii)
25010 (?b . org-export-as-html-and-open)
25011 (?\C-b . org-export-as-html-and-open)
25012 (?h . org-export-as-html)
25013 (?H . org-export-as-html-to-buffer)
25014 (?R . org-export-region-as-html)
25015 (?x . org-export-as-xoxo)))))
25016 (keepp (equal type ?\ ))
25017 (file buffer-file-name)
25018 (buffer (get-buffer-create "*Org Export Visible*"))
25019 s e)
25020 ;; Need to hack the drawers here.
25021 (save-excursion
25022 (goto-char (point-min))
25023 (while (re-search-forward org-drawer-regexp nil t)
25024 (goto-char (match-beginning 1))
25025 (or (org-invisible-p) (org-flag-drawer nil))))
25026 (with-current-buffer buffer (erase-buffer))
25027 (save-excursion
25028 (setq s (goto-char (point-min)))
25029 (while (not (= (point) (point-max)))
25030 (goto-char (org-find-invisible))
25031 (append-to-buffer buffer s (point))
25032 (setq s (goto-char (org-find-visible))))
25033 (org-cycle-hide-drawers 'all)
25034 (goto-char (point-min))
25035 (unless keepp
25036 ;; Copy all comment lines to the end, to make sure #+ settings are
25037 ;; still available for the second export step. Kind of a hack, but
25038 ;; does do the trick.
25039 (if (looking-at "#[^\r\n]*")
25040 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
25041 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
25042 (append-to-buffer buffer (1+ (match-beginning 0))
25043 (min (point-max) (1+ (match-end 0))))))
25044 (set-buffer buffer)
25045 (let ((buffer-file-name file)
25046 (org-inhibit-startup t))
25047 (org-mode)
25048 (show-all)
25049 (unless keepp (funcall binding arg))))
25050 (if (not keepp)
25051 (kill-buffer buffer)
25052 (switch-to-buffer-other-window buffer)
25053 (goto-char (point-min)))))
25055 (defun org-find-visible ()
25056 (let ((s (point)))
25057 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25058 (get-char-property s 'invisible)))
25060 (defun org-find-invisible ()
25061 (let ((s (point)))
25062 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25063 (not (get-char-property s 'invisible))))
25066 ;;; HTML export
25068 (defun org-get-current-options ()
25069 "Return a string with current options as keyword options.
25070 Does include HTML export options as well as TODO and CATEGORY stuff."
25071 (format
25072 "#+TITLE: %s
25073 #+AUTHOR: %s
25074 #+EMAIL: %s
25075 #+LANGUAGE: %s
25076 #+TEXT: Some descriptive text to be emitted. Several lines OK.
25077 #+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
25078 #+CATEGORY: %s
25079 #+SEQ_TODO: %s
25080 #+TYP_TODO: %s
25081 #+PRIORITIES: %c %c %c
25082 #+DRAWERS: %s
25083 #+STARTUP: %s %s %s %s %s
25084 #+TAGS: %s
25085 #+ARCHIVE: %s
25086 #+LINK: %s
25088 (buffer-name) (user-full-name) user-mail-address org-export-default-language
25089 org-export-headline-levels
25090 org-export-with-section-numbers
25091 org-export-with-toc
25092 org-export-preserve-breaks
25093 org-export-html-expand
25094 org-export-with-fixed-width
25095 org-export-with-tables
25096 org-export-with-sub-superscripts
25097 org-export-with-special-strings
25098 org-export-with-footnotes
25099 org-export-with-emphasize
25100 org-export-with-TeX-macros
25101 org-export-with-LaTeX-fragments
25102 org-export-skip-text-before-1st-heading
25103 org-export-with-drawers
25104 org-export-with-tags
25105 (file-name-nondirectory buffer-file-name)
25106 "TODO FEEDBACK VERIFY DONE"
25107 "Me Jason Marie DONE"
25108 org-highest-priority org-lowest-priority org-default-priority
25109 (mapconcat 'identity org-drawers " ")
25110 (cdr (assoc org-startup-folded
25111 '((nil . "showall") (t . "overview") (content . "content"))))
25112 (if org-odd-levels-only "odd" "oddeven")
25113 (if org-hide-leading-stars "hidestars" "showstars")
25114 (if org-startup-align-all-tables "align" "noalign")
25115 (cond ((eq org-log-done t) "logdone")
25116 ((equal org-log-done 'note) "lognotedone")
25117 ((not org-log-done) "nologdone"))
25118 (or (mapconcat (lambda (x)
25119 (cond
25120 ((equal '(:startgroup) x) "{")
25121 ((equal '(:endgroup) x) "}")
25122 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
25123 (t (car x))))
25124 (or org-tag-alist (org-get-buffer-tags)) " ") "")
25125 org-archive-location
25126 "org file:~/org/%s.org"
25129 (defun org-insert-export-options-template ()
25130 "Insert into the buffer a template with information for exporting."
25131 (interactive)
25132 (if (not (bolp)) (newline))
25133 (let ((s (org-get-current-options)))
25134 (and (string-match "#\\+CATEGORY" s)
25135 (setq s (substring s 0 (match-beginning 0))))
25136 (insert s)))
25138 (defun org-toggle-fixed-width-section (arg)
25139 "Toggle the fixed-width export.
25140 If there is no active region, the QUOTE keyword at the current headline is
25141 inserted or removed. When present, it causes the text between this headline
25142 and the next to be exported as fixed-width text, and unmodified.
25143 If there is an active region, this command adds or removes a colon as the
25144 first character of this line. If the first character of a line is a colon,
25145 this line is also exported in fixed-width font."
25146 (interactive "P")
25147 (let* ((cc 0)
25148 (regionp (org-region-active-p))
25149 (beg (if regionp (region-beginning) (point)))
25150 (end (if regionp (region-end)))
25151 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
25152 (case-fold-search nil)
25153 (re "[ \t]*\\(:\\)")
25154 off)
25155 (if regionp
25156 (save-excursion
25157 (goto-char beg)
25158 (setq cc (current-column))
25159 (beginning-of-line 1)
25160 (setq off (looking-at re))
25161 (while (> nlines 0)
25162 (setq nlines (1- nlines))
25163 (beginning-of-line 1)
25164 (cond
25165 (arg
25166 (move-to-column cc t)
25167 (insert ":\n")
25168 (forward-line -1))
25169 ((and off (looking-at re))
25170 (replace-match "" t t nil 1))
25171 ((not off) (move-to-column cc t) (insert ":")))
25172 (forward-line 1)))
25173 (save-excursion
25174 (org-back-to-heading)
25175 (if (looking-at (concat outline-regexp
25176 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
25177 (replace-match "" t t nil 1)
25178 (if (looking-at outline-regexp)
25179 (progn
25180 (goto-char (match-end 0))
25181 (insert org-quote-string " "))))))))
25183 (defun org-export-as-html-and-open (arg)
25184 "Export the outline as HTML and immediately open it with a browser.
25185 If there is an active region, export only the region.
25186 The prefix ARG specifies how many levels of the outline should become
25187 headlines. The default is 3. Lower levels will become bulleted lists."
25188 (interactive "P")
25189 (org-export-as-html arg 'hidden)
25190 (org-open-file buffer-file-name))
25192 (defun org-export-as-html-batch ()
25193 "Call `org-export-as-html', may be used in batch processing as
25194 emacs --batch
25195 --load=$HOME/lib/emacs/org.el
25196 --eval \"(setq org-export-headline-levels 2)\"
25197 --visit=MyFile --funcall org-export-as-html-batch"
25198 (org-export-as-html org-export-headline-levels 'hidden))
25200 (defun org-export-as-html-to-buffer (arg)
25201 "Call `org-exort-as-html` with output to a temporary buffer.
25202 No file is created. The prefix ARG is passed through to `org-export-as-html'."
25203 (interactive "P")
25204 (org-export-as-html arg nil nil "*Org HTML Export*")
25205 (switch-to-buffer-other-window "*Org HTML Export*"))
25207 (defun org-replace-region-by-html (beg end)
25208 "Assume the current region has org-mode syntax, and convert it to HTML.
25209 This can be used in any buffer. For example, you could write an
25210 itemized list in org-mode syntax in an HTML buffer and then use this
25211 command to convert it."
25212 (interactive "r")
25213 (let (reg html buf pop-up-frames)
25214 (save-window-excursion
25215 (if (org-mode-p)
25216 (setq html (org-export-region-as-html
25217 beg end t 'string))
25218 (setq reg (buffer-substring beg end)
25219 buf (get-buffer-create "*Org tmp*"))
25220 (with-current-buffer buf
25221 (erase-buffer)
25222 (insert reg)
25223 (org-mode)
25224 (setq html (org-export-region-as-html
25225 (point-min) (point-max) t 'string)))
25226 (kill-buffer buf)))
25227 (delete-region beg end)
25228 (insert html)))
25230 (defun org-export-region-as-html (beg end &optional body-only buffer)
25231 "Convert region from BEG to END in org-mode buffer to HTML.
25232 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
25233 contents, and only produce the region of converted text, useful for
25234 cut-and-paste operations.
25235 If BUFFER is a buffer or a string, use/create that buffer as a target
25236 of the converted HTML. If BUFFER is the symbol `string', return the
25237 produced HTML as a string and leave not buffer behind. For example,
25238 a Lisp program could call this function in the following way:
25240 (setq html (org-export-region-as-html beg end t 'string))
25242 When called interactively, the output buffer is selected, and shown
25243 in a window. A non-interactive call will only retunr the buffer."
25244 (interactive "r\nP")
25245 (when (interactive-p)
25246 (setq buffer "*Org HTML Export*"))
25247 (let ((transient-mark-mode t) (zmacs-regions t)
25248 rtn)
25249 (goto-char end)
25250 (set-mark (point)) ;; to activate the region
25251 (goto-char beg)
25252 (setq rtn (org-export-as-html
25253 nil nil nil
25254 buffer body-only))
25255 (if (fboundp 'deactivate-mark) (deactivate-mark))
25256 (if (and (interactive-p) (bufferp rtn))
25257 (switch-to-buffer-other-window rtn)
25258 rtn)))
25260 (defvar html-table-tag nil) ; dynamically scoped into this.
25261 (defun org-export-as-html (arg &optional hidden ext-plist
25262 to-buffer body-only pub-dir)
25263 "Export the outline as a pretty HTML file.
25264 If there is an active region, export only the region. The prefix
25265 ARG specifies how many levels of the outline should become
25266 headlines. The default is 3. Lower levels will become bulleted
25267 lists. When HIDDEN is non-nil, don't display the HTML buffer.
25268 EXT-PLIST is a property list with external parameters overriding
25269 org-mode's default settings, but still inferior to file-local
25270 settings. When TO-BUFFER is non-nil, create a buffer with that
25271 name and export to that buffer. If TO-BUFFER is the symbol
25272 `string', don't leave any buffer behind but just return the
25273 resulting HTML as a string. When BODY-ONLY is set, don't produce
25274 the file header and footer, simply return the content of
25275 <body>...</body>, without even the body tags themselves. When
25276 PUB-DIR is set, use this as the publishing directory."
25277 (interactive "P")
25279 ;; Make sure we have a file name when we need it.
25280 (when (and (not (or to-buffer body-only))
25281 (not buffer-file-name))
25282 (if (buffer-base-buffer)
25283 (org-set-local 'buffer-file-name
25284 (with-current-buffer (buffer-base-buffer)
25285 buffer-file-name))
25286 (error "Need a file name to be able to export.")))
25288 (message "Exporting...")
25289 (setq-default org-todo-line-regexp org-todo-line-regexp)
25290 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25291 (setq-default org-done-keywords org-done-keywords)
25292 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25293 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25294 ext-plist
25295 (org-infile-export-plist)))
25297 (style (plist-get opt-plist :style))
25298 (html-extension (plist-get opt-plist :html-extension))
25299 (link-validate (plist-get opt-plist :link-validation-function))
25300 valid thetoc have-headings first-heading-pos
25301 (odd org-odd-levels-only)
25302 (region-p (org-region-active-p))
25303 (subtree-p
25304 (when region-p
25305 (save-excursion
25306 (goto-char (region-beginning))
25307 (and (org-at-heading-p)
25308 (>= (org-end-of-subtree t t) (region-end))))))
25309 ;; The following two are dynamically scoped into other
25310 ;; routines below.
25311 (org-current-export-dir
25312 (or pub-dir (org-export-directory :html opt-plist)))
25313 (org-current-export-file buffer-file-name)
25314 (level 0) (line "") (origline "") txt todo
25315 (umax nil)
25316 (umax-toc nil)
25317 (filename (if to-buffer nil
25318 (expand-file-name
25319 (concat
25320 (file-name-sans-extension
25321 (or (and subtree-p
25322 (org-entry-get (region-beginning)
25323 "EXPORT_FILE_NAME" t))
25324 (file-name-nondirectory buffer-file-name)))
25325 "." html-extension)
25326 (file-name-as-directory
25327 (or pub-dir (org-export-directory :html opt-plist))))))
25328 (current-dir (if buffer-file-name
25329 (file-name-directory buffer-file-name)
25330 default-directory))
25331 (buffer (if to-buffer
25332 (cond
25333 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25334 (t (get-buffer-create to-buffer)))
25335 (find-file-noselect filename)))
25336 (org-levels-open (make-vector org-level-max nil))
25337 (date (plist-get opt-plist :date))
25338 (author (plist-get opt-plist :author))
25339 (title (or (and subtree-p (org-export-get-title-from-subtree))
25340 (plist-get opt-plist :title)
25341 (and (not
25342 (plist-get opt-plist :skip-before-1st-heading))
25343 (org-export-grab-title-from-buffer))
25344 (and buffer-file-name
25345 (file-name-sans-extension
25346 (file-name-nondirectory buffer-file-name)))
25347 "UNTITLED"))
25348 (html-table-tag (plist-get opt-plist :html-table-tag))
25349 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25350 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25351 (inquote nil)
25352 (infixed nil)
25353 (in-local-list nil)
25354 (local-list-num nil)
25355 (local-list-indent nil)
25356 (llt org-plain-list-ordered-item-terminator)
25357 (email (plist-get opt-plist :email))
25358 (language (plist-get opt-plist :language))
25359 (lang-words nil)
25360 (target-alist nil) tg
25361 (head-count 0) cnt
25362 (start 0)
25363 (coding-system (and (boundp 'buffer-file-coding-system)
25364 buffer-file-coding-system))
25365 (coding-system-for-write (or org-export-html-coding-system
25366 coding-system))
25367 (save-buffer-coding-system (or org-export-html-coding-system
25368 coding-system))
25369 (charset (and coding-system-for-write
25370 (fboundp 'coding-system-get)
25371 (coding-system-get coding-system-for-write
25372 'mime-charset)))
25373 (region
25374 (buffer-substring
25375 (if region-p (region-beginning) (point-min))
25376 (if region-p (region-end) (point-max))))
25377 (lines
25378 (org-split-string
25379 (org-cleaned-string-for-export
25380 region
25381 :emph-multiline t
25382 :for-html t
25383 :skip-before-1st-heading
25384 (plist-get opt-plist :skip-before-1st-heading)
25385 :drawers (plist-get opt-plist :drawers)
25386 :archived-trees
25387 (plist-get opt-plist :archived-trees)
25388 :add-text
25389 (plist-get opt-plist :text)
25390 :LaTeX-fragments
25391 (plist-get opt-plist :LaTeX-fragments))
25392 "[\r\n]"))
25393 table-open type
25394 table-buffer table-orig-buffer
25395 ind start-is-num starter didclose
25396 rpl path desc descp desc1 desc2 link
25399 (let ((inhibit-read-only t))
25400 (org-unmodified
25401 (remove-text-properties (point-min) (point-max)
25402 '(:org-license-to-kill t))))
25404 (message "Exporting...")
25406 (setq org-min-level (org-get-min-level lines))
25407 (setq org-last-level org-min-level)
25408 (org-init-section-numbers)
25410 (cond
25411 ((and date (string-match "%" date))
25412 (setq date (format-time-string date (current-time))))
25413 (date)
25414 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25416 ;; Get the language-dependent settings
25417 (setq lang-words (or (assoc language org-export-language-setup)
25418 (assoc "en" org-export-language-setup)))
25420 ;; Switch to the output buffer
25421 (set-buffer buffer)
25422 (let ((inhibit-read-only t)) (erase-buffer))
25423 (fundamental-mode)
25425 (and (fboundp 'set-buffer-file-coding-system)
25426 (set-buffer-file-coding-system coding-system-for-write))
25428 (let ((case-fold-search nil)
25429 (org-odd-levels-only odd))
25430 ;; create local variables for all options, to make sure all called
25431 ;; functions get the correct information
25432 (mapc (lambda (x)
25433 (set (make-local-variable (cdr x))
25434 (plist-get opt-plist (car x))))
25435 org-export-plist-vars)
25436 (setq umax (if arg (prefix-numeric-value arg)
25437 org-export-headline-levels))
25438 (setq umax-toc (if (integerp org-export-with-toc)
25439 (min org-export-with-toc umax)
25440 umax))
25441 (unless body-only
25442 ;; File header
25443 (insert (format
25444 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25445 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25446 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25447 lang=\"%s\" xml:lang=\"%s\">
25448 <head>
25449 <title>%s</title>
25450 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25451 <meta name=\"generator\" content=\"Org-mode\"/>
25452 <meta name=\"generated\" content=\"%s\"/>
25453 <meta name=\"author\" content=\"%s\"/>
25455 </head><body>
25457 language language (org-html-expand title)
25458 (or charset "iso-8859-1") date author style))
25460 (insert (or (plist-get opt-plist :preamble) ""))
25462 (when (plist-get opt-plist :auto-preamble)
25463 (if title (insert (format org-export-html-title-format
25464 (org-html-expand title))))))
25466 (if (and org-export-with-toc (not body-only))
25467 (progn
25468 (push (format "<h%d>%s</h%d>\n"
25469 org-export-html-toplevel-hlevel
25470 (nth 3 lang-words)
25471 org-export-html-toplevel-hlevel)
25472 thetoc)
25473 (push "<ul>\n<li>" thetoc)
25474 (setq lines
25475 (mapcar '(lambda (line)
25476 (if (string-match org-todo-line-regexp line)
25477 ;; This is a headline
25478 (progn
25479 (setq have-headings t)
25480 (setq level (- (match-end 1) (match-beginning 1))
25481 level (org-tr-level level)
25482 txt (save-match-data
25483 (org-html-expand
25484 (org-export-cleanup-toc-line
25485 (match-string 3 line))))
25486 todo
25487 (or (and org-export-mark-todo-in-toc
25488 (match-beginning 2)
25489 (not (member (match-string 2 line)
25490 org-done-keywords)))
25491 ; TODO, not DONE
25492 (and org-export-mark-todo-in-toc
25493 (= level umax-toc)
25494 (org-search-todo-below
25495 line lines level))))
25496 (if (string-match
25497 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25498 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25499 (if (string-match quote-re0 txt)
25500 (setq txt (replace-match "" t t txt)))
25501 (if org-export-with-section-numbers
25502 (setq txt (concat (org-section-number level)
25503 " " txt)))
25504 (if (<= level (max umax umax-toc))
25505 (setq head-count (+ head-count 1)))
25506 (if (<= level umax-toc)
25507 (progn
25508 (if (> level org-last-level)
25509 (progn
25510 (setq cnt (- level org-last-level))
25511 (while (>= (setq cnt (1- cnt)) 0)
25512 (push "\n<ul>\n<li>" thetoc))
25513 (push "\n" thetoc)))
25514 (if (< level org-last-level)
25515 (progn
25516 (setq cnt (- org-last-level level))
25517 (while (>= (setq cnt (1- cnt)) 0)
25518 (push "</li>\n</ul>" thetoc))
25519 (push "\n" thetoc)))
25520 ;; Check for targets
25521 (while (string-match org-target-regexp line)
25522 (setq tg (match-string 1 line)
25523 line (replace-match
25524 (concat "@<span class=\"target\">" tg "@</span> ")
25525 t t line))
25526 (push (cons (org-solidify-link-text tg)
25527 (format "sec-%d" head-count))
25528 target-alist))
25529 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25530 (setq txt (replace-match "" t t txt)))
25531 (push
25532 (format
25533 (if todo
25534 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25535 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25536 head-count txt) thetoc)
25538 (setq org-last-level level))
25540 line)
25541 lines))
25542 (while (> org-last-level (1- org-min-level))
25543 (setq org-last-level (1- org-last-level))
25544 (push "</li>\n</ul>\n" thetoc))
25545 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25547 (setq head-count 0)
25548 (org-init-section-numbers)
25550 (while (setq line (pop lines) origline line)
25551 (catch 'nextline
25553 ;; end of quote section?
25554 (when (and inquote (string-match "^\\*+ " line))
25555 (insert "</pre>\n")
25556 (setq inquote nil))
25557 ;; inside a quote section?
25558 (when inquote
25559 (insert (org-html-protect line) "\n")
25560 (throw 'nextline nil))
25562 ;; verbatim lines
25563 (when (and org-export-with-fixed-width
25564 (string-match "^[ \t]*:\\(.*\\)" line))
25565 (when (not infixed)
25566 (setq infixed t)
25567 (insert "<pre>\n"))
25568 (insert (org-html-protect (match-string 1 line)) "\n")
25569 (when (and lines
25570 (not (string-match "^[ \t]*\\(:.*\\)"
25571 (car lines))))
25572 (setq infixed nil)
25573 (insert "</pre>\n"))
25574 (throw 'nextline nil))
25576 ;; Protected HTML
25577 (when (get-text-property 0 'org-protected line)
25578 (let (par)
25579 (when (re-search-backward
25580 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25581 (setq par (match-string 1))
25582 (replace-match "\\2\n"))
25583 (insert line "\n")
25584 (while (and lines
25585 (or (= (length (car lines)) 0)
25586 (get-text-property 0 'org-protected (car lines))))
25587 (insert (pop lines) "\n"))
25588 (and par (insert "<p>\n")))
25589 (throw 'nextline nil))
25591 ;; Horizontal line
25592 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25593 (insert "\n<hr/>\n")
25594 (throw 'nextline nil))
25596 ;; make targets to anchors
25597 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25598 (cond
25599 ((match-end 2)
25600 (setq line (replace-match
25601 (concat "@<a name=\""
25602 (org-solidify-link-text (match-string 1 line))
25603 "\">\\nbsp@</a>")
25604 t t line)))
25605 ((and org-export-with-toc (equal (string-to-char line) ?*))
25606 (setq line (replace-match
25607 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25608 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25609 t t line)))
25611 (setq line (replace-match
25612 (concat "@<a name=\""
25613 (org-solidify-link-text (match-string 1 line))
25614 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25615 t t line)))))
25617 (setq line (org-html-handle-time-stamps line))
25619 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25620 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25621 ;; Also handle sub_superscripts and checkboxes
25622 (or (string-match org-table-hline-regexp line)
25623 (setq line (org-html-expand line)))
25625 ;; Format the links
25626 (setq start 0)
25627 (while (string-match org-bracket-link-analytic-regexp line start)
25628 (setq start (match-beginning 0))
25629 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25630 (setq path (match-string 3 line))
25631 (setq desc1 (if (match-end 5) (match-string 5 line))
25632 desc2 (if (match-end 2) (concat type ":" path) path)
25633 descp (and desc1 (not (equal desc1 desc2)))
25634 desc (or desc1 desc2))
25635 ;; Make an image out of the description if that is so wanted
25636 (when (and descp (org-file-image-p desc))
25637 (save-match-data
25638 (if (string-match "^file:" desc)
25639 (setq desc (substring desc (match-end 0)))))
25640 (setq desc (concat "<img src=\"" desc "\"/>")))
25641 ;; FIXME: do we need to unescape here somewhere?
25642 (cond
25643 ((equal type "internal")
25644 (setq rpl
25645 (concat
25646 "<a href=\"#"
25647 (org-solidify-link-text
25648 (save-match-data (org-link-unescape path)) target-alist)
25649 "\">" desc "</a>")))
25650 ((member type '("http" "https"))
25651 ;; standard URL, just check if we need to inline an image
25652 (if (and (or (eq t org-export-html-inline-images)
25653 (and org-export-html-inline-images (not descp)))
25654 (org-file-image-p path))
25655 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25656 (setq link (concat type ":" path))
25657 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25658 ((member type '("ftp" "mailto" "news"))
25659 ;; standard URL
25660 (setq link (concat type ":" path))
25661 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25662 ((string= type "file")
25663 ;; FILE link
25664 (let* ((filename path)
25665 (abs-p (file-name-absolute-p filename))
25666 thefile file-is-image-p search)
25667 (save-match-data
25668 (if (string-match "::\\(.*\\)" filename)
25669 (setq search (match-string 1 filename)
25670 filename (replace-match "" t nil filename)))
25671 (setq valid
25672 (if (functionp link-validate)
25673 (funcall link-validate filename current-dir)
25675 (setq file-is-image-p (org-file-image-p filename))
25676 (setq thefile (if abs-p (expand-file-name filename) filename))
25677 (when (and org-export-html-link-org-files-as-html
25678 (string-match "\\.org$" thefile))
25679 (setq thefile (concat (substring thefile 0
25680 (match-beginning 0))
25681 "." html-extension))
25682 (if (and search
25683 ;; make sure this is can be used as target search
25684 (not (string-match "^[0-9]*$" search))
25685 (not (string-match "^\\*" search))
25686 (not (string-match "^/.*/$" search)))
25687 (setq thefile (concat thefile "#"
25688 (org-solidify-link-text
25689 (org-link-unescape search)))))
25690 (when (string-match "^file:" desc)
25691 (setq desc (replace-match "" t t desc))
25692 (if (string-match "\\.org$" desc)
25693 (setq desc (replace-match "" t t desc))))))
25694 (setq rpl (if (and file-is-image-p
25695 (or (eq t org-export-html-inline-images)
25696 (and org-export-html-inline-images
25697 (not descp))))
25698 (concat "<img src=\"" thefile "\"/>")
25699 (concat "<a href=\"" thefile "\">" desc "</a>")))
25700 (if (not valid) (setq rpl desc))))
25701 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25702 (setq rpl (concat "<i>&lt;" type ":"
25703 (save-match-data (org-link-unescape path))
25704 "&gt;</i>"))))
25705 (setq line (replace-match rpl t t line)
25706 start (+ start (length rpl))))
25708 ;; TODO items
25709 (if (and (string-match org-todo-line-regexp line)
25710 (match-beginning 2))
25712 (setq line
25713 (concat (substring line 0 (match-beginning 2))
25714 "<span class=\""
25715 (if (member (match-string 2 line)
25716 org-done-keywords)
25717 "done" "todo")
25718 "\">" (match-string 2 line)
25719 "</span>" (substring line (match-end 2)))))
25721 ;; Does this contain a reference to a footnote?
25722 (when org-export-with-footnotes
25723 (setq start 0)
25724 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25725 (if (get-text-property (match-beginning 2) 'org-protected line)
25726 (setq start (match-end 2))
25727 (let ((n (match-string 2 line)))
25728 (setq line
25729 (replace-match
25730 (format
25731 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25732 (match-string 1 line) n n n)
25733 t t line))))))
25735 (cond
25736 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25737 ;; This is a headline
25738 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25739 txt (match-string 2 line))
25740 (if (string-match quote-re0 txt)
25741 (setq txt (replace-match "" t t txt)))
25742 (if (<= level (max umax umax-toc))
25743 (setq head-count (+ head-count 1)))
25744 (when in-local-list
25745 ;; Close any local lists before inserting a new header line
25746 (while local-list-num
25747 (org-close-li)
25748 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25749 (pop local-list-num))
25750 (setq local-list-indent nil
25751 in-local-list nil))
25752 (setq first-heading-pos (or first-heading-pos (point)))
25753 (org-html-level-start level txt umax
25754 (and org-export-with-toc (<= level umax))
25755 head-count)
25756 ;; QUOTES
25757 (when (string-match quote-re line)
25758 (insert "<pre>")
25759 (setq inquote t)))
25761 ((and org-export-with-tables
25762 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25763 (if (not table-open)
25764 ;; New table starts
25765 (setq table-open t table-buffer nil table-orig-buffer nil))
25766 ;; Accumulate lines
25767 (setq table-buffer (cons line table-buffer)
25768 table-orig-buffer (cons origline table-orig-buffer))
25769 (when (or (not lines)
25770 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25771 (car lines))))
25772 (setq table-open nil
25773 table-buffer (nreverse table-buffer)
25774 table-orig-buffer (nreverse table-orig-buffer))
25775 (org-close-par-maybe)
25776 (insert (org-format-table-html table-buffer table-orig-buffer))))
25778 ;; Normal lines
25779 (when (string-match
25780 (cond
25781 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25782 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25783 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25784 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25785 line)
25786 (setq ind (org-get-string-indentation line)
25787 start-is-num (match-beginning 4)
25788 starter (if (match-beginning 2)
25789 (substring (match-string 2 line) 0 -1))
25790 line (substring line (match-beginning 5)))
25791 (unless (string-match "[^ \t]" line)
25792 ;; empty line. Pretend indentation is large.
25793 (setq ind (if org-empty-line-terminates-plain-lists
25795 (1+ (or (car local-list-indent) 1)))))
25796 (setq didclose nil)
25797 (while (and in-local-list
25798 (or (and (= ind (car local-list-indent))
25799 (not starter))
25800 (< ind (car local-list-indent))))
25801 (setq didclose t)
25802 (org-close-li)
25803 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25804 (pop local-list-num) (pop local-list-indent)
25805 (setq in-local-list local-list-indent))
25806 (cond
25807 ((and starter
25808 (or (not in-local-list)
25809 (> ind (car local-list-indent))))
25810 ;; Start new (level of) list
25811 (org-close-par-maybe)
25812 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25813 (push start-is-num local-list-num)
25814 (push ind local-list-indent)
25815 (setq in-local-list t))
25816 (starter
25817 ;; continue current list
25818 (org-close-li)
25819 (insert "<li>\n"))
25820 (didclose
25821 ;; we did close a list, normal text follows: need <p>
25822 (org-open-par)))
25823 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25824 (setq line
25825 (replace-match
25826 (if (equal (match-string 1 line) "X")
25827 "<b>[X]</b>"
25828 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25829 t t line))))
25831 ;; Empty lines start a new paragraph. If hand-formatted lists
25832 ;; are not fully interpreted, lines starting with "-", "+", "*"
25833 ;; also start a new paragraph.
25834 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25836 ;; Is this the start of a footnote?
25837 (when org-export-with-footnotes
25838 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25839 (org-close-par-maybe)
25840 (let ((n (match-string 1 line)))
25841 (setq line (replace-match
25842 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25844 ;; Check if the line break needs to be conserved
25845 (cond
25846 ((string-match "\\\\\\\\[ \t]*$" line)
25847 (setq line (replace-match "<br/>" t t line)))
25848 (org-export-preserve-breaks
25849 (setq line (concat line "<br/>"))))
25851 (insert line "\n")))))
25853 ;; Properly close all local lists and other lists
25854 (when inquote (insert "</pre>\n"))
25855 (when in-local-list
25856 ;; Close any local lists before inserting a new header line
25857 (while local-list-num
25858 (org-close-li)
25859 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25860 (pop local-list-num))
25861 (setq local-list-indent nil
25862 in-local-list nil))
25863 (org-html-level-start 1 nil umax
25864 (and org-export-with-toc (<= level umax))
25865 head-count)
25867 (unless body-only
25868 (when (plist-get opt-plist :auto-postamble)
25869 (insert "<div id=\"postamble\">")
25870 (when (and org-export-author-info author)
25871 (insert "<p class=\"author\"> "
25872 (nth 1 lang-words) ": " author "\n")
25873 (when email
25874 (if (listp (split-string email ",+ *"))
25875 (mapc (lambda(e)
25876 (insert "<a href=\"mailto:" e "\">&lt;"
25877 e "&gt;</a>\n"))
25878 (split-string email ",+ *"))
25879 (insert "<a href=\"mailto:" email "\">&lt;"
25880 email "&gt;</a>\n")))
25881 (insert "</p>\n"))
25882 (when (and date org-export-time-stamp-file)
25883 (insert "<p class=\"date\"> "
25884 (nth 2 lang-words) ": "
25885 date "</p>\n"))
25886 (insert "</div>"))
25888 (if org-export-html-with-timestamp
25889 (insert org-export-html-html-helper-timestamp))
25890 (insert (or (plist-get opt-plist :postamble) ""))
25891 (insert "</body>\n</html>\n"))
25893 (normal-mode)
25894 (if (eq major-mode default-major-mode) (html-mode))
25896 ;; insert the table of contents
25897 (goto-char (point-min))
25898 (when thetoc
25899 (if (or (re-search-forward
25900 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25901 (re-search-forward
25902 "\\[TABLE-OF-CONTENTS\\]" nil t))
25903 (progn
25904 (goto-char (match-beginning 0))
25905 (replace-match ""))
25906 (goto-char first-heading-pos)
25907 (when (looking-at "\\s-*</p>")
25908 (goto-char (match-end 0))
25909 (insert "\n")))
25910 (insert "<div id=\"table-of-contents\">\n")
25911 (mapc 'insert thetoc)
25912 (insert "</div>\n"))
25913 ;; remove empty paragraphs and lists
25914 (goto-char (point-min))
25915 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25916 (replace-match ""))
25917 (goto-char (point-min))
25918 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25919 (replace-match ""))
25920 (goto-char (point-min))
25921 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
25922 (replace-match ""))
25923 ;; Convert whitespace place holders
25924 (goto-char (point-min))
25925 (let (beg end n)
25926 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25927 (setq n (get-text-property beg 'org-whitespace)
25928 end (next-single-property-change beg 'org-whitespace))
25929 (goto-char beg)
25930 (delete-region beg end)
25931 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25932 (make-string n ?x)))))
25934 (or to-buffer (progn (save-buffer) (kill-buffer (current-buffer))))
25935 (goto-char (point-min))
25936 (message "Exporting... done")
25937 (if (eq to-buffer 'string)
25938 (prog1 (buffer-substring (point-min) (point-max))
25939 (kill-buffer (current-buffer)))
25940 (current-buffer)))))
25942 (defvar org-table-colgroup-info nil)
25943 (defun org-format-table-ascii (lines)
25944 "Format a table for ascii export."
25945 (if (stringp lines)
25946 (setq lines (org-split-string lines "\n")))
25947 (if (not (string-match "^[ \t]*|" (car lines)))
25948 ;; Table made by table.el - test for spanning
25949 lines
25951 ;; A normal org table
25952 ;; Get rid of hlines at beginning and end
25953 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25954 (setq lines (nreverse lines))
25955 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25956 (setq lines (nreverse lines))
25957 (when org-export-table-remove-special-lines
25958 ;; Check if the table has a marking column. If yes remove the
25959 ;; column and the special lines
25960 (setq lines (org-table-clean-before-export lines)))
25961 ;; Get rid of the vertical lines except for grouping
25962 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25963 rtn line vl1 start)
25964 (while (setq line (pop lines))
25965 (if (string-match org-table-hline-regexp line)
25966 (and (string-match "|\\(.*\\)|" line)
25967 (setq line (replace-match " \\1" t nil line)))
25968 (setq start 0 vl1 vl)
25969 (while (string-match "|" line start)
25970 (setq start (match-end 0))
25971 (or (pop vl1) (setq line (replace-match " " t t line)))))
25972 (push line rtn))
25973 (nreverse rtn))))
25975 (defun org-colgroup-info-to-vline-list (info)
25976 (let (vl new last)
25977 (while info
25978 (setq last new new (pop info))
25979 (if (or (memq last '(:end :startend))
25980 (memq new '(:start :startend)))
25981 (push t vl)
25982 (push nil vl)))
25983 (setq vl (nreverse vl))
25984 (and vl (setcar vl nil))
25985 vl))
25987 (defun org-format-table-html (lines olines)
25988 "Find out which HTML converter to use and return the HTML code."
25989 (if (stringp lines)
25990 (setq lines (org-split-string lines "\n")))
25991 (if (string-match "^[ \t]*|" (car lines))
25992 ;; A normal org table
25993 (org-format-org-table-html lines)
25994 ;; Table made by table.el - test for spanning
25995 (let* ((hlines (delq nil (mapcar
25996 (lambda (x)
25997 (if (string-match "^[ \t]*\\+-" x) x
25998 nil))
25999 lines)))
26000 (first (car hlines))
26001 (ll (and (string-match "\\S-+" first)
26002 (match-string 0 first)))
26003 (re (concat "^[ \t]*" (regexp-quote ll)))
26004 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
26005 hlines))))
26006 (if (and (not spanning)
26007 (not org-export-prefer-native-exporter-for-tables))
26008 ;; We can use my own converter with HTML conversions
26009 (org-format-table-table-html lines)
26010 ;; Need to use the code generator in table.el, with the original text.
26011 (org-format-table-table-html-using-table-generate-source olines)))))
26013 (defun org-format-org-table-html (lines &optional splice)
26014 "Format a table into HTML."
26015 ;; Get rid of hlines at beginning and end
26016 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26017 (setq lines (nreverse lines))
26018 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26019 (setq lines (nreverse lines))
26020 (when org-export-table-remove-special-lines
26021 ;; Check if the table has a marking column. If yes remove the
26022 ;; column and the special lines
26023 (setq lines (org-table-clean-before-export lines)))
26025 (let ((head (and org-export-highlight-first-table-line
26026 (delq nil (mapcar
26027 (lambda (x) (string-match "^[ \t]*|-" x))
26028 (cdr lines)))))
26029 (nlines 0) fnum i
26030 tbopen line fields html gr colgropen)
26031 (if splice (setq head nil))
26032 (unless splice (push (if head "<thead>" "<tbody>") html))
26033 (setq tbopen t)
26034 (while (setq line (pop lines))
26035 (catch 'next-line
26036 (if (string-match "^[ \t]*|-" line)
26037 (progn
26038 (unless splice
26039 (push (if head "</thead>" "</tbody>") html)
26040 (if lines (push "<tbody>" html) (setq tbopen nil)))
26041 (setq head nil) ;; head ends here, first time around
26042 ;; ignore this line
26043 (throw 'next-line t)))
26044 ;; Break the line into fields
26045 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26046 (unless fnum (setq fnum (make-vector (length fields) 0)))
26047 (setq nlines (1+ nlines) i -1)
26048 (push (concat "<tr>"
26049 (mapconcat
26050 (lambda (x)
26051 (setq i (1+ i))
26052 (if (and (< i nlines)
26053 (string-match org-table-number-regexp x))
26054 (incf (aref fnum i)))
26055 (if head
26056 (concat (car org-export-table-header-tags) x
26057 (cdr org-export-table-header-tags))
26058 (concat (car org-export-table-data-tags) x
26059 (cdr org-export-table-data-tags))))
26060 fields "")
26061 "</tr>")
26062 html)))
26063 (unless splice (if tbopen (push "</tbody>" html)))
26064 (unless splice (push "</table>\n" html))
26065 (setq html (nreverse html))
26066 (unless splice
26067 ;; Put in col tags with the alignment (unfortuntely often ignored...)
26068 (push (mapconcat
26069 (lambda (x)
26070 (setq gr (pop org-table-colgroup-info))
26071 (format "%s<col align=\"%s\"></col>%s"
26072 (if (memq gr '(:start :startend))
26073 (prog1
26074 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
26075 (setq colgropen t))
26077 (if (> (/ (float x) nlines) org-table-number-fraction)
26078 "right" "left")
26079 (if (memq gr '(:end :startend))
26080 (progn (setq colgropen nil) "</colgroup>")
26081 "")))
26082 fnum "")
26083 html)
26084 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
26085 (push html-table-tag html))
26086 (concat (mapconcat 'identity html "\n") "\n")))
26088 (defun org-table-clean-before-export (lines)
26089 "Check if the table has a marking column.
26090 If yes remove the column and the special lines."
26091 (setq org-table-colgroup-info nil)
26092 (if (memq nil
26093 (mapcar
26094 (lambda (x) (or (string-match "^[ \t]*|-" x)
26095 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
26096 lines))
26097 (progn
26098 (setq org-table-clean-did-remove-column nil)
26099 (delq nil
26100 (mapcar
26101 (lambda (x)
26102 (cond
26103 ((string-match "^[ \t]*| */ *|" x)
26104 (setq org-table-colgroup-info
26105 (mapcar (lambda (x)
26106 (cond ((member x '("<" "&lt;")) :start)
26107 ((member x '(">" "&gt;")) :end)
26108 ((member x '("<>" "&lt;&gt;")) :startend)
26109 (t nil)))
26110 (org-split-string x "[ \t]*|[ \t]*")))
26111 nil)
26112 (t x)))
26113 lines)))
26114 (setq org-table-clean-did-remove-column t)
26115 (delq nil
26116 (mapcar
26117 (lambda (x)
26118 (cond
26119 ((string-match "^[ \t]*| */ *|" x)
26120 (setq org-table-colgroup-info
26121 (mapcar (lambda (x)
26122 (cond ((member x '("<" "&lt;")) :start)
26123 ((member x '(">" "&gt;")) :end)
26124 ((member x '("<>" "&lt;&gt;")) :startend)
26125 (t nil)))
26126 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
26127 nil)
26128 ((string-match "^[ \t]*| *[!_^/] *|" x)
26129 nil) ; ignore this line
26130 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
26131 (string-match "^\\([ \t]*\\)|[^|]*|" x))
26132 ;; remove the first column
26133 (replace-match "\\1|" t nil x))))
26134 lines))))
26136 (defun org-format-table-table-html (lines)
26137 "Format a table generated by table.el into HTML.
26138 This conversion does *not* use `table-generate-source' from table.el.
26139 This has the advantage that Org-mode's HTML conversions can be used.
26140 But it has the disadvantage, that no cell- or row-spanning is allowed."
26141 (let (line field-buffer
26142 (head org-export-highlight-first-table-line)
26143 fields html empty)
26144 (setq html (concat html-table-tag "\n"))
26145 (while (setq line (pop lines))
26146 (setq empty "&nbsp;")
26147 (catch 'next-line
26148 (if (string-match "^[ \t]*\\+-" line)
26149 (progn
26150 (if field-buffer
26151 (progn
26152 (setq
26153 html
26154 (concat
26155 html
26156 "<tr>"
26157 (mapconcat
26158 (lambda (x)
26159 (if (equal x "") (setq x empty))
26160 (if head
26161 (concat (car org-export-table-header-tags) x
26162 (cdr org-export-table-header-tags))
26163 (concat (car org-export-table-data-tags) x
26164 (cdr org-export-table-data-tags))))
26165 field-buffer "\n")
26166 "</tr>\n"))
26167 (setq head nil)
26168 (setq field-buffer nil)))
26169 ;; Ignore this line
26170 (throw 'next-line t)))
26171 ;; Break the line into fields and store the fields
26172 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26173 (if field-buffer
26174 (setq field-buffer (mapcar
26175 (lambda (x)
26176 (concat x "<br/>" (pop fields)))
26177 field-buffer))
26178 (setq field-buffer fields))))
26179 (setq html (concat html "</table>\n"))
26180 html))
26182 (defun org-format-table-table-html-using-table-generate-source (lines)
26183 "Format a table into html, using `table-generate-source' from table.el.
26184 This has the advantage that cell- or row-spanning is allowed.
26185 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
26186 (require 'table)
26187 (with-current-buffer (get-buffer-create " org-tmp1 ")
26188 (erase-buffer)
26189 (insert (mapconcat 'identity lines "\n"))
26190 (goto-char (point-min))
26191 (if (not (re-search-forward "|[^+]" nil t))
26192 (error "Error processing table"))
26193 (table-recognize-table)
26194 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
26195 (table-generate-source 'html " org-tmp2 ")
26196 (set-buffer " org-tmp2 ")
26197 (buffer-substring (point-min) (point-max))))
26199 (defun org-html-handle-time-stamps (s)
26200 "Format time stamps in string S, or remove them."
26201 (catch 'exit
26202 (let (r b)
26203 (while (string-match org-maybe-keyword-time-regexp s)
26204 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
26205 ;; never export CLOCK
26206 (throw 'exit ""))
26207 (or b (setq b (substring s 0 (match-beginning 0))))
26208 (if (not org-export-with-timestamps)
26209 (setq r (concat r (substring s 0 (match-beginning 0)))
26210 s (substring s (match-end 0)))
26211 (setq r (concat
26212 r (substring s 0 (match-beginning 0))
26213 (if (match-end 1)
26214 (format "@<span class=\"timestamp-kwd\">%s @</span>"
26215 (match-string 1 s)))
26216 (format " @<span class=\"timestamp\">%s@</span>"
26217 (substring
26218 (org-translate-time (match-string 3 s)) 1 -1)))
26219 s (substring s (match-end 0)))))
26220 ;; Line break if line started and ended with time stamp stuff
26221 (if (not r)
26223 (setq r (concat r s))
26224 (unless (string-match "\\S-" (concat b s))
26225 (setq r (concat r "@<br/>")))
26226 r))))
26228 (defun org-html-protect (s)
26229 ;; convert & to &amp;, < to &lt; and > to &gt;
26230 (let ((start 0))
26231 (while (string-match "&" s start)
26232 (setq s (replace-match "&amp;" t t s)
26233 start (1+ (match-beginning 0))))
26234 (while (string-match "<" s)
26235 (setq s (replace-match "&lt;" t t s)))
26236 (while (string-match ">" s)
26237 (setq s (replace-match "&gt;" t t s))))
26240 (defun org-export-cleanup-toc-line (s)
26241 "Remove tags and time staps from lines going into the toc."
26242 (when (memq org-export-with-tags '(not-in-toc nil))
26243 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
26244 (setq s (replace-match "" t t s))))
26245 (when org-export-remove-timestamps-from-toc
26246 (while (string-match org-maybe-keyword-time-regexp s)
26247 (setq s (replace-match "" t t s))))
26248 (while (string-match org-bracket-link-regexp s)
26249 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
26250 t t s)))
26253 (defun org-html-expand (string)
26254 "Prepare STRING for HTML export. Applies all active conversions.
26255 If there are links in the string, don't modify these."
26256 (let* ((re (concat org-bracket-link-regexp "\\|"
26257 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
26258 m s l res)
26259 (while (setq m (string-match re string))
26260 (setq s (substring string 0 m)
26261 l (match-string 0 string)
26262 string (substring string (match-end 0)))
26263 (push (org-html-do-expand s) res)
26264 (push l res))
26265 (push (org-html-do-expand string) res)
26266 (apply 'concat (nreverse res))))
26268 (defun org-html-do-expand (s)
26269 "Apply all active conversions to translate special ASCII to HTML."
26270 (setq s (org-html-protect s))
26271 (if org-export-html-expand
26272 (let ((start 0))
26273 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
26274 (setq s (replace-match "<\\1>" t nil s)))))
26275 (if org-export-with-emphasize
26276 (setq s (org-export-html-convert-emphasize s)))
26277 (if org-export-with-special-strings
26278 (setq s (org-export-html-convert-special-strings s)))
26279 (if org-export-with-sub-superscripts
26280 (setq s (org-export-html-convert-sub-super s)))
26281 (if org-export-with-TeX-macros
26282 (let ((start 0) wd ass)
26283 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26284 (if (get-text-property (match-beginning 0) 'org-protected s)
26285 (setq start (match-end 0))
26286 (setq wd (match-string 1 s))
26287 (if (setq ass (assoc wd org-html-entities))
26288 (setq s (replace-match (or (cdr ass)
26289 (concat "&" (car ass) ";"))
26290 t t s))
26291 (setq start (+ start (length wd))))))))
26294 (defun org-create-multibrace-regexp (left right n)
26295 "Create a regular expression which will match a balanced sexp.
26296 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26297 as single character strings.
26298 The regexp returned will match the entire expression including the
26299 delimiters. It will also define a single group which contains the
26300 match except for the outermost delimiters. The maximum depth of
26301 stacked delimiters is N. Escaping delimiters is not possible."
26302 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26303 (or "\\|")
26304 (re nothing)
26305 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26306 (while (> n 1)
26307 (setq n (1- n)
26308 re (concat re or next)
26309 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26310 (concat left "\\(" re "\\)" right)))
26312 (defvar org-match-substring-regexp
26313 (concat
26314 "\\([^\\]\\)\\([_^]\\)\\("
26315 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26316 "\\|"
26317 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26318 "\\|"
26319 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26320 "The regular expression matching a sub- or superscript.")
26322 (defvar org-match-substring-with-braces-regexp
26323 (concat
26324 "\\([^\\]\\)\\([_^]\\)\\("
26325 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26326 "\\)")
26327 "The regular expression matching a sub- or superscript, forcing braces.")
26329 (defconst org-export-html-special-string-regexps
26330 '(("\\\\-" . "&shy;")
26331 ("---\\([^-]\\)" . "&mdash;\\1")
26332 ("--\\([^-]\\)" . "&ndash;\\1")
26333 ("\\.\\.\\." . "&hellip;"))
26334 "Regular expressions for special string conversion.")
26336 (defun org-export-html-convert-special-strings (string)
26337 "Convert special characters in STRING to HTML."
26338 (let ((all org-export-html-special-string-regexps)
26339 e a re rpl start)
26340 (while (setq a (pop all))
26341 (setq re (car a) rpl (cdr a) start 0)
26342 (while (string-match re string start)
26343 (if (get-text-property (match-beginning 0) 'org-protected string)
26344 (setq start (match-end 0))
26345 (setq string (replace-match rpl t nil string)))))
26346 string))
26348 (defun org-export-html-convert-sub-super (string)
26349 "Convert sub- and superscripts in STRING to HTML."
26350 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26351 (while (string-match org-match-substring-regexp string s)
26352 (cond
26353 ((and requireb (match-end 8)) (setq s (match-end 2)))
26354 ((get-text-property (match-beginning 2) 'org-protected string)
26355 (setq s (match-end 2)))
26357 (setq s (match-end 1)
26358 key (if (string= (match-string 2 string) "_") "sub" "sup")
26359 c (or (match-string 8 string)
26360 (match-string 6 string)
26361 (match-string 5 string))
26362 string (replace-match
26363 (concat (match-string 1 string)
26364 "<" key ">" c "</" key ">")
26365 t t string)))))
26366 (while (string-match "\\\\\\([_^]\\)" string)
26367 (setq string (replace-match (match-string 1 string) t t string)))
26368 string))
26370 (defun org-export-html-convert-emphasize (string)
26371 "Apply emphasis."
26372 (let ((s 0) rpl)
26373 (while (string-match org-emph-re string s)
26374 (if (not (equal
26375 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26376 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26377 (setq s (match-beginning 0)
26379 (concat
26380 (match-string 1 string)
26381 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26382 (match-string 4 string)
26383 (nth 3 (assoc (match-string 3 string)
26384 org-emphasis-alist))
26385 (match-string 5 string))
26386 string (replace-match rpl t t string)
26387 s (+ s (- (length rpl) 2)))
26388 (setq s (1+ s))))
26389 string))
26391 (defvar org-par-open nil)
26392 (defun org-open-par ()
26393 "Insert <p>, but first close previous paragraph if any."
26394 (org-close-par-maybe)
26395 (insert "\n<p>")
26396 (setq org-par-open t))
26397 (defun org-close-par-maybe ()
26398 "Close paragraph if there is one open."
26399 (when org-par-open
26400 (insert "</p>")
26401 (setq org-par-open nil)))
26402 (defun org-close-li ()
26403 "Close <li> if necessary."
26404 (org-close-par-maybe)
26405 (insert "</li>\n"))
26407 (defvar body-only) ; dynamically scoped into this.
26408 (defun org-html-level-start (level title umax with-toc head-count)
26409 "Insert a new level in HTML export.
26410 When TITLE is nil, just close all open levels."
26411 (org-close-par-maybe)
26412 (let ((l org-level-max))
26413 (while (>= l level)
26414 (if (aref org-levels-open (1- l))
26415 (progn
26416 (org-html-level-close l umax)
26417 (aset org-levels-open (1- l) nil)))
26418 (setq l (1- l)))
26419 (when title
26420 ;; If title is nil, this means this function is called to close
26421 ;; all levels, so the rest is done only if title is given
26422 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26423 (setq title (replace-match
26424 (if org-export-with-tags
26425 (save-match-data
26426 (concat
26427 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26428 (mapconcat 'identity (org-split-string
26429 (match-string 1 title) ":")
26430 "&nbsp;")
26431 "</span>"))
26433 t t title)))
26434 (if (> level umax)
26435 (progn
26436 (if (aref org-levels-open (1- level))
26437 (progn
26438 (org-close-li)
26439 (insert "<li>" title "<br/>\n"))
26440 (aset org-levels-open (1- level) t)
26441 (org-close-par-maybe)
26442 (insert "<ul>\n<li>" title "<br/>\n")))
26443 (aset org-levels-open (1- level) t)
26444 (if (and org-export-with-section-numbers (not body-only))
26445 (setq title (concat (org-section-number level) " " title)))
26446 (setq level (+ level org-export-html-toplevel-hlevel -1))
26447 (if with-toc
26448 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26449 level level head-count title level))
26450 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26451 (org-open-par)))))
26453 (defun org-html-level-close (level max-outline-level)
26454 "Terminate one level in HTML export."
26455 (if (<= level max-outline-level)
26456 (insert "</div>\n")
26457 (org-close-li)
26458 (insert "</ul>\n")))
26460 ;;; iCalendar export
26462 ;;;###autoload
26463 (defun org-export-icalendar-this-file ()
26464 "Export current file as an iCalendar file.
26465 The iCalendar file will be located in the same directory as the Org-mode
26466 file, but with extension `.ics'."
26467 (interactive)
26468 (org-export-icalendar nil buffer-file-name))
26470 ;;;###autoload
26471 (defun org-export-icalendar-all-agenda-files ()
26472 "Export all files in `org-agenda-files' to iCalendar .ics files.
26473 Each iCalendar file will be located in the same directory as the Org-mode
26474 file, but with extension `.ics'."
26475 (interactive)
26476 (apply 'org-export-icalendar nil (org-agenda-files t)))
26478 ;;;###autoload
26479 (defun org-export-icalendar-combine-agenda-files ()
26480 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26481 The file is stored under the name `org-combined-agenda-icalendar-file'."
26482 (interactive)
26483 (apply 'org-export-icalendar t (org-agenda-files t)))
26485 (defun org-export-icalendar (combine &rest files)
26486 "Create iCalendar files for all elements of FILES.
26487 If COMBINE is non-nil, combine all calendar entries into a single large
26488 file and store it under the name `org-combined-agenda-icalendar-file'."
26489 (save-excursion
26490 (org-prepare-agenda-buffers files)
26491 (let* ((dir (org-export-directory
26492 :ical (list :publishing-directory
26493 org-export-publishing-directory)))
26494 file ical-file ical-buffer category started org-agenda-new-buffers)
26496 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26497 (when combine
26498 (setq ical-file
26499 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26500 org-combined-agenda-icalendar-file
26501 (expand-file-name org-combined-agenda-icalendar-file dir))
26502 ical-buffer (org-get-agenda-file-buffer ical-file))
26503 (set-buffer ical-buffer) (erase-buffer))
26504 (while (setq file (pop files))
26505 (catch 'nextfile
26506 (org-check-agenda-file file)
26507 (set-buffer (org-get-agenda-file-buffer file))
26508 (unless combine
26509 (setq ical-file (concat (file-name-as-directory dir)
26510 (file-name-sans-extension
26511 (file-name-nondirectory buffer-file-name))
26512 ".ics"))
26513 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26514 (with-current-buffer ical-buffer (erase-buffer)))
26515 (setq category (or org-category
26516 (file-name-sans-extension
26517 (file-name-nondirectory buffer-file-name))))
26518 (if (symbolp category) (setq category (symbol-name category)))
26519 (let ((standard-output ical-buffer))
26520 (if combine
26521 (and (not started) (setq started t)
26522 (org-start-icalendar-file org-icalendar-combined-name))
26523 (org-start-icalendar-file category))
26524 (org-print-icalendar-entries combine)
26525 (when (or (and combine (not files)) (not combine))
26526 (org-finish-icalendar-file)
26527 (set-buffer ical-buffer)
26528 (save-buffer)
26529 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26530 (org-release-buffers org-agenda-new-buffers))))
26532 (defvar org-after-save-iCalendar-file-hook nil
26533 "Hook run after an iCalendar file has been saved.
26534 The iCalendar buffer is still current when this hook is run.
26535 A good way to use this is to tell a desktop calenndar application to re-read
26536 the iCalendar file.")
26538 (defun org-print-icalendar-entries (&optional combine)
26539 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26540 When COMBINE is non nil, add the category to each line."
26541 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26542 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26543 (dts (org-ical-ts-to-string
26544 (format-time-string (cdr org-time-stamp-formats) (current-time))
26545 "DTSTART"))
26546 hd ts ts2 state status (inc t) pos b sexp rrule
26547 scheduledp deadlinep tmp pri category entry location summary desc
26548 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26549 (org-refresh-category-properties)
26550 (save-excursion
26551 (goto-char (point-min))
26552 (while (re-search-forward re1 nil t)
26553 (catch :skip
26554 (org-agenda-skip)
26555 (setq pos (match-beginning 0)
26556 ts (match-string 0)
26557 inc t
26558 hd (org-get-heading)
26559 summary (org-icalendar-cleanup-string
26560 (org-entry-get nil "SUMMARY"))
26561 desc (org-icalendar-cleanup-string
26562 (or (org-entry-get nil "DESCRIPTION")
26563 (and org-icalendar-include-body (org-get-entry)))
26564 t org-icalendar-include-body)
26565 location (org-icalendar-cleanup-string
26566 (org-entry-get nil "LOCATION"))
26567 category (org-get-category))
26568 (if (looking-at re2)
26569 (progn
26570 (goto-char (match-end 0))
26571 (setq ts2 (match-string 1) inc nil))
26572 (setq tmp (buffer-substring (max (point-min)
26573 (- pos org-ds-keyword-length))
26574 pos)
26575 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26576 (progn
26577 (setq inc nil)
26578 (replace-match "\\1" t nil ts))
26580 deadlinep (string-match org-deadline-regexp tmp)
26581 scheduledp (string-match org-scheduled-regexp tmp)
26582 ;; donep (org-entry-is-done-p)
26584 (if (or (string-match org-tr-regexp hd)
26585 (string-match org-ts-regexp hd))
26586 (setq hd (replace-match "" t t hd)))
26587 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26588 (setq rrule
26589 (concat "\nRRULE:FREQ="
26590 (cdr (assoc
26591 (match-string 2 ts)
26592 '(("d" . "DAILY")("w" . "WEEKLY")
26593 ("m" . "MONTHLY")("y" . "YEARLY"))))
26594 ";INTERVAL=" (match-string 1 ts)))
26595 (setq rrule ""))
26596 (setq summary (or summary hd))
26597 (if (string-match org-bracket-link-regexp summary)
26598 (setq summary
26599 (replace-match (if (match-end 3)
26600 (match-string 3 summary)
26601 (match-string 1 summary))
26602 t t summary)))
26603 (if deadlinep (setq summary (concat "DL: " summary)))
26604 (if scheduledp (setq summary (concat "S: " summary)))
26605 (if (string-match "\\`<%%" ts)
26606 (with-current-buffer sexp-buffer
26607 (insert (substring ts 1 -1) " " summary "\n"))
26608 (princ (format "BEGIN:VEVENT
26610 %s%s
26611 SUMMARY:%s%s%s
26612 CATEGORIES:%s
26613 END:VEVENT\n"
26614 (org-ical-ts-to-string ts "DTSTART")
26615 (org-ical-ts-to-string ts2 "DTEND" inc)
26616 rrule summary
26617 (if (and desc (string-match "\\S-" desc))
26618 (concat "\nDESCRIPTION: " desc) "")
26619 (if (and location (string-match "\\S-" location))
26620 (concat "\nLOCATION: " location) "")
26621 category)))))
26623 (when (and org-icalendar-include-sexps
26624 (condition-case nil (require 'icalendar) (error nil))
26625 (fboundp 'icalendar-export-region))
26626 ;; Get all the literal sexps
26627 (goto-char (point-min))
26628 (while (re-search-forward "^&?%%(" nil t)
26629 (catch :skip
26630 (org-agenda-skip)
26631 (setq b (match-beginning 0))
26632 (goto-char (1- (match-end 0)))
26633 (forward-sexp 1)
26634 (end-of-line 1)
26635 (setq sexp (buffer-substring b (point)))
26636 (with-current-buffer sexp-buffer
26637 (insert sexp "\n"))
26638 (princ (org-diary-to-ical-string sexp-buffer)))))
26640 (when org-icalendar-include-todo
26641 (goto-char (point-min))
26642 (while (re-search-forward org-todo-line-regexp nil t)
26643 (catch :skip
26644 (org-agenda-skip)
26645 (setq state (match-string 2))
26646 (setq status (if (member state org-done-keywords)
26647 "COMPLETED" "NEEDS-ACTION"))
26648 (when (and state
26649 (or (not (member state org-done-keywords))
26650 (eq org-icalendar-include-todo 'all))
26651 (not (member org-archive-tag (org-get-tags-at)))
26653 (setq hd (match-string 3)
26654 summary (org-icalendar-cleanup-string
26655 (org-entry-get nil "SUMMARY"))
26656 desc (org-icalendar-cleanup-string
26657 (or (org-entry-get nil "DESCRIPTION")
26658 (and org-icalendar-include-body (org-get-entry)))
26659 t org-icalendar-include-body)
26660 location (org-icalendar-cleanup-string
26661 (org-entry-get nil "LOCATION")))
26662 (if (string-match org-bracket-link-regexp hd)
26663 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26664 (match-string 1 hd))
26665 t t hd)))
26666 (if (string-match org-priority-regexp hd)
26667 (setq pri (string-to-char (match-string 2 hd))
26668 hd (concat (substring hd 0 (match-beginning 1))
26669 (substring hd (match-end 1))))
26670 (setq pri org-default-priority))
26671 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26672 (- org-lowest-priority org-highest-priority))))))
26674 (princ (format "BEGIN:VTODO
26676 SUMMARY:%s%s%s
26677 CATEGORIES:%s
26678 SEQUENCE:1
26679 PRIORITY:%d
26680 STATUS:%s
26681 END:VTODO\n"
26683 (or summary hd)
26684 (if (and location (string-match "\\S-" location))
26685 (concat "\nLOCATION: " location) "")
26686 (if (and desc (string-match "\\S-" desc))
26687 (concat "\nDESCRIPTION: " desc) "")
26688 category pri status)))))))))
26690 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26691 "Take out stuff and quote what needs to be quoted.
26692 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26693 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26694 characters."
26695 (if (not s)
26697 (when is-body
26698 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26699 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26700 (while (string-match re s) (setq s (replace-match "" t t s)))
26701 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26702 (let ((start 0))
26703 (while (string-match "\\([,;\\]\\)" s start)
26704 (setq start (+ (match-beginning 0) 2)
26705 s (replace-match "\\\\\\1" nil nil s))))
26706 (when is-body
26707 (while (string-match "[ \t]*\n[ \t]*" s)
26708 (setq s (replace-match "\\n" t t s))))
26709 (setq s (org-trim s))
26710 (if is-body
26711 (if maxlength
26712 (if (and (numberp maxlength)
26713 (> (length s) maxlength))
26714 (setq s (substring s 0 maxlength)))))
26717 (defun org-get-entry ()
26718 "Clean-up description string."
26719 (save-excursion
26720 (org-back-to-heading t)
26721 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26723 (defun org-start-icalendar-file (name)
26724 "Start an iCalendar file by inserting the header."
26725 (let ((user user-full-name)
26726 (name (or name "unknown"))
26727 (timezone (cadr (current-time-zone))))
26728 (princ
26729 (format "BEGIN:VCALENDAR
26730 VERSION:2.0
26731 X-WR-CALNAME:%s
26732 PRODID:-//%s//Emacs with Org-mode//EN
26733 X-WR-TIMEZONE:%s
26734 CALSCALE:GREGORIAN\n" name user timezone))))
26736 (defun org-finish-icalendar-file ()
26737 "Finish an iCalendar file by inserting the END statement."
26738 (princ "END:VCALENDAR\n"))
26740 (defun org-ical-ts-to-string (s keyword &optional inc)
26741 "Take a time string S and convert it to iCalendar format.
26742 KEYWORD is added in front, to make a complete line like DTSTART....
26743 When INC is non-nil, increase the hour by two (if time string contains
26744 a time), or the day by one (if it does not contain a time)."
26745 (let ((t1 (org-parse-time-string s 'nodefault))
26746 t2 fmt have-time time)
26747 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26748 (setq t2 t1 have-time t)
26749 (setq t2 (org-parse-time-string s)))
26750 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26751 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26752 (when inc
26753 (if have-time
26754 (if org-agenda-default-appointment-duration
26755 (setq mi (+ org-agenda-default-appointment-duration mi))
26756 (setq h (+ 2 h)))
26757 (setq d (1+ d))))
26758 (setq time (encode-time s mi h d m y)))
26759 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26760 (concat keyword (format-time-string fmt time))))
26762 ;;; XOXO export
26764 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26765 (with-current-buffer buffer
26766 (apply 'insert output)))
26767 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26769 (defun org-export-as-xoxo (&optional buffer)
26770 "Export the org buffer as XOXO.
26771 The XOXO buffer is named *xoxo-<source buffer name>*"
26772 (interactive (list (current-buffer)))
26773 ;; A quickie abstraction
26775 ;; Output everything as XOXO
26776 (with-current-buffer (get-buffer buffer)
26777 (let* ((pos (point))
26778 (opt-plist (org-combine-plists (org-default-export-plist)
26779 (org-infile-export-plist)))
26780 (filename (concat (file-name-as-directory
26781 (org-export-directory :xoxo opt-plist))
26782 (file-name-sans-extension
26783 (file-name-nondirectory buffer-file-name))
26784 ".html"))
26785 (out (find-file-noselect filename))
26786 (last-level 1)
26787 (hanging-li nil))
26788 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26789 ;; Check the output buffer is empty.
26790 (with-current-buffer out (erase-buffer))
26791 ;; Kick off the output
26792 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26793 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26794 (let* ((hd (match-string-no-properties 1))
26795 (level (length hd))
26796 (text (concat
26797 (match-string-no-properties 2)
26798 (save-excursion
26799 (goto-char (match-end 0))
26800 (let ((str ""))
26801 (catch 'loop
26802 (while 't
26803 (forward-line)
26804 (if (looking-at "^[ \t]\\(.*\\)")
26805 (setq str (concat str (match-string-no-properties 1)))
26806 (throw 'loop str)))))))))
26808 ;; Handle level rendering
26809 (cond
26810 ((> level last-level)
26811 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26813 ((< level last-level)
26814 (dotimes (- (- last-level level) 1)
26815 (if hanging-li
26816 (org-export-as-xoxo-insert-into out "</li>\n"))
26817 (org-export-as-xoxo-insert-into out "</ol>\n"))
26818 (when hanging-li
26819 (org-export-as-xoxo-insert-into out "</li>\n")
26820 (setq hanging-li nil)))
26822 ((equal level last-level)
26823 (if hanging-li
26824 (org-export-as-xoxo-insert-into out "</li>\n")))
26827 (setq last-level level)
26829 ;; And output the new li
26830 (setq hanging-li 't)
26831 (if (equal ?+ (elt text 0))
26832 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26833 (org-export-as-xoxo-insert-into out "<li>" text))))
26835 ;; Finally finish off the ol
26836 (dotimes (- last-level 1)
26837 (if hanging-li
26838 (org-export-as-xoxo-insert-into out "</li>\n"))
26839 (org-export-as-xoxo-insert-into out "</ol>\n"))
26841 (goto-char pos)
26842 ;; Finish the buffer off and clean it up.
26843 (switch-to-buffer-other-window out)
26844 (indent-region (point-min) (point-max) nil)
26845 (save-buffer)
26846 (goto-char (point-min))
26850 ;;;; Key bindings
26852 ;; Make `C-c C-x' a prefix key
26853 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26855 ;; TAB key with modifiers
26856 (org-defkey org-mode-map "\C-i" 'org-cycle)
26857 (org-defkey org-mode-map [(tab)] 'org-cycle)
26858 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26859 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26860 (org-defkey org-mode-map "\M-\t" 'org-complete)
26861 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26862 ;; The following line is necessary under Suse GNU/Linux
26863 (unless (featurep 'xemacs)
26864 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26865 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26866 (define-key org-mode-map [backtab] 'org-shifttab)
26868 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26869 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26870 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26872 ;; Cursor keys with modifiers
26873 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26874 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26875 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26876 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26878 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26879 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26880 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26881 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26883 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26884 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26885 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26886 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26888 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26889 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26891 ;;; Extra keys for tty access.
26892 ;; We only set them when really needed because otherwise the
26893 ;; menus don't show the simple keys
26895 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26896 (not window-system))
26897 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26898 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26899 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26900 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26901 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26902 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26903 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26904 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26905 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26906 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26907 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26908 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26909 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26910 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26911 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26912 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26913 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26914 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26915 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26916 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26917 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26918 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26920 ;; All the other keys
26922 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26923 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26924 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26925 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26926 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26927 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26928 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26929 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26930 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26931 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26932 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26933 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26934 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26935 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26936 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26937 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26938 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26939 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26940 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26941 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26942 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26943 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26944 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26945 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26946 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26947 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26948 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26949 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26950 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26951 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26952 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26953 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26954 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26955 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26956 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26957 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26958 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26959 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26960 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26961 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
26962 (org-defkey org-mode-map "\C-c^" 'org-sort)
26963 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26964 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26965 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26966 (org-defkey org-mode-map "\C-m" 'org-return)
26967 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26968 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26969 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26970 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26971 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26972 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26973 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26974 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26975 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26976 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26977 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26978 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26979 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26980 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26981 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26982 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26984 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26985 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26986 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26987 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26989 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26990 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26991 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26992 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26993 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26994 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26995 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26996 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26997 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26998 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26999 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
27000 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
27002 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
27004 (when (featurep 'xemacs)
27005 (org-defkey org-mode-map 'button3 'popup-mode-menu))
27007 (defsubst org-table-p () (org-at-table-p))
27009 (defun org-self-insert-command (N)
27010 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
27011 If the cursor is in a table looking at whitespace, the whitespace is
27012 overwritten, and the table is not marked as requiring realignment."
27013 (interactive "p")
27014 (if (and (org-table-p)
27015 (progn
27016 ;; check if we blank the field, and if that triggers align
27017 (and org-table-auto-blank-field
27018 (member last-command
27019 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
27020 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
27021 ;; got extra space, this field does not determine column width
27022 (let (org-table-may-need-update) (org-table-blank-field))
27023 ;; no extra space, this field may determine column width
27024 (org-table-blank-field)))
27026 (eq N 1)
27027 (looking-at "[^|\n]* |"))
27028 (let (org-table-may-need-update)
27029 (goto-char (1- (match-end 0)))
27030 (delete-backward-char 1)
27031 (goto-char (match-beginning 0))
27032 (self-insert-command N))
27033 (setq org-table-may-need-update t)
27034 (self-insert-command N)
27035 (org-fix-tags-on-the-fly)))
27037 (defun org-fix-tags-on-the-fly ()
27038 (when (and (equal (char-after (point-at-bol)) ?*)
27039 (org-on-heading-p))
27040 (org-align-tags-here org-tags-column)))
27042 (defun org-delete-backward-char (N)
27043 "Like `delete-backward-char', insert whitespace at field end in tables.
27044 When deleting backwards, in tables this function will insert whitespace in
27045 front of the next \"|\" separator, to keep the table aligned. The table will
27046 still be marked for re-alignment if the field did fill the entire column,
27047 because, in this case the deletion might narrow the column."
27048 (interactive "p")
27049 (if (and (org-table-p)
27050 (eq N 1)
27051 (string-match "|" (buffer-substring (point-at-bol) (point)))
27052 (looking-at ".*?|"))
27053 (let ((pos (point))
27054 (noalign (looking-at "[^|\n\r]* |"))
27055 (c org-table-may-need-update))
27056 (backward-delete-char N)
27057 (skip-chars-forward "^|")
27058 (insert " ")
27059 (goto-char (1- pos))
27060 ;; noalign: if there were two spaces at the end, this field
27061 ;; does not determine the width of the column.
27062 (if noalign (setq org-table-may-need-update c)))
27063 (backward-delete-char N)
27064 (org-fix-tags-on-the-fly)))
27066 (defun org-delete-char (N)
27067 "Like `delete-char', but insert whitespace at field end in tables.
27068 When deleting characters, in tables this function will insert whitespace in
27069 front of the next \"|\" separator, to keep the table aligned. The table will
27070 still be marked for re-alignment if the field did fill the entire column,
27071 because, in this case the deletion might narrow the column."
27072 (interactive "p")
27073 (if (and (org-table-p)
27074 (not (bolp))
27075 (not (= (char-after) ?|))
27076 (eq N 1))
27077 (if (looking-at ".*?|")
27078 (let ((pos (point))
27079 (noalign (looking-at "[^|\n\r]* |"))
27080 (c org-table-may-need-update))
27081 (replace-match (concat
27082 (substring (match-string 0) 1 -1)
27083 " |"))
27084 (goto-char pos)
27085 ;; noalign: if there were two spaces at the end, this field
27086 ;; does not determine the width of the column.
27087 (if noalign (setq org-table-may-need-update c)))
27088 (delete-char N))
27089 (delete-char N)
27090 (org-fix-tags-on-the-fly)))
27092 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
27093 (put 'org-self-insert-command 'delete-selection t)
27094 (put 'orgtbl-self-insert-command 'delete-selection t)
27095 (put 'org-delete-char 'delete-selection 'supersede)
27096 (put 'org-delete-backward-char 'delete-selection 'supersede)
27098 ;; Make `flyspell-mode' delay after some commands
27099 (put 'org-self-insert-command 'flyspell-delayed t)
27100 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
27101 (put 'org-delete-char 'flyspell-delayed t)
27102 (put 'org-delete-backward-char 'flyspell-delayed t)
27104 ;; Make pabbrev-mode expand after org-mode commands
27105 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
27106 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
27108 ;; How to do this: Measure non-white length of current string
27109 ;; If equal to column width, we should realign.
27111 (defun org-remap (map &rest commands)
27112 "In MAP, remap the functions given in COMMANDS.
27113 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
27114 (let (new old)
27115 (while commands
27116 (setq old (pop commands) new (pop commands))
27117 (if (fboundp 'command-remapping)
27118 (org-defkey map (vector 'remap old) new)
27119 (substitute-key-definition old new map global-map)))))
27121 (when (eq org-enable-table-editor 'optimized)
27122 ;; If the user wants maximum table support, we need to hijack
27123 ;; some standard editing functions
27124 (org-remap org-mode-map
27125 'self-insert-command 'org-self-insert-command
27126 'delete-char 'org-delete-char
27127 'delete-backward-char 'org-delete-backward-char)
27128 (org-defkey org-mode-map "|" 'org-force-self-insert))
27130 (defun org-shiftcursor-error ()
27131 "Throw an error because Shift-Cursor command was applied in wrong context."
27132 (error "This command is active in special context like tables, headlines or timestamps"))
27134 (defun org-shifttab (&optional arg)
27135 "Global visibility cycling or move to previous table field.
27136 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
27137 on context.
27138 See the individual commands for more information."
27139 (interactive "P")
27140 (cond
27141 ((org-at-table-p) (call-interactively 'org-table-previous-field))
27142 (arg (message "Content view to level: ")
27143 (org-content (prefix-numeric-value arg))
27144 (setq org-cycle-global-status 'overview))
27145 (t (call-interactively 'org-global-cycle))))
27147 (defun org-shiftmetaleft ()
27148 "Promote subtree or delete table column.
27149 Calls `org-promote-subtree', `org-outdent-item',
27150 or `org-table-delete-column', depending on context.
27151 See the individual commands for more information."
27152 (interactive)
27153 (cond
27154 ((org-at-table-p) (call-interactively 'org-table-delete-column))
27155 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
27156 ((org-at-item-p) (call-interactively 'org-outdent-item))
27157 (t (org-shiftcursor-error))))
27159 (defun org-shiftmetaright ()
27160 "Demote subtree or insert table column.
27161 Calls `org-demote-subtree', `org-indent-item',
27162 or `org-table-insert-column', depending on context.
27163 See the individual commands for more information."
27164 (interactive)
27165 (cond
27166 ((org-at-table-p) (call-interactively 'org-table-insert-column))
27167 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
27168 ((org-at-item-p) (call-interactively 'org-indent-item))
27169 (t (org-shiftcursor-error))))
27171 (defun org-shiftmetaup (&optional arg)
27172 "Move subtree up or kill table row.
27173 Calls `org-move-subtree-up' or `org-table-kill-row' or
27174 `org-move-item-up' depending on context. See the individual commands
27175 for more information."
27176 (interactive "P")
27177 (cond
27178 ((org-at-table-p) (call-interactively 'org-table-kill-row))
27179 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27180 ((org-at-item-p) (call-interactively 'org-move-item-up))
27181 (t (org-shiftcursor-error))))
27182 (defun org-shiftmetadown (&optional arg)
27183 "Move subtree down or insert table row.
27184 Calls `org-move-subtree-down' or `org-table-insert-row' or
27185 `org-move-item-down', depending on context. See the individual
27186 commands for more information."
27187 (interactive "P")
27188 (cond
27189 ((org-at-table-p) (call-interactively 'org-table-insert-row))
27190 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27191 ((org-at-item-p) (call-interactively 'org-move-item-down))
27192 (t (org-shiftcursor-error))))
27194 (defun org-metaleft (&optional arg)
27195 "Promote heading or move table column to left.
27196 Calls `org-do-promote' or `org-table-move-column', depending on context.
27197 With no specific context, calls the Emacs default `backward-word'.
27198 See the individual commands for more information."
27199 (interactive "P")
27200 (cond
27201 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
27202 ((or (org-on-heading-p) (org-region-active-p))
27203 (call-interactively 'org-do-promote))
27204 ((org-at-item-p) (call-interactively 'org-outdent-item))
27205 (t (call-interactively 'backward-word))))
27207 (defun org-metaright (&optional arg)
27208 "Demote subtree or move table column to right.
27209 Calls `org-do-demote' or `org-table-move-column', depending on context.
27210 With no specific context, calls the Emacs default `forward-word'.
27211 See the individual commands for more information."
27212 (interactive "P")
27213 (cond
27214 ((org-at-table-p) (call-interactively 'org-table-move-column))
27215 ((or (org-on-heading-p) (org-region-active-p))
27216 (call-interactively 'org-do-demote))
27217 ((org-at-item-p) (call-interactively 'org-indent-item))
27218 (t (call-interactively 'forward-word))))
27220 (defun org-metaup (&optional arg)
27221 "Move subtree up or move table row up.
27222 Calls `org-move-subtree-up' or `org-table-move-row' or
27223 `org-move-item-up', depending on context. See the individual commands
27224 for more information."
27225 (interactive "P")
27226 (cond
27227 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
27228 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27229 ((org-at-item-p) (call-interactively 'org-move-item-up))
27230 (t (transpose-lines 1) (beginning-of-line -1))))
27232 (defun org-metadown (&optional arg)
27233 "Move subtree down or move table row down.
27234 Calls `org-move-subtree-down' or `org-table-move-row' or
27235 `org-move-item-down', depending on context. See the individual
27236 commands for more information."
27237 (interactive "P")
27238 (cond
27239 ((org-at-table-p) (call-interactively 'org-table-move-row))
27240 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27241 ((org-at-item-p) (call-interactively 'org-move-item-down))
27242 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
27244 (defun org-shiftup (&optional arg)
27245 "Increase item in timestamp or increase priority of current headline.
27246 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
27247 depending on context. See the individual commands for more information."
27248 (interactive "P")
27249 (cond
27250 ((org-at-timestamp-p t)
27251 (call-interactively (if org-edit-timestamp-down-means-later
27252 'org-timestamp-down 'org-timestamp-up)))
27253 ((org-on-heading-p) (call-interactively 'org-priority-up))
27254 ((org-at-item-p) (call-interactively 'org-previous-item))
27255 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
27257 (defun org-shiftdown (&optional arg)
27258 "Decrease item in timestamp or decrease priority of current headline.
27259 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
27260 depending on context. See the individual commands for more information."
27261 (interactive "P")
27262 (cond
27263 ((org-at-timestamp-p t)
27264 (call-interactively (if org-edit-timestamp-down-means-later
27265 'org-timestamp-up 'org-timestamp-down)))
27266 ((org-on-heading-p) (call-interactively 'org-priority-down))
27267 (t (call-interactively 'org-next-item))))
27269 (defun org-shiftright ()
27270 "Next TODO keyword or timestamp one day later, depending on context."
27271 (interactive)
27272 (cond
27273 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
27274 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
27275 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
27276 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
27277 (t (org-shiftcursor-error))))
27279 (defun org-shiftleft ()
27280 "Previous TODO keyword or timestamp one day earlier, depending on context."
27281 (interactive)
27282 (cond
27283 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27284 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27285 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27286 ((org-at-property-p)
27287 (call-interactively 'org-property-previous-allowed-value))
27288 (t (org-shiftcursor-error))))
27290 (defun org-shiftcontrolright ()
27291 "Switch to next TODO set."
27292 (interactive)
27293 (cond
27294 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27295 (t (org-shiftcursor-error))))
27297 (defun org-shiftcontrolleft ()
27298 "Switch to previous TODO set."
27299 (interactive)
27300 (cond
27301 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27302 (t (org-shiftcursor-error))))
27304 (defun org-ctrl-c-ret ()
27305 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27306 (interactive)
27307 (cond
27308 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27309 (t (call-interactively 'org-insert-heading))))
27311 (defun org-copy-special ()
27312 "Copy region in table or copy current subtree.
27313 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27314 See the individual commands for more information."
27315 (interactive)
27316 (call-interactively
27317 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27319 (defun org-cut-special ()
27320 "Cut region in table or cut current subtree.
27321 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27322 See the individual commands for more information."
27323 (interactive)
27324 (call-interactively
27325 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27327 (defun org-paste-special (arg)
27328 "Paste rectangular region into table, or past subtree relative to level.
27329 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27330 See the individual commands for more information."
27331 (interactive "P")
27332 (if (org-at-table-p)
27333 (org-table-paste-rectangle)
27334 (org-paste-subtree arg)))
27336 (defun org-ctrl-c-ctrl-c (&optional arg)
27337 "Set tags in headline, or update according to changed information at point.
27339 This command does many different things, depending on context:
27341 - If the cursor is in a headline, prompt for tags and insert them
27342 into the current line, aligned to `org-tags-column'. When called
27343 with prefix arg, realign all tags in the current buffer.
27345 - If the cursor is in one of the special #+KEYWORD lines, this
27346 triggers scanning the buffer for these lines and updating the
27347 information.
27349 - If the cursor is inside a table, realign the table. This command
27350 works even if the automatic table editor has been turned off.
27352 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27353 the entire table.
27355 - If the cursor is a the beginning of a dynamic block, update it.
27357 - If the cursor is inside a table created by the table.el package,
27358 activate that table.
27360 - If the current buffer is a remember buffer, close note and file it.
27361 with a prefix argument, file it without further interaction to the default
27362 location.
27364 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27365 links in this buffer.
27367 - If the cursor is on a numbered item in a plain list, renumber the
27368 ordered list.
27370 - If the cursor is on a checkbox, toggle it."
27371 (interactive "P")
27372 (let ((org-enable-table-editor t))
27373 (cond
27374 ((or org-clock-overlays
27375 org-occur-highlights
27376 org-latex-fragment-image-overlays)
27377 (org-remove-clock-overlays)
27378 (org-remove-occur-highlights)
27379 (org-remove-latex-fragment-image-overlays)
27380 (message "Temporary highlights/overlays removed from current buffer"))
27381 ((and (local-variable-p 'org-finish-function (current-buffer))
27382 (fboundp org-finish-function))
27383 (funcall org-finish-function))
27384 ((org-at-property-p)
27385 (call-interactively 'org-property-action))
27386 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27387 ((org-on-heading-p) (call-interactively 'org-set-tags))
27388 ((org-at-table.el-p)
27389 (require 'table)
27390 (beginning-of-line 1)
27391 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27392 (call-interactively 'table-recognize-table))
27393 ((org-at-table-p)
27394 (org-table-maybe-eval-formula)
27395 (if arg
27396 (call-interactively 'org-table-recalculate)
27397 (org-table-maybe-recalculate-line))
27398 (call-interactively 'org-table-align))
27399 ((org-at-item-checkbox-p)
27400 (call-interactively 'org-toggle-checkbox))
27401 ((org-at-item-p)
27402 (call-interactively 'org-maybe-renumber-ordered-list))
27403 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27404 ;; Dynamic block
27405 (beginning-of-line 1)
27406 (org-update-dblock))
27407 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27408 (cond
27409 ((equal (match-string 1) "TBLFM")
27410 ;; Recalculate the table before this line
27411 (save-excursion
27412 (beginning-of-line 1)
27413 (skip-chars-backward " \r\n\t")
27414 (if (org-at-table-p)
27415 (org-call-with-arg 'org-table-recalculate t))))
27417 (call-interactively 'org-mode-restart))))
27418 (t (error "C-c C-c can do nothing useful at this location.")))))
27420 (defun org-mode-restart ()
27421 "Restart Org-mode, to scan again for special lines.
27422 Also updates the keyword regular expressions."
27423 (interactive)
27424 (let ((org-inhibit-startup t)) (org-mode))
27425 (message "Org-mode restarted to refresh keyword and special line setup"))
27427 (defun org-kill-note-or-show-branches ()
27428 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27429 (interactive)
27430 (if (not org-finish-function)
27431 (call-interactively 'show-branches)
27432 (let ((org-note-abort t))
27433 (funcall org-finish-function))))
27435 (defun org-return (&optional indent)
27436 "Goto next table row or insert a newline.
27437 Calls `org-table-next-row' or `newline', depending on context.
27438 See the individual commands for more information."
27439 (interactive)
27440 (cond
27441 ((bobp) (if indent (newline-and-indent) (newline)))
27442 ((and (org-at-heading-p)
27443 (looking-at
27444 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27445 (org-show-entry)
27446 (end-of-line 1)
27447 (newline))
27448 ((org-at-table-p)
27449 (org-table-justify-field-maybe)
27450 (call-interactively 'org-table-next-row))
27451 (t (if indent (newline-and-indent) (newline)))))
27453 (defun org-return-indent ()
27454 "Goto next table row or insert a newline and indent.
27455 Calls `org-table-next-row' or `newline-and-indent', depending on
27456 context. See the individual commands for more information."
27457 (interactive)
27458 (org-return t))
27460 (defun org-ctrl-c-star ()
27461 "Compute table, or change heading status of lines.
27462 Calls `org-table-recalculate' or `org-toggle-region-headlines',
27463 depending on context. This will also turn a plain list item or a normal
27464 line into a subheading."
27465 (interactive)
27466 (cond
27467 ((org-at-table-p)
27468 (call-interactively 'org-table-recalculate))
27469 ((org-region-active-p)
27470 ;; Convert all lines in region to list items
27471 (call-interactively 'org-toggle-region-headings))
27472 ((org-on-heading-p)
27473 (org-toggle-region-headings (point-at-bol)
27474 (min (1+ (point-at-eol)) (point-max))))
27475 ((org-at-item-p)
27476 ;; Convert to heading
27477 ;; FIXME: not yet implemented
27479 (t (org-toggle-region-headings (point-at-bol)
27480 (min (1+ (point-at-eol)) (point-max))))))
27482 (defun org-ctrl-c-minus ()
27483 "Insert separator line in table or modify bullet status of line.
27484 Also turns a plain line or a region of lines into list items.
27485 Calls `org-table-insert-hline', `org-toggle-region-items', or
27486 `org-cycle-list-bullet', depending on context."
27487 (interactive)
27488 (cond
27489 ((org-at-table-p)
27490 (call-interactively 'org-table-insert-hline))
27491 ((org-on-heading-p)
27492 ;; Convert to item
27493 (save-excursion
27494 (beginning-of-line 1)
27495 (if (looking-at "\\*+ ")
27496 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
27497 ((org-region-active-p)
27498 ;; Convert all lines in region to list items
27499 (call-interactively 'org-toggle-region-items))
27500 ((org-in-item-p)
27501 (call-interactively 'org-cycle-list-bullet))
27502 (t (org-toggle-region-items (point-at-bol)
27503 (min (1+ (point-at-eol)) (point-max))))))
27505 (defun org-toggle-region-items (beg end)
27506 "Convert all lines in region to list items.
27507 If the first line is already an item, convert all list items in the region
27508 to normal lines."
27509 (interactive "r")
27510 (let (l2 l)
27511 (save-excursion
27512 (goto-char end)
27513 (setq l2 (org-current-line))
27514 (goto-char beg)
27515 (beginning-of-line 1)
27516 (setq l (1- (org-current-line)))
27517 (if (org-at-item-p)
27518 ;; We already have items, de-itemize
27519 (while (< (setq l (1+ l)) l2)
27520 (when (org-at-item-p)
27521 (goto-char (match-beginning 2))
27522 (delete-region (match-beginning 2) (match-end 2))
27523 (and (looking-at "[ \t]+") (replace-match "")))
27524 (beginning-of-line 2))
27525 (while (< (setq l (1+ l)) l2)
27526 (unless (org-at-item-p)
27527 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27528 (replace-match "\\1- \\2")))
27529 (beginning-of-line 2))))))
27531 (defun org-toggle-region-headings (beg end)
27532 "Convert all lines in region to list items.
27533 If the first line is already an item, convert all list items in the region
27534 to normal lines."
27535 (interactive "r")
27536 (let (l2 l)
27537 (save-excursion
27538 (goto-char end)
27539 (setq l2 (org-current-line))
27540 (goto-char beg)
27541 (beginning-of-line 1)
27542 (setq l (1- (org-current-line)))
27543 (if (org-on-heading-p)
27544 ;; We already have headlines, de-star them
27545 (while (< (setq l (1+ l)) l2)
27546 (when (org-on-heading-p t)
27547 (and (looking-at outline-regexp) (replace-match "")))
27548 (beginning-of-line 2))
27549 (let* ((stars (save-excursion
27550 (re-search-backward org-complex-heading-regexp nil t)
27551 (or (match-string 1) "*")))
27552 (add-stars (if org-odd-levels-only "**" "*"))
27553 (rpl (concat stars add-stars " \\2")))
27554 (while (< (setq l (1+ l)) l2)
27555 (unless (org-on-heading-p)
27556 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27557 (replace-match rpl)))
27558 (beginning-of-line 2)))))))
27560 (defun org-meta-return (&optional arg)
27561 "Insert a new heading or wrap a region in a table.
27562 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27563 See the individual commands for more information."
27564 (interactive "P")
27565 (cond
27566 ((org-at-table-p)
27567 (call-interactively 'org-table-wrap-region))
27568 (t (call-interactively 'org-insert-heading))))
27570 ;;; Menu entries
27572 ;; Define the Org-mode menus
27573 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27574 '("Tbl"
27575 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27576 ["Next Field" org-cycle (org-at-table-p)]
27577 ["Previous Field" org-shifttab (org-at-table-p)]
27578 ["Next Row" org-return (org-at-table-p)]
27579 "--"
27580 ["Blank Field" org-table-blank-field (org-at-table-p)]
27581 ["Edit Field" org-table-edit-field (org-at-table-p)]
27582 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27583 "--"
27584 ("Column"
27585 ["Move Column Left" org-metaleft (org-at-table-p)]
27586 ["Move Column Right" org-metaright (org-at-table-p)]
27587 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27588 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27589 ("Row"
27590 ["Move Row Up" org-metaup (org-at-table-p)]
27591 ["Move Row Down" org-metadown (org-at-table-p)]
27592 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27593 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27594 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27595 "--"
27596 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27597 ("Rectangle"
27598 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27599 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27600 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27601 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27602 "--"
27603 ("Calculate"
27604 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27605 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27606 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27607 "--"
27608 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27609 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27610 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27611 "--"
27612 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27613 "--"
27614 ["Sum Column/Rectangle" org-table-sum
27615 (or (org-at-table-p) (org-region-active-p))]
27616 ["Which Column?" org-table-current-column (org-at-table-p)])
27617 ["Debug Formulas"
27618 org-table-toggle-formula-debugger
27619 :style toggle :selected org-table-formula-debug]
27620 ["Show Col/Row Numbers"
27621 org-table-toggle-coordinate-overlays
27622 :style toggle :selected org-table-overlay-coordinates]
27623 "--"
27624 ["Create" org-table-create (and (not (org-at-table-p))
27625 org-enable-table-editor)]
27626 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27627 ["Import from File" org-table-import (not (org-at-table-p))]
27628 ["Export to File" org-table-export (org-at-table-p)]
27629 "--"
27630 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27632 (easy-menu-define org-org-menu org-mode-map "Org menu"
27633 '("Org"
27634 ("Show/Hide"
27635 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27636 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27637 ["Sparse Tree" org-occur t]
27638 ["Reveal Context" org-reveal t]
27639 ["Show All" show-all t]
27640 "--"
27641 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27642 "--"
27643 ["New Heading" org-insert-heading t]
27644 ("Navigate Headings"
27645 ["Up" outline-up-heading t]
27646 ["Next" outline-next-visible-heading t]
27647 ["Previous" outline-previous-visible-heading t]
27648 ["Next Same Level" outline-forward-same-level t]
27649 ["Previous Same Level" outline-backward-same-level t]
27650 "--"
27651 ["Jump" org-goto t])
27652 ("Edit Structure"
27653 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27654 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27655 "--"
27656 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27657 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27658 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27659 "--"
27660 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27661 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27662 ["Demote Heading" org-metaright (not (org-at-table-p))]
27663 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27664 "--"
27665 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27666 "--"
27667 ["Convert to odd levels" org-convert-to-odd-levels t]
27668 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27669 ("Editing"
27670 ["Emphasis..." org-emphasize t])
27671 ("Archive"
27672 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27673 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27674 ; :active t :keys "C-u C-c C-x C-a"]
27675 ["Sparse trees open ARCHIVE trees"
27676 (setq org-sparse-tree-open-archived-trees
27677 (not org-sparse-tree-open-archived-trees))
27678 :style toggle :selected org-sparse-tree-open-archived-trees]
27679 ["Cycling opens ARCHIVE trees"
27680 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27681 :style toggle :selected org-cycle-open-archived-trees]
27682 ["Agenda includes ARCHIVE trees"
27683 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27684 :style toggle :selected (not org-agenda-skip-archived-trees)]
27685 "--"
27686 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27687 ; ["Check and Move Children" (org-archive-subtree '(4))
27688 ; :active t :keys "C-u C-c C-x C-s"]
27690 "--"
27691 ("TODO Lists"
27692 ["TODO/DONE/-" org-todo t]
27693 ("Select keyword"
27694 ["Next keyword" org-shiftright (org-on-heading-p)]
27695 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27696 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27697 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27698 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27699 ["Show TODO Tree" org-show-todo-tree t]
27700 ["Global TODO list" org-todo-list t]
27701 "--"
27702 ["Set Priority" org-priority t]
27703 ["Priority Up" org-shiftup t]
27704 ["Priority Down" org-shiftdown t])
27705 ("TAGS and Properties"
27706 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27707 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27708 "--"
27709 ["Set property" 'org-set-property t]
27710 ["Column view of properties" org-columns t]
27711 ["Insert Column View DBlock" org-insert-columns-dblock t])
27712 ("Dates and Scheduling"
27713 ["Timestamp" org-time-stamp t]
27714 ["Timestamp (inactive)" org-time-stamp-inactive t]
27715 ("Change Date"
27716 ["1 Day Later" org-shiftright t]
27717 ["1 Day Earlier" org-shiftleft t]
27718 ["1 ... Later" org-shiftup t]
27719 ["1 ... Earlier" org-shiftdown t])
27720 ["Compute Time Range" org-evaluate-time-range t]
27721 ["Schedule Item" org-schedule t]
27722 ["Deadline" org-deadline t]
27723 "--"
27724 ["Custom time format" org-toggle-time-stamp-overlays
27725 :style radio :selected org-display-custom-times]
27726 "--"
27727 ["Goto Calendar" org-goto-calendar t]
27728 ["Date from Calendar" org-date-from-calendar t])
27729 ("Logging work"
27730 ["Clock in" org-clock-in t]
27731 ["Clock out" org-clock-out t]
27732 ["Clock cancel" org-clock-cancel t]
27733 ["Goto running clock" org-clock-goto t]
27734 ["Display times" org-clock-display t]
27735 ["Create clock table" org-clock-report t]
27736 "--"
27737 ["Record DONE time"
27738 (progn (setq org-log-done (not org-log-done))
27739 (message "Switching to %s will %s record a timestamp"
27740 (car org-done-keywords)
27741 (if org-log-done "automatically" "not")))
27742 :style toggle :selected org-log-done])
27743 "--"
27744 ["Agenda Command..." org-agenda t]
27745 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27746 ("File List for Agenda")
27747 ("Special views current file"
27748 ["TODO Tree" org-show-todo-tree t]
27749 ["Check Deadlines" org-check-deadlines t]
27750 ["Timeline" org-timeline t]
27751 ["Tags Tree" org-tags-sparse-tree t])
27752 "--"
27753 ("Hyperlinks"
27754 ["Store Link (Global)" org-store-link t]
27755 ["Insert Link" org-insert-link t]
27756 ["Follow Link" org-open-at-point t]
27757 "--"
27758 ["Next link" org-next-link t]
27759 ["Previous link" org-previous-link t]
27760 "--"
27761 ["Descriptive Links"
27762 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27763 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27764 ["Literal Links"
27765 (progn
27766 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27767 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27768 "--"
27769 ["Export/Publish..." org-export t]
27770 ("LaTeX"
27771 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27772 :selected org-cdlatex-mode]
27773 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27774 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27775 ["Modify math symbol" org-cdlatex-math-modify
27776 (org-inside-LaTeX-fragment-p)]
27777 ["Export LaTeX fragments as images"
27778 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27779 :style toggle :selected org-export-with-LaTeX-fragments])
27780 "--"
27781 ("Documentation"
27782 ["Show Version" org-version t]
27783 ["Info Documentation" org-info t])
27784 ("Customize"
27785 ["Browse Org Group" org-customize t]
27786 "--"
27787 ["Expand This Menu" org-create-customize-menu
27788 (fboundp 'customize-menu-create)])
27789 "--"
27790 ["Refresh setup" org-mode-restart t]
27793 (defun org-info (&optional node)
27794 "Read documentation for Org-mode in the info system.
27795 With optional NODE, go directly to that node."
27796 (interactive)
27797 (require 'info)
27798 (info (format "(org)%s" (or node ""))))
27800 (defun org-install-agenda-files-menu ()
27801 (let ((bl (buffer-list)))
27802 (save-excursion
27803 (while bl
27804 (set-buffer (pop bl))
27805 (if (org-mode-p) (setq bl nil)))
27806 (when (org-mode-p)
27807 (easy-menu-change
27808 '("Org") "File List for Agenda"
27809 (append
27810 (list
27811 ["Edit File List" (org-edit-agenda-file-list) t]
27812 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27813 ["Remove Current File from List" org-remove-file t]
27814 ["Cycle through agenda files" org-cycle-agenda-files t]
27815 ["Occur in all agenda files" org-occur-in-agenda-files t]
27816 "--")
27817 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27819 ;;;; Documentation
27821 (defun org-customize ()
27822 "Call the customize function with org as argument."
27823 (interactive)
27824 (customize-browse 'org))
27826 (defun org-create-customize-menu ()
27827 "Create a full customization menu for Org-mode, insert it into the menu."
27828 (interactive)
27829 (if (fboundp 'customize-menu-create)
27830 (progn
27831 (easy-menu-change
27832 '("Org") "Customize"
27833 `(["Browse Org group" org-customize t]
27834 "--"
27835 ,(customize-menu-create 'org)
27836 ["Set" Custom-set t]
27837 ["Save" Custom-save t]
27838 ["Reset to Current" Custom-reset-current t]
27839 ["Reset to Saved" Custom-reset-saved t]
27840 ["Reset to Standard Settings" Custom-reset-standard t]))
27841 (message "\"Org\"-menu now contains full customization menu"))
27842 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27844 ;;;; Miscellaneous stuff
27847 ;;; Generally useful functions
27849 (defun org-context ()
27850 "Return a list of contexts of the current cursor position.
27851 If several contexts apply, all are returned.
27852 Each context entry is a list with a symbol naming the context, and
27853 two positions indicating start and end of the context. Possible
27854 contexts are:
27856 :headline anywhere in a headline
27857 :headline-stars on the leading stars in a headline
27858 :todo-keyword on a TODO keyword (including DONE) in a headline
27859 :tags on the TAGS in a headline
27860 :priority on the priority cookie in a headline
27861 :item on the first line of a plain list item
27862 :item-bullet on the bullet/number of a plain list item
27863 :checkbox on the checkbox in a plain list item
27864 :table in an org-mode table
27865 :table-special on a special filed in a table
27866 :table-table in a table.el table
27867 :link on a hyperlink
27868 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27869 :target on a <<target>>
27870 :radio-target on a <<<radio-target>>>
27871 :latex-fragment on a LaTeX fragment
27872 :latex-preview on a LaTeX fragment with overlayed preview image
27874 This function expects the position to be visible because it uses font-lock
27875 faces as a help to recognize the following contexts: :table-special, :link,
27876 and :keyword."
27877 (let* ((f (get-text-property (point) 'face))
27878 (faces (if (listp f) f (list f)))
27879 (p (point)) clist o)
27880 ;; First the large context
27881 (cond
27882 ((org-on-heading-p t)
27883 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27884 (when (progn
27885 (beginning-of-line 1)
27886 (looking-at org-todo-line-tags-regexp))
27887 (push (org-point-in-group p 1 :headline-stars) clist)
27888 (push (org-point-in-group p 2 :todo-keyword) clist)
27889 (push (org-point-in-group p 4 :tags) clist))
27890 (goto-char p)
27891 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27892 (if (looking-at "\\[#[A-Z0-9]\\]")
27893 (push (org-point-in-group p 0 :priority) clist)))
27895 ((org-at-item-p)
27896 (push (org-point-in-group p 2 :item-bullet) clist)
27897 (push (list :item (point-at-bol)
27898 (save-excursion (org-end-of-item) (point)))
27899 clist)
27900 (and (org-at-item-checkbox-p)
27901 (push (org-point-in-group p 0 :checkbox) clist)))
27903 ((org-at-table-p)
27904 (push (list :table (org-table-begin) (org-table-end)) clist)
27905 (if (memq 'org-formula faces)
27906 (push (list :table-special
27907 (previous-single-property-change p 'face)
27908 (next-single-property-change p 'face)) clist)))
27909 ((org-at-table-p 'any)
27910 (push (list :table-table) clist)))
27911 (goto-char p)
27913 ;; Now the small context
27914 (cond
27915 ((org-at-timestamp-p)
27916 (push (org-point-in-group p 0 :timestamp) clist))
27917 ((memq 'org-link faces)
27918 (push (list :link
27919 (previous-single-property-change p 'face)
27920 (next-single-property-change p 'face)) clist))
27921 ((memq 'org-special-keyword faces)
27922 (push (list :keyword
27923 (previous-single-property-change p 'face)
27924 (next-single-property-change p 'face)) clist))
27925 ((org-on-target-p)
27926 (push (org-point-in-group p 0 :target) clist)
27927 (goto-char (1- (match-beginning 0)))
27928 (if (looking-at org-radio-target-regexp)
27929 (push (org-point-in-group p 0 :radio-target) clist))
27930 (goto-char p))
27931 ((setq o (car (delq nil
27932 (mapcar
27933 (lambda (x)
27934 (if (memq x org-latex-fragment-image-overlays) x))
27935 (org-overlays-at (point))))))
27936 (push (list :latex-fragment
27937 (org-overlay-start o) (org-overlay-end o)) clist)
27938 (push (list :latex-preview
27939 (org-overlay-start o) (org-overlay-end o)) clist))
27940 ((org-inside-LaTeX-fragment-p)
27941 ;; FIXME: positions wrong.
27942 (push (list :latex-fragment (point) (point)) clist)))
27944 (setq clist (nreverse (delq nil clist)))
27945 clist))
27947 ;; FIXME: Compare with at-regexp-p Do we need both?
27948 (defun org-in-regexp (re &optional nlines visually)
27949 "Check if point is inside a match of regexp.
27950 Normally only the current line is checked, but you can include NLINES extra
27951 lines both before and after point into the search.
27952 If VISUALLY is set, require that the cursor is not after the match but
27953 really on, so that the block visually is on the match."
27954 (catch 'exit
27955 (let ((pos (point))
27956 (eol (point-at-eol (+ 1 (or nlines 0))))
27957 (inc (if visually 1 0)))
27958 (save-excursion
27959 (beginning-of-line (- 1 (or nlines 0)))
27960 (while (re-search-forward re eol t)
27961 (if (and (<= (match-beginning 0) pos)
27962 (>= (+ inc (match-end 0)) pos))
27963 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27965 (defun org-at-regexp-p (regexp)
27966 "Is point inside a match of REGEXP in the current line?"
27967 (catch 'exit
27968 (save-excursion
27969 (let ((pos (point)) (end (point-at-eol)))
27970 (beginning-of-line 1)
27971 (while (re-search-forward regexp end t)
27972 (if (and (<= (match-beginning 0) pos)
27973 (>= (match-end 0) pos))
27974 (throw 'exit t)))
27975 nil))))
27977 (defun org-occur-in-agenda-files (regexp &optional nlines)
27978 "Call `multi-occur' with buffers for all agenda files."
27979 (interactive "sOrg-files matching: \np")
27980 (let* ((files (org-agenda-files))
27981 (tnames (mapcar 'file-truename files))
27982 (extra org-agenda-text-search-extra-files)
27984 (while (setq f (pop extra))
27985 (unless (member (file-truename f) tnames)
27986 (add-to-list 'files f 'append)
27987 (add-to-list 'tnames (file-truename f) 'append)))
27988 (multi-occur
27989 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27990 regexp)))
27992 (if (boundp 'occur-mode-find-occurrence-hook)
27993 ;; Emacs 23
27994 (add-hook 'occur-mode-find-occurrence-hook
27995 (lambda ()
27996 (when (org-mode-p)
27997 (org-reveal))))
27998 ;; Emacs 22
27999 (defadvice occur-mode-goto-occurrence
28000 (after org-occur-reveal activate)
28001 (and (org-mode-p) (org-reveal)))
28002 (defadvice occur-mode-goto-occurrence-other-window
28003 (after org-occur-reveal activate)
28004 (and (org-mode-p) (org-reveal)))
28005 (defadvice occur-mode-display-occurrence
28006 (after org-occur-reveal activate)
28007 (when (org-mode-p)
28008 (let ((pos (occur-mode-find-occurrence)))
28009 (with-current-buffer (marker-buffer pos)
28010 (save-excursion
28011 (goto-char pos)
28012 (org-reveal)))))))
28014 (defun org-uniquify (list)
28015 "Remove duplicate elements from LIST."
28016 (let (res)
28017 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
28018 res))
28020 (defun org-delete-all (elts list)
28021 "Remove all elements in ELTS from LIST."
28022 (while elts
28023 (setq list (delete (pop elts) list)))
28024 list)
28026 (defun org-back-over-empty-lines ()
28027 "Move backwards over witespace, to the beginning of the first empty line.
28028 Returns the number o empty lines passed."
28029 (let ((pos (point)))
28030 (skip-chars-backward " \t\n\r")
28031 (beginning-of-line 2)
28032 (goto-char (min (point) pos))
28033 (count-lines (point) pos)))
28035 (defun org-skip-whitespace ()
28036 (skip-chars-forward " \t\n\r"))
28038 (defun org-point-in-group (point group &optional context)
28039 "Check if POINT is in match-group GROUP.
28040 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
28041 match. If the match group does ot exist or point is not inside it,
28042 return nil."
28043 (and (match-beginning group)
28044 (>= point (match-beginning group))
28045 (<= point (match-end group))
28046 (if context
28047 (list context (match-beginning group) (match-end group))
28048 t)))
28050 (defun org-switch-to-buffer-other-window (&rest args)
28051 "Switch to buffer in a second window on the current frame.
28052 In particular, do not allow pop-up frames."
28053 (let (pop-up-frames special-display-buffer-names special-display-regexps
28054 special-display-function)
28055 (apply 'switch-to-buffer-other-window args)))
28057 (defun org-combine-plists (&rest plists)
28058 "Create a single property list from all plists in PLISTS.
28059 The process starts by copying the first list, and then setting properties
28060 from the other lists. Settings in the last list are the most significant
28061 ones and overrule settings in the other lists."
28062 (let ((rtn (copy-sequence (pop plists)))
28063 p v ls)
28064 (while plists
28065 (setq ls (pop plists))
28066 (while ls
28067 (setq p (pop ls) v (pop ls))
28068 (setq rtn (plist-put rtn p v))))
28069 rtn))
28071 (defun org-move-line-down (arg)
28072 "Move the current line down. With prefix argument, move it past ARG lines."
28073 (interactive "p")
28074 (let ((col (current-column))
28075 beg end pos)
28076 (beginning-of-line 1) (setq beg (point))
28077 (beginning-of-line 2) (setq end (point))
28078 (beginning-of-line (+ 1 arg))
28079 (setq pos (move-marker (make-marker) (point)))
28080 (insert (delete-and-extract-region beg end))
28081 (goto-char pos)
28082 (move-to-column col)))
28084 (defun org-move-line-up (arg)
28085 "Move the current line up. With prefix argument, move it past ARG lines."
28086 (interactive "p")
28087 (let ((col (current-column))
28088 beg end pos)
28089 (beginning-of-line 1) (setq beg (point))
28090 (beginning-of-line 2) (setq end (point))
28091 (beginning-of-line (- arg))
28092 (setq pos (move-marker (make-marker) (point)))
28093 (insert (delete-and-extract-region beg end))
28094 (goto-char pos)
28095 (move-to-column col)))
28097 (defun org-replace-escapes (string table)
28098 "Replace %-escapes in STRING with values in TABLE.
28099 TABLE is an association list with keys like \"%a\" and string values.
28100 The sequences in STRING may contain normal field width and padding information,
28101 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
28102 so values can contain further %-escapes if they are define later in TABLE."
28103 (let ((case-fold-search nil)
28104 e re rpl)
28105 (while (setq e (pop table))
28106 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
28107 (while (string-match re string)
28108 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
28109 (cdr e)))
28110 (setq string (replace-match rpl t t string))))
28111 string))
28114 (defun org-sublist (list start end)
28115 "Return a section of LIST, from START to END.
28116 Counting starts at 1."
28117 (let (rtn (c start))
28118 (setq list (nthcdr (1- start) list))
28119 (while (and list (<= c end))
28120 (push (pop list) rtn)
28121 (setq c (1+ c)))
28122 (nreverse rtn)))
28124 (defun org-find-base-buffer-visiting (file)
28125 "Like `find-buffer-visiting' but alway return the base buffer and
28126 not an indirect buffer"
28127 (let ((buf (find-buffer-visiting file)))
28128 (if buf
28129 (or (buffer-base-buffer buf) buf)
28130 nil)))
28132 (defun org-image-file-name-regexp ()
28133 "Return regexp matching the file names of images."
28134 (if (fboundp 'image-file-name-regexp)
28135 (image-file-name-regexp)
28136 (let ((image-file-name-extensions
28137 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
28138 "xbm" "xpm" "pbm" "pgm" "ppm")))
28139 (concat "\\."
28140 (regexp-opt (nconc (mapcar 'upcase
28141 image-file-name-extensions)
28142 image-file-name-extensions)
28144 "\\'"))))
28146 (defun org-file-image-p (file)
28147 "Return non-nil if FILE is an image."
28148 (save-match-data
28149 (string-match (org-image-file-name-regexp) file)))
28151 ;;; Paragraph filling stuff.
28152 ;; We want this to be just right, so use the full arsenal.
28154 (defun org-indent-line-function ()
28155 "Indent line like previous, but further if previous was headline or item."
28156 (interactive)
28157 (let* ((pos (point))
28158 (itemp (org-at-item-p))
28159 column bpos bcol tpos tcol bullet btype bullet-type)
28160 ;; Find the previous relevant line
28161 (beginning-of-line 1)
28162 (cond
28163 ((looking-at "#") (setq column 0))
28164 ((looking-at "\\*+ ") (setq column 0))
28166 (beginning-of-line 0)
28167 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
28168 (beginning-of-line 0))
28169 (cond
28170 ((looking-at "\\*+[ \t]+")
28171 (goto-char (match-end 0))
28172 (setq column (current-column)))
28173 ((org-in-item-p)
28174 (org-beginning-of-item)
28175 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28176 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
28177 (setq bpos (match-beginning 1) tpos (match-end 0)
28178 bcol (progn (goto-char bpos) (current-column))
28179 tcol (progn (goto-char tpos) (current-column))
28180 bullet (match-string 1)
28181 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
28182 (if (not itemp)
28183 (setq column tcol)
28184 (goto-char pos)
28185 (beginning-of-line 1)
28186 (if (looking-at "\\S-")
28187 (progn
28188 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28189 (setq bullet (match-string 1)
28190 btype (if (string-match "[0-9]" bullet) "n" bullet))
28191 (setq column (if (equal btype bullet-type) bcol tcol)))
28192 (setq column (org-get-indentation)))))
28193 (t (setq column (org-get-indentation))))))
28194 (goto-char pos)
28195 (if (<= (current-column) (current-indentation))
28196 (indent-line-to column)
28197 (save-excursion (indent-line-to column)))
28198 (setq column (current-column))
28199 (beginning-of-line 1)
28200 (if (looking-at
28201 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
28202 (replace-match (concat "\\1" (format org-property-format
28203 (match-string 2) (match-string 3)))
28204 t nil))
28205 (move-to-column column)))
28207 (defun org-set-autofill-regexps ()
28208 (interactive)
28209 ;; In the paragraph separator we include headlines, because filling
28210 ;; text in a line directly attached to a headline would otherwise
28211 ;; fill the headline as well.
28212 (org-set-local 'comment-start-skip "^#+[ \t]*")
28213 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
28214 ;; The paragraph starter includes hand-formatted lists.
28215 (org-set-local 'paragraph-start
28216 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
28217 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
28218 ;; But only if the user has not turned off tables or fixed-width regions
28219 (org-set-local
28220 'auto-fill-inhibit-regexp
28221 (concat "\\*+ \\|#\\+"
28222 "\\|[ \t]*" org-keyword-time-regexp
28223 (if (or org-enable-table-editor org-enable-fixed-width-editor)
28224 (concat
28225 "\\|[ \t]*["
28226 (if org-enable-table-editor "|" "")
28227 (if org-enable-fixed-width-editor ":" "")
28228 "]"))))
28229 ;; We use our own fill-paragraph function, to make sure that tables
28230 ;; and fixed-width regions are not wrapped. That function will pass
28231 ;; through to `fill-paragraph' when appropriate.
28232 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
28233 ; Adaptive filling: To get full control, first make sure that
28234 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
28235 (org-set-local 'adaptive-fill-regexp "\000")
28236 (org-set-local 'adaptive-fill-function
28237 'org-adaptive-fill-function)
28238 (org-set-local
28239 'align-mode-rules-list
28240 '((org-in-buffer-settings
28241 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
28242 (modes . '(org-mode))))))
28244 (defun org-fill-paragraph (&optional justify)
28245 "Re-align a table, pass through to fill-paragraph if no table."
28246 (let ((table-p (org-at-table-p))
28247 (table.el-p (org-at-table.el-p)))
28248 (cond ((and (equal (char-after (point-at-bol)) ?*)
28249 (save-excursion (goto-char (point-at-bol))
28250 (looking-at outline-regexp)))
28251 t) ; skip headlines
28252 (table.el-p t) ; skip table.el tables
28253 (table-p (org-table-align) t) ; align org-mode tables
28254 (t nil)))) ; call paragraph-fill
28256 ;; For reference, this is the default value of adaptive-fill-regexp
28257 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
28259 (defun org-adaptive-fill-function ()
28260 "Return a fill prefix for org-mode files.
28261 In particular, this makes sure hanging paragraphs for hand-formatted lists
28262 work correctly."
28263 (cond ((looking-at "#[ \t]+")
28264 (match-string 0))
28265 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
28266 (save-excursion
28267 (goto-char (match-end 0))
28268 (make-string (current-column) ?\ )))
28269 (t nil)))
28271 ;;;; Functions extending outline functionality
28274 (defun org-beginning-of-line (&optional arg)
28275 "Go to the beginning of the current line. If that is invisible, continue
28276 to a visible line beginning. This makes the function of C-a more intuitive.
28277 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28278 first attempt, and only move to after the tags when the cursor is already
28279 beyond the end of the headline."
28280 (interactive "P")
28281 (let ((pos (point)))
28282 (beginning-of-line 1)
28283 (if (bobp)
28285 (backward-char 1)
28286 (if (org-invisible-p)
28287 (while (and (not (bobp)) (org-invisible-p))
28288 (backward-char 1)
28289 (beginning-of-line 1))
28290 (forward-char 1)))
28291 (when org-special-ctrl-a/e
28292 (cond
28293 ((and (looking-at org-todo-line-regexp)
28294 (= (char-after (match-end 1)) ?\ ))
28295 (goto-char
28296 (if (eq org-special-ctrl-a/e t)
28297 (cond ((> pos (match-beginning 3)) (match-beginning 3))
28298 ((= pos (point)) (match-beginning 3))
28299 (t (point)))
28300 (cond ((> pos (point)) (point))
28301 ((not (eq last-command this-command)) (point))
28302 (t (match-beginning 3))))))
28303 ((org-at-item-p)
28304 (goto-char
28305 (if (eq org-special-ctrl-a/e t)
28306 (cond ((> pos (match-end 4)) (match-end 4))
28307 ((= pos (point)) (match-end 4))
28308 (t (point)))
28309 (cond ((> pos (point)) (point))
28310 ((not (eq last-command this-command)) (point))
28311 (t (match-end 4))))))))))
28313 (defun org-end-of-line (&optional arg)
28314 "Go to the end of the line.
28315 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28316 first attempt, and only move to after the tags when the cursor is already
28317 beyond the end of the headline."
28318 (interactive "P")
28319 (if (or (not org-special-ctrl-a/e)
28320 (not (org-on-heading-p)))
28321 (end-of-line arg)
28322 (let ((pos (point)))
28323 (beginning-of-line 1)
28324 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
28325 (if (eq org-special-ctrl-a/e t)
28326 (if (or (< pos (match-beginning 1))
28327 (= pos (match-end 0)))
28328 (goto-char (match-beginning 1))
28329 (goto-char (match-end 0)))
28330 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
28331 (goto-char (match-end 0))
28332 (goto-char (match-beginning 1))))
28333 (end-of-line arg)))))
28335 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
28336 (define-key org-mode-map "\C-e" 'org-end-of-line)
28338 (defun org-kill-line (&optional arg)
28339 "Kill line, to tags or end of line."
28340 (interactive "P")
28341 (cond
28342 ((or (not org-special-ctrl-k)
28343 (bolp)
28344 (not (org-on-heading-p)))
28345 (call-interactively 'kill-line))
28346 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
28347 (kill-region (point) (match-beginning 1))
28348 (org-set-tags nil t))
28349 (t (kill-region (point) (point-at-eol)))))
28351 (define-key org-mode-map "\C-k" 'org-kill-line)
28353 (defun org-invisible-p ()
28354 "Check if point is at a character currently not visible."
28355 ;; Early versions of noutline don't have `outline-invisible-p'.
28356 (if (fboundp 'outline-invisible-p)
28357 (outline-invisible-p)
28358 (get-char-property (point) 'invisible)))
28360 (defun org-invisible-p2 ()
28361 "Check if point is at a character currently not visible."
28362 (save-excursion
28363 (if (and (eolp) (not (bobp))) (backward-char 1))
28364 ;; Early versions of noutline don't have `outline-invisible-p'.
28365 (if (fboundp 'outline-invisible-p)
28366 (outline-invisible-p)
28367 (get-char-property (point) 'invisible))))
28369 (defalias 'org-back-to-heading 'outline-back-to-heading)
28370 (defalias 'org-on-heading-p 'outline-on-heading-p)
28371 (defalias 'org-at-heading-p 'outline-on-heading-p)
28372 (defun org-at-heading-or-item-p ()
28373 (or (org-on-heading-p) (org-at-item-p)))
28375 (defun org-on-target-p ()
28376 (or (org-in-regexp org-radio-target-regexp)
28377 (org-in-regexp org-target-regexp)))
28379 (defun org-up-heading-all (arg)
28380 "Move to the heading line of which the present line is a subheading.
28381 This function considers both visible and invisible heading lines.
28382 With argument, move up ARG levels."
28383 (if (fboundp 'outline-up-heading-all)
28384 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28385 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28387 (defun org-up-heading-safe ()
28388 "Move to the heading line of which the present line is a subheading.
28389 This version will not throw an error. It will return the level of the
28390 headline found, or nil if no higher level is found."
28391 (let ((pos (point)) start-level level
28392 (re (concat "^" outline-regexp)))
28393 (catch 'exit
28394 (outline-back-to-heading t)
28395 (setq start-level (funcall outline-level))
28396 (if (equal start-level 1) (throw 'exit nil))
28397 (while (re-search-backward re nil t)
28398 (setq level (funcall outline-level))
28399 (if (< level start-level) (throw 'exit level)))
28400 nil)))
28402 (defun org-first-sibling-p ()
28403 "Is this heading the first child of its parents?"
28404 (interactive)
28405 (let ((re (concat "^" outline-regexp))
28406 level l)
28407 (unless (org-at-heading-p t)
28408 (error "Not at a heading"))
28409 (setq level (funcall outline-level))
28410 (save-excursion
28411 (if (not (re-search-backward re nil t))
28413 (setq l (funcall outline-level))
28414 (< l level)))))
28416 (defun org-goto-sibling (&optional previous)
28417 "Goto the next sibling, even if it is invisible.
28418 When PREVIOUS is set, go to the previous sibling instead. Returns t
28419 when a sibling was found. When none is found, return nil and don't
28420 move point."
28421 (let ((fun (if previous 're-search-backward 're-search-forward))
28422 (pos (point))
28423 (re (concat "^" outline-regexp))
28424 level l)
28425 (when (condition-case nil (org-back-to-heading t) (error nil))
28426 (setq level (funcall outline-level))
28427 (catch 'exit
28428 (or previous (forward-char 1))
28429 (while (funcall fun re nil t)
28430 (setq l (funcall outline-level))
28431 (when (< l level) (goto-char pos) (throw 'exit nil))
28432 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28433 (goto-char pos)
28434 nil))))
28436 (defun org-show-siblings ()
28437 "Show all siblings of the current headline."
28438 (save-excursion
28439 (while (org-goto-sibling) (org-flag-heading nil)))
28440 (save-excursion
28441 (while (org-goto-sibling 'previous)
28442 (org-flag-heading nil))))
28444 (defun org-show-hidden-entry ()
28445 "Show an entry where even the heading is hidden."
28446 (save-excursion
28447 (org-show-entry)))
28449 (defun org-flag-heading (flag &optional entry)
28450 "Flag the current heading. FLAG non-nil means make invisible.
28451 When ENTRY is non-nil, show the entire entry."
28452 (save-excursion
28453 (org-back-to-heading t)
28454 ;; Check if we should show the entire entry
28455 (if entry
28456 (progn
28457 (org-show-entry)
28458 (save-excursion
28459 (and (outline-next-heading)
28460 (org-flag-heading nil))))
28461 (outline-flag-region (max (point-min) (1- (point)))
28462 (save-excursion (outline-end-of-heading) (point))
28463 flag))))
28465 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28466 ;; This is an exact copy of the original function, but it uses
28467 ;; `org-back-to-heading', to make it work also in invisible
28468 ;; trees. And is uses an invisible-OK argument.
28469 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28470 (org-back-to-heading invisible-OK)
28471 (let ((first t)
28472 (level (funcall outline-level)))
28473 (while (and (not (eobp))
28474 (or first (> (funcall outline-level) level)))
28475 (setq first nil)
28476 (outline-next-heading))
28477 (unless to-heading
28478 (if (memq (preceding-char) '(?\n ?\^M))
28479 (progn
28480 ;; Go to end of line before heading
28481 (forward-char -1)
28482 (if (memq (preceding-char) '(?\n ?\^M))
28483 ;; leave blank line before heading
28484 (forward-char -1))))))
28485 (point))
28487 (defun org-show-subtree ()
28488 "Show everything after this heading at deeper levels."
28489 (outline-flag-region
28490 (point)
28491 (save-excursion
28492 (outline-end-of-subtree) (outline-next-heading) (point))
28493 nil))
28495 (defun org-show-entry ()
28496 "Show the body directly following this heading.
28497 Show the heading too, if it is currently invisible."
28498 (interactive)
28499 (save-excursion
28500 (condition-case nil
28501 (progn
28502 (org-back-to-heading t)
28503 (outline-flag-region
28504 (max (point-min) (1- (point)))
28505 (save-excursion
28506 (re-search-forward
28507 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28508 (or (match-beginning 1) (point-max)))
28509 nil))
28510 (error nil))))
28512 (defun org-make-options-regexp (kwds)
28513 "Make a regular expression for keyword lines."
28514 (concat
28516 "#?[ \t]*\\+\\("
28517 (mapconcat 'regexp-quote kwds "\\|")
28518 "\\):[ \t]*"
28519 "\\(.+\\)"))
28521 ;; Make isearch reveal the necessary context
28522 (defun org-isearch-end ()
28523 "Reveal context after isearch exits."
28524 (when isearch-success ; only if search was successful
28525 (if (featurep 'xemacs)
28526 ;; Under XEmacs, the hook is run in the correct place,
28527 ;; we directly show the context.
28528 (org-show-context 'isearch)
28529 ;; In Emacs the hook runs *before* restoring the overlays.
28530 ;; So we have to use a one-time post-command-hook to do this.
28531 ;; (Emacs 22 has a special variable, see function `org-mode')
28532 (unless (and (boundp 'isearch-mode-end-hook-quit)
28533 isearch-mode-end-hook-quit)
28534 ;; Only when the isearch was not quitted.
28535 (org-add-hook 'post-command-hook 'org-isearch-post-command
28536 'append 'local)))))
28538 (defun org-isearch-post-command ()
28539 "Remove self from hook, and show context."
28540 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28541 (org-show-context 'isearch))
28544 ;;;; Integration with and fixes for other packages
28546 ;;; Imenu support
28548 (defvar org-imenu-markers nil
28549 "All markers currently used by Imenu.")
28550 (make-variable-buffer-local 'org-imenu-markers)
28552 (defun org-imenu-new-marker (&optional pos)
28553 "Return a new marker for use by Imenu, and remember the marker."
28554 (let ((m (make-marker)))
28555 (move-marker m (or pos (point)))
28556 (push m org-imenu-markers)
28559 (defun org-imenu-get-tree ()
28560 "Produce the index for Imenu."
28561 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28562 (setq org-imenu-markers nil)
28563 (let* ((n org-imenu-depth)
28564 (re (concat "^" outline-regexp))
28565 (subs (make-vector (1+ n) nil))
28566 (last-level 0)
28567 m tree level head)
28568 (save-excursion
28569 (save-restriction
28570 (widen)
28571 (goto-char (point-max))
28572 (while (re-search-backward re nil t)
28573 (setq level (org-reduced-level (funcall outline-level)))
28574 (when (<= level n)
28575 (looking-at org-complex-heading-regexp)
28576 (setq head (org-match-string-no-properties 4)
28577 m (org-imenu-new-marker))
28578 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28579 (if (>= level last-level)
28580 (push (cons head m) (aref subs level))
28581 (push (cons head (aref subs (1+ level))) (aref subs level))
28582 (loop for i from (1+ level) to n do (aset subs i nil)))
28583 (setq last-level level)))))
28584 (aref subs 1)))
28586 (eval-after-load "imenu"
28587 '(progn
28588 (add-hook 'imenu-after-jump-hook
28589 (lambda () (org-show-context 'org-goto)))))
28591 ;; Speedbar support
28593 (defun org-speedbar-set-agenda-restriction ()
28594 "Restrict future agenda commands to the location at point in speedbar.
28595 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28596 (interactive)
28597 (let (p m tp np dir txt w)
28598 (cond
28599 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28600 'org-imenu t))
28601 (setq m (get-text-property p 'org-imenu-marker))
28602 (save-excursion
28603 (save-restriction
28604 (set-buffer (marker-buffer m))
28605 (goto-char m)
28606 (org-agenda-set-restriction-lock 'subtree))))
28607 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28608 'speedbar-function 'speedbar-find-file))
28609 (setq tp (previous-single-property-change
28610 (1+ p) 'speedbar-function)
28611 np (next-single-property-change
28612 tp 'speedbar-function)
28613 dir (speedbar-line-directory)
28614 txt (buffer-substring-no-properties (or tp (point-min))
28615 (or np (point-max))))
28616 (save-excursion
28617 (save-restriction
28618 (set-buffer (find-file-noselect
28619 (let ((default-directory dir))
28620 (expand-file-name txt))))
28621 (unless (org-mode-p)
28622 (error "Cannot restrict to non-Org-mode file"))
28623 (org-agenda-set-restriction-lock 'file))))
28624 (t (error "Don't know how to restrict Org-mode's agenda")))
28625 (org-move-overlay org-speedbar-restriction-lock-overlay
28626 (point-at-bol) (point-at-eol))
28627 (setq current-prefix-arg nil)
28628 (org-agenda-maybe-redo)))
28630 (eval-after-load "speedbar"
28631 '(progn
28632 (speedbar-add-supported-extension ".org")
28633 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28634 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28635 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28636 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28637 (add-hook 'speedbar-visiting-tag-hook
28638 (lambda () (org-show-context 'org-goto)))))
28641 ;;; Fixes and Hacks
28643 ;; Make flyspell not check words in links, to not mess up our keymap
28644 (defun org-mode-flyspell-verify ()
28645 "Don't let flyspell put overlays at active buttons."
28646 (not (get-text-property (point) 'keymap)))
28648 ;; Make `bookmark-jump' show the jump location if it was hidden.
28649 (eval-after-load "bookmark"
28650 '(if (boundp 'bookmark-after-jump-hook)
28651 ;; We can use the hook
28652 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28653 ;; Hook not available, use advice
28654 (defadvice bookmark-jump (after org-make-visible activate)
28655 "Make the position visible."
28656 (org-bookmark-jump-unhide))))
28658 (defun org-bookmark-jump-unhide ()
28659 "Unhide the current position, to show the bookmark location."
28660 (and (org-mode-p)
28661 (or (org-invisible-p)
28662 (save-excursion (goto-char (max (point-min) (1- (point))))
28663 (org-invisible-p)))
28664 (org-show-context 'bookmark-jump)))
28666 ;; Fix a bug in htmlize where there are text properties (face nil)
28667 (eval-after-load "htmlize"
28668 '(progn
28669 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28670 "Make sure there are no nil faces"
28671 (setq ad-return-value (delq nil ad-return-value)))))
28673 ;; Make session.el ignore our circular variable
28674 (eval-after-load "session"
28675 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28677 ;;;; Experimental code
28679 (defun org-closed-in-range ()
28680 "Sparse tree of items closed in a certain time range.
28681 Still experimental, may disappear in the future."
28682 (interactive)
28683 ;; Get the time interval from the user.
28684 (let* ((time1 (time-to-seconds
28685 (org-read-date nil 'to-time nil "Starting date: ")))
28686 (time2 (time-to-seconds
28687 (org-read-date nil 'to-time nil "End date:")))
28688 ;; callback function
28689 (callback (lambda ()
28690 (let ((time
28691 (time-to-seconds
28692 (apply 'encode-time
28693 (org-parse-time-string
28694 (match-string 1))))))
28695 ;; check if time in interval
28696 (and (>= time time1) (<= time time2))))))
28697 ;; make tree, check each match with the callback
28698 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28700 ;;;; Finish up
28702 (provide 'org)
28704 (run-hooks 'org-load-hook)
28706 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28707 ;;; org.el ends here