Made transition to new value type easier.
[org-mode.git] / org.el
blobed9da3705dfc341beb776354411c021ca4b38532
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 :get '(lambda (var) ; Make sure all entries have 5 elements
1977 (if (integerp (default-value var))
1978 (list (default-value var) 5)
1979 (default-value var)))
1980 :type '(list
1981 (integer :tag "when inserting times")
1982 (integer :tag "when modifying times")))
1984 (defcustom org-display-custom-times nil
1985 "Non-nil means, overlay custom formats over all time stamps.
1986 The formats are defined through the variable `org-time-stamp-custom-formats'.
1987 To turn this on on a per-file basis, insert anywhere in the file:
1988 #+STARTUP: customtime"
1989 :group 'org-time
1990 :set 'set-default
1991 :type 'sexp)
1992 (make-variable-buffer-local 'org-display-custom-times)
1994 (defcustom org-time-stamp-custom-formats
1995 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1996 "Custom formats for time stamps. See `format-time-string' for the syntax.
1997 These are overlayed over the default ISO format if the variable
1998 `org-display-custom-times' is set. Time like %H:%M should be at the
1999 end of the second format."
2000 :group 'org-time
2001 :type 'sexp)
2003 (defun org-time-stamp-format (&optional long inactive)
2004 "Get the right format for a time string."
2005 (let ((f (if long (cdr org-time-stamp-formats)
2006 (car org-time-stamp-formats))))
2007 (if inactive
2008 (concat "[" (substring f 1 -1) "]")
2009 f)))
2011 (defcustom org-read-date-prefer-future t
2012 "Non-nil means, assume future for incomplete date input from user.
2013 This affects the following situations:
2014 1. The user gives a day, but no month.
2015 For example, if today is the 15th, and you enter \"3\", Org-mode will
2016 read this as the third of *next* month. However, if you enter \"17\",
2017 it will be considered as *this* month.
2018 2. The user gives a month but not a year.
2019 For example, if it is april and you enter \"feb 2\", this will be read
2020 as feb 2, *next* year. \"May 5\", however, will be this year.
2022 When this option is nil, the current month and year will always be used
2023 as defaults."
2024 :group 'org-time
2025 :type 'boolean)
2027 (defcustom org-read-date-display-live t
2028 "Non-nil means, display current interpretation of date prompt live.
2029 This display will be in an overlay, in the minibuffer."
2030 :group 'org-time
2031 :type 'boolean)
2033 (defcustom org-read-date-popup-calendar t
2034 "Non-nil means, pop up a calendar when prompting for a date.
2035 In the calendar, the date can be selected with mouse-1. However, the
2036 minibuffer will also be active, and you can simply enter the date as well.
2037 When nil, only the minibuffer will be available."
2038 :group 'org-time
2039 :type 'boolean)
2040 (if (fboundp 'defvaralias)
2041 (defvaralias 'org-popup-calendar-for-date-prompt
2042 'org-read-date-popup-calendar))
2044 (defcustom org-extend-today-until 0
2045 "The hour when your day really ends.
2046 This has influence for the following applications:
2047 - When switching the agenda to \"today\". It it is still earlier than
2048 the time given here, the day recognized as TODAY is actually yesterday.
2049 - When a date is read from the user and it is still before the time given
2050 here, the current date and time will be assumed to be yesterday, 23:59.
2052 FIXME:
2053 IMPORTANT: This is still a very experimental feature, it may disappear
2054 again or it may be extended to mean more things."
2055 :group 'org-time
2056 :type 'number)
2058 (defcustom org-edit-timestamp-down-means-later nil
2059 "Non-nil means, S-down will increase the time in a time stamp.
2060 When nil, S-up will increase."
2061 :group 'org-time
2062 :type 'boolean)
2064 (defcustom org-calendar-follow-timestamp-change t
2065 "Non-nil means, make the calendar window follow timestamp changes.
2066 When a timestamp is modified and the calendar window is visible, it will be
2067 moved to the new date."
2068 :group 'org-time
2069 :type 'boolean)
2071 (defcustom org-clock-heading-function nil
2072 "When non-nil, should be a function to create `org-clock-heading'.
2073 This is the string shown in the mode line when a clock is running.
2074 The function is called with point at the beginning of the headline."
2075 :group 'org-time ; FIXME: Should we have a separate group????
2076 :type 'function)
2078 (defgroup org-tags nil
2079 "Options concerning tags in Org-mode."
2080 :tag "Org Tags"
2081 :group 'org)
2083 (defcustom org-tag-alist nil
2084 "List of tags allowed in Org-mode files.
2085 When this list is nil, Org-mode will base TAG input on what is already in the
2086 buffer.
2087 The value of this variable is an alist, the car of each entry must be a
2088 keyword as a string, the cdr may be a character that is used to select
2089 that tag through the fast-tag-selection interface.
2090 See the manual for details."
2091 :group 'org-tags
2092 :type '(repeat
2093 (choice
2094 (cons (string :tag "Tag name")
2095 (character :tag "Access char"))
2096 (const :tag "Start radio group" (:startgroup))
2097 (const :tag "End radio group" (:endgroup)))))
2099 (defcustom org-use-fast-tag-selection 'auto
2100 "Non-nil means, use fast tag selection scheme.
2101 This is a special interface to select and deselect tags with single keys.
2102 When nil, fast selection is never used.
2103 When the symbol `auto', fast selection is used if and only if selection
2104 characters for tags have been configured, either through the variable
2105 `org-tag-alist' or through a #+TAGS line in the buffer.
2106 When t, fast selection is always used and selection keys are assigned
2107 automatically if necessary."
2108 :group 'org-tags
2109 :type '(choice
2110 (const :tag "Always" t)
2111 (const :tag "Never" nil)
2112 (const :tag "When selection characters are configured" 'auto)))
2114 (defcustom org-fast-tag-selection-single-key nil
2115 "Non-nil means, fast tag selection exits after first change.
2116 When nil, you have to press RET to exit it.
2117 During fast tag selection, you can toggle this flag with `C-c'.
2118 This variable can also have the value `expert'. In this case, the window
2119 displaying the tags menu is not even shown, until you press C-c again."
2120 :group 'org-tags
2121 :type '(choice
2122 (const :tag "No" nil)
2123 (const :tag "Yes" t)
2124 (const :tag "Expert" expert)))
2126 (defvar org-fast-tag-selection-include-todo nil
2127 "Non-nil means, fast tags selection interface will also offer TODO states.
2128 This is an undocumented feature, you should not rely on it.")
2130 (defcustom org-tags-column -80
2131 "The column to which tags should be indented in a headline.
2132 If this number is positive, it specifies the column. If it is negative,
2133 it means that the tags should be flushright to that column. For example,
2134 -80 works well for a normal 80 character screen."
2135 :group 'org-tags
2136 :type 'integer)
2138 (defcustom org-auto-align-tags t
2139 "Non-nil means, realign tags after pro/demotion of TODO state change.
2140 These operations change the length of a headline and therefore shift
2141 the tags around. With this options turned on, after each such operation
2142 the tags are again aligned to `org-tags-column'."
2143 :group 'org-tags
2144 :type 'boolean)
2146 (defcustom org-use-tag-inheritance t
2147 "Non-nil means, tags in levels apply also for sublevels.
2148 When nil, only the tags directly given in a specific line apply there.
2149 If you turn off this option, you very likely want to turn on the
2150 companion option `org-tags-match-list-sublevels'."
2151 :group 'org-tags
2152 :type 'boolean)
2154 (defcustom org-tags-match-list-sublevels nil
2155 "Non-nil means list also sublevels of headlines matching tag search.
2156 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2157 the sublevels of a headline matching a tag search often also match
2158 the same search. Listing all of them can create very long lists.
2159 Setting this variable to nil causes subtrees of a match to be skipped.
2160 This option is off by default, because inheritance in on. If you turn
2161 inheritance off, you very likely want to turn this option on.
2163 As a special case, if the tag search is restricted to TODO items, the
2164 value of this variable is ignored and sublevels are always checked, to
2165 make sure all corresponding TODO items find their way into the list."
2166 :group 'org-tags
2167 :type 'boolean)
2169 (defvar org-tags-history nil
2170 "History of minibuffer reads for tags.")
2171 (defvar org-last-tags-completion-table nil
2172 "The last used completion table for tags.")
2173 (defvar org-after-tags-change-hook nil
2174 "Hook that is run after the tags in a line have changed.")
2176 (defgroup org-properties nil
2177 "Options concerning properties in Org-mode."
2178 :tag "Org Properties"
2179 :group 'org)
2181 (defcustom org-property-format "%-10s %s"
2182 "How property key/value pairs should be formatted by `indent-line'.
2183 When `indent-line' hits a property definition, it will format the line
2184 according to this format, mainly to make sure that the values are
2185 lined-up with respect to each other."
2186 :group 'org-properties
2187 :type 'string)
2189 (defcustom org-use-property-inheritance nil
2190 "Non-nil means, properties apply also for sublevels.
2191 This setting is only relevant during property searches, not when querying
2192 an entry with `org-entry-get'. To retrieve a property with inheritance,
2193 you need to call `org-entry-get' with the inheritance flag.
2194 Turning this on can cause significant overhead when doing a search, so
2195 this is turned off by default.
2196 When nil, only the properties directly given in the current entry count.
2197 The value may also be a list of properties that shouldhave inheritance.
2199 However, note that some special properties use inheritance under special
2200 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2201 and the properties ending in \"_ALL\" when they are used as descriptor
2202 for valid values of a property."
2203 :group 'org-properties
2204 :type '(choice
2205 (const :tag "Not" nil)
2206 (const :tag "Always" nil)
2207 (repeat :tag "Specific properties" (string :tag "Property"))))
2209 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2210 "The default column format, if no other format has been defined.
2211 This variable can be set on the per-file basis by inserting a line
2213 #+COLUMNS: %25ITEM ....."
2214 :group 'org-properties
2215 :type 'string)
2217 (defcustom org-global-properties nil
2218 "List of property/value pairs that can be inherited by any entry.
2219 You can set buffer-local values for this by adding lines like
2221 #+PROPERTY: NAME VALUE"
2222 :group 'org-properties
2223 :type '(repeat
2224 (cons (string :tag "Property")
2225 (string :tag "Value"))))
2227 (defvar org-local-properties nil
2228 "List of property/value pairs that can be inherited by any entry.
2229 Valid for the current buffer.
2230 This variable is populated from #+PROPERTY lines.")
2232 (defgroup org-agenda nil
2233 "Options concerning agenda views in Org-mode."
2234 :tag "Org Agenda"
2235 :group 'org)
2237 (defvar org-category nil
2238 "Variable used by org files to set a category for agenda display.
2239 Such files should use a file variable to set it, for example
2241 # -*- mode: org; org-category: \"ELisp\"
2243 or contain a special line
2245 #+CATEGORY: ELisp
2247 If the file does not specify a category, then file's base name
2248 is used instead.")
2249 (make-variable-buffer-local 'org-category)
2251 (defcustom org-agenda-files nil
2252 "The files to be used for agenda display.
2253 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2254 \\[org-remove-file]. You can also use customize to edit the list.
2256 If an entry is a directory, all files in that directory that are matched by
2257 `org-agenda-file-regexp' will be part of the file list.
2259 If the value of the variable is not a list but a single file name, then
2260 the list of agenda files is actually stored and maintained in that file, one
2261 agenda file per line."
2262 :group 'org-agenda
2263 :type '(choice
2264 (repeat :tag "List of files and directories" file)
2265 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2267 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2268 "Regular expression to match files for `org-agenda-files'.
2269 If any element in the list in that variable contains a directory instead
2270 of a normal file, all files in that directory that are matched by this
2271 regular expression will be included."
2272 :group 'org-agenda
2273 :type 'regexp)
2275 (defcustom org-agenda-skip-unavailable-files nil
2276 "t means to just skip non-reachable files in `org-agenda-files'.
2277 Nil means to remove them, after a query, from the list."
2278 :group 'org-agenda
2279 :type 'boolean)
2281 (defcustom org-agenda-text-search-extra-files nil
2282 "List of extra files to be searched by text search commands.
2283 These files will be search in addition to the agenda files bu the
2284 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2285 Note that these files will only be searched for text search commands,
2286 not for the other agenda views like todo lists, tag earches or the weekly
2287 agenda. This variable is intended to list notes and possibly archive files
2288 that should also be searched by these two commands."
2289 :group 'org-agenda
2290 :type '(repeat file))
2292 (if (fboundp 'defvaralias)
2293 (defvaralias 'org-agenda-multi-occur-extra-files
2294 'org-agenda-text-search-extra-files))
2296 (defcustom org-agenda-confirm-kill 1
2297 "When set, remote killing from the agenda buffer needs confirmation.
2298 When t, a confirmation is always needed. When a number N, confirmation is
2299 only needed when the text to be killed contains more than N non-white lines."
2300 :group 'org-agenda
2301 :type '(choice
2302 (const :tag "Never" nil)
2303 (const :tag "Always" t)
2304 (number :tag "When more than N lines")))
2306 (defcustom org-calendar-to-agenda-key [?c]
2307 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2308 The command `org-calendar-goto-agenda' will be bound to this key. The
2309 default is the character `c' because then `c' can be used to switch back and
2310 forth between agenda and calendar."
2311 :group 'org-agenda
2312 :type 'sexp)
2314 (defcustom org-agenda-compact-blocks nil
2315 "Non-nil means, make the block agenda more compact.
2316 This is done by leaving out unnecessary lines."
2317 :group 'org-agenda
2318 :type nil)
2320 (defgroup org-agenda-export nil
2321 "Options concerning exporting agenda views in Org-mode."
2322 :tag "Org Agenda Export"
2323 :group 'org-agenda)
2325 (defcustom org-agenda-with-colors t
2326 "Non-nil means, use colors in agenda views."
2327 :group 'org-agenda-export
2328 :type 'boolean)
2330 (defcustom org-agenda-exporter-settings nil
2331 "Alist of variable/value pairs that should be active during agenda export.
2332 This is a good place to set uptions for ps-print and for htmlize."
2333 :group 'org-agenda-export
2334 :type '(repeat
2335 (list
2336 (variable)
2337 (sexp :tag "Value"))))
2339 (defcustom org-agenda-export-html-style ""
2340 "The style specification for exported HTML Agenda files.
2341 If this variable contains a string, it will replace the default <style>
2342 section as produced by `htmlize'.
2343 Since there are different ways of setting style information, this variable
2344 needs to contain the full HTML structure to provide a style, including the
2345 surrounding HTML tags. The style specifications should include definitions
2346 the fonts used by the agenda, here is an example:
2348 <style type=\"text/css\">
2349 p { font-weight: normal; color: gray; }
2350 .org-agenda-structure {
2351 font-size: 110%;
2352 color: #003399;
2353 font-weight: 600;
2355 .org-todo {
2356 color: #cc6666;Week-agenda:
2357 font-weight: bold;
2359 .org-done {
2360 color: #339933;
2362 .title { text-align: center; }
2363 .todo, .deadline { color: red; }
2364 .done { color: green; }
2365 </style>
2367 or, if you want to keep the style in a file,
2369 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2371 As the value of this option simply gets inserted into the HTML <head> header,
2372 you can \"misuse\" it to also add other text to the header. However,
2373 <style>...</style> is required, if not present the variable will be ignored."
2374 :group 'org-agenda-export
2375 :group 'org-export-html
2376 :type 'string)
2378 (defgroup org-agenda-custom-commands nil
2379 "Options concerning agenda views in Org-mode."
2380 :tag "Org Agenda Custom Commands"
2381 :group 'org-agenda)
2383 (defcustom org-agenda-custom-commands nil
2384 "Custom commands for the agenda.
2385 These commands will be offered on the splash screen displayed by the
2386 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2388 (key desc type match options files)
2390 key The key (one or more characters as a string) to be associated
2391 with the command.
2392 desc A description of the commend, when omitted or nil, a default
2393 description is built using MATCH.
2394 type The command type, any of the following symbols:
2395 agenda The daily/weekly agenda.
2396 todo Entries with a specific TODO keyword, in all agenda files.
2397 search Entries containing search words entry or headline.
2398 tags Tags/Property/TODO match in all agenda files.
2399 tags-todo Tags/P/T match in all agenda files, TODO entries only.
2400 todo-tree Sparse tree of specific TODO keyword in *current* file.
2401 tags-tree Sparse tree with all tags matches in *current* file.
2402 occur-tree Occur sparse tree for *current* file.
2403 ... A user-defined function.
2404 match What to search for:
2405 - a single keyword for TODO keyword searches
2406 - a tags match expression for tags searches
2407 - a regular expression for occur searches
2408 options A list of option settings, similar to that in a let form, so like
2409 this: ((opt1 val1) (opt2 val2) ...)
2410 files A list of files file to write the produced agenda buffer to
2411 with the command `org-store-agenda-views'.
2412 If a file name ends in \".html\", an HTML version of the buffer
2413 is written out. If it ends in \".ps\", a postscript version is
2414 produced. Otherwide, only the plain text is written to the file.
2416 You can also define a set of commands, to create a composite agenda buffer.
2417 In this case, an entry looks like this:
2419 (key desc (cmd1 cmd2 ...) general-options file)
2421 where
2423 desc A description string to be displayed in the dispatcher menu.
2424 cmd An agenda command, similar to the above. However, tree commands
2425 are no allowed, but instead you can get agenda and global todo list.
2426 So valid commands for a set are:
2427 (agenda)
2428 (alltodo)
2429 (stuck)
2430 (todo \"match\" options files)
2431 (search \"match\" options files)
2432 (tags \"match\" options files)
2433 (tags-todo \"match\" options files)
2435 Each command can carry a list of options, and another set of options can be
2436 given for the whole set of commands. Individual command options take
2437 precedence over the general options.
2439 When using several characters as key to a command, the first characters
2440 are prefix commands. For the dispatcher to display useful information, you
2441 should provide a description for the prefix, like
2443 (setq org-agenda-custom-commands
2444 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2445 (\"hl\" tags \"+HOME+Lisa\")
2446 (\"hp\" tags \"+HOME+Peter\")
2447 (\"hk\" tags \"+HOME+Kim\")))"
2448 :group 'org-agenda-custom-commands
2449 :type '(repeat
2450 (choice :value ("a" "" tags "" nil)
2451 (list :tag "Single command"
2452 (string :tag "Access Key(s) ")
2453 (option (string :tag "Description"))
2454 (choice
2455 (const :tag "Agenda" agenda)
2456 (const :tag "TODO list" alltodo)
2457 (const :tag "Search words" search)
2458 (const :tag "Stuck projects" stuck)
2459 (const :tag "Tags search (all agenda files)" tags)
2460 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2461 (const :tag "TODO keyword search (all agenda files)" todo)
2462 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2463 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2464 (const :tag "Occur tree (current buffer)" occur-tree)
2465 (sexp :tag "Other, user-defined function"))
2466 (string :tag "Match")
2467 (repeat :tag "Local options"
2468 (list (variable :tag "Option") (sexp :tag "Value")))
2469 (option (repeat :tag "Export" (file :tag "Export to"))))
2470 (list :tag "Command series, all agenda files"
2471 (string :tag "Access Key(s)")
2472 (string :tag "Description ")
2473 (repeat
2474 (choice
2475 (const :tag "Agenda" (agenda))
2476 (const :tag "TODO list" (alltodo))
2477 (list :tag "Search words"
2478 (const :format "" search)
2479 (string :tag "Match")
2480 (repeat :tag "Local options"
2481 (list (variable :tag "Option")
2482 (sexp :tag "Value"))))
2483 (const :tag "Stuck projects" (stuck))
2484 (list :tag "Tags search"
2485 (const :format "" tags)
2486 (string :tag "Match")
2487 (repeat :tag "Local options"
2488 (list (variable :tag "Option")
2489 (sexp :tag "Value"))))
2491 (list :tag "Tags search, TODO entries only"
2492 (const :format "" tags-todo)
2493 (string :tag "Match")
2494 (repeat :tag "Local options"
2495 (list (variable :tag "Option")
2496 (sexp :tag "Value"))))
2498 (list :tag "TODO keyword search"
2499 (const :format "" todo)
2500 (string :tag "Match")
2501 (repeat :tag "Local options"
2502 (list (variable :tag "Option")
2503 (sexp :tag "Value"))))
2505 (list :tag "Other, user-defined function"
2506 (symbol :tag "function")
2507 (string :tag "Match")
2508 (repeat :tag "Local options"
2509 (list (variable :tag "Option")
2510 (sexp :tag "Value"))))))
2512 (repeat :tag "General options"
2513 (list (variable :tag "Option")
2514 (sexp :tag "Value")))
2515 (option (repeat :tag "Export" (file :tag "Export to"))))
2516 (cons :tag "Prefix key documentation"
2517 (string :tag "Access Key(s)")
2518 (string :tag "Description ")))))
2520 (defcustom org-agenda-query-register ?o
2521 "The register holding the current query string.
2522 The prupose of this is that if you construct a query string interactively,
2523 you can then use it to define a custom command."
2524 :group 'org-agenda-custom-commands
2525 :type 'character)
2527 (defcustom org-stuck-projects
2528 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2529 "How to identify stuck projects.
2530 This is a list of four items:
2531 1. A tags/todo matcher string that is used to identify a project.
2532 The entire tree below a headline matched by this is considered one project.
2533 2. A list of TODO keywords identifying non-stuck projects.
2534 If the project subtree contains any headline with one of these todo
2535 keywords, the project is considered to be not stuck. If you specify
2536 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2537 3. A list of tags identifying non-stuck projects.
2538 If the project subtree contains any headline with one of these tags,
2539 the project is considered to be not stuck. If you specify \"*\" as
2540 a tag, any tag will mark the project unstuck.
2541 4. An arbitrary regular expression matching non-stuck projects.
2543 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2544 or `C-c a #' to produce the list."
2545 :group 'org-agenda-custom-commands
2546 :type '(list
2547 (string :tag "Tags/TODO match to identify a project")
2548 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2549 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2550 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2553 (defgroup org-agenda-skip nil
2554 "Options concerning skipping parts of agenda files."
2555 :tag "Org Agenda Skip"
2556 :group 'org-agenda)
2558 (defcustom org-agenda-todo-list-sublevels t
2559 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2560 When nil, the sublevels of a TODO entry are not checked, resulting in
2561 potentially much shorter TODO lists."
2562 :group 'org-agenda-skip
2563 :group 'org-todo
2564 :type 'boolean)
2566 (defcustom org-agenda-todo-ignore-with-date nil
2567 "Non-nil means, don't show entries with a date in the global todo list.
2568 You can use this if you prefer to mark mere appointments with a TODO keyword,
2569 but don't want them to show up in the TODO list.
2570 When this is set, it also covers deadlines and scheduled items, the settings
2571 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2572 will be ignored."
2573 :group 'org-agenda-skip
2574 :group 'org-todo
2575 :type 'boolean)
2577 (defcustom org-agenda-todo-ignore-scheduled nil
2578 "Non-nil means, don't show scheduled entries in the global todo list.
2579 The idea behind this is that by scheduling it, you have already taken care
2580 of this item.
2581 See also `org-agenda-todo-ignore-with-date'."
2582 :group 'org-agenda-skip
2583 :group 'org-todo
2584 :type 'boolean)
2586 (defcustom org-agenda-todo-ignore-deadlines nil
2587 "Non-nil means, don't show near deadline entries in the global todo list.
2588 Near means closer than `org-deadline-warning-days' days.
2589 The idea behind this is that such items will appear in the agenda anyway.
2590 See also `org-agenda-todo-ignore-with-date'."
2591 :group 'org-agenda-skip
2592 :group 'org-todo
2593 :type 'boolean)
2595 (defcustom org-agenda-skip-scheduled-if-done nil
2596 "Non-nil means don't show scheduled items in agenda when they are done.
2597 This is relevant for the daily/weekly agenda, not for the TODO list. And
2598 it applies only to the actual date of the scheduling. Warnings about
2599 an item with a past scheduling dates are always turned off when the item
2600 is DONE."
2601 :group 'org-agenda-skip
2602 :type 'boolean)
2604 (defcustom org-agenda-skip-deadline-if-done nil
2605 "Non-nil means don't show deadines when the corresponding item is done.
2606 When nil, the deadline is still shown and should give you a happy feeling.
2607 This is relevant for the daily/weekly agenda. And it applied only to the
2608 actualy date of the deadline. Warnings about approching and past-due
2609 deadlines are always turned off when the item is DONE."
2610 :group 'org-agenda-skip
2611 :type 'boolean)
2613 (defcustom org-agenda-skip-timestamp-if-done nil
2614 "Non-nil means don't select item by timestamp or -range if it is DONE."
2615 :group 'org-agenda-skip
2616 :type 'boolean)
2618 (defcustom org-timeline-show-empty-dates 3
2619 "Non-nil means, `org-timeline' also shows dates without an entry.
2620 When nil, only the days which actually have entries are shown.
2621 When t, all days between the first and the last date are shown.
2622 When an integer, show also empty dates, but if there is a gap of more than
2623 N days, just insert a special line indicating the size of the gap."
2624 :group 'org-agenda-skip
2625 :type '(choice
2626 (const :tag "None" nil)
2627 (const :tag "All" t)
2628 (number :tag "at most")))
2631 (defgroup org-agenda-startup nil
2632 "Options concerning initial settings in the Agenda in Org Mode."
2633 :tag "Org Agenda Startup"
2634 :group 'org-agenda)
2636 (defcustom org-finalize-agenda-hook nil
2637 "Hook run just before displaying an agenda buffer."
2638 :group 'org-agenda-startup
2639 :type 'hook)
2641 (defcustom org-agenda-mouse-1-follows-link nil
2642 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2643 A longer mouse click will still set point. Does not work on XEmacs.
2644 Needs to be set before org.el is loaded."
2645 :group 'org-agenda-startup
2646 :type 'boolean)
2648 (defcustom org-agenda-start-with-follow-mode nil
2649 "The initial value of follow-mode in a newly created agenda window."
2650 :group 'org-agenda-startup
2651 :type 'boolean)
2653 (defgroup org-agenda-windows nil
2654 "Options concerning the windows used by the Agenda in Org Mode."
2655 :tag "Org Agenda Windows"
2656 :group 'org-agenda)
2658 (defcustom org-agenda-window-setup 'reorganize-frame
2659 "How the agenda buffer should be displayed.
2660 Possible values for this option are:
2662 current-window Show agenda in the current window, keeping all other windows.
2663 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2664 other-window Use `switch-to-buffer-other-window' to display agenda.
2665 reorganize-frame Show only two windows on the current frame, the current
2666 window and the agenda.
2667 See also the variable `org-agenda-restore-windows-after-quit'."
2668 :group 'org-agenda-windows
2669 :type '(choice
2670 (const current-window)
2671 (const other-frame)
2672 (const other-window)
2673 (const reorganize-frame)))
2675 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2676 "The min and max height of the agenda window as a fraction of frame height.
2677 The value of the variable is a cons cell with two numbers between 0 and 1.
2678 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2679 :group 'org-agenda-windows
2680 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2682 (defcustom org-agenda-restore-windows-after-quit nil
2683 "Non-nil means, restore window configuration open exiting agenda.
2684 Before the window configuration is changed for displaying the agenda,
2685 the current status is recorded. When the agenda is exited with
2686 `q' or `x' and this option is set, the old state is restored. If
2687 `org-agenda-window-setup' is `other-frame', the value of this
2688 option will be ignored.."
2689 :group 'org-agenda-windows
2690 :type 'boolean)
2692 (defcustom org-indirect-buffer-display 'other-window
2693 "How should indirect tree buffers be displayed?
2694 This applies to indirect buffers created with the commands
2695 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2696 Valid values are:
2697 current-window Display in the current window
2698 other-window Just display in another window.
2699 dedicated-frame Create one new frame, and re-use it each time.
2700 new-frame Make a new frame each time. Note that in this case
2701 previously-made indirect buffers are kept, and you need to
2702 kill these buffers yourself."
2703 :group 'org-structure
2704 :group 'org-agenda-windows
2705 :type '(choice
2706 (const :tag "In current window" current-window)
2707 (const :tag "In current frame, other window" other-window)
2708 (const :tag "Each time a new frame" new-frame)
2709 (const :tag "One dedicated frame" dedicated-frame)))
2711 (defgroup org-agenda-daily/weekly nil
2712 "Options concerning the daily/weekly agenda."
2713 :tag "Org Agenda Daily/Weekly"
2714 :group 'org-agenda)
2716 (defcustom org-agenda-ndays 7
2717 "Number of days to include in overview display.
2718 Should be 1 or 7."
2719 :group 'org-agenda-daily/weekly
2720 :type 'number)
2722 (defcustom org-agenda-start-on-weekday 1
2723 "Non-nil means, start the overview always on the specified weekday.
2724 0 denotes Sunday, 1 denotes Monday etc.
2725 When nil, always start on the current day."
2726 :group 'org-agenda-daily/weekly
2727 :type '(choice (const :tag "Today" nil)
2728 (number :tag "Weekday No.")))
2730 (defcustom org-agenda-show-all-dates t
2731 "Non-nil means, `org-agenda' shows every day in the selected range.
2732 When nil, only the days which actually have entries are shown."
2733 :group 'org-agenda-daily/weekly
2734 :type 'boolean)
2736 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2737 "Format string for displaying dates in the agenda.
2738 Used by the daily/weekly agenda and by the timeline. This should be
2739 a format string understood by `format-time-string', or a function returning
2740 the formatted date as a string. The function must take a single argument,
2741 a calendar-style date list like (month day year)."
2742 :group 'org-agenda-daily/weekly
2743 :type '(choice
2744 (string :tag "Format string")
2745 (function :tag "Function")))
2747 (defun org-agenda-format-date-aligned (date)
2748 "Format a date string for display in the daily/weekly agenda, or timeline.
2749 This function makes sure that dates are aligned for easy reading."
2750 (format "%-9s %2d %s %4d"
2751 (calendar-day-name date)
2752 (extract-calendar-day date)
2753 (calendar-month-name (extract-calendar-month date))
2754 (extract-calendar-year date)))
2756 (defcustom org-agenda-include-diary nil
2757 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2758 :group 'org-agenda-daily/weekly
2759 :type 'boolean)
2761 (defcustom org-agenda-include-all-todo nil
2762 "Set means weekly/daily agenda will always contain all TODO entries.
2763 The TODO entries will be listed at the top of the agenda, before
2764 the entries for specific days."
2765 :group 'org-agenda-daily/weekly
2766 :type 'boolean)
2768 (defcustom org-agenda-repeating-timestamp-show-all t
2769 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2770 When nil, only one occurence is shown, either today or the
2771 nearest into the future."
2772 :group 'org-agenda-daily/weekly
2773 :type 'boolean)
2775 (defcustom org-deadline-warning-days 14
2776 "No. of days before expiration during which a deadline becomes active.
2777 This variable governs the display in sparse trees and in the agenda.
2778 When 0 or negative, it means use this number (the absolute value of it)
2779 even if a deadline has a different individual lead time specified."
2780 :group 'org-time
2781 :group 'org-agenda-daily/weekly
2782 :type 'number)
2784 (defcustom org-scheduled-past-days 10000
2785 "No. of days to continue listing scheduled items that are not marked DONE.
2786 When an item is scheduled on a date, it shows up in the agenda on this
2787 day and will be listed until it is marked done for the number of days
2788 given here."
2789 :group 'org-agenda-daily/weekly
2790 :type 'number)
2792 (defgroup org-agenda-time-grid nil
2793 "Options concerning the time grid in the Org-mode Agenda."
2794 :tag "Org Agenda Time Grid"
2795 :group 'org-agenda)
2797 (defcustom org-agenda-use-time-grid t
2798 "Non-nil means, show a time grid in the agenda schedule.
2799 A time grid is a set of lines for specific times (like every two hours between
2800 8:00 and 20:00). The items scheduled for a day at specific times are
2801 sorted in between these lines.
2802 For details about when the grid will be shown, and what it will look like, see
2803 the variable `org-agenda-time-grid'."
2804 :group 'org-agenda-time-grid
2805 :type 'boolean)
2807 (defcustom org-agenda-time-grid
2808 '((daily today require-timed)
2809 "----------------"
2810 (800 1000 1200 1400 1600 1800 2000))
2812 "The settings for time grid for agenda display.
2813 This is a list of three items. The first item is again a list. It contains
2814 symbols specifying conditions when the grid should be displayed:
2816 daily if the agenda shows a single day
2817 weekly if the agenda shows an entire week
2818 today show grid on current date, independent of daily/weekly display
2819 require-timed show grid only if at least one item has a time specification
2821 The second item is a string which will be places behing the grid time.
2823 The third item is a list of integers, indicating the times that should have
2824 a grid line."
2825 :group 'org-agenda-time-grid
2826 :type
2827 '(list
2828 (set :greedy t :tag "Grid Display Options"
2829 (const :tag "Show grid in single day agenda display" daily)
2830 (const :tag "Show grid in weekly agenda display" weekly)
2831 (const :tag "Always show grid for today" today)
2832 (const :tag "Show grid only if any timed entries are present"
2833 require-timed)
2834 (const :tag "Skip grid times already present in an entry"
2835 remove-match))
2836 (string :tag "Grid String")
2837 (repeat :tag "Grid Times" (integer :tag "Time"))))
2839 (defgroup org-agenda-sorting nil
2840 "Options concerning sorting in the Org-mode Agenda."
2841 :tag "Org Agenda Sorting"
2842 :group 'org-agenda)
2844 (defconst org-sorting-choice
2845 '(choice
2846 (const time-up) (const time-down)
2847 (const category-keep) (const category-up) (const category-down)
2848 (const tag-down) (const tag-up)
2849 (const priority-up) (const priority-down))
2850 "Sorting choices.")
2852 (defcustom org-agenda-sorting-strategy
2853 '((agenda time-up category-keep priority-down)
2854 (todo category-keep priority-down)
2855 (tags category-keep priority-down)
2856 (search category-keep))
2857 "Sorting structure for the agenda items of a single day.
2858 This is a list of symbols which will be used in sequence to determine
2859 if an entry should be listed before another entry. The following
2860 symbols are recognized:
2862 time-up Put entries with time-of-day indications first, early first
2863 time-down Put entries with time-of-day indications first, late first
2864 category-keep Keep the default order of categories, corresponding to the
2865 sequence in `org-agenda-files'.
2866 category-up Sort alphabetically by category, A-Z.
2867 category-down Sort alphabetically by category, Z-A.
2868 tag-up Sort alphabetically by last tag, A-Z.
2869 tag-down Sort alphabetically by last tag, Z-A.
2870 priority-up Sort numerically by priority, high priority last.
2871 priority-down Sort numerically by priority, high priority first.
2873 The different possibilities will be tried in sequence, and testing stops
2874 if one comparison returns a \"not-equal\". For example, the default
2875 '(time-up category-keep priority-down)
2876 means: Pull out all entries having a specified time of day and sort them,
2877 in order to make a time schedule for the current day the first thing in the
2878 agenda listing for the day. Of the entries without a time indication, keep
2879 the grouped in categories, don't sort the categories, but keep them in
2880 the sequence given in `org-agenda-files'. Within each category sort by
2881 priority.
2883 Leaving out `category-keep' would mean that items will be sorted across
2884 categories by priority.
2886 Instead of a single list, this can also be a set of list for specific
2887 contents, with a context symbol in the car of the list, any of
2888 `agenda', `todo', `tags' for the corresponding agenda views."
2889 :group 'org-agenda-sorting
2890 :type `(choice
2891 (repeat :tag "General" ,org-sorting-choice)
2892 (list :tag "Individually"
2893 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2894 (repeat ,org-sorting-choice))
2895 (cons (const :tag "Strategy for TODO lists" todo)
2896 (repeat ,org-sorting-choice))
2897 (cons (const :tag "Strategy for Tags matches" tags)
2898 (repeat ,org-sorting-choice)))))
2900 (defcustom org-sort-agenda-notime-is-late t
2901 "Non-nil means, items without time are considered late.
2902 This is only relevant for sorting. When t, items which have no explicit
2903 time like 15:30 will be considered as 99:01, i.e. later than any items which
2904 do have a time. When nil, the default time is before 0:00. You can use this
2905 option to decide if the schedule for today should come before or after timeless
2906 agenda entries."
2907 :group 'org-agenda-sorting
2908 :type 'boolean)
2910 (defgroup org-agenda-line-format nil
2911 "Options concerning the entry prefix in the Org-mode agenda display."
2912 :tag "Org Agenda Line Format"
2913 :group 'org-agenda)
2915 (defcustom org-agenda-prefix-format
2916 '((agenda . " %-12:c%?-12t% s")
2917 (timeline . " % s")
2918 (todo . " %-12:c")
2919 (tags . " %-12:c")
2920 (search . " %-12:c"))
2921 "Format specifications for the prefix of items in the agenda views.
2922 An alist with four entries, for the different agenda types. The keys to the
2923 sublists are `agenda', `timeline', `todo', and `tags'. The values
2924 are format strings.
2925 This format works similar to a printf format, with the following meaning:
2927 %c the category of the item, \"Diary\" for entries from the diary, or
2928 as given by the CATEGORY keyword or derived from the file name.
2929 %T the *last* tag of the item. Last because inherited tags come
2930 first in the list.
2931 %t the time-of-day specification if one applies to the entry, in the
2932 format HH:MM
2933 %s Scheduling/Deadline information, a short string
2935 All specifiers work basically like the standard `%s' of printf, but may
2936 contain two additional characters: A question mark just after the `%' and
2937 a whitespace/punctuation character just before the final letter.
2939 If the first character after `%' is a question mark, the entire field
2940 will only be included if the corresponding value applies to the
2941 current entry. This is useful for fields which should have fixed
2942 width when present, but zero width when absent. For example,
2943 \"%?-12t\" will result in a 12 character time field if a time of the
2944 day is specified, but will completely disappear in entries which do
2945 not contain a time.
2947 If there is punctuation or whitespace character just before the final
2948 format letter, this character will be appended to the field value if
2949 the value is not empty. For example, the format \"%-12:c\" leads to
2950 \"Diary: \" if the category is \"Diary\". If the category were be
2951 empty, no additional colon would be interted.
2953 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2954 - Indent the line with two space characters
2955 - Give the category in a 12 chars wide field, padded with whitespace on
2956 the right (because of `-'). Append a colon if there is a category
2957 (because of `:').
2958 - If there is a time-of-day, put it into a 12 chars wide field. If no
2959 time, don't put in an empty field, just skip it (because of '?').
2960 - Finally, put the scheduling information and append a whitespace.
2962 As another example, if you don't want the time-of-day of entries in
2963 the prefix, you could use:
2965 (setq org-agenda-prefix-format \" %-11:c% s\")
2967 See also the variables `org-agenda-remove-times-when-in-prefix' and
2968 `org-agenda-remove-tags'."
2969 :type '(choice
2970 (string :tag "General format")
2971 (list :greedy t :tag "View dependent"
2972 (cons (const agenda) (string :tag "Format"))
2973 (cons (const timeline) (string :tag "Format"))
2974 (cons (const todo) (string :tag "Format"))
2975 (cons (const tags) (string :tag "Format"))
2976 (cons (const search) (string :tag "Format"))))
2977 :group 'org-agenda-line-format)
2979 (defvar org-prefix-format-compiled nil
2980 "The compiled version of the most recently used prefix format.
2981 See the variable `org-agenda-prefix-format'.")
2983 (defcustom org-agenda-todo-keyword-format "%-1s"
2984 "Format for the TODO keyword in agenda lines.
2985 Set this to something like \"%-12s\" if you want all TODO keywords
2986 to occupy a fixed space in the agenda display."
2987 :group 'org-agenda-line-format
2988 :type 'string)
2990 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2991 "Text preceeding scheduled items in the agenda view.
2992 This is a list with two strings. The first applies when the item is
2993 scheduled on the current day. The second applies when it has been scheduled
2994 previously, it may contain a %d to capture how many days ago the item was
2995 scheduled."
2996 :group 'org-agenda-line-format
2997 :type '(list
2998 (string :tag "Scheduled today ")
2999 (string :tag "Scheduled previously")))
3001 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
3002 "Text preceeding deadline items in the agenda view.
3003 This is a list with two strings. The first applies when the item has its
3004 deadline on the current day. The second applies when it is in the past or
3005 in the future, it may contain %d to capture how many days away the deadline
3006 is (was)."
3007 :group 'org-agenda-line-format
3008 :type '(list
3009 (string :tag "Deadline today ")
3010 (string :tag "Deadline relative")))
3012 (defcustom org-agenda-remove-times-when-in-prefix t
3013 "Non-nil means, remove duplicate time specifications in agenda items.
3014 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
3015 time-of-day specification in a headline or diary entry is extracted and
3016 placed into the prefix. If this option is non-nil, the original specification
3017 \(a timestamp or -range, or just a plain time(range) specification like
3018 11:30-4pm) will be removed for agenda display. This makes the agenda less
3019 cluttered.
3020 The option can be t or nil. It may also be the symbol `beg', indicating
3021 that the time should only be removed what it is located at the beginning of
3022 the headline/diary entry."
3023 :group 'org-agenda-line-format
3024 :type '(choice
3025 (const :tag "Always" t)
3026 (const :tag "Never" nil)
3027 (const :tag "When at beginning of entry" beg)))
3030 (defcustom org-agenda-default-appointment-duration nil
3031 "Default duration for appointments that only have a starting time.
3032 When nil, no duration is specified in such cases.
3033 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
3034 :group 'org-agenda-line-format
3035 :type '(choice
3036 (integer :tag "Minutes")
3037 (const :tag "No default duration")))
3040 (defcustom org-agenda-remove-tags nil
3041 "Non-nil means, remove the tags from the headline copy in the agenda.
3042 When this is the symbol `prefix', only remove tags when
3043 `org-agenda-prefix-format' contains a `%T' specifier."
3044 :group 'org-agenda-line-format
3045 :type '(choice
3046 (const :tag "Always" t)
3047 (const :tag "Never" nil)
3048 (const :tag "When prefix format contains %T" prefix)))
3050 (if (fboundp 'defvaralias)
3051 (defvaralias 'org-agenda-remove-tags-when-in-prefix
3052 'org-agenda-remove-tags))
3054 (defcustom org-agenda-tags-column -80
3055 "Shift tags in agenda items to this column.
3056 If this number is positive, it specifies the column. If it is negative,
3057 it means that the tags should be flushright to that column. For example,
3058 -80 works well for a normal 80 character screen."
3059 :group 'org-agenda-line-format
3060 :type 'integer)
3062 (if (fboundp 'defvaralias)
3063 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
3065 (defcustom org-agenda-fontify-priorities t
3066 "Non-nil means, highlight low and high priorities in agenda.
3067 When t, the highest priority entries are bold, lowest priority italic.
3068 This may also be an association list of priority faces. The face may be
3069 a names face, or a list like `(:background \"Red\")'."
3070 :group 'org-agenda-line-format
3071 :type '(choice
3072 (const :tag "Never" nil)
3073 (const :tag "Defaults" t)
3074 (repeat :tag "Specify"
3075 (list (character :tag "Priority" :value ?A)
3076 (sexp :tag "face")))))
3078 (defgroup org-latex nil
3079 "Options for embedding LaTeX code into Org-mode"
3080 :tag "Org LaTeX"
3081 :group 'org)
3083 (defcustom org-format-latex-options
3084 '(:foreground default :background default :scale 1.0
3085 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3086 :matchers ("begin" "$" "$$" "\\(" "\\["))
3087 "Options for creating images from LaTeX fragments.
3088 This is a property list with the following properties:
3089 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
3090 `default' means use the forground of the default face.
3091 :background the background color, or \"Transparent\".
3092 `default' means use the background of the default face.
3093 :scale a scaling factor for the size of the images
3094 :html-foreground, :html-background, :html-scale
3095 The same numbers for HTML export.
3096 :matchers a list indicating which matchers should be used to
3097 find LaTeX fragments. Valid members of this list are:
3098 \"begin\" find environments
3099 \"$\" find math expressions surrounded by $...$
3100 \"$$\" find math expressions surrounded by $$....$$
3101 \"\\(\" find math expressions surrounded by \\(...\\)
3102 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3103 :group 'org-latex
3104 :type 'plist)
3106 (defcustom org-format-latex-header "\\documentclass{article}
3107 \\usepackage{fullpage} % do not remove
3108 \\usepackage{amssymb}
3109 \\usepackage[usenames]{color}
3110 \\usepackage{amsmath}
3111 \\usepackage{latexsym}
3112 \\usepackage[mathscr]{eucal}
3113 \\pagestyle{empty} % do not remove"
3114 "The document header used for processing LaTeX fragments."
3115 :group 'org-latex
3116 :type 'string)
3118 (defgroup org-export nil
3119 "Options for exporting org-listings."
3120 :tag "Org Export"
3121 :group 'org)
3123 (defgroup org-export-general nil
3124 "General options for exporting Org-mode files."
3125 :tag "Org Export General"
3126 :group 'org-export)
3128 ;; FIXME
3129 (defvar org-export-publishing-directory nil)
3131 (defcustom org-export-with-special-strings t
3132 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3133 When this option is turned on, these strings will be exported as:
3135 Org HTML LaTeX
3136 -----+----------+--------
3137 \\- &shy; \\-
3138 -- &ndash; --
3139 --- &mdash; ---
3140 ... &hellip; \ldots
3142 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3143 :group 'org-export-translation
3144 :type 'boolean)
3146 (defcustom org-export-language-setup
3147 '(("en" "Author" "Date" "Table of Contents")
3148 ("cs" "Autor" "Datum" "Obsah")
3149 ("da" "Ophavsmand" "Dato" "Indhold")
3150 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3151 ("es" "Autor" "Fecha" "\xcdndice")
3152 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3153 ("it" "Autore" "Data" "Indice")
3154 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3155 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3156 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3157 "Terms used in export text, translated to different languages.
3158 Use the variable `org-export-default-language' to set the language,
3159 or use the +OPTION lines for a per-file setting."
3160 :group 'org-export-general
3161 :type '(repeat
3162 (list
3163 (string :tag "HTML language tag")
3164 (string :tag "Author")
3165 (string :tag "Date")
3166 (string :tag "Table of Contents"))))
3168 (defcustom org-export-default-language "en"
3169 "The default language of HTML export, as a string.
3170 This should have an association in `org-export-language-setup'."
3171 :group 'org-export-general
3172 :type 'string)
3174 (defcustom org-export-skip-text-before-1st-heading t
3175 "Non-nil means, skip all text before the first headline when exporting.
3176 When nil, that text is exported as well."
3177 :group 'org-export-general
3178 :type 'boolean)
3180 (defcustom org-export-headline-levels 3
3181 "The last level which is still exported as a headline.
3182 Inferior levels will produce itemize lists when exported.
3183 Note that a numeric prefix argument to an exporter function overrides
3184 this setting.
3186 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3187 :group 'org-export-general
3188 :type 'number)
3190 (defcustom org-export-with-section-numbers t
3191 "Non-nil means, add section numbers to headlines when exporting.
3193 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3194 :group 'org-export-general
3195 :type 'boolean)
3197 (defcustom org-export-with-toc t
3198 "Non-nil means, create a table of contents in exported files.
3199 The TOC contains headlines with levels up to`org-export-headline-levels'.
3200 When an integer, include levels up to N in the toc, this may then be
3201 different from `org-export-headline-levels', but it will not be allowed
3202 to be larger than the number of headline levels.
3203 When nil, no table of contents is made.
3205 Headlines which contain any TODO items will be marked with \"(*)\" in
3206 ASCII export, and with red color in HTML output, if the option
3207 `org-export-mark-todo-in-toc' is set.
3209 In HTML output, the TOC will be clickable.
3211 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3212 or \"toc:3\"."
3213 :group 'org-export-general
3214 :type '(choice
3215 (const :tag "No Table of Contents" nil)
3216 (const :tag "Full Table of Contents" t)
3217 (integer :tag "TOC to level")))
3219 (defcustom org-export-mark-todo-in-toc nil
3220 "Non-nil means, mark TOC lines that contain any open TODO items."
3221 :group 'org-export-general
3222 :type 'boolean)
3224 (defcustom org-export-preserve-breaks nil
3225 "Non-nil means, preserve all line breaks when exporting.
3226 Normally, in HTML output paragraphs will be reformatted. In ASCII
3227 export, line breaks will always be preserved, regardless of this variable.
3229 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3230 :group 'org-export-general
3231 :type 'boolean)
3233 (defcustom org-export-with-archived-trees 'headline
3234 "Whether subtrees with the ARCHIVE tag should be exported.
3235 This can have three different values
3236 nil Do not export, pretend this tree is not present
3237 t Do export the entire tree
3238 headline Only export the headline, but skip the tree below it."
3239 :group 'org-export-general
3240 :group 'org-archive
3241 :type '(choice
3242 (const :tag "not at all" nil)
3243 (const :tag "headline only" 'headline)
3244 (const :tag "entirely" t)))
3246 (defcustom org-export-author-info t
3247 "Non-nil means, insert author name and email into the exported file.
3249 This option can also be set with the +OPTIONS line,
3250 e.g. \"author-info:nil\"."
3251 :group 'org-export-general
3252 :type 'boolean)
3254 (defcustom org-export-time-stamp-file t
3255 "Non-nil means, insert a time stamp into the exported file.
3256 The time stamp shows when the file was created.
3258 This option can also be set with the +OPTIONS line,
3259 e.g. \"timestamp:nil\"."
3260 :group 'org-export-general
3261 :type 'boolean)
3263 (defcustom org-export-with-timestamps t
3264 "If nil, do not export time stamps and associated keywords."
3265 :group 'org-export-general
3266 :type 'boolean)
3268 (defcustom org-export-remove-timestamps-from-toc t
3269 "If nil, remove timestamps from the table of contents entries."
3270 :group 'org-export-general
3271 :type 'boolean)
3273 (defcustom org-export-with-tags 'not-in-toc
3274 "If nil, do not export tags, just remove them from headlines.
3275 If this is the symbol `not-in-toc', tags will be removed from table of
3276 contents entries, but still be shown in the headlines of the document.
3278 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3279 :group 'org-export-general
3280 :type '(choice
3281 (const :tag "Off" nil)
3282 (const :tag "Not in TOC" not-in-toc)
3283 (const :tag "On" t)))
3285 (defcustom org-export-with-drawers nil
3286 "Non-nil means, export with drawers like the property drawer.
3287 When t, all drawers are exported. This may also be a list of
3288 drawer names to export."
3289 :group 'org-export-general
3290 :type '(choice
3291 (const :tag "All drawers" t)
3292 (const :tag "None" nil)
3293 (repeat :tag "Selected drawers"
3294 (string :tag "Drawer name"))))
3296 (defgroup org-export-translation nil
3297 "Options for translating special ascii sequences for the export backends."
3298 :tag "Org Export Translation"
3299 :group 'org-export)
3301 (defcustom org-export-with-emphasize t
3302 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3303 If the export target supports emphasizing text, the word will be
3304 typeset in bold, italic, or underlined, respectively. Works only for
3305 single words, but you can say: I *really* *mean* *this*.
3306 Not all export backends support this.
3308 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3309 :group 'org-export-translation
3310 :type 'boolean)
3312 (defcustom org-export-with-footnotes t
3313 "If nil, export [1] as a footnote marker.
3314 Lines starting with [1] will be formatted as footnotes.
3316 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3317 :group 'org-export-translation
3318 :type 'boolean)
3320 (defcustom org-export-with-sub-superscripts t
3321 "Non-nil means, interpret \"_\" and \"^\" for export.
3322 When this option is turned on, you can use TeX-like syntax for sub- and
3323 superscripts. Several characters after \"_\" or \"^\" will be
3324 considered as a single item - so grouping with {} is normally not
3325 needed. For example, the following things will be parsed as single
3326 sub- or superscripts.
3328 10^24 or 10^tau several digits will be considered 1 item.
3329 10^-12 or 10^-tau a leading sign with digits or a word
3330 x^2-y^3 will be read as x^2 - y^3, because items are
3331 terminated by almost any nonword/nondigit char.
3332 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3334 Still, ambiguity is possible - so when in doubt use {} to enclose the
3335 sub/superscript. If you set this variable to the symbol `{}',
3336 the braces are *required* in order to trigger interpretations as
3337 sub/superscript. This can be helpful in documents that need \"_\"
3338 frequently in plain text.
3340 Not all export backends support this, but HTML does.
3342 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3343 :group 'org-export-translation
3344 :type '(choice
3345 (const :tag "Always interpret" t)
3346 (const :tag "Only with braces" {})
3347 (const :tag "Never interpret" nil)))
3349 (defcustom org-export-with-special-strings t
3350 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3351 When this option is turned on, these strings will be exported as:
3353 \\- : &shy;
3354 -- : &ndash;
3355 --- : &mdash;
3357 Not all export backends support this, but HTML does.
3359 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3360 :group 'org-export-translation
3361 :type 'boolean)
3363 (defcustom org-export-with-TeX-macros t
3364 "Non-nil means, interpret simple TeX-like macros when exporting.
3365 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3366 No only real TeX macros will work here, but the standard HTML entities
3367 for math can be used as macro names as well. For a list of supported
3368 names in HTML export, see the constant `org-html-entities'.
3369 Not all export backends support this.
3371 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3372 :group 'org-export-translation
3373 :group 'org-export-latex
3374 :type 'boolean)
3376 (defcustom org-export-with-LaTeX-fragments nil
3377 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3378 When set, the exporter will find LaTeX environments if the \\begin line is
3379 the first non-white thing on a line. It will also find the math delimiters
3380 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3381 display math.
3383 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3384 :group 'org-export-translation
3385 :group 'org-export-latex
3386 :type 'boolean)
3388 (defcustom org-export-with-fixed-width t
3389 "Non-nil means, lines starting with \":\" will be in fixed width font.
3390 This can be used to have pre-formatted text, fragments of code etc. For
3391 example:
3392 : ;; Some Lisp examples
3393 : (while (defc cnt)
3394 : (ding))
3395 will be looking just like this in also HTML. See also the QUOTE keyword.
3396 Not all export backends support this.
3398 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3399 :group 'org-export-translation
3400 :type 'boolean)
3402 (defcustom org-match-sexp-depth 3
3403 "Number of stacked braces for sub/superscript matching.
3404 This has to be set before loading org.el to be effective."
3405 :group 'org-export-translation
3406 :type 'integer)
3408 (defgroup org-export-tables nil
3409 "Options for exporting tables in Org-mode."
3410 :tag "Org Export Tables"
3411 :group 'org-export)
3413 (defcustom org-export-with-tables t
3414 "If non-nil, lines starting with \"|\" define a table.
3415 For example:
3417 | Name | Address | Birthday |
3418 |-------------+----------+-----------|
3419 | Arthur Dent | England | 29.2.2100 |
3421 Not all export backends support this.
3423 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3424 :group 'org-export-tables
3425 :type 'boolean)
3427 (defcustom org-export-highlight-first-table-line t
3428 "Non-nil means, highlight the first table line.
3429 In HTML export, this means use <th> instead of <td>.
3430 In tables created with table.el, this applies to the first table line.
3431 In Org-mode tables, all lines before the first horizontal separator
3432 line will be formatted with <th> tags."
3433 :group 'org-export-tables
3434 :type 'boolean)
3436 (defcustom org-export-table-remove-special-lines t
3437 "Remove special lines and marking characters in calculating tables.
3438 This removes the special marking character column from tables that are set
3439 up for spreadsheet calculations. It also removes the entire lines
3440 marked with `!', `_', or `^'. The lines with `$' are kept, because
3441 the values of constants may be useful to have."
3442 :group 'org-export-tables
3443 :type 'boolean)
3445 (defcustom org-export-prefer-native-exporter-for-tables nil
3446 "Non-nil means, always export tables created with table.el natively.
3447 Natively means, use the HTML code generator in table.el.
3448 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3449 the table does not use row- or column-spanning). This has the
3450 advantage, that the automatic HTML conversions for math symbols and
3451 sub/superscripts can be applied. Org-mode's HTML generator is also
3452 much faster."
3453 :group 'org-export-tables
3454 :type 'boolean)
3456 (defgroup org-export-ascii nil
3457 "Options specific for ASCII export of Org-mode files."
3458 :tag "Org Export ASCII"
3459 :group 'org-export)
3461 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3462 "Characters for underlining headings in ASCII export.
3463 In the given sequence, these characters will be used for level 1, 2, ..."
3464 :group 'org-export-ascii
3465 :type '(repeat character))
3467 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3468 "Bullet characters for headlines converted to lists in ASCII export.
3469 The first character is used for the first lest level generated in this
3470 way, and so on. If there are more levels than characters given here,
3471 the list will be repeated.
3472 Note that plain lists will keep the same bullets as the have in the
3473 Org-mode file."
3474 :group 'org-export-ascii
3475 :type '(repeat character))
3477 (defgroup org-export-xml nil
3478 "Options specific for XML export of Org-mode files."
3479 :tag "Org Export XML"
3480 :group 'org-export)
3482 (defgroup org-export-html nil
3483 "Options specific for HTML export of Org-mode files."
3484 :tag "Org Export HTML"
3485 :group 'org-export)
3487 (defcustom org-export-html-coding-system nil
3489 :group 'org-export-html
3490 :type 'coding-system)
3492 (defcustom org-export-html-extension "html"
3493 "The extension for exported HTML files."
3494 :group 'org-export-html
3495 :type 'string)
3497 (defcustom org-export-html-style
3498 "<style type=\"text/css\">
3499 html {
3500 font-family: Times, serif;
3501 font-size: 12pt;
3503 .title { text-align: center; }
3504 .todo { color: red; }
3505 .done { color: green; }
3506 .timestamp { color: grey }
3507 .timestamp-kwd { color: CadetBlue }
3508 .tag { background-color:lightblue; font-weight:normal }
3509 .target { background-color: lavender; }
3510 pre {
3511 border: 1pt solid #AEBDCC;
3512 background-color: #F3F5F7;
3513 padding: 5pt;
3514 font-family: courier, monospace;
3516 table { border-collapse: collapse; }
3517 td, th {
3518 vertical-align: top;
3519 <!--border: 1pt solid #ADB9CC;-->
3521 </style>"
3522 "The default style specification for exported HTML files.
3523 Since there are different ways of setting style information, this variable
3524 needs to contain the full HTML structure to provide a style, including the
3525 surrounding HTML tags. The style specifications should include definitions
3526 for new classes todo, done, title, and deadline. For example, legal values
3527 would be:
3529 <style type=\"text/css\">
3530 p { font-weight: normal; color: gray; }
3531 h1 { color: black; }
3532 .title { text-align: center; }
3533 .todo, .deadline { color: red; }
3534 .done { color: green; }
3535 </style>
3537 or, if you want to keep the style in a file,
3539 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3541 As the value of this option simply gets inserted into the HTML <head> header,
3542 you can \"misuse\" it to add arbitrary text to the header."
3543 :group 'org-export-html
3544 :type 'string)
3547 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3548 "Format for typesetting the document title in HTML export."
3549 :group 'org-export-html
3550 :type 'string)
3552 (defcustom org-export-html-toplevel-hlevel 2
3553 "The <H> level for level 1 headings in HTML export."
3554 :group 'org-export-html
3555 :type 'string)
3557 (defcustom org-export-html-link-org-files-as-html t
3558 "Non-nil means, make file links to `file.org' point to `file.html'.
3559 When org-mode is exporting an org-mode file to HTML, links to
3560 non-html files are directly put into a href tag in HTML.
3561 However, links to other Org-mode files (recognized by the
3562 extension `.org.) should become links to the corresponding html
3563 file, assuming that the linked org-mode file will also be
3564 converted to HTML.
3565 When nil, the links still point to the plain `.org' file."
3566 :group 'org-export-html
3567 :type 'boolean)
3569 (defcustom org-export-html-inline-images 'maybe
3570 "Non-nil means, inline images into exported HTML pages.
3571 This is done using an <img> tag. When nil, an anchor with href is used to
3572 link to the image. If this option is `maybe', then images in links with
3573 an empty description will be inlined, while images with a description will
3574 be linked only."
3575 :group 'org-export-html
3576 :type '(choice (const :tag "Never" nil)
3577 (const :tag "Always" t)
3578 (const :tag "When there is no description" maybe)))
3580 ;; FIXME: rename
3581 (defcustom org-export-html-expand t
3582 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3583 When nil, these tags will be exported as plain text and therefore
3584 not be interpreted by a browser.
3586 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3587 :group 'org-export-html
3588 :type 'boolean)
3590 (defcustom org-export-html-table-tag
3591 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3592 "The HTML tag that is used to start a table.
3593 This must be a <table> tag, but you may change the options like
3594 borders and spacing."
3595 :group 'org-export-html
3596 :type 'string)
3598 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3599 "The opening tag for table header fields.
3600 This is customizable so that alignment options can be specified."
3601 :group 'org-export-tables
3602 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3604 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3605 "The opening tag for table data fields.
3606 This is customizable so that alignment options can be specified."
3607 :group 'org-export-tables
3608 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3610 (defcustom org-export-html-with-timestamp nil
3611 "If non-nil, write `org-export-html-html-helper-timestamp'
3612 into the exported HTML text. Otherwise, the buffer will just be saved
3613 to a file."
3614 :group 'org-export-html
3615 :type 'boolean)
3617 (defcustom org-export-html-html-helper-timestamp
3618 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3619 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3620 :group 'org-export-html
3621 :type 'string)
3623 (defgroup org-export-icalendar nil
3624 "Options specific for iCalendar export of Org-mode files."
3625 :tag "Org Export iCalendar"
3626 :group 'org-export)
3628 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3629 "The file name for the iCalendar file covering all agenda files.
3630 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3631 The file name should be absolute, the file will be overwritten without warning."
3632 :group 'org-export-icalendar
3633 :type 'file)
3635 (defcustom org-icalendar-include-todo nil
3636 "Non-nil means, export to iCalendar files should also cover TODO items."
3637 :group 'org-export-icalendar
3638 :type '(choice
3639 (const :tag "None" nil)
3640 (const :tag "Unfinished" t)
3641 (const :tag "All" all)))
3643 (defcustom org-icalendar-include-sexps t
3644 "Non-nil means, export to iCalendar files should also cover sexp entries.
3645 These are entries like in the diary, but directly in an Org-mode file."
3646 :group 'org-export-icalendar
3647 :type 'boolean)
3649 (defcustom org-icalendar-include-body 100
3650 "Amount of text below headline to be included in iCalendar export.
3651 This is a number of characters that should maximally be included.
3652 Properties, scheduling and clocking lines will always be removed.
3653 The text will be inserted into the DESCRIPTION field."
3654 :group 'org-export-icalendar
3655 :type '(choice
3656 (const :tag "Nothing" nil)
3657 (const :tag "Everything" t)
3658 (integer :tag "Max characters")))
3660 (defcustom org-icalendar-combined-name "OrgMode"
3661 "Calendar name for the combined iCalendar representing all agenda files."
3662 :group 'org-export-icalendar
3663 :type 'string)
3665 (defgroup org-font-lock nil
3666 "Font-lock settings for highlighting in Org-mode."
3667 :tag "Org Font Lock"
3668 :group 'org)
3670 (defcustom org-level-color-stars-only nil
3671 "Non-nil means fontify only the stars in each headline.
3672 When nil, the entire headline is fontified.
3673 Changing it requires restart of `font-lock-mode' to become effective
3674 also in regions already fontified."
3675 :group 'org-font-lock
3676 :type 'boolean)
3678 (defcustom org-hide-leading-stars nil
3679 "Non-nil means, hide the first N-1 stars in a headline.
3680 This works by using the face `org-hide' for these stars. This
3681 face is white for a light background, and black for a dark
3682 background. You may have to customize the face `org-hide' to
3683 make this work.
3684 Changing it requires restart of `font-lock-mode' to become effective
3685 also in regions already fontified.
3686 You may also set this on a per-file basis by adding one of the following
3687 lines to the buffer:
3689 #+STARTUP: hidestars
3690 #+STARTUP: showstars"
3691 :group 'org-font-lock
3692 :type 'boolean)
3694 (defcustom org-fontify-done-headline nil
3695 "Non-nil means, change the face of a headline if it is marked DONE.
3696 Normally, only the TODO/DONE keyword indicates the state of a headline.
3697 When this is non-nil, the headline after the keyword is set to the
3698 `org-headline-done' as an additional indication."
3699 :group 'org-font-lock
3700 :type 'boolean)
3702 (defcustom org-fontify-emphasized-text t
3703 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3704 Changing this variable requires a restart of Emacs to take effect."
3705 :group 'org-font-lock
3706 :type 'boolean)
3708 (defcustom org-highlight-latex-fragments-and-specials nil
3709 "Non-nil means, fontify what is treated specially by the exporters."
3710 :group 'org-font-lock
3711 :type 'boolean)
3713 (defcustom org-hide-emphasis-markers nil
3714 "Non-nil mean font-lock should hide the emphasis marker characters."
3715 :group 'org-font-lock
3716 :type 'boolean)
3718 (defvar org-emph-re nil
3719 "Regular expression for matching emphasis.")
3720 (defvar org-verbatim-re nil
3721 "Regular expression for matching verbatim text.")
3722 (defvar org-emphasis-regexp-components) ; defined just below
3723 (defvar org-emphasis-alist) ; defined just below
3724 (defun org-set-emph-re (var val)
3725 "Set variable and compute the emphasis regular expression."
3726 (set var val)
3727 (when (and (boundp 'org-emphasis-alist)
3728 (boundp 'org-emphasis-regexp-components)
3729 org-emphasis-alist org-emphasis-regexp-components)
3730 (let* ((e org-emphasis-regexp-components)
3731 (pre (car e))
3732 (post (nth 1 e))
3733 (border (nth 2 e))
3734 (body (nth 3 e))
3735 (nl (nth 4 e))
3736 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3737 (body1 (concat body "*?"))
3738 (markers (mapconcat 'car org-emphasis-alist ""))
3739 (vmarkers (mapconcat
3740 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3741 org-emphasis-alist "")))
3742 ;; make sure special characters appear at the right position in the class
3743 (if (string-match "\\^" markers)
3744 (setq markers (concat (replace-match "" t t markers) "^")))
3745 (if (string-match "-" markers)
3746 (setq markers (concat (replace-match "" t t markers) "-")))
3747 (if (string-match "\\^" vmarkers)
3748 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3749 (if (string-match "-" vmarkers)
3750 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3751 (if (> nl 0)
3752 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3753 (int-to-string nl) "\\}")))
3754 ;; Make the regexp
3755 (setq org-emph-re
3756 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3757 "\\("
3758 "\\([" markers "]\\)"
3759 "\\("
3760 "[^" border "]\\|"
3761 "[^" border (if (and nil stacked) markers) "]"
3762 body1
3763 "[^" border (if (and nil stacked) markers) "]"
3764 "\\)"
3765 "\\3\\)"
3766 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3767 (setq org-verbatim-re
3768 (concat "\\([" pre "]\\|^\\)"
3769 "\\("
3770 "\\([" vmarkers "]\\)"
3771 "\\("
3772 "[^" border "]\\|"
3773 "[^" border "]"
3774 body1
3775 "[^" border "]"
3776 "\\)"
3777 "\\3\\)"
3778 "\\([" post "]\\|$\\)")))))
3780 (defcustom org-emphasis-regexp-components
3781 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3782 "Components used to build the regular expression for emphasis.
3783 This is a list with 6 entries. Terminology: In an emphasis string
3784 like \" *strong word* \", we call the initial space PREMATCH, the final
3785 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3786 and \"trong wor\" is the body. The different components in this variable
3787 specify what is allowed/forbidden in each part:
3789 pre Chars allowed as prematch. Beginning of line will be allowed too.
3790 post Chars allowed as postmatch. End of line will be allowed too.
3791 border The chars *forbidden* as border characters.
3792 body-regexp A regexp like \".\" to match a body character. Don't use
3793 non-shy groups here, and don't allow newline here.
3794 newline The maximum number of newlines allowed in an emphasis exp.
3796 Use customize to modify this, or restart Emacs after changing it."
3797 :group 'org-font-lock
3798 :set 'org-set-emph-re
3799 :type '(list
3800 (sexp :tag "Allowed chars in pre ")
3801 (sexp :tag "Allowed chars in post ")
3802 (sexp :tag "Forbidden chars in border ")
3803 (sexp :tag "Regexp for body ")
3804 (integer :tag "number of newlines allowed")
3805 (option (boolean :tag "Stacking (DISABLED) "))))
3807 (defcustom org-emphasis-alist
3808 '(("*" bold "<b>" "</b>")
3809 ("/" italic "<i>" "</i>")
3810 ("_" underline "<u>" "</u>")
3811 ("=" org-code "<code>" "</code>" verbatim)
3812 ("~" org-verbatim "" "" verbatim)
3813 ("+" (:strike-through t) "<del>" "</del>")
3815 "Special syntax for emphasized text.
3816 Text starting and ending with a special character will be emphasized, for
3817 example *bold*, _underlined_ and /italic/. This variable sets the marker
3818 characters, the face to be used by font-lock for highlighting in Org-mode
3819 Emacs buffers, and the HTML tags to be used for this.
3820 Use customize to modify this, or restart Emacs after changing it."
3821 :group 'org-font-lock
3822 :set 'org-set-emph-re
3823 :type '(repeat
3824 (list
3825 (string :tag "Marker character")
3826 (choice
3827 (face :tag "Font-lock-face")
3828 (plist :tag "Face property list"))
3829 (string :tag "HTML start tag")
3830 (string :tag "HTML end tag")
3831 (option (const verbatim)))))
3833 ;;; The faces
3835 (defgroup org-faces nil
3836 "Faces in Org-mode."
3837 :tag "Org Faces"
3838 :group 'org-font-lock)
3840 (defun org-compatible-face (inherits specs)
3841 "Make a compatible face specification.
3842 If INHERITS is an existing face and if the Emacs version supports it,
3843 just inherit the face. If not, use SPECS to define the face.
3844 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3845 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3846 to the top of the list. The `min-colors' attribute will be removed from
3847 any other entries, and any resulting duplicates will be removed entirely."
3848 (cond
3849 ((and inherits (facep inherits)
3850 (not (featurep 'xemacs)) (> emacs-major-version 22))
3851 ;; In Emacs 23, we use inheritance where possible.
3852 ;; We only do this in Emacs 23, because only there the outline
3853 ;; faces have been changed to the original org-mode-level-faces.
3854 (list (list t :inherit inherits)))
3855 ((or (featurep 'xemacs) (< emacs-major-version 22))
3856 ;; These do not understand the `min-colors' attribute.
3857 (let (r e a)
3858 (while (setq e (pop specs))
3859 (cond
3860 ((memq (car e) '(t default)) (push e r))
3861 ((setq a (member '(min-colors 8) (car e)))
3862 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3863 (cdr e)))))
3864 ((setq a (assq 'min-colors (car e)))
3865 (setq e (cons (delq a (car e)) (cdr e)))
3866 (or (assoc (car e) r) (push e r)))
3867 (t (or (assoc (car e) r) (push e r)))))
3868 (nreverse r)))
3869 (t specs)))
3870 (put 'org-compatible-face 'lisp-indent-function 1)
3872 (defface org-hide
3873 '((((background light)) (:foreground "white"))
3874 (((background dark)) (:foreground "black")))
3875 "Face used to hide leading stars in headlines.
3876 The forground color of this face should be equal to the background
3877 color of the frame."
3878 :group 'org-faces)
3880 (defface org-level-1 ;; font-lock-function-name-face
3881 (org-compatible-face 'outline-1
3882 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3883 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3884 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3885 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3886 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3887 (t (:bold t))))
3888 "Face used for level 1 headlines."
3889 :group 'org-faces)
3891 (defface org-level-2 ;; font-lock-variable-name-face
3892 (org-compatible-face 'outline-2
3893 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3894 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3895 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3896 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3897 (t (:bold t))))
3898 "Face used for level 2 headlines."
3899 :group 'org-faces)
3901 (defface org-level-3 ;; font-lock-keyword-face
3902 (org-compatible-face 'outline-3
3903 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3904 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3905 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3906 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3907 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3908 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3909 (t (:bold t))))
3910 "Face used for level 3 headlines."
3911 :group 'org-faces)
3913 (defface org-level-4 ;; font-lock-comment-face
3914 (org-compatible-face 'outline-4
3915 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3916 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3917 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3918 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3919 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3920 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3921 (t (:bold t))))
3922 "Face used for level 4 headlines."
3923 :group 'org-faces)
3925 (defface org-level-5 ;; font-lock-type-face
3926 (org-compatible-face 'outline-5
3927 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3928 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3929 (((class color) (min-colors 8)) (:foreground "green"))))
3930 "Face used for level 5 headlines."
3931 :group 'org-faces)
3933 (defface org-level-6 ;; font-lock-constant-face
3934 (org-compatible-face 'outline-6
3935 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3936 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3937 (((class color) (min-colors 8)) (:foreground "magenta"))))
3938 "Face used for level 6 headlines."
3939 :group 'org-faces)
3941 (defface org-level-7 ;; font-lock-builtin-face
3942 (org-compatible-face 'outline-7
3943 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3944 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3945 (((class color) (min-colors 8)) (:foreground "blue"))))
3946 "Face used for level 7 headlines."
3947 :group 'org-faces)
3949 (defface org-level-8 ;; font-lock-string-face
3950 (org-compatible-face 'outline-8
3951 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3952 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3953 (((class color) (min-colors 8)) (:foreground "green"))))
3954 "Face used for level 8 headlines."
3955 :group 'org-faces)
3957 (defface org-special-keyword ;; font-lock-string-face
3958 (org-compatible-face nil
3959 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3960 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3961 (t (:italic t))))
3962 "Face used for special keywords."
3963 :group 'org-faces)
3965 (defface org-drawer ;; font-lock-function-name-face
3966 (org-compatible-face nil
3967 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3968 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3969 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3970 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3971 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3972 (t (:bold t))))
3973 "Face used for drawers."
3974 :group 'org-faces)
3976 (defface org-property-value nil
3977 "Face used for the value of a property."
3978 :group 'org-faces)
3980 (defface org-column
3981 (org-compatible-face nil
3982 '((((class color) (min-colors 16) (background light))
3983 (:background "grey90"))
3984 (((class color) (min-colors 16) (background dark))
3985 (:background "grey30"))
3986 (((class color) (min-colors 8))
3987 (:background "cyan" :foreground "black"))
3988 (t (:inverse-video t))))
3989 "Face for column display of entry properties."
3990 :group 'org-faces)
3992 (when (fboundp 'set-face-attribute)
3993 ;; Make sure that a fixed-width face is used when we have a column table.
3994 (set-face-attribute 'org-column nil
3995 :height (face-attribute 'default :height)
3996 :family (face-attribute 'default :family)))
3998 (defface org-warning
3999 (org-compatible-face 'font-lock-warning-face
4000 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4001 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4002 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4003 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4004 (t (:bold t))))
4005 "Face for deadlines and TODO keywords."
4006 :group 'org-faces)
4008 (defface org-archived ; similar to shadow
4009 (org-compatible-face 'shadow
4010 '((((class color grayscale) (min-colors 88) (background light))
4011 (:foreground "grey50"))
4012 (((class color grayscale) (min-colors 88) (background dark))
4013 (:foreground "grey70"))
4014 (((class color) (min-colors 8) (background light))
4015 (:foreground "green"))
4016 (((class color) (min-colors 8) (background dark))
4017 (:foreground "yellow"))))
4018 "Face for headline with the ARCHIVE tag."
4019 :group 'org-faces)
4021 (defface org-link
4022 '((((class color) (background light)) (:foreground "Purple" :underline t))
4023 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4024 (t (:underline t)))
4025 "Face for links."
4026 :group 'org-faces)
4028 (defface org-ellipsis
4029 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
4030 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
4031 (t (:strike-through t)))
4032 "Face for the ellipsis in folded text."
4033 :group 'org-faces)
4035 (defface org-target
4036 '((((class color) (background light)) (:underline t))
4037 (((class color) (background dark)) (:underline t))
4038 (t (:underline t)))
4039 "Face for links."
4040 :group 'org-faces)
4042 (defface org-date
4043 '((((class color) (background light)) (:foreground "Purple" :underline t))
4044 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4045 (t (:underline t)))
4046 "Face for links."
4047 :group 'org-faces)
4049 (defface org-sexp-date
4050 '((((class color) (background light)) (:foreground "Purple"))
4051 (((class color) (background dark)) (:foreground "Cyan"))
4052 (t (:underline t)))
4053 "Face for links."
4054 :group 'org-faces)
4056 (defface org-tag
4057 '((t (:bold t)))
4058 "Face for tags."
4059 :group 'org-faces)
4061 (defface org-todo ; font-lock-warning-face
4062 (org-compatible-face nil
4063 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4064 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4065 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4066 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4067 (t (:inverse-video t :bold t))))
4068 "Face for TODO keywords."
4069 :group 'org-faces)
4071 (defface org-done ;; font-lock-type-face
4072 (org-compatible-face nil
4073 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
4074 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
4075 (((class color) (min-colors 8)) (:foreground "green"))
4076 (t (:bold t))))
4077 "Face used for todo keywords that indicate DONE items."
4078 :group 'org-faces)
4080 (defface org-headline-done ;; font-lock-string-face
4081 (org-compatible-face nil
4082 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4083 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4084 (((class color) (min-colors 8) (background light)) (:bold nil))))
4085 "Face used to indicate that a headline is DONE.
4086 This face is only used if `org-fontify-done-headline' is set. If applies
4087 to the part of the headline after the DONE keyword."
4088 :group 'org-faces)
4090 (defcustom org-todo-keyword-faces nil
4091 "Faces for specific TODO keywords.
4092 This is a list of cons cells, with TODO keywords in the car
4093 and faces in the cdr. The face can be a symbol, or a property
4094 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
4095 :group 'org-faces
4096 :group 'org-todo
4097 :type '(repeat
4098 (cons
4099 (string :tag "keyword")
4100 (sexp :tag "face"))))
4102 (defface org-table ;; font-lock-function-name-face
4103 (org-compatible-face nil
4104 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4105 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4106 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4107 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4108 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4109 (((class color) (min-colors 8) (background dark)))))
4110 "Face used for tables."
4111 :group 'org-faces)
4113 (defface org-formula
4114 (org-compatible-face nil
4115 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4116 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4117 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4118 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4119 (t (:bold t :italic t))))
4120 "Face for formulas."
4121 :group 'org-faces)
4123 (defface org-code
4124 (org-compatible-face nil
4125 '((((class color grayscale) (min-colors 88) (background light))
4126 (:foreground "grey50"))
4127 (((class color grayscale) (min-colors 88) (background dark))
4128 (:foreground "grey70"))
4129 (((class color) (min-colors 8) (background light))
4130 (:foreground "green"))
4131 (((class color) (min-colors 8) (background dark))
4132 (:foreground "yellow"))))
4133 "Face for fixed-with text like code snippets."
4134 :group 'org-faces
4135 :version "22.1")
4137 (defface org-verbatim
4138 (org-compatible-face nil
4139 '((((class color grayscale) (min-colors 88) (background light))
4140 (:foreground "grey50" :underline t))
4141 (((class color grayscale) (min-colors 88) (background dark))
4142 (:foreground "grey70" :underline t))
4143 (((class color) (min-colors 8) (background light))
4144 (:foreground "green" :underline t))
4145 (((class color) (min-colors 8) (background dark))
4146 (:foreground "yellow" :underline t))))
4147 "Face for fixed-with text like code snippets."
4148 :group 'org-faces
4149 :version "22.1")
4151 (defface org-agenda-structure ;; font-lock-function-name-face
4152 (org-compatible-face nil
4153 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4154 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4155 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4156 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4157 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4158 (t (:bold t))))
4159 "Face used in agenda for captions and dates."
4160 :group 'org-faces)
4162 (defface org-scheduled-today
4163 (org-compatible-face nil
4164 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4165 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4166 (((class color) (min-colors 8)) (:foreground "green"))
4167 (t (:bold t :italic t))))
4168 "Face for items scheduled for a certain day."
4169 :group 'org-faces)
4171 (defface org-scheduled-previously
4172 (org-compatible-face nil
4173 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4174 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4175 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4176 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4177 (t (:bold t))))
4178 "Face for items scheduled previously, and not yet done."
4179 :group 'org-faces)
4181 (defface org-upcoming-deadline
4182 (org-compatible-face nil
4183 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4184 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4185 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4186 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4187 (t (:bold t))))
4188 "Face for items scheduled previously, and not yet done."
4189 :group 'org-faces)
4191 (defcustom org-agenda-deadline-faces
4192 '((1.0 . org-warning)
4193 (0.5 . org-upcoming-deadline)
4194 (0.0 . default))
4195 "Faces for showing deadlines in the agenda.
4196 This is a list of cons cells. The cdr of each cell is a face to be used,
4197 and it can also just be like '(:foreground \"yellow\").
4198 Each car is a fraction of the head-warning time that must have passed for
4199 this the face in the cdr to be used for display. The numbers must be
4200 given in descending order. The head-warning time is normally taken
4201 from `org-deadline-warning-days', but can also be specified in the deadline
4202 timestamp itself, like this:
4204 DEADLINE: <2007-08-13 Mon -8d>
4206 You may use d for days, w for weeks, m for months and y for years. Months
4207 and years will only be treated in an approximate fashion (30.4 days for a
4208 month and 365.24 days for a year)."
4209 :group 'org-faces
4210 :group 'org-agenda-daily/weekly
4211 :type '(repeat
4212 (cons
4213 (number :tag "Fraction of head-warning time passed")
4214 (sexp :tag "Face"))))
4216 ;; FIXME: this is not a good face yet.
4217 (defface org-agenda-restriction-lock
4218 (org-compatible-face nil
4219 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4220 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4221 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4222 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4223 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4224 (t (:inverse-video t))))
4225 "Face for showing the agenda restriction lock."
4226 :group 'org-faces)
4228 (defface org-time-grid ;; font-lock-variable-name-face
4229 (org-compatible-face nil
4230 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4231 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4232 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4233 "Face used for time grids."
4234 :group 'org-faces)
4236 (defconst org-level-faces
4237 '(org-level-1 org-level-2 org-level-3 org-level-4
4238 org-level-5 org-level-6 org-level-7 org-level-8
4241 (defcustom org-n-level-faces (length org-level-faces)
4242 "The number of different faces to be used for headlines.
4243 Org-mode defines 8 different headline faces, so this can be at most 8.
4244 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4245 :type 'number
4246 :group 'org-faces)
4248 ;;; Functions and variables from ther packages
4249 ;; Declared here to avoid compiler warnings
4251 (eval-and-compile
4252 (unless (fboundp 'declare-function)
4253 (defmacro declare-function (fn file &optional arglist fileonly))))
4255 ;; XEmacs only
4256 (defvar outline-mode-menu-heading)
4257 (defvar outline-mode-menu-show)
4258 (defvar outline-mode-menu-hide)
4259 (defvar zmacs-regions) ; XEmacs regions
4261 ;; Emacs only
4262 (defvar mark-active)
4264 ;; Various packages
4265 ;; FIXME: get the argument lists for the UNKNOWN stuff
4266 (declare-function add-to-diary-list "diary-lib"
4267 (date string specifier &optional marker globcolor literal))
4268 (declare-function table--at-cell-p "table" (position &optional object at-column))
4269 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4270 (declare-function bbdb "ext:bbdb-com" (string elidep))
4271 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4272 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4273 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4274 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4275 (declare-function bbdb-record-name "ext:bbdb" (record))
4276 (declare-function bibtex-beginning-of-entry "bibtex" ())
4277 (declare-function bibtex-generate-autokey "bibtex" ())
4278 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4279 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4280 (defvar calc-embedded-close-formula)
4281 (defvar calc-embedded-open-formula)
4282 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4283 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4284 (declare-function calendar-check-holidays "holidays" (date))
4285 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4286 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4287 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4288 (declare-function calendar-forward-day "cal-move" (arg))
4289 (declare-function calendar-french-date-string "cal-french" (&optional date))
4290 (declare-function calendar-goto-date "cal-move" (date))
4291 (declare-function calendar-goto-today "cal-move" ())
4292 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4293 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4294 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4295 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4296 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4297 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4298 (defvar calendar-mode-map)
4299 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4300 (declare-function cdlatex-tab "ext:cdlatex" ())
4301 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4302 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4303 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4304 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4305 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4306 (defvar font-lock-unfontify-region-function)
4307 (declare-function gnus-article-show-summary "gnus-art" ())
4308 (declare-function gnus-summary-last-subject "gnus-sum" ())
4309 (defvar gnus-other-frame-object)
4310 (defvar gnus-group-name)
4311 (defvar gnus-article-current)
4312 (defvar Info-current-file)
4313 (defvar Info-current-node)
4314 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4315 (declare-function mh-find-path "mh-utils" ())
4316 (declare-function mh-get-header-field "mh-utils" (field))
4317 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4318 (declare-function mh-header-display "mh-show" ())
4319 (declare-function mh-index-previous-folder "mh-search" ())
4320 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4321 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4322 (declare-function mh-search-choose "mh-search" (&optional searcher))
4323 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4324 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4325 (declare-function mh-show-header-display "mh-show" t t)
4326 (declare-function mh-show-msg "mh-show" (msg))
4327 (declare-function mh-show-show "mh-show" t t)
4328 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4329 (defvar mh-progs)
4330 (defvar mh-current-folder)
4331 (defvar mh-show-folder-buffer)
4332 (defvar mh-index-folder)
4333 (defvar mh-searcher)
4334 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4335 (declare-function parse-time-string "parse-time" (string))
4336 (declare-function remember "remember" (&optional initial))
4337 (declare-function remember-buffer-desc "remember" ())
4338 (declare-function remember-finalize "remember" ())
4339 (defvar remember-save-after-remembering)
4340 (defvar remember-data-file)
4341 (defvar remember-register)
4342 (defvar remember-buffer)
4343 (defvar remember-handler-functions)
4344 (defvar remember-annotation-functions)
4345 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4346 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4347 (declare-function rmail-what-message "rmail" ())
4348 (defvar rmail-current-message)
4349 (defvar texmathp-why)
4350 (declare-function vm-beginning-of-message "ext:vm-page" ())
4351 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4352 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4353 (declare-function vm-isearch-narrow "ext:vm-search" ())
4354 (declare-function vm-isearch-update "ext:vm-search" ())
4355 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4356 (declare-function vm-su-message-id "ext:vm-summary" (m))
4357 (declare-function vm-su-subject "ext:vm-summary" (m))
4358 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4359 (defvar vm-message-pointer)
4360 (defvar vm-folder-directory)
4361 (defvar w3m-current-url)
4362 (defvar w3m-current-title)
4363 ;; backward compatibility to old version of wl
4364 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4365 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4366 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4367 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4368 (declare-function wl-summary-line-from "ext:wl-summary" ())
4369 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4370 (declare-function wl-summary-message-number "ext:wl-summary" ())
4371 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4372 (defvar wl-summary-buffer-elmo-folder)
4373 (defvar wl-summary-buffer-folder-name)
4374 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4376 (defvar org-latex-regexps)
4377 (defvar constants-unit-system)
4379 ;;; Variables for pre-computed regular expressions, all buffer local
4381 (defvar org-drawer-regexp nil
4382 "Matches first line of a hidden block.")
4383 (make-variable-buffer-local 'org-drawer-regexp)
4384 (defvar org-todo-regexp nil
4385 "Matches any of the TODO state keywords.")
4386 (make-variable-buffer-local 'org-todo-regexp)
4387 (defvar org-not-done-regexp nil
4388 "Matches any of the TODO state keywords except the last one.")
4389 (make-variable-buffer-local 'org-not-done-regexp)
4390 (defvar org-todo-line-regexp nil
4391 "Matches a headline and puts TODO state into group 2 if present.")
4392 (make-variable-buffer-local 'org-todo-line-regexp)
4393 (defvar org-complex-heading-regexp nil
4394 "Matches a headline and puts everything into groups:
4395 group 1: the stars
4396 group 2: The todo keyword, maybe
4397 group 3: Priority cookie
4398 group 4: True headline
4399 group 5: Tags")
4400 (make-variable-buffer-local 'org-complex-heading-regexp)
4401 (defvar org-todo-line-tags-regexp nil
4402 "Matches a headline and puts TODO state into group 2 if present.
4403 Also put tags into group 4 if tags are present.")
4404 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4405 (defvar org-nl-done-regexp nil
4406 "Matches newline followed by a headline with the DONE keyword.")
4407 (make-variable-buffer-local 'org-nl-done-regexp)
4408 (defvar org-looking-at-done-regexp nil
4409 "Matches the DONE keyword a point.")
4410 (make-variable-buffer-local 'org-looking-at-done-regexp)
4411 (defvar org-ds-keyword-length 12
4412 "Maximum length of the Deadline and SCHEDULED keywords.")
4413 (make-variable-buffer-local 'org-ds-keyword-length)
4414 (defvar org-deadline-regexp nil
4415 "Matches the DEADLINE keyword.")
4416 (make-variable-buffer-local 'org-deadline-regexp)
4417 (defvar org-deadline-time-regexp nil
4418 "Matches the DEADLINE keyword together with a time stamp.")
4419 (make-variable-buffer-local 'org-deadline-time-regexp)
4420 (defvar org-deadline-line-regexp nil
4421 "Matches the DEADLINE keyword and the rest of the line.")
4422 (make-variable-buffer-local 'org-deadline-line-regexp)
4423 (defvar org-scheduled-regexp nil
4424 "Matches the SCHEDULED keyword.")
4425 (make-variable-buffer-local 'org-scheduled-regexp)
4426 (defvar org-scheduled-time-regexp nil
4427 "Matches the SCHEDULED keyword together with a time stamp.")
4428 (make-variable-buffer-local 'org-scheduled-time-regexp)
4429 (defvar org-closed-time-regexp nil
4430 "Matches the CLOSED keyword together with a time stamp.")
4431 (make-variable-buffer-local 'org-closed-time-regexp)
4433 (defvar org-keyword-time-regexp nil
4434 "Matches any of the 4 keywords, together with the time stamp.")
4435 (make-variable-buffer-local 'org-keyword-time-regexp)
4436 (defvar org-keyword-time-not-clock-regexp nil
4437 "Matches any of the 3 keywords, together with the time stamp.")
4438 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4439 (defvar org-maybe-keyword-time-regexp nil
4440 "Matches a timestamp, possibly preceeded by a keyword.")
4441 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4442 (defvar org-planning-or-clock-line-re nil
4443 "Matches a line with planning or clock info.")
4444 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4446 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4447 rear-nonsticky t mouse-map t fontified t)
4448 "Properties to remove when a string without properties is wanted.")
4450 (defsubst org-match-string-no-properties (num &optional string)
4451 (if (featurep 'xemacs)
4452 (let ((s (match-string num string)))
4453 (remove-text-properties 0 (length s) org-rm-props s)
4455 (match-string-no-properties num string)))
4457 (defsubst org-no-properties (s)
4458 (if (fboundp 'set-text-properties)
4459 (set-text-properties 0 (length s) nil s)
4460 (remove-text-properties 0 (length s) org-rm-props s))
4463 (defsubst org-get-alist-option (option key)
4464 (cond ((eq key t) t)
4465 ((eq option t) t)
4466 ((assoc key option) (cdr (assoc key option)))
4467 (t (cdr (assq 'default option)))))
4469 (defsubst org-inhibit-invisibility ()
4470 "Modified `buffer-invisibility-spec' for Emacs 21.
4471 Some ops with invisible text do not work correctly on Emacs 21. For these
4472 we turn off invisibility temporarily. Use this in a `let' form."
4473 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4475 (defsubst org-set-local (var value)
4476 "Make VAR local in current buffer and set it to VALUE."
4477 (set (make-variable-buffer-local var) value))
4479 (defsubst org-mode-p ()
4480 "Check if the current buffer is in Org-mode."
4481 (eq major-mode 'org-mode))
4483 (defsubst org-last (list)
4484 "Return the last element of LIST."
4485 (car (last list)))
4487 (defun org-let (list &rest body)
4488 (eval (cons 'let (cons list body))))
4489 (put 'org-let 'lisp-indent-function 1)
4491 (defun org-let2 (list1 list2 &rest body)
4492 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4493 (put 'org-let2 'lisp-indent-function 2)
4494 (defconst org-startup-options
4495 '(("fold" org-startup-folded t)
4496 ("overview" org-startup-folded t)
4497 ("nofold" org-startup-folded nil)
4498 ("showall" org-startup-folded nil)
4499 ("content" org-startup-folded content)
4500 ("hidestars" org-hide-leading-stars t)
4501 ("showstars" org-hide-leading-stars nil)
4502 ("odd" org-odd-levels-only t)
4503 ("oddeven" org-odd-levels-only nil)
4504 ("align" org-startup-align-all-tables t)
4505 ("noalign" org-startup-align-all-tables nil)
4506 ("customtime" org-display-custom-times t)
4507 ("logdone" org-log-done time)
4508 ("lognotedone" org-log-done note)
4509 ("nologdone" org-log-done nil)
4510 ("lognoteclock-out" org-log-note-clock-out t)
4511 ("nolognoteclock-out" org-log-note-clock-out nil)
4512 ("logrepeat" org-log-repeat state)
4513 ("lognoterepeat" org-log-repeat note)
4514 ("nologrepeat" org-log-repeat nil)
4515 ("constcgs" constants-unit-system cgs)
4516 ("constSI" constants-unit-system SI))
4517 "Variable associated with STARTUP options for org-mode.
4518 Each element is a list of three items: The startup options as written
4519 in the #+STARTUP line, the corresponding variable, and the value to
4520 set this variable to if the option is found. An optional forth element PUSH
4521 means to push this value onto the list in the variable.")
4523 (defun org-set-regexps-and-options ()
4524 "Precompute regular expressions for current buffer."
4525 (when (org-mode-p)
4526 (org-set-local 'org-todo-kwd-alist nil)
4527 (org-set-local 'org-todo-key-alist nil)
4528 (org-set-local 'org-todo-key-trigger nil)
4529 (org-set-local 'org-todo-keywords-1 nil)
4530 (org-set-local 'org-done-keywords nil)
4531 (org-set-local 'org-todo-heads nil)
4532 (org-set-local 'org-todo-sets nil)
4533 (org-set-local 'org-todo-log-states nil)
4534 (let ((re (org-make-options-regexp
4535 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4536 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4537 "CONSTANTS" "PROPERTY" "DRAWERS")))
4538 (splitre "[ \t]+")
4539 kwds kws0 kwsa key log value cat arch tags const links hw dws
4540 tail sep kws1 prio props drawers)
4541 (save-excursion
4542 (save-restriction
4543 (widen)
4544 (goto-char (point-min))
4545 (while (re-search-forward re nil t)
4546 (setq key (match-string 1) value (org-match-string-no-properties 2))
4547 (cond
4548 ((equal key "CATEGORY")
4549 (if (string-match "[ \t]+$" value)
4550 (setq value (replace-match "" t t value)))
4551 (setq cat value))
4552 ((member key '("SEQ_TODO" "TODO"))
4553 (push (cons 'sequence (org-split-string value splitre)) kwds))
4554 ((equal key "TYP_TODO")
4555 (push (cons 'type (org-split-string value splitre)) kwds))
4556 ((equal key "TAGS")
4557 (setq tags (append tags (org-split-string value splitre))))
4558 ((equal key "COLUMNS")
4559 (org-set-local 'org-columns-default-format value))
4560 ((equal key "LINK")
4561 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4562 (push (cons (match-string 1 value)
4563 (org-trim (match-string 2 value)))
4564 links)))
4565 ((equal key "PRIORITIES")
4566 (setq prio (org-split-string value " +")))
4567 ((equal key "PROPERTY")
4568 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4569 (push (cons (match-string 1 value) (match-string 2 value))
4570 props)))
4571 ((equal key "DRAWERS")
4572 (setq drawers (org-split-string value splitre)))
4573 ((equal key "CONSTANTS")
4574 (setq const (append const (org-split-string value splitre))))
4575 ((equal key "STARTUP")
4576 (let ((opts (org-split-string value splitre))
4577 l var val)
4578 (while (setq l (pop opts))
4579 (when (setq l (assoc l org-startup-options))
4580 (setq var (nth 1 l) val (nth 2 l))
4581 (if (not (nth 3 l))
4582 (set (make-local-variable var) val)
4583 (if (not (listp (symbol-value var)))
4584 (set (make-local-variable var) nil))
4585 (set (make-local-variable var) (symbol-value var))
4586 (add-to-list var val))))))
4587 ((equal key "ARCHIVE")
4588 (string-match " *$" value)
4589 (setq arch (replace-match "" t t value))
4590 (remove-text-properties 0 (length arch)
4591 '(face t fontified t) arch)))
4593 (when cat
4594 (org-set-local 'org-category (intern cat))
4595 (push (cons "CATEGORY" cat) props))
4596 (when prio
4597 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4598 (setq prio (mapcar 'string-to-char prio))
4599 (org-set-local 'org-highest-priority (nth 0 prio))
4600 (org-set-local 'org-lowest-priority (nth 1 prio))
4601 (org-set-local 'org-default-priority (nth 2 prio)))
4602 (and props (org-set-local 'org-local-properties (nreverse props)))
4603 (and drawers (org-set-local 'org-drawers drawers))
4604 (and arch (org-set-local 'org-archive-location arch))
4605 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4606 ;; Process the TODO keywords
4607 (unless kwds
4608 ;; Use the global values as if they had been given locally.
4609 (setq kwds (default-value 'org-todo-keywords))
4610 (if (stringp (car kwds))
4611 (setq kwds (list (cons org-todo-interpretation
4612 (default-value 'org-todo-keywords)))))
4613 (setq kwds (reverse kwds)))
4614 (setq kwds (nreverse kwds))
4615 (let (inter kws kw)
4616 (while (setq kws (pop kwds))
4617 (setq inter (pop kws) sep (member "|" kws)
4618 kws0 (delete "|" (copy-sequence kws))
4619 kwsa nil
4620 kws1 (mapcar
4621 (lambda (x)
4622 ;; 1 2
4623 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4624 (progn
4625 (setq kw (match-string 1 x)
4626 key (and (match-end 2) (match-string 2 x))
4627 log (org-extract-log-state-settings x))
4628 (push (cons kw (and key (string-to-char key))) kwsa)
4629 (and log (push log org-todo-log-states))
4631 (error "Invalid TODO keyword %s" x)))
4632 kws0)
4633 kwsa (if kwsa (append '((:startgroup))
4634 (nreverse kwsa)
4635 '((:endgroup))))
4636 hw (car kws1)
4637 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4638 tail (list inter hw (car dws) (org-last dws)))
4639 (add-to-list 'org-todo-heads hw 'append)
4640 (push kws1 org-todo-sets)
4641 (setq org-done-keywords (append org-done-keywords dws nil))
4642 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4643 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4644 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4645 (setq org-todo-sets (nreverse org-todo-sets)
4646 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4647 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4648 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4649 ;; Process the constants
4650 (when const
4651 (let (e cst)
4652 (while (setq e (pop const))
4653 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4654 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4655 (setq org-table-formula-constants-local cst)))
4657 ;; Process the tags.
4658 (when tags
4659 (let (e tgs)
4660 (while (setq e (pop tags))
4661 (cond
4662 ((equal e "{") (push '(:startgroup) tgs))
4663 ((equal e "}") (push '(:endgroup) tgs))
4664 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4665 (push (cons (match-string 1 e)
4666 (string-to-char (match-string 2 e)))
4667 tgs))
4668 (t (push (list e) tgs))))
4669 (org-set-local 'org-tag-alist nil)
4670 (while (setq e (pop tgs))
4671 (or (and (stringp (car e))
4672 (assoc (car e) org-tag-alist))
4673 (push e org-tag-alist))))))
4675 ;; Compute the regular expressions and other local variables
4676 (if (not org-done-keywords)
4677 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4678 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4679 (length org-scheduled-string)))
4680 org-drawer-regexp
4681 (concat "^[ \t]*:\\("
4682 (mapconcat 'regexp-quote org-drawers "\\|")
4683 "\\):[ \t]*$")
4684 org-not-done-keywords
4685 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4686 org-todo-regexp
4687 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4688 "\\|") "\\)\\>")
4689 org-not-done-regexp
4690 (concat "\\<\\("
4691 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4692 "\\)\\>")
4693 org-todo-line-regexp
4694 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4695 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4696 "\\)\\>\\)?[ \t]*\\(.*\\)")
4697 org-complex-heading-regexp
4698 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4699 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4700 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4701 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4702 org-nl-done-regexp
4703 (concat "\n\\*+[ \t]+"
4704 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4705 "\\)" "\\>")
4706 org-todo-line-tags-regexp
4707 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4708 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4709 (org-re
4710 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4711 org-looking-at-done-regexp
4712 (concat "^" "\\(?:"
4713 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4714 "\\>")
4715 org-deadline-regexp (concat "\\<" org-deadline-string)
4716 org-deadline-time-regexp
4717 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4718 org-deadline-line-regexp
4719 (concat "\\<\\(" org-deadline-string "\\).*")
4720 org-scheduled-regexp
4721 (concat "\\<" org-scheduled-string)
4722 org-scheduled-time-regexp
4723 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4724 org-closed-time-regexp
4725 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4726 org-keyword-time-regexp
4727 (concat "\\<\\(" org-scheduled-string
4728 "\\|" org-deadline-string
4729 "\\|" org-closed-string
4730 "\\|" org-clock-string "\\)"
4731 " *[[<]\\([^]>]+\\)[]>]")
4732 org-keyword-time-not-clock-regexp
4733 (concat "\\<\\(" org-scheduled-string
4734 "\\|" org-deadline-string
4735 "\\|" org-closed-string
4736 "\\)"
4737 " *[[<]\\([^]>]+\\)[]>]")
4738 org-maybe-keyword-time-regexp
4739 (concat "\\(\\<\\(" org-scheduled-string
4740 "\\|" org-deadline-string
4741 "\\|" org-closed-string
4742 "\\|" org-clock-string "\\)\\)?"
4743 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4744 org-planning-or-clock-line-re
4745 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4746 "\\|" org-deadline-string
4747 "\\|" org-closed-string "\\|" org-clock-string
4748 "\\)\\>\\)")
4750 (org-compute-latex-and-specials-regexp)
4751 (org-set-font-lock-defaults)))
4753 (defun org-extract-log-state-settings (x)
4754 "Extract the log state setting from a TODO keyword string.
4755 This will extract info from a string like \"WAIT(w@/!)\"."
4756 (let (kw key log1 log2)
4757 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4758 (setq kw (match-string 1 x)
4759 key (and (match-end 2) (match-string 2 x))
4760 log1 (and (match-end 3) (match-string 3 x))
4761 log2 (and (match-end 4) (match-string 4 x)))
4762 (and (or log1 log2)
4763 (list kw
4764 (and log1 (if (equal log1 "!") 'time 'note))
4765 (and log2 (if (equal log2 "!") 'time 'note)))))))
4767 (defun org-remove-keyword-keys (list)
4768 "Remove a pair of parenthesis at the end of each string in LIST."
4769 (mapcar (lambda (x)
4770 (if (string-match "(.*)$" x)
4771 (substring x 0 (match-beginning 0))
4773 list))
4775 ;; FIXME: this could be done much better, using second characters etc.
4776 (defun org-assign-fast-keys (alist)
4777 "Assign fast keys to a keyword-key alist.
4778 Respect keys that are already there."
4779 (let (new e k c c1 c2 (char ?a))
4780 (while (setq e (pop alist))
4781 (cond
4782 ((equal e '(:startgroup)) (push e new))
4783 ((equal e '(:endgroup)) (push e new))
4785 (setq k (car e) c2 nil)
4786 (if (cdr e)
4787 (setq c (cdr e))
4788 ;; automatically assign a character.
4789 (setq c1 (string-to-char
4790 (downcase (substring
4791 k (if (= (string-to-char k) ?@) 1 0)))))
4792 (if (or (rassoc c1 new) (rassoc c1 alist))
4793 (while (or (rassoc char new) (rassoc char alist))
4794 (setq char (1+ char)))
4795 (setq c2 c1))
4796 (setq c (or c2 char)))
4797 (push (cons k c) new))))
4798 (nreverse new)))
4800 ;;; Some variables ujsed in various places
4802 (defvar org-window-configuration nil
4803 "Used in various places to store a window configuration.")
4804 (defvar org-finish-function nil
4805 "Function to be called when `C-c C-c' is used.
4806 This is for getting out of special buffers like remember.")
4809 ;; FIXME: Occasionally check by commenting these, to make sure
4810 ;; no other functions uses these, forgetting to let-bind them.
4811 (defvar entry)
4812 (defvar state)
4813 (defvar last-state)
4814 (defvar date)
4815 (defvar description)
4817 ;; Defined somewhere in this file, but used before definition.
4818 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4819 (defvar org-agenda-buffer-name)
4820 (defvar org-agenda-undo-list)
4821 (defvar org-agenda-pending-undo-list)
4822 (defvar org-agenda-overriding-header)
4823 (defvar orgtbl-mode)
4824 (defvar org-html-entities)
4825 (defvar org-struct-menu)
4826 (defvar org-org-menu)
4827 (defvar org-tbl-menu)
4828 (defvar org-agenda-keymap)
4830 ;;;; Emacs/XEmacs compatibility
4832 ;; Overlay compatibility functions
4833 (defun org-make-overlay (beg end &optional buffer)
4834 (if (featurep 'xemacs)
4835 (make-extent beg end buffer)
4836 (make-overlay beg end buffer)))
4837 (defun org-delete-overlay (ovl)
4838 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4839 (defun org-detach-overlay (ovl)
4840 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4841 (defun org-move-overlay (ovl beg end &optional buffer)
4842 (if (featurep 'xemacs)
4843 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4844 (move-overlay ovl beg end buffer)))
4845 (defun org-overlay-put (ovl prop value)
4846 (if (featurep 'xemacs)
4847 (set-extent-property ovl prop value)
4848 (overlay-put ovl prop value)))
4849 (defun org-overlay-display (ovl text &optional face evap)
4850 "Make overlay OVL display TEXT with face FACE."
4851 (if (featurep 'xemacs)
4852 (let ((gl (make-glyph text)))
4853 (and face (set-glyph-face gl face))
4854 (set-extent-property ovl 'invisible t)
4855 (set-extent-property ovl 'end-glyph gl))
4856 (overlay-put ovl 'display text)
4857 (if face (overlay-put ovl 'face face))
4858 (if evap (overlay-put ovl 'evaporate t))))
4859 (defun org-overlay-before-string (ovl text &optional face evap)
4860 "Make overlay OVL display TEXT with face FACE."
4861 (if (featurep 'xemacs)
4862 (let ((gl (make-glyph text)))
4863 (and face (set-glyph-face gl face))
4864 (set-extent-property ovl 'begin-glyph gl))
4865 (if face (org-add-props text nil 'face face))
4866 (overlay-put ovl 'before-string text)
4867 (if evap (overlay-put ovl 'evaporate t))))
4868 (defun org-overlay-get (ovl prop)
4869 (if (featurep 'xemacs)
4870 (extent-property ovl prop)
4871 (overlay-get ovl prop)))
4872 (defun org-overlays-at (pos)
4873 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4874 (defun org-overlays-in (&optional start end)
4875 (if (featurep 'xemacs)
4876 (extent-list nil start end)
4877 (overlays-in start end)))
4878 (defun org-overlay-start (o)
4879 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4880 (defun org-overlay-end (o)
4881 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4882 (defun org-find-overlays (prop &optional pos delete)
4883 "Find all overlays specifying PROP at POS or point.
4884 If DELETE is non-nil, delete all those overlays."
4885 (let ((overlays (org-overlays-at (or pos (point))))
4886 ov found)
4887 (while (setq ov (pop overlays))
4888 (if (org-overlay-get ov prop)
4889 (if delete (org-delete-overlay ov) (push ov found))))
4890 found))
4892 ;; Region compatibility
4894 (defun org-add-hook (hook function &optional append local)
4895 "Add-hook, compatible with both Emacsen."
4896 (if (and local (featurep 'xemacs))
4897 (add-local-hook hook function append)
4898 (add-hook hook function append local)))
4900 (defvar org-ignore-region nil
4901 "To temporarily disable the active region.")
4903 (defun org-region-active-p ()
4904 "Is `transient-mark-mode' on and the region active?
4905 Works on both Emacs and XEmacs."
4906 (if org-ignore-region
4908 (if (featurep 'xemacs)
4909 (and zmacs-regions (region-active-p))
4910 (if (fboundp 'use-region-p)
4911 (use-region-p)
4912 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4914 ;; Invisibility compatibility
4916 (defun org-add-to-invisibility-spec (arg)
4917 "Add elements to `buffer-invisibility-spec'.
4918 See documentation for `buffer-invisibility-spec' for the kind of elements
4919 that can be added."
4920 (cond
4921 ((fboundp 'add-to-invisibility-spec)
4922 (add-to-invisibility-spec arg))
4923 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4924 (setq buffer-invisibility-spec (list arg)))
4926 (setq buffer-invisibility-spec
4927 (cons arg buffer-invisibility-spec)))))
4929 (defun org-remove-from-invisibility-spec (arg)
4930 "Remove elements from `buffer-invisibility-spec'."
4931 (if (fboundp 'remove-from-invisibility-spec)
4932 (remove-from-invisibility-spec arg)
4933 (if (consp buffer-invisibility-spec)
4934 (setq buffer-invisibility-spec
4935 (delete arg buffer-invisibility-spec)))))
4937 (defun org-in-invisibility-spec-p (arg)
4938 "Is ARG a member of `buffer-invisibility-spec'?"
4939 (if (consp buffer-invisibility-spec)
4940 (member arg buffer-invisibility-spec)
4941 nil))
4943 ;;;; Define the Org-mode
4945 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4946 (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."))
4949 ;; We use a before-change function to check if a table might need
4950 ;; an update.
4951 (defvar org-table-may-need-update t
4952 "Indicates that a table might need an update.
4953 This variable is set by `org-before-change-function'.
4954 `org-table-align' sets it back to nil.")
4955 (defvar org-mode-map)
4956 (defvar org-mode-hook nil)
4957 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4958 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4959 (defvar org-table-buffer-is-an nil)
4960 (defconst org-outline-regexp "\\*+ ")
4962 ;;;###autoload
4963 (define-derived-mode org-mode outline-mode "Org"
4964 "Outline-based notes management and organizer, alias
4965 \"Carsten's outline-mode for keeping track of everything.\"
4967 Org-mode develops organizational tasks around a NOTES file which
4968 contains information about projects as plain text. Org-mode is
4969 implemented on top of outline-mode, which is ideal to keep the content
4970 of large files well structured. It supports ToDo items, deadlines and
4971 time stamps, which magically appear in the diary listing of the Emacs
4972 calendar. Tables are easily created with a built-in table editor.
4973 Plain text URL-like links connect to websites, emails (VM), Usenet
4974 messages (Gnus), BBDB entries, and any files related to the project.
4975 For printing and sharing of notes, an Org-mode file (or a part of it)
4976 can be exported as a structured ASCII or HTML file.
4978 The following commands are available:
4980 \\{org-mode-map}"
4982 ;; Get rid of Outline menus, they are not needed
4983 ;; Need to do this here because define-derived-mode sets up
4984 ;; the keymap so late. Still, it is a waste to call this each time
4985 ;; we switch another buffer into org-mode.
4986 (if (featurep 'xemacs)
4987 (when (boundp 'outline-mode-menu-heading)
4988 ;; Assume this is Greg's port, it used easymenu
4989 (easy-menu-remove outline-mode-menu-heading)
4990 (easy-menu-remove outline-mode-menu-show)
4991 (easy-menu-remove outline-mode-menu-hide))
4992 (define-key org-mode-map [menu-bar headings] 'undefined)
4993 (define-key org-mode-map [menu-bar hide] 'undefined)
4994 (define-key org-mode-map [menu-bar show] 'undefined))
4996 (easy-menu-add org-org-menu)
4997 (easy-menu-add org-tbl-menu)
4998 (org-install-agenda-files-menu)
4999 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
5000 (org-add-to-invisibility-spec '(org-cwidth))
5001 (when (featurep 'xemacs)
5002 (org-set-local 'line-move-ignore-invisible t))
5003 (org-set-local 'outline-regexp org-outline-regexp)
5004 (org-set-local 'outline-level 'org-outline-level)
5005 (when (and org-ellipsis
5006 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5007 (fboundp 'make-glyph-code))
5008 (unless org-display-table
5009 (setq org-display-table (make-display-table)))
5010 (set-display-table-slot
5011 org-display-table 4
5012 (vconcat (mapcar
5013 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5014 org-ellipsis)))
5015 (if (stringp org-ellipsis) org-ellipsis "..."))))
5016 (setq buffer-display-table org-display-table))
5017 (org-set-regexps-and-options)
5018 ;; Calc embedded
5019 (org-set-local 'calc-embedded-open-mode "# ")
5020 (modify-syntax-entry ?# "<")
5021 (modify-syntax-entry ?@ "w")
5022 (if org-startup-truncated (setq truncate-lines t))
5023 (org-set-local 'font-lock-unfontify-region-function
5024 'org-unfontify-region)
5025 ;; Activate before-change-function
5026 (org-set-local 'org-table-may-need-update t)
5027 (org-add-hook 'before-change-functions 'org-before-change-function nil
5028 'local)
5029 ;; Check for running clock before killing a buffer
5030 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5031 ;; Paragraphs and auto-filling
5032 (org-set-autofill-regexps)
5033 (setq indent-line-function 'org-indent-line-function)
5034 (org-update-radio-target-regexp)
5036 ;; Comment characters
5037 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
5038 (org-set-local 'comment-padding " ")
5040 ;; Align options lines
5041 (org-set-local
5042 'align-mode-rules-list
5043 '((org-in-buffer-settings
5044 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5045 (modes . '(org-mode)))))
5047 ;; Imenu
5048 (org-set-local 'imenu-create-index-function
5049 'org-imenu-get-tree)
5051 ;; Make isearch reveal context
5052 (if (or (featurep 'xemacs)
5053 (not (boundp 'outline-isearch-open-invisible-function)))
5054 ;; Emacs 21 and XEmacs make use of the hook
5055 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5056 ;; Emacs 22 deals with this through a special variable
5057 (org-set-local 'outline-isearch-open-invisible-function
5058 (lambda (&rest ignore) (org-show-context 'isearch))))
5060 ;; If empty file that did not turn on org-mode automatically, make it to.
5061 (if (and org-insert-mode-line-in-empty-file
5062 (interactive-p)
5063 (= (point-min) (point-max)))
5064 (insert "# -*- mode: org -*-\n\n"))
5066 (unless org-inhibit-startup
5067 (when org-startup-align-all-tables
5068 (let ((bmp (buffer-modified-p)))
5069 (org-table-map-tables 'org-table-align)
5070 (set-buffer-modified-p bmp)))
5071 (org-cycle-hide-drawers 'all)
5072 (cond
5073 ((eq org-startup-folded t)
5074 (org-cycle '(4)))
5075 ((eq org-startup-folded 'content)
5076 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5077 (org-cycle '(4)) (org-cycle '(4)))))))
5079 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5081 (defsubst org-call-with-arg (command arg)
5082 "Call COMMAND interactively, but pretend prefix are was ARG."
5083 (let ((current-prefix-arg arg)) (call-interactively command)))
5085 (defsubst org-current-line (&optional pos)
5086 (save-excursion
5087 (and pos (goto-char pos))
5088 ;; works also in narrowed buffer, because we start at 1, not point-min
5089 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
5091 (defun org-current-time ()
5092 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5093 (if (> (car org-time-stamp-rounding-minutes) 1)
5094 (let ((r (car org-time-stamp-rounding-minutes))
5095 (time (decode-time)))
5096 (apply 'encode-time
5097 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5098 (nthcdr 2 time))))
5099 (current-time)))
5101 (defun org-add-props (string plist &rest props)
5102 "Add text properties to entire string, from beginning to end.
5103 PLIST may be a list of properties, PROPS are individual properties and values
5104 that will be added to PLIST. Returns the string that was modified."
5105 (add-text-properties
5106 0 (length string) (if props (append plist props) plist) string)
5107 string)
5108 (put 'org-add-props 'lisp-indent-function 2)
5111 ;;;; Font-Lock stuff, including the activators
5113 (defvar org-mouse-map (make-sparse-keymap))
5114 (org-defkey org-mouse-map
5115 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5116 (org-defkey org-mouse-map
5117 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5118 (when org-mouse-1-follows-link
5119 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5120 (when org-tab-follows-link
5121 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5122 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5123 (when org-return-follows-link
5124 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5125 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5127 (require 'font-lock)
5129 (defconst org-non-link-chars "]\t\n\r<>")
5130 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5131 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5132 (defvar org-link-re-with-space nil
5133 "Matches a link with spaces, optional angular brackets around it.")
5134 (defvar org-link-re-with-space2 nil
5135 "Matches a link with spaces, optional angular brackets around it.")
5136 (defvar org-angle-link-re nil
5137 "Matches link with angular brackets, spaces are allowed.")
5138 (defvar org-plain-link-re nil
5139 "Matches plain link, without spaces.")
5140 (defvar org-bracket-link-regexp nil
5141 "Matches a link in double brackets.")
5142 (defvar org-bracket-link-analytic-regexp nil
5143 "Regular expression used to analyze links.
5144 Here is what the match groups contain after a match:
5145 1: http:
5146 2: http
5147 3: path
5148 4: [desc]
5149 5: desc")
5150 (defvar org-any-link-re nil
5151 "Regular expression matching any link.")
5153 (defun org-make-link-regexps ()
5154 "Update the link regular expressions.
5155 This should be called after the variable `org-link-types' has changed."
5156 (setq org-link-re-with-space
5157 (concat
5158 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5159 "\\([^" org-non-link-chars " ]"
5160 "[^" org-non-link-chars "]*"
5161 "[^" org-non-link-chars " ]\\)>?")
5162 org-link-re-with-space2
5163 (concat
5164 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5165 "\\([^" org-non-link-chars " ]"
5166 "[^]\t\n\r]*"
5167 "[^" org-non-link-chars " ]\\)>?")
5168 org-angle-link-re
5169 (concat
5170 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5171 "\\([^" org-non-link-chars " ]"
5172 "[^" org-non-link-chars "]*"
5173 "\\)>")
5174 org-plain-link-re
5175 (concat
5176 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5177 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5178 org-bracket-link-regexp
5179 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5180 org-bracket-link-analytic-regexp
5181 (concat
5182 "\\[\\["
5183 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5184 "\\([^]]+\\)"
5185 "\\]"
5186 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5187 "\\]")
5188 org-any-link-re
5189 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5190 org-angle-link-re "\\)\\|\\("
5191 org-plain-link-re "\\)")))
5193 (org-make-link-regexps)
5195 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5196 "Regular expression for fast time stamp matching.")
5197 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5198 "Regular expression for fast time stamp matching.")
5199 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5200 "Regular expression matching time strings for analysis.
5201 This one does not require the space after the date.")
5202 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5203 "Regular expression matching time strings for analysis.")
5204 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5205 "Regular expression matching time stamps, with groups.")
5206 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5207 "Regular expression matching time stamps (also [..]), with groups.")
5208 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5209 "Regular expression matching a time stamp range.")
5210 (defconst org-tr-regexp-both
5211 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5212 "Regular expression matching a time stamp range.")
5213 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5214 org-ts-regexp "\\)?")
5215 "Regular expression matching a time stamp or time stamp range.")
5216 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5217 org-ts-regexp-both "\\)?")
5218 "Regular expression matching a time stamp or time stamp range.
5219 The time stamps may be either active or inactive.")
5221 (defvar org-emph-face nil)
5223 (defun org-do-emphasis-faces (limit)
5224 "Run through the buffer and add overlays to links."
5225 (let (rtn)
5226 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5227 (if (not (= (char-after (match-beginning 3))
5228 (char-after (match-beginning 4))))
5229 (progn
5230 (setq rtn t)
5231 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5232 'face
5233 (nth 1 (assoc (match-string 3)
5234 org-emphasis-alist)))
5235 (add-text-properties (match-beginning 2) (match-end 2)
5236 '(font-lock-multiline t))
5237 (when org-hide-emphasis-markers
5238 (add-text-properties (match-end 4) (match-beginning 5)
5239 '(invisible org-link))
5240 (add-text-properties (match-beginning 3) (match-end 3)
5241 '(invisible org-link)))))
5242 (backward-char 1))
5243 rtn))
5245 (defun org-emphasize (&optional char)
5246 "Insert or change an emphasis, i.e. a font like bold or italic.
5247 If there is an active region, change that region to a new emphasis.
5248 If there is no region, just insert the marker characters and position
5249 the cursor between them.
5250 CHAR should be either the marker character, or the first character of the
5251 HTML tag associated with that emphasis. If CHAR is a space, the means
5252 to remove the emphasis of the selected region.
5253 If char is not given (for example in an interactive call) it
5254 will be prompted for."
5255 (interactive)
5256 (let ((eal org-emphasis-alist) e det
5257 (erc org-emphasis-regexp-components)
5258 (prompt "")
5259 (string "") beg end move tag c s)
5260 (if (org-region-active-p)
5261 (setq beg (region-beginning) end (region-end)
5262 string (buffer-substring beg end))
5263 (setq move t))
5265 (while (setq e (pop eal))
5266 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5267 c (aref tag 0))
5268 (push (cons c (string-to-char (car e))) det)
5269 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5270 (substring tag 1)))))
5271 (unless char
5272 (message "%s" (concat "Emphasis marker or tag:" prompt))
5273 (setq char (read-char-exclusive)))
5274 (setq char (or (cdr (assoc char det)) char))
5275 (if (equal char ?\ )
5276 (setq s "" move nil)
5277 (unless (assoc (char-to-string char) org-emphasis-alist)
5278 (error "No such emphasis marker: \"%c\"" char))
5279 (setq s (char-to-string char)))
5280 (while (and (> (length string) 1)
5281 (equal (substring string 0 1) (substring string -1))
5282 (assoc (substring string 0 1) org-emphasis-alist))
5283 (setq string (substring string 1 -1)))
5284 (setq string (concat s string s))
5285 (if beg (delete-region beg end))
5286 (unless (or (bolp)
5287 (string-match (concat "[" (nth 0 erc) "\n]")
5288 (char-to-string (char-before (point)))))
5289 (insert " "))
5290 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5291 (char-to-string (char-after (point))))
5292 (insert " ") (backward-char 1))
5293 (insert string)
5294 (and move (backward-char 1))))
5296 (defconst org-nonsticky-props
5297 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5300 (defun org-activate-plain-links (limit)
5301 "Run through the buffer and add overlays to links."
5302 (catch 'exit
5303 (let (f)
5304 (while (re-search-forward org-plain-link-re limit t)
5305 (setq f (get-text-property (match-beginning 0) 'face))
5306 (if (or (eq f 'org-tag)
5307 (and (listp f) (memq 'org-tag f)))
5309 (add-text-properties (match-beginning 0) (match-end 0)
5310 (list 'mouse-face 'highlight
5311 'rear-nonsticky org-nonsticky-props
5312 'keymap org-mouse-map
5314 (throw 'exit t))))))
5316 (defun org-activate-code (limit)
5317 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5318 (unless (get-text-property (match-beginning 1) 'face)
5319 (remove-text-properties (match-beginning 0) (match-end 0)
5320 '(display t invisible t intangible t))
5321 t)))
5323 (defun org-activate-angle-links (limit)
5324 "Run through the buffer and add overlays to links."
5325 (if (re-search-forward org-angle-link-re limit t)
5326 (progn
5327 (add-text-properties (match-beginning 0) (match-end 0)
5328 (list 'mouse-face 'highlight
5329 'rear-nonsticky org-nonsticky-props
5330 'keymap org-mouse-map
5332 t)))
5334 (defmacro org-maybe-intangible (props)
5335 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5336 In emacs 21, invisible text is not avoided by the command loop, so the
5337 intangible property is needed to make sure point skips this text.
5338 In Emacs 22, this is not necessary. The intangible text property has
5339 led to problems with flyspell. These problems are fixed in flyspell.el,
5340 but we still avoid setting the property in Emacs 22 and later.
5341 We use a macro so that the test can happen at compilation time."
5342 (if (< emacs-major-version 22)
5343 `(append '(intangible t) ,props)
5344 props))
5346 (defun org-activate-bracket-links (limit)
5347 "Run through the buffer and add overlays to bracketed links."
5348 (if (re-search-forward org-bracket-link-regexp limit t)
5349 (let* ((help (concat "LINK: "
5350 (org-match-string-no-properties 1)))
5351 ;; FIXME: above we should remove the escapes.
5352 ;; but that requires another match, protecting match data,
5353 ;; a lot of overhead for font-lock.
5354 (ip (org-maybe-intangible
5355 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5356 'keymap org-mouse-map 'mouse-face 'highlight
5357 'font-lock-multiline t 'help-echo help)))
5358 (vp (list 'rear-nonsticky org-nonsticky-props
5359 'keymap org-mouse-map 'mouse-face 'highlight
5360 ' font-lock-multiline t 'help-echo help)))
5361 ;; We need to remove the invisible property here. Table narrowing
5362 ;; may have made some of this invisible.
5363 (remove-text-properties (match-beginning 0) (match-end 0)
5364 '(invisible nil))
5365 (if (match-end 3)
5366 (progn
5367 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5368 (add-text-properties (match-beginning 3) (match-end 3) vp)
5369 (add-text-properties (match-end 3) (match-end 0) ip))
5370 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5371 (add-text-properties (match-beginning 1) (match-end 1) vp)
5372 (add-text-properties (match-end 1) (match-end 0) ip))
5373 t)))
5375 (defun org-activate-dates (limit)
5376 "Run through the buffer and add overlays to dates."
5377 (if (re-search-forward org-tsr-regexp-both limit t)
5378 (progn
5379 (add-text-properties (match-beginning 0) (match-end 0)
5380 (list 'mouse-face 'highlight
5381 'rear-nonsticky org-nonsticky-props
5382 'keymap org-mouse-map))
5383 (when org-display-custom-times
5384 (if (match-end 3)
5385 (org-display-custom-time (match-beginning 3) (match-end 3)))
5386 (org-display-custom-time (match-beginning 1) (match-end 1)))
5387 t)))
5389 (defvar org-target-link-regexp nil
5390 "Regular expression matching radio targets in plain text.")
5391 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5392 "Regular expression matching a link target.")
5393 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5394 "Regular expression matching a radio target.")
5395 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5396 "Regular expression matching any target.")
5398 (defun org-activate-target-links (limit)
5399 "Run through the buffer and add overlays to target matches."
5400 (when org-target-link-regexp
5401 (let ((case-fold-search t))
5402 (if (re-search-forward org-target-link-regexp limit t)
5403 (progn
5404 (add-text-properties (match-beginning 0) (match-end 0)
5405 (list 'mouse-face 'highlight
5406 'rear-nonsticky org-nonsticky-props
5407 'keymap org-mouse-map
5408 'help-echo "Radio target link"
5409 'org-linked-text t))
5410 t)))))
5412 (defun org-update-radio-target-regexp ()
5413 "Find all radio targets in this file and update the regular expression."
5414 (interactive)
5415 (when (memq 'radio org-activate-links)
5416 (setq org-target-link-regexp
5417 (org-make-target-link-regexp (org-all-targets 'radio)))
5418 (org-restart-font-lock)))
5420 (defun org-hide-wide-columns (limit)
5421 (let (s e)
5422 (setq s (text-property-any (point) (or limit (point-max))
5423 'org-cwidth t))
5424 (when s
5425 (setq e (next-single-property-change s 'org-cwidth))
5426 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5427 (goto-char e)
5428 t)))
5430 (defvar org-latex-and-specials-regexp nil
5431 "Regular expression for highlighting export special stuff.")
5432 (defvar org-match-substring-regexp)
5433 (defvar org-match-substring-with-braces-regexp)
5434 (defvar org-export-html-special-string-regexps)
5436 (defun org-compute-latex-and-specials-regexp ()
5437 "Compute regular expression for stuff treated specially by exporters."
5438 (if (not org-highlight-latex-fragments-and-specials)
5439 (org-set-local 'org-latex-and-specials-regexp nil)
5440 (let*
5441 ((matchers (plist-get org-format-latex-options :matchers))
5442 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5443 org-latex-regexps)))
5444 (options (org-combine-plists (org-default-export-plist)
5445 (org-infile-export-plist)))
5446 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5447 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5448 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5449 (org-export-html-expand (plist-get options :expand-quoted-html))
5450 (org-export-with-special-strings (plist-get options :special-strings))
5451 (re-sub
5452 (cond
5453 ((equal org-export-with-sub-superscripts '{})
5454 (list org-match-substring-with-braces-regexp))
5455 (org-export-with-sub-superscripts
5456 (list org-match-substring-regexp))
5457 (t nil)))
5458 (re-latex
5459 (if org-export-with-LaTeX-fragments
5460 (mapcar (lambda (x) (nth 1 x)) latexs)))
5461 (re-macros
5462 (if org-export-with-TeX-macros
5463 (list (concat "\\\\"
5464 (regexp-opt
5465 (append (mapcar 'car org-html-entities)
5466 (if (boundp 'org-latex-entities)
5467 org-latex-entities nil))
5468 'words))) ; FIXME
5470 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5471 (re-special (if org-export-with-special-strings
5472 (mapcar (lambda (x) (car x))
5473 org-export-html-special-string-regexps)))
5474 (re-rest
5475 (delq nil
5476 (list
5477 (if org-export-html-expand "@<[^>\n]+>")
5478 ))))
5479 (org-set-local
5480 'org-latex-and-specials-regexp
5481 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5482 re-rest) "\\|")))))
5484 (defface org-latex-and-export-specials
5485 (let ((font (cond ((assq :inherit custom-face-attributes)
5486 '(:inherit underline))
5487 (t '(:underline t)))))
5488 `((((class grayscale) (background light))
5489 (:foreground "DimGray" ,@font))
5490 (((class grayscale) (background dark))
5491 (:foreground "LightGray" ,@font))
5492 (((class color) (background light))
5493 (:foreground "SaddleBrown"))
5494 (((class color) (background dark))
5495 (:foreground "burlywood"))
5496 (t (,@font))))
5497 "Face used to highlight math latex and other special exporter stuff."
5498 :group 'org-faces)
5500 (defun org-do-latex-and-special-faces (limit)
5501 "Run through the buffer and add overlays to links."
5502 (when org-latex-and-specials-regexp
5503 (let (rtn d)
5504 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5505 limit t))
5506 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5507 'face))
5508 '(org-code org-verbatim underline)))
5509 (progn
5510 (setq rtn t
5511 d (cond ((member (char-after (1+ (match-beginning 0)))
5512 '(?_ ?^)) 1)
5513 (t 0)))
5514 (font-lock-prepend-text-property
5515 (+ d (match-beginning 0)) (match-end 0)
5516 'face 'org-latex-and-export-specials)
5517 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5518 '(font-lock-multiline t)))))
5519 rtn)))
5521 (defun org-restart-font-lock ()
5522 "Restart font-lock-mode, to force refontification."
5523 (when (and (boundp 'font-lock-mode) font-lock-mode)
5524 (font-lock-mode -1)
5525 (font-lock-mode 1)))
5527 (defun org-all-targets (&optional radio)
5528 "Return a list of all targets in this file.
5529 With optional argument RADIO, only find radio targets."
5530 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5531 rtn)
5532 (save-excursion
5533 (goto-char (point-min))
5534 (while (re-search-forward re nil t)
5535 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5536 rtn)))
5538 (defun org-make-target-link-regexp (targets)
5539 "Make regular expression matching all strings in TARGETS.
5540 The regular expression finds the targets also if there is a line break
5541 between words."
5542 (and targets
5543 (concat
5544 "\\<\\("
5545 (mapconcat
5546 (lambda (x)
5547 (while (string-match " +" x)
5548 (setq x (replace-match "\\s-+" t t x)))
5550 targets
5551 "\\|")
5552 "\\)\\>")))
5554 (defun org-activate-tags (limit)
5555 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5556 (progn
5557 (add-text-properties (match-beginning 1) (match-end 1)
5558 (list 'mouse-face 'highlight
5559 'rear-nonsticky org-nonsticky-props
5560 'keymap org-mouse-map))
5561 t)))
5563 (defun org-outline-level ()
5564 (save-excursion
5565 (looking-at outline-regexp)
5566 (if (match-beginning 1)
5567 (+ (org-get-string-indentation (match-string 1)) 1000)
5568 (1- (- (match-end 0) (match-beginning 0))))))
5570 (defvar org-font-lock-keywords nil)
5572 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5573 "Regular expression matching a property line.")
5575 (defun org-set-font-lock-defaults ()
5576 (let* ((em org-fontify-emphasized-text)
5577 (lk org-activate-links)
5578 (org-font-lock-extra-keywords
5579 (list
5580 ;; Headlines
5581 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5582 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5583 ;; Table lines
5584 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5585 (1 'org-table t))
5586 ;; Table internals
5587 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5588 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5589 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5590 ;; Drawers
5591 (list org-drawer-regexp '(0 'org-special-keyword t))
5592 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5593 ;; Properties
5594 (list org-property-re
5595 '(1 'org-special-keyword t)
5596 '(3 'org-property-value t))
5597 (if org-format-transports-properties-p
5598 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5599 ;; Links
5600 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5601 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5602 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5603 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5604 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5605 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5606 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5607 '(org-hide-wide-columns (0 nil append))
5608 ;; TODO lines
5609 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5610 '(1 (org-get-todo-face 1) t))
5611 ;; DONE
5612 (if org-fontify-done-headline
5613 (list (concat "^[*]+ +\\<\\("
5614 (mapconcat 'regexp-quote org-done-keywords "\\|")
5615 "\\)\\(.*\\)")
5616 '(2 'org-headline-done t))
5617 nil)
5618 ;; Priorities
5619 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5620 ;; Special keywords
5621 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5622 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5623 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5624 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5625 ;; Emphasis
5626 (if em
5627 (if (featurep 'xemacs)
5628 '(org-do-emphasis-faces (0 nil append))
5629 '(org-do-emphasis-faces)))
5630 ;; Checkboxes
5631 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5632 2 'bold prepend)
5633 (if org-provide-checkbox-statistics
5634 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5635 (0 (org-get-checkbox-statistics-face) t)))
5636 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5637 '(1 'org-archived prepend))
5638 ;; Specials
5639 '(org-do-latex-and-special-faces)
5640 ;; Code
5641 '(org-activate-code (1 'org-code t))
5642 ;; COMMENT
5643 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5644 "\\|" org-quote-string "\\)\\>")
5645 '(1 'org-special-keyword t))
5646 '("^#.*" (0 'font-lock-comment-face t))
5648 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5649 ;; Now set the full font-lock-keywords
5650 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5651 (org-set-local 'font-lock-defaults
5652 '(org-font-lock-keywords t nil nil backward-paragraph))
5653 (kill-local-variable 'font-lock-keywords) nil))
5655 (defvar org-m nil)
5656 (defvar org-l nil)
5657 (defvar org-f nil)
5658 (defun org-get-level-face (n)
5659 "Get the right face for match N in font-lock matching of healdines."
5660 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5661 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5662 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5663 (cond
5664 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5665 ((eq n 2) org-f)
5666 (t (if org-level-color-stars-only nil org-f))))
5668 (defun org-get-todo-face (kwd)
5669 "Get the right face for a TODO keyword KWD.
5670 If KWD is a number, get the corresponding match group."
5671 (if (numberp kwd) (setq kwd (match-string kwd)))
5672 (or (cdr (assoc kwd org-todo-keyword-faces))
5673 (and (member kwd org-done-keywords) 'org-done)
5674 'org-todo))
5676 (defun org-unfontify-region (beg end &optional maybe_loudly)
5677 "Remove fontification and activation overlays from links."
5678 (font-lock-default-unfontify-region beg end)
5679 (let* ((buffer-undo-list t)
5680 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5681 (inhibit-modification-hooks t)
5682 deactivate-mark buffer-file-name buffer-file-truename)
5683 (remove-text-properties beg end
5684 '(mouse-face t keymap t org-linked-text t
5685 invisible t intangible t))))
5687 ;;;; Visibility cycling, including org-goto and indirect buffer
5689 ;;; Cycling
5691 (defvar org-cycle-global-status nil)
5692 (make-variable-buffer-local 'org-cycle-global-status)
5693 (defvar org-cycle-subtree-status nil)
5694 (make-variable-buffer-local 'org-cycle-subtree-status)
5696 ;;;###autoload
5697 (defun org-cycle (&optional arg)
5698 "Visibility cycling for Org-mode.
5700 - When this function is called with a prefix argument, rotate the entire
5701 buffer through 3 states (global cycling)
5702 1. OVERVIEW: Show only top-level headlines.
5703 2. CONTENTS: Show all headlines of all levels, but no body text.
5704 3. SHOW ALL: Show everything.
5706 - When point is at the beginning of a headline, rotate the subtree started
5707 by this line through 3 different states (local cycling)
5708 1. FOLDED: Only the main headline is shown.
5709 2. CHILDREN: The main headline and the direct children are shown.
5710 From this state, you can move to one of the children
5711 and zoom in further.
5712 3. SUBTREE: Show the entire subtree, including body text.
5714 - When there is a numeric prefix, go up to a heading with level ARG, do
5715 a `show-subtree' and return to the previous cursor position. If ARG
5716 is negative, go up that many levels.
5718 - When point is not at the beginning of a headline, execute
5719 `indent-relative', like TAB normally does. See the option
5720 `org-cycle-emulate-tab' for details.
5722 - Special case: if point is at the beginning of the buffer and there is
5723 no headline in line 1, this function will act as if called with prefix arg.
5724 But only if also the variable `org-cycle-global-at-bob' is t."
5725 (interactive "P")
5726 (let* ((outline-regexp
5727 (if (and (org-mode-p) org-cycle-include-plain-lists)
5728 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5729 outline-regexp))
5730 (bob-special (and org-cycle-global-at-bob (bobp)
5731 (not (looking-at outline-regexp))))
5732 (org-cycle-hook
5733 (if bob-special
5734 (delq 'org-optimize-window-after-visibility-change
5735 (copy-sequence org-cycle-hook))
5736 org-cycle-hook))
5737 (pos (point)))
5739 (if (or bob-special (equal arg '(4)))
5740 ;; special case: use global cycling
5741 (setq arg t))
5743 (cond
5745 ((org-at-table-p 'any)
5746 ;; Enter the table or move to the next field in the table
5747 (or (org-table-recognize-table.el)
5748 (progn
5749 (if arg (org-table-edit-field t)
5750 (org-table-justify-field-maybe)
5751 (call-interactively 'org-table-next-field)))))
5753 ((eq arg t) ;; Global cycling
5755 (cond
5756 ((and (eq last-command this-command)
5757 (eq org-cycle-global-status 'overview))
5758 ;; We just created the overview - now do table of contents
5759 ;; This can be slow in very large buffers, so indicate action
5760 (message "CONTENTS...")
5761 (org-content)
5762 (message "CONTENTS...done")
5763 (setq org-cycle-global-status 'contents)
5764 (run-hook-with-args 'org-cycle-hook 'contents))
5766 ((and (eq last-command this-command)
5767 (eq org-cycle-global-status 'contents))
5768 ;; We just showed the table of contents - now show everything
5769 (show-all)
5770 (message "SHOW ALL")
5771 (setq org-cycle-global-status 'all)
5772 (run-hook-with-args 'org-cycle-hook 'all))
5775 ;; Default action: go to overview
5776 (org-overview)
5777 (message "OVERVIEW")
5778 (setq org-cycle-global-status 'overview)
5779 (run-hook-with-args 'org-cycle-hook 'overview))))
5781 ((and org-drawers org-drawer-regexp
5782 (save-excursion
5783 (beginning-of-line 1)
5784 (looking-at org-drawer-regexp)))
5785 ;; Toggle block visibility
5786 (org-flag-drawer
5787 (not (get-char-property (match-end 0) 'invisible))))
5789 ((integerp arg)
5790 ;; Show-subtree, ARG levels up from here.
5791 (save-excursion
5792 (org-back-to-heading)
5793 (outline-up-heading (if (< arg 0) (- arg)
5794 (- (funcall outline-level) arg)))
5795 (org-show-subtree)))
5797 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5798 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5799 ;; At a heading: rotate between three different views
5800 (org-back-to-heading)
5801 (let ((goal-column 0) eoh eol eos)
5802 ;; First, some boundaries
5803 (save-excursion
5804 (org-back-to-heading)
5805 (save-excursion
5806 (beginning-of-line 2)
5807 (while (and (not (eobp)) ;; this is like `next-line'
5808 (get-char-property (1- (point)) 'invisible))
5809 (beginning-of-line 2)) (setq eol (point)))
5810 (outline-end-of-heading) (setq eoh (point))
5811 (org-end-of-subtree t)
5812 (unless (eobp)
5813 (skip-chars-forward " \t\n")
5814 (beginning-of-line 1) ; in case this is an item
5816 (setq eos (1- (point))))
5817 ;; Find out what to do next and set `this-command'
5818 (cond
5819 ((= eos eoh)
5820 ;; Nothing is hidden behind this heading
5821 (message "EMPTY ENTRY")
5822 (setq org-cycle-subtree-status nil)
5823 (save-excursion
5824 (goto-char eos)
5825 (outline-next-heading)
5826 (if (org-invisible-p) (org-flag-heading nil))))
5827 ((or (>= eol eos)
5828 (not (string-match "\\S-" (buffer-substring eol eos))))
5829 ;; Entire subtree is hidden in one line: open it
5830 (org-show-entry)
5831 (show-children)
5832 (message "CHILDREN")
5833 (save-excursion
5834 (goto-char eos)
5835 (outline-next-heading)
5836 (if (org-invisible-p) (org-flag-heading nil)))
5837 (setq org-cycle-subtree-status 'children)
5838 (run-hook-with-args 'org-cycle-hook 'children))
5839 ((and (eq last-command this-command)
5840 (eq org-cycle-subtree-status 'children))
5841 ;; We just showed the children, now show everything.
5842 (org-show-subtree)
5843 (message "SUBTREE")
5844 (setq org-cycle-subtree-status 'subtree)
5845 (run-hook-with-args 'org-cycle-hook 'subtree))
5847 ;; Default action: hide the subtree.
5848 (hide-subtree)
5849 (message "FOLDED")
5850 (setq org-cycle-subtree-status 'folded)
5851 (run-hook-with-args 'org-cycle-hook 'folded)))))
5853 ;; TAB emulation
5854 (buffer-read-only (org-back-to-heading))
5856 ((org-try-cdlatex-tab))
5858 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5859 (or (not (bolp))
5860 (not (looking-at outline-regexp))))
5861 (call-interactively (global-key-binding "\t")))
5863 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5864 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5865 (or (and (eq org-cycle-emulate-tab 'white)
5866 (= (match-end 0) (point-at-eol)))
5867 (and (eq org-cycle-emulate-tab 'whitestart)
5868 (>= (match-end 0) pos))))
5870 (eq org-cycle-emulate-tab t))
5871 ; (if (and (looking-at "[ \n\r\t]")
5872 ; (string-match "^[ \t]*$" (buffer-substring
5873 ; (point-at-bol) (point))))
5874 ; (progn
5875 ; (beginning-of-line 1)
5876 ; (and (looking-at "[ \t]+") (replace-match ""))))
5877 (call-interactively (global-key-binding "\t")))
5879 (t (save-excursion
5880 (org-back-to-heading)
5881 (org-cycle))))))
5883 ;;;###autoload
5884 (defun org-global-cycle (&optional arg)
5885 "Cycle the global visibility. For details see `org-cycle'."
5886 (interactive "P")
5887 (let ((org-cycle-include-plain-lists
5888 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5889 (if (integerp arg)
5890 (progn
5891 (show-all)
5892 (hide-sublevels arg)
5893 (setq org-cycle-global-status 'contents))
5894 (org-cycle '(4)))))
5896 (defun org-overview ()
5897 "Switch to overview mode, shoing only top-level headlines.
5898 Really, this shows all headlines with level equal or greater than the level
5899 of the first headline in the buffer. This is important, because if the
5900 first headline is not level one, then (hide-sublevels 1) gives confusing
5901 results."
5902 (interactive)
5903 (let ((level (save-excursion
5904 (goto-char (point-min))
5905 (if (re-search-forward (concat "^" outline-regexp) nil t)
5906 (progn
5907 (goto-char (match-beginning 0))
5908 (funcall outline-level))))))
5909 (and level (hide-sublevels level))))
5911 (defun org-content (&optional arg)
5912 "Show all headlines in the buffer, like a table of contents.
5913 With numerical argument N, show content up to level N."
5914 (interactive "P")
5915 (save-excursion
5916 ;; Visit all headings and show their offspring
5917 (and (integerp arg) (org-overview))
5918 (goto-char (point-max))
5919 (catch 'exit
5920 (while (and (progn (condition-case nil
5921 (outline-previous-visible-heading 1)
5922 (error (goto-char (point-min))))
5924 (looking-at outline-regexp))
5925 (if (integerp arg)
5926 (show-children (1- arg))
5927 (show-branches))
5928 (if (bobp) (throw 'exit nil))))))
5931 (defun org-optimize-window-after-visibility-change (state)
5932 "Adjust the window after a change in outline visibility.
5933 This function is the default value of the hook `org-cycle-hook'."
5934 (when (get-buffer-window (current-buffer))
5935 (cond
5936 ; ((eq state 'overview) (org-first-headline-recenter 1))
5937 ; ((eq state 'overview) (org-beginning-of-line))
5938 ((eq state 'content) nil)
5939 ((eq state 'all) nil)
5940 ((eq state 'folded) nil)
5941 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5942 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5944 (defun org-compact-display-after-subtree-move ()
5945 (let (beg end)
5946 (save-excursion
5947 (if (org-up-heading-safe)
5948 (progn
5949 (hide-subtree)
5950 (show-entry)
5951 (show-children)
5952 (org-cycle-show-empty-lines 'children)
5953 (org-cycle-hide-drawers 'children))
5954 (org-overview)))))
5956 (defun org-cycle-show-empty-lines (state)
5957 "Show empty lines above all visible headlines.
5958 The region to be covered depends on STATE when called through
5959 `org-cycle-hook'. Lisp program can use t for STATE to get the
5960 entire buffer covered. Note that an empty line is only shown if there
5961 are at least `org-cycle-separator-lines' empty lines before the headeline."
5962 (when (> org-cycle-separator-lines 0)
5963 (save-excursion
5964 (let* ((n org-cycle-separator-lines)
5965 (re (cond
5966 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5967 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5968 (t (let ((ns (number-to-string (- n 2))))
5969 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5970 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5971 beg end)
5972 (cond
5973 ((memq state '(overview contents t))
5974 (setq beg (point-min) end (point-max)))
5975 ((memq state '(children folded))
5976 (setq beg (point) end (progn (org-end-of-subtree t t)
5977 (beginning-of-line 2)
5978 (point)))))
5979 (when beg
5980 (goto-char beg)
5981 (while (re-search-forward re end t)
5982 (if (not (get-char-property (match-end 1) 'invisible))
5983 (outline-flag-region
5984 (match-beginning 1) (match-end 1) nil)))))))
5985 ;; Never hide empty lines at the end of the file.
5986 (save-excursion
5987 (goto-char (point-max))
5988 (outline-previous-heading)
5989 (outline-end-of-heading)
5990 (if (and (looking-at "[ \t\n]+")
5991 (= (match-end 0) (point-max)))
5992 (outline-flag-region (point) (match-end 0) nil))))
5994 (defun org-subtree-end-visible-p ()
5995 "Is the end of the current subtree visible?"
5996 (pos-visible-in-window-p
5997 (save-excursion (org-end-of-subtree t) (point))))
5999 (defun org-first-headline-recenter (&optional N)
6000 "Move cursor to the first headline and recenter the headline.
6001 Optional argument N means, put the headline into the Nth line of the window."
6002 (goto-char (point-min))
6003 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6004 (beginning-of-line)
6005 (recenter (prefix-numeric-value N))))
6007 ;;; Org-goto
6009 (defvar org-goto-window-configuration nil)
6010 (defvar org-goto-marker nil)
6011 (defvar org-goto-map
6012 (let ((map (make-sparse-keymap)))
6013 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6014 (while (setq cmd (pop cmds))
6015 (substitute-key-definition cmd cmd map global-map)))
6016 (suppress-keymap map)
6017 (org-defkey map "\C-m" 'org-goto-ret)
6018 (org-defkey map [(return)] 'org-goto-ret)
6019 (org-defkey map [(left)] 'org-goto-left)
6020 (org-defkey map [(right)] 'org-goto-right)
6021 (org-defkey map [(control ?g)] 'org-goto-quit)
6022 (org-defkey map "\C-i" 'org-cycle)
6023 (org-defkey map [(tab)] 'org-cycle)
6024 (org-defkey map [(down)] 'outline-next-visible-heading)
6025 (org-defkey map [(up)] 'outline-previous-visible-heading)
6026 (if org-goto-auto-isearch
6027 (if (fboundp 'define-key-after)
6028 (define-key-after map [t] 'org-goto-local-auto-isearch)
6029 nil)
6030 (org-defkey map "q" 'org-goto-quit)
6031 (org-defkey map "n" 'outline-next-visible-heading)
6032 (org-defkey map "p" 'outline-previous-visible-heading)
6033 (org-defkey map "f" 'outline-forward-same-level)
6034 (org-defkey map "b" 'outline-backward-same-level)
6035 (org-defkey map "u" 'outline-up-heading))
6036 (org-defkey map "/" 'org-occur)
6037 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6038 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6039 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6040 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6041 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6042 map))
6044 (defconst org-goto-help
6045 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6046 RET=jump to location [Q]uit and return to previous location
6047 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6049 (defvar org-goto-start-pos) ; dynamically scoped parameter
6051 (defun org-goto (&optional alternative-interface)
6052 "Look up a different location in the current file, keeping current visibility.
6054 When you want look-up or go to a different location in a document, the
6055 fastest way is often to fold the entire buffer and then dive into the tree.
6056 This method has the disadvantage, that the previous location will be folded,
6057 which may not be what you want.
6059 This command works around this by showing a copy of the current buffer
6060 in an indirect buffer, in overview mode. You can dive into the tree in
6061 that copy, use org-occur and incremental search to find a location.
6062 When pressing RET or `Q', the command returns to the original buffer in
6063 which the visibility is still unchanged. After RET is will also jump to
6064 the location selected in the indirect buffer and expose the
6065 the headline hierarchy above."
6066 (interactive "P")
6067 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
6068 (org-refile-use-outline-path t)
6069 (interface
6070 (if (not alternative-interface)
6071 org-goto-interface
6072 (if (eq org-goto-interface 'outline)
6073 'outline-path-completion
6074 'outline)))
6075 (org-goto-start-pos (point))
6076 (selected-point
6077 (if (eq interface 'outline)
6078 (car (org-get-location (current-buffer) org-goto-help))
6079 (nth 3 (org-refile-get-location "Goto: ")))))
6080 (if selected-point
6081 (progn
6082 (org-mark-ring-push org-goto-start-pos)
6083 (goto-char selected-point)
6084 (if (or (org-invisible-p) (org-invisible-p2))
6085 (org-show-context 'org-goto)))
6086 (message "Quit"))))
6088 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6089 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6090 (defvar org-goto-local-auto-isearch-map) ; defined below
6092 (defun org-get-location (buf help)
6093 "Let the user select a location in the Org-mode buffer BUF.
6094 This function uses a recursive edit. It returns the selected position
6095 or nil."
6096 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6097 (isearch-hide-immediately nil)
6098 (isearch-search-fun-function
6099 (lambda () 'org-goto-local-search-forward-headings))
6100 (org-goto-selected-point org-goto-exit-command))
6101 (save-excursion
6102 (save-window-excursion
6103 (delete-other-windows)
6104 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6105 (switch-to-buffer
6106 (condition-case nil
6107 (make-indirect-buffer (current-buffer) "*org-goto*")
6108 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6109 (with-output-to-temp-buffer "*Help*"
6110 (princ help))
6111 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6112 (setq buffer-read-only nil)
6113 (let ((org-startup-truncated t)
6114 (org-startup-folded nil)
6115 (org-startup-align-all-tables nil))
6116 (org-mode)
6117 (org-overview))
6118 (setq buffer-read-only t)
6119 (if (and (boundp 'org-goto-start-pos)
6120 (integer-or-marker-p org-goto-start-pos))
6121 (let ((org-show-hierarchy-above t)
6122 (org-show-siblings t)
6123 (org-show-following-heading t))
6124 (goto-char org-goto-start-pos)
6125 (and (org-invisible-p) (org-show-context)))
6126 (goto-char (point-min)))
6127 (org-beginning-of-line)
6128 (message "Select location and press RET")
6129 (use-local-map org-goto-map)
6130 (recursive-edit)
6132 (kill-buffer "*org-goto*")
6133 (cons org-goto-selected-point org-goto-exit-command)))
6135 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6136 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6137 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6138 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6140 (defun org-goto-local-search-forward-headings (string bound noerror)
6141 "Search and make sure that anu matches are in headlines."
6142 (catch 'return
6143 (while (search-forward string bound noerror)
6144 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6145 (and (member :headline context)
6146 (not (member :tags context))))
6147 (throw 'return (point))))))
6149 (defun org-goto-local-auto-isearch ()
6150 "Start isearch."
6151 (interactive)
6152 (goto-char (point-min))
6153 (let ((keys (this-command-keys)))
6154 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6155 (isearch-mode t)
6156 (isearch-process-search-char (string-to-char keys)))))
6158 (defun org-goto-ret (&optional arg)
6159 "Finish `org-goto' by going to the new location."
6160 (interactive "P")
6161 (setq org-goto-selected-point (point)
6162 org-goto-exit-command 'return)
6163 (throw 'exit nil))
6165 (defun org-goto-left ()
6166 "Finish `org-goto' by going to the new location."
6167 (interactive)
6168 (if (org-on-heading-p)
6169 (progn
6170 (beginning-of-line 1)
6171 (setq org-goto-selected-point (point)
6172 org-goto-exit-command 'left)
6173 (throw 'exit nil))
6174 (error "Not on a heading")))
6176 (defun org-goto-right ()
6177 "Finish `org-goto' by going to the new location."
6178 (interactive)
6179 (if (org-on-heading-p)
6180 (progn
6181 (setq org-goto-selected-point (point)
6182 org-goto-exit-command 'right)
6183 (throw 'exit nil))
6184 (error "Not on a heading")))
6186 (defun org-goto-quit ()
6187 "Finish `org-goto' without cursor motion."
6188 (interactive)
6189 (setq org-goto-selected-point nil)
6190 (setq org-goto-exit-command 'quit)
6191 (throw 'exit nil))
6193 ;;; Indirect buffer display of subtrees
6195 (defvar org-indirect-dedicated-frame nil
6196 "This is the frame being used for indirect tree display.")
6197 (defvar org-last-indirect-buffer nil)
6199 (defun org-tree-to-indirect-buffer (&optional arg)
6200 "Create indirect buffer and narrow it to current subtree.
6201 With numerical prefix ARG, go up to this level and then take that tree.
6202 If ARG is negative, go up that many levels.
6203 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6204 indirect buffer previously made with this command, to avoid proliferation of
6205 indirect buffers. However, when you call the command with a `C-u' prefix, or
6206 when `org-indirect-buffer-display' is `new-frame', the last buffer
6207 is kept so that you can work with several indirect buffers at the same time.
6208 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6209 requests that a new frame be made for the new buffer, so that the dedicated
6210 frame is not changed."
6211 (interactive "P")
6212 (let ((cbuf (current-buffer))
6213 (cwin (selected-window))
6214 (pos (point))
6215 beg end level heading ibuf)
6216 (save-excursion
6217 (org-back-to-heading t)
6218 (when (numberp arg)
6219 (setq level (org-outline-level))
6220 (if (< arg 0) (setq arg (+ level arg)))
6221 (while (> (setq level (org-outline-level)) arg)
6222 (outline-up-heading 1 t)))
6223 (setq beg (point)
6224 heading (org-get-heading))
6225 (org-end-of-subtree t) (setq end (point)))
6226 (if (and (buffer-live-p org-last-indirect-buffer)
6227 (not (eq org-indirect-buffer-display 'new-frame))
6228 (not arg))
6229 (kill-buffer org-last-indirect-buffer))
6230 (setq ibuf (org-get-indirect-buffer cbuf)
6231 org-last-indirect-buffer ibuf)
6232 (cond
6233 ((or (eq org-indirect-buffer-display 'new-frame)
6234 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6235 (select-frame (make-frame))
6236 (delete-other-windows)
6237 (switch-to-buffer ibuf)
6238 (org-set-frame-title heading))
6239 ((eq org-indirect-buffer-display 'dedicated-frame)
6240 (raise-frame
6241 (select-frame (or (and org-indirect-dedicated-frame
6242 (frame-live-p org-indirect-dedicated-frame)
6243 org-indirect-dedicated-frame)
6244 (setq org-indirect-dedicated-frame (make-frame)))))
6245 (delete-other-windows)
6246 (switch-to-buffer ibuf)
6247 (org-set-frame-title (concat "Indirect: " heading)))
6248 ((eq org-indirect-buffer-display 'current-window)
6249 (switch-to-buffer ibuf))
6250 ((eq org-indirect-buffer-display 'other-window)
6251 (pop-to-buffer ibuf))
6252 (t (error "Invalid value.")))
6253 (if (featurep 'xemacs)
6254 (save-excursion (org-mode) (turn-on-font-lock)))
6255 (narrow-to-region beg end)
6256 (show-all)
6257 (goto-char pos)
6258 (and (window-live-p cwin) (select-window cwin))))
6260 (defun org-get-indirect-buffer (&optional buffer)
6261 (setq buffer (or buffer (current-buffer)))
6262 (let ((n 1) (base (buffer-name buffer)) bname)
6263 (while (buffer-live-p
6264 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6265 (setq n (1+ n)))
6266 (condition-case nil
6267 (make-indirect-buffer buffer bname 'clone)
6268 (error (make-indirect-buffer buffer bname)))))
6270 (defun org-set-frame-title (title)
6271 "Set the title of the current frame to the string TITLE."
6272 ;; FIXME: how to name a single frame in XEmacs???
6273 (unless (featurep 'xemacs)
6274 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6276 ;;;; Structure editing
6278 ;;; Inserting headlines
6280 (defun org-insert-heading (&optional force-heading)
6281 "Insert a new heading or item with same depth at point.
6282 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6283 If point is at the beginning of a headline, insert a sibling before the
6284 current headline. If point is not at the beginning, do not split the line,
6285 but create the new hedline after the current line."
6286 (interactive "P")
6287 (if (= (buffer-size) 0)
6288 (insert "\n* ")
6289 (when (or force-heading (not (org-insert-item)))
6290 (let* ((head (save-excursion
6291 (condition-case nil
6292 (progn
6293 (org-back-to-heading)
6294 (match-string 0))
6295 (error "*"))))
6296 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6297 pos)
6298 (cond
6299 ((and (org-on-heading-p) (bolp)
6300 (or (bobp)
6301 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6302 ;; insert before the current line
6303 (open-line (if blank 2 1)))
6304 ((and (bolp)
6305 (or (bobp)
6306 (save-excursion
6307 (backward-char 1) (not (org-invisible-p)))))
6308 ;; insert right here
6309 nil)
6311 ; ;; in the middle of the line
6312 ; (org-show-entry)
6313 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
6314 ; (if (and
6315 ; (org-on-heading-p)
6316 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6317 ; ;; protect the tags
6318 ;; (let ((tags (match-string 2)) pos)
6319 ; (delete-region (match-beginning 1) (match-end 1))
6320 ; (setq pos (point-at-bol))
6321 ; (newline (if blank 2 1))
6322 ; (save-excursion
6323 ; (goto-char pos)
6324 ; (end-of-line 1)
6325 ; (insert " " tags)
6326 ; (org-set-tags nil 'align)))
6327 ; (newline (if blank 2 1)))
6328 ; (newline (if blank 2 1))))
6331 ;; in the middle of the line
6332 (org-show-entry)
6333 (let ((split
6334 (org-get-alist-option org-M-RET-may-split-line 'headline))
6335 tags pos)
6336 (if (org-on-heading-p)
6337 (progn
6338 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6339 (setq tags (and (match-end 2) (match-string 2)))
6340 (and (match-end 1)
6341 (delete-region (match-beginning 1) (match-end 1)))
6342 (setq pos (point-at-bol))
6343 (or split (end-of-line 1))
6344 (delete-horizontal-space)
6345 (newline (if blank 2 1))
6346 (when tags
6347 (save-excursion
6348 (goto-char pos)
6349 (end-of-line 1)
6350 (insert " " tags)
6351 (org-set-tags nil 'align))))
6352 (or split (end-of-line 1))
6353 (newline (if blank 2 1))))))
6354 (insert head) (just-one-space)
6355 (setq pos (point))
6356 (end-of-line 1)
6357 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6358 (run-hooks 'org-insert-heading-hook)))))
6360 (defun org-insert-heading-after-current ()
6361 "Insert a new heading with same level as current, after current subtree."
6362 (interactive)
6363 (org-back-to-heading)
6364 (org-insert-heading)
6365 (org-move-subtree-down)
6366 (end-of-line 1))
6368 (defun org-insert-todo-heading (arg)
6369 "Insert a new heading with the same level and TODO state as current heading.
6370 If the heading has no TODO state, or if the state is DONE, use the first
6371 state (TODO by default). Also with prefix arg, force first state."
6372 (interactive "P")
6373 (when (not (org-insert-item 'checkbox))
6374 (org-insert-heading)
6375 (save-excursion
6376 (org-back-to-heading)
6377 (outline-previous-heading)
6378 (looking-at org-todo-line-regexp))
6379 (if (or arg
6380 (not (match-beginning 2))
6381 (member (match-string 2) org-done-keywords))
6382 (insert (car org-todo-keywords-1) " ")
6383 (insert (match-string 2) " "))))
6385 (defun org-insert-subheading (arg)
6386 "Insert a new subheading and demote it.
6387 Works for outline headings and for plain lists alike."
6388 (interactive "P")
6389 (org-insert-heading arg)
6390 (cond
6391 ((org-on-heading-p) (org-do-demote))
6392 ((org-at-item-p) (org-indent-item 1))))
6394 (defun org-insert-todo-subheading (arg)
6395 "Insert a new subheading with TODO keyword or checkbox and demote it.
6396 Works for outline headings and for plain lists alike."
6397 (interactive "P")
6398 (org-insert-todo-heading arg)
6399 (cond
6400 ((org-on-heading-p) (org-do-demote))
6401 ((org-at-item-p) (org-indent-item 1))))
6403 ;;; Promotion and Demotion
6405 (defun org-promote-subtree ()
6406 "Promote the entire subtree.
6407 See also `org-promote'."
6408 (interactive)
6409 (save-excursion
6410 (org-map-tree 'org-promote))
6411 (org-fix-position-after-promote))
6413 (defun org-demote-subtree ()
6414 "Demote the entire subtree. See `org-demote'.
6415 See also `org-promote'."
6416 (interactive)
6417 (save-excursion
6418 (org-map-tree 'org-demote))
6419 (org-fix-position-after-promote))
6422 (defun org-do-promote ()
6423 "Promote the current heading higher up the tree.
6424 If the region is active in `transient-mark-mode', promote all headings
6425 in the region."
6426 (interactive)
6427 (save-excursion
6428 (if (org-region-active-p)
6429 (org-map-region 'org-promote (region-beginning) (region-end))
6430 (org-promote)))
6431 (org-fix-position-after-promote))
6433 (defun org-do-demote ()
6434 "Demote the current heading lower down the tree.
6435 If the region is active in `transient-mark-mode', demote all headings
6436 in the region."
6437 (interactive)
6438 (save-excursion
6439 (if (org-region-active-p)
6440 (org-map-region 'org-demote (region-beginning) (region-end))
6441 (org-demote)))
6442 (org-fix-position-after-promote))
6444 (defun org-fix-position-after-promote ()
6445 "Make sure that after pro/demotion cursor position is right."
6446 (let ((pos (point)))
6447 (when (save-excursion
6448 (beginning-of-line 1)
6449 (looking-at org-todo-line-regexp)
6450 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6451 (cond ((eobp) (insert " "))
6452 ((eolp) (insert " "))
6453 ((equal (char-after) ?\ ) (forward-char 1))))))
6455 (defun org-reduced-level (l)
6456 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6458 (defun org-get-legal-level (level &optional change)
6459 "Rectify a level change under the influence of `org-odd-levels-only'
6460 LEVEL is a current level, CHANGE is by how much the level should be
6461 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6462 even level numbers will become the next higher odd number."
6463 (if org-odd-levels-only
6464 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6465 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6466 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6467 (max 1 (+ level change))))
6469 (defun org-promote ()
6470 "Promote the current heading higher up the tree.
6471 If the region is active in `transient-mark-mode', promote all headings
6472 in the region."
6473 (org-back-to-heading t)
6474 (let* ((level (save-match-data (funcall outline-level)))
6475 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6476 (diff (abs (- level (length up-head) -1))))
6477 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6478 (replace-match up-head nil t)
6479 ;; Fixup tag positioning
6480 (and org-auto-align-tags (org-set-tags nil t))
6481 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6483 (defun org-demote ()
6484 "Demote the current heading lower down the tree.
6485 If the region is active in `transient-mark-mode', demote all headings
6486 in the region."
6487 (org-back-to-heading t)
6488 (let* ((level (save-match-data (funcall outline-level)))
6489 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6490 (diff (abs (- level (length down-head) -1))))
6491 (replace-match down-head nil t)
6492 ;; Fixup tag positioning
6493 (and org-auto-align-tags (org-set-tags nil t))
6494 (if org-adapt-indentation (org-fixup-indentation diff))))
6496 (defun org-map-tree (fun)
6497 "Call FUN for every heading underneath the current one."
6498 (org-back-to-heading)
6499 (let ((level (funcall outline-level)))
6500 (save-excursion
6501 (funcall fun)
6502 (while (and (progn
6503 (outline-next-heading)
6504 (> (funcall outline-level) level))
6505 (not (eobp)))
6506 (funcall fun)))))
6508 (defun org-map-region (fun beg end)
6509 "Call FUN for every heading between BEG and END."
6510 (let ((org-ignore-region t))
6511 (save-excursion
6512 (setq end (copy-marker end))
6513 (goto-char beg)
6514 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6515 (< (point) end))
6516 (funcall fun))
6517 (while (and (progn
6518 (outline-next-heading)
6519 (< (point) end))
6520 (not (eobp)))
6521 (funcall fun)))))
6523 (defun org-fixup-indentation (diff)
6524 "Change the indentation in the current entry by DIFF
6525 However, if any line in the current entry has no indentation, or if it
6526 would end up with no indentation after the change, nothing at all is done."
6527 (save-excursion
6528 (let ((end (save-excursion (outline-next-heading)
6529 (point-marker)))
6530 (prohibit (if (> diff 0)
6531 "^\\S-"
6532 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6533 col)
6534 (unless (save-excursion (end-of-line 1)
6535 (re-search-forward prohibit end t))
6536 (while (and (< (point) end)
6537 (re-search-forward "^[ \t]+" end t))
6538 (goto-char (match-end 0))
6539 (setq col (current-column))
6540 (if (< diff 0) (replace-match ""))
6541 (indent-to (+ diff col))))
6542 (move-marker end nil))))
6544 (defun org-convert-to-odd-levels ()
6545 "Convert an org-mode file with all levels allowed to one with odd levels.
6546 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6547 level 5 etc."
6548 (interactive)
6549 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6550 (let ((org-odd-levels-only nil) n)
6551 (save-excursion
6552 (goto-char (point-min))
6553 (while (re-search-forward "^\\*\\*+ " nil t)
6554 (setq n (- (length (match-string 0)) 2))
6555 (while (>= (setq n (1- n)) 0)
6556 (org-demote))
6557 (end-of-line 1))))))
6560 (defun org-convert-to-oddeven-levels ()
6561 "Convert an org-mode file with only odd levels to one with odd and even levels.
6562 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6563 section with an even level, conversion would destroy the structure of the file. An error
6564 is signaled in this case."
6565 (interactive)
6566 (goto-char (point-min))
6567 ;; First check if there are no even levels
6568 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6569 (org-show-context t)
6570 (error "Not all levels are odd in this file. Conversion not possible."))
6571 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6572 (let ((org-odd-levels-only nil) n)
6573 (save-excursion
6574 (goto-char (point-min))
6575 (while (re-search-forward "^\\*\\*+ " nil t)
6576 (setq n (/ (1- (length (match-string 0))) 2))
6577 (while (>= (setq n (1- n)) 0)
6578 (org-promote))
6579 (end-of-line 1))))))
6581 (defun org-tr-level (n)
6582 "Make N odd if required."
6583 (if org-odd-levels-only (1+ (/ n 2)) n))
6585 ;;; Vertical tree motion, cutting and pasting of subtrees
6587 (defun org-move-subtree-up (&optional arg)
6588 "Move the current subtree up past ARG headlines of the same level."
6589 (interactive "p")
6590 (org-move-subtree-down (- (prefix-numeric-value arg))))
6592 (defun org-move-subtree-down (&optional arg)
6593 "Move the current subtree down past ARG headlines of the same level."
6594 (interactive "p")
6595 (setq arg (prefix-numeric-value arg))
6596 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6597 'outline-get-last-sibling))
6598 (ins-point (make-marker))
6599 (cnt (abs arg))
6600 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6601 ;; Select the tree
6602 (org-back-to-heading)
6603 (setq beg0 (point))
6604 (save-excursion
6605 (setq ne-beg (org-back-over-empty-lines))
6606 (setq beg (point)))
6607 (save-match-data
6608 (save-excursion (outline-end-of-heading)
6609 (setq folded (org-invisible-p)))
6610 (outline-end-of-subtree))
6611 (outline-next-heading)
6612 (setq ne-end (org-back-over-empty-lines))
6613 (setq end (point))
6614 (goto-char beg0)
6615 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6616 ;; include less whitespace
6617 (save-excursion
6618 (goto-char beg)
6619 (forward-line (- ne-beg ne-end))
6620 (setq beg (point))))
6621 ;; Find insertion point, with error handling
6622 (while (> cnt 0)
6623 (or (and (funcall movfunc) (looking-at outline-regexp))
6624 (progn (goto-char beg0)
6625 (error "Cannot move past superior level or buffer limit")))
6626 (setq cnt (1- cnt)))
6627 (if (> arg 0)
6628 ;; Moving forward - still need to move over subtree
6629 (progn (org-end-of-subtree t t)
6630 (save-excursion
6631 (org-back-over-empty-lines)
6632 (or (bolp) (newline)))))
6633 (setq ne-ins (org-back-over-empty-lines))
6634 (move-marker ins-point (point))
6635 (setq txt (buffer-substring beg end))
6636 (delete-region beg end)
6637 (outline-flag-region (1- beg) beg nil)
6638 (outline-flag-region (1- (point)) (point) nil)
6639 (insert txt)
6640 (or (bolp) (insert "\n"))
6641 (setq ins-end (point))
6642 (goto-char ins-point)
6643 (org-skip-whitespace)
6644 (when (and (< arg 0)
6645 (org-first-sibling-p)
6646 (> ne-ins ne-beg))
6647 ;; Move whitespace back to beginning
6648 (save-excursion
6649 (goto-char ins-end)
6650 (let ((kill-whole-line t))
6651 (kill-line (- ne-ins ne-beg)) (point)))
6652 (insert (make-string (- ne-ins ne-beg) ?\n)))
6653 (move-marker ins-point nil)
6654 (org-compact-display-after-subtree-move)
6655 (unless folded
6656 (org-show-entry)
6657 (show-children)
6658 (org-cycle-hide-drawers 'children))))
6660 (defvar org-subtree-clip ""
6661 "Clipboard for cut and paste of subtrees.
6662 This is actually only a copy of the kill, because we use the normal kill
6663 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6665 (defvar org-subtree-clip-folded nil
6666 "Was the last copied subtree folded?
6667 This is used to fold the tree back after pasting.")
6669 (defun org-cut-subtree (&optional n)
6670 "Cut the current subtree into the clipboard.
6671 With prefix arg N, cut this many sequential subtrees.
6672 This is a short-hand for marking the subtree and then cutting it."
6673 (interactive "p")
6674 (org-copy-subtree n 'cut))
6676 (defun org-copy-subtree (&optional n cut)
6677 "Cut the current subtree into the clipboard.
6678 With prefix arg N, cut this many sequential subtrees.
6679 This is a short-hand for marking the subtree and then copying it.
6680 If CUT is non-nil, actually cut the subtree."
6681 (interactive "p")
6682 (let (beg end folded (beg0 (point)))
6683 (if (interactive-p)
6684 (org-back-to-heading nil) ; take what looks like a subtree
6685 (org-back-to-heading t)) ; take what is really there
6686 (org-back-over-empty-lines)
6687 (setq beg (point))
6688 (skip-chars-forward " \t\r\n")
6689 (save-match-data
6690 (save-excursion (outline-end-of-heading)
6691 (setq folded (org-invisible-p)))
6692 (condition-case nil
6693 (outline-forward-same-level (1- n))
6694 (error nil))
6695 (org-end-of-subtree t t))
6696 (org-back-over-empty-lines)
6697 (setq end (point))
6698 (goto-char beg0)
6699 (when (> end beg)
6700 (setq org-subtree-clip-folded folded)
6701 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6702 (setq org-subtree-clip (current-kill 0))
6703 (message "%s: Subtree(s) with %d characters"
6704 (if cut "Cut" "Copied")
6705 (length org-subtree-clip)))))
6707 (defun org-paste-subtree (&optional level tree)
6708 "Paste the clipboard as a subtree, with modification of headline level.
6709 The entire subtree is promoted or demoted in order to match a new headline
6710 level. By default, the new level is derived from the visible headings
6711 before and after the insertion point, and taken to be the inferior headline
6712 level of the two. So if the previous visible heading is level 3 and the
6713 next is level 4 (or vice versa), level 4 will be used for insertion.
6714 This makes sure that the subtree remains an independent subtree and does
6715 not swallow low level entries.
6717 You can also force a different level, either by using a numeric prefix
6718 argument, or by inserting the heading marker by hand. For example, if the
6719 cursor is after \"*****\", then the tree will be shifted to level 5.
6721 If you want to insert the tree as is, just use \\[yank].
6723 If optional TREE is given, use this text instead of the kill ring."
6724 (interactive "P")
6725 (unless (org-kill-is-subtree-p tree)
6726 (error "%s"
6727 (substitute-command-keys
6728 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6729 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6730 (^re (concat "^\\(" outline-regexp "\\)"))
6731 (re (concat "\\(" outline-regexp "\\)"))
6732 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6734 (old-level (if (string-match ^re txt)
6735 (- (match-end 0) (match-beginning 0) 1)
6736 -1))
6737 (force-level (cond (level (prefix-numeric-value level))
6738 ((string-match
6739 ^re_ (buffer-substring (point-at-bol) (point)))
6740 (- (match-end 1) (match-beginning 1)))
6741 (t nil)))
6742 (previous-level (save-excursion
6743 (condition-case nil
6744 (progn
6745 (outline-previous-visible-heading 1)
6746 (if (looking-at re)
6747 (- (match-end 0) (match-beginning 0) 1)
6749 (error 1))))
6750 (next-level (save-excursion
6751 (condition-case nil
6752 (progn
6753 (or (looking-at outline-regexp)
6754 (outline-next-visible-heading 1))
6755 (if (looking-at re)
6756 (- (match-end 0) (match-beginning 0) 1)
6758 (error 1))))
6759 (new-level (or force-level (max previous-level next-level)))
6760 (shift (if (or (= old-level -1)
6761 (= new-level -1)
6762 (= old-level new-level))
6764 (- new-level old-level)))
6765 (delta (if (> shift 0) -1 1))
6766 (func (if (> shift 0) 'org-demote 'org-promote))
6767 (org-odd-levels-only nil)
6768 beg end)
6769 ;; Remove the forced level indicator
6770 (if force-level
6771 (delete-region (point-at-bol) (point)))
6772 ;; Paste
6773 (beginning-of-line 1)
6774 (org-back-over-empty-lines) ;; FIXME: correct fix????
6775 (setq beg (point))
6776 (insert-before-markers txt) ;; FIXME: correct fix????
6777 (unless (string-match "\n\\'" txt) (insert "\n"))
6778 (setq end (point))
6779 (goto-char beg)
6780 (skip-chars-forward " \t\n\r")
6781 (setq beg (point))
6782 ;; Shift if necessary
6783 (unless (= shift 0)
6784 (save-restriction
6785 (narrow-to-region beg end)
6786 (while (not (= shift 0))
6787 (org-map-region func (point-min) (point-max))
6788 (setq shift (+ delta shift)))
6789 (goto-char (point-min))))
6790 (when (interactive-p)
6791 (message "Clipboard pasted as level %d subtree" new-level))
6792 (if (and kill-ring
6793 (eq org-subtree-clip (current-kill 0))
6794 org-subtree-clip-folded)
6795 ;; The tree was folded before it was killed/copied
6796 (hide-subtree))))
6798 (defun org-kill-is-subtree-p (&optional txt)
6799 "Check if the current kill is an outline subtree, or a set of trees.
6800 Returns nil if kill does not start with a headline, or if the first
6801 headline level is not the largest headline level in the tree.
6802 So this will actually accept several entries of equal levels as well,
6803 which is OK for `org-paste-subtree'.
6804 If optional TXT is given, check this string instead of the current kill."
6805 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6806 (start-level (and kill
6807 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6808 org-outline-regexp "\\)")
6809 kill)
6810 (- (match-end 2) (match-beginning 2) 1)))
6811 (re (concat "^" org-outline-regexp))
6812 (start (1+ (match-beginning 2))))
6813 (if (not start-level)
6814 (progn
6815 nil) ;; does not even start with a heading
6816 (catch 'exit
6817 (while (setq start (string-match re kill (1+ start)))
6818 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6819 (throw 'exit nil)))
6820 t))))
6822 (defun org-narrow-to-subtree ()
6823 "Narrow buffer to the current subtree."
6824 (interactive)
6825 (save-excursion
6826 (save-match-data
6827 (narrow-to-region
6828 (progn (org-back-to-heading) (point))
6829 (progn (org-end-of-subtree t t) (point))))))
6832 ;;; Outline Sorting
6834 (defun org-sort (with-case)
6835 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6836 Optional argument WITH-CASE means sort case-sensitively."
6837 (interactive "P")
6838 (if (org-at-table-p)
6839 (org-call-with-arg 'org-table-sort-lines with-case)
6840 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6842 (defvar org-priority-regexp) ; defined later in the file
6844 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6845 "Sort entries on a certain level of an outline tree.
6846 If there is an active region, the entries in the region are sorted.
6847 Else, if the cursor is before the first entry, sort the top-level items.
6848 Else, the children of the entry at point are sorted.
6850 Sorting can be alphabetically, numerically, and by date/time as given by
6851 the first time stamp in the entry. The command prompts for the sorting
6852 type unless it has been given to the function through the SORTING-TYPE
6853 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6854 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6855 called with point at the beginning of the record. It must return either
6856 a string or a number that should serve as the sorting key for that record.
6858 Comparing entries ignores case by default. However, with an optional argument
6859 WITH-CASE, the sorting considers case as well."
6860 (interactive "P")
6861 (let ((case-func (if with-case 'identity 'downcase))
6862 start beg end stars re re2
6863 txt what tmp plain-list-p)
6864 ;; Find beginning and end of region to sort
6865 (cond
6866 ((org-region-active-p)
6867 ;; we will sort the region
6868 (setq end (region-end)
6869 what "region")
6870 (goto-char (region-beginning))
6871 (if (not (org-on-heading-p)) (outline-next-heading))
6872 (setq start (point)))
6873 ((org-at-item-p)
6874 ;; we will sort this plain list
6875 (org-beginning-of-item-list) (setq start (point))
6876 (org-end-of-item-list) (setq end (point))
6877 (goto-char start)
6878 (setq plain-list-p t
6879 what "plain list"))
6880 ((or (org-on-heading-p)
6881 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6882 ;; we will sort the children of the current headline
6883 (org-back-to-heading)
6884 (setq start (point)
6885 end (progn (org-end-of-subtree t t)
6886 (org-back-over-empty-lines)
6887 (point))
6888 what "children")
6889 (goto-char start)
6890 (show-subtree)
6891 (outline-next-heading))
6893 ;; we will sort the top-level entries in this file
6894 (goto-char (point-min))
6895 (or (org-on-heading-p) (outline-next-heading))
6896 (setq start (point) end (point-max) what "top-level")
6897 (goto-char start)
6898 (show-all)))
6900 (setq beg (point))
6901 (if (>= beg end) (error "Nothing to sort"))
6903 (unless plain-list-p
6904 (looking-at "\\(\\*+\\)")
6905 (setq stars (match-string 1)
6906 re (concat "^" (regexp-quote stars) " +")
6907 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6908 txt (buffer-substring beg end))
6909 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6910 (if (and (not (equal stars "*")) (string-match re2 txt))
6911 (error "Region to sort contains a level above the first entry")))
6913 (unless sorting-type
6914 (message
6915 (if plain-list-p
6916 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6917 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6918 what)
6919 (setq sorting-type (read-char-exclusive))
6921 (and (= (downcase sorting-type) ?f)
6922 (setq getkey-func
6923 (completing-read "Sort using function: "
6924 obarray 'fboundp t nil nil))
6925 (setq getkey-func (intern getkey-func)))
6927 (and (= (downcase sorting-type) ?r)
6928 (setq property
6929 (completing-read "Property: "
6930 (mapcar 'list (org-buffer-property-keys t))
6931 nil t))))
6933 (message "Sorting entries...")
6935 (save-restriction
6936 (narrow-to-region start end)
6938 (let ((dcst (downcase sorting-type))
6939 (now (current-time)))
6940 (sort-subr
6941 (/= dcst sorting-type)
6942 ;; This function moves to the beginning character of the "record" to
6943 ;; be sorted.
6944 (if plain-list-p
6945 (lambda nil
6946 (if (org-at-item-p) t (goto-char (point-max))))
6947 (lambda nil
6948 (if (re-search-forward re nil t)
6949 (goto-char (match-beginning 0))
6950 (goto-char (point-max)))))
6951 ;; This function moves to the last character of the "record" being
6952 ;; sorted.
6953 (if plain-list-p
6954 'org-end-of-item
6955 (lambda nil
6956 (save-match-data
6957 (condition-case nil
6958 (outline-forward-same-level 1)
6959 (error
6960 (goto-char (point-max)))))))
6962 ;; This function returns the value that gets sorted against.
6963 (if plain-list-p
6964 (lambda nil
6965 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6966 (cond
6967 ((= dcst ?n)
6968 (string-to-number (buffer-substring (match-end 0)
6969 (point-at-eol))))
6970 ((= dcst ?a)
6971 (buffer-substring (match-end 0) (point-at-eol)))
6972 ((= dcst ?t)
6973 (if (re-search-forward org-ts-regexp
6974 (point-at-eol) t)
6975 (org-time-string-to-time (match-string 0))
6976 now))
6977 ((= dcst ?f)
6978 (if getkey-func
6979 (progn
6980 (setq tmp (funcall getkey-func))
6981 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6982 tmp)
6983 (error "Invalid key function `%s'" getkey-func)))
6984 (t (error "Invalid sorting type `%c'" sorting-type)))))
6985 (lambda nil
6986 (cond
6987 ((= dcst ?n)
6988 (if (looking-at outline-regexp)
6989 (string-to-number (buffer-substring (match-end 0)
6990 (point-at-eol)))
6991 nil))
6992 ((= dcst ?a)
6993 (funcall case-func (buffer-substring (point-at-bol)
6994 (point-at-eol))))
6995 ((= dcst ?t)
6996 (if (re-search-forward org-ts-regexp
6997 (save-excursion
6998 (forward-line 2)
6999 (point)) t)
7000 (org-time-string-to-time (match-string 0))
7001 now))
7002 ((= dcst ?p)
7003 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7004 (string-to-char (match-string 2))
7005 org-default-priority))
7006 ((= dcst ?r)
7007 (or (org-entry-get nil property) ""))
7008 ((= dcst ?f)
7009 (if getkey-func
7010 (progn
7011 (setq tmp (funcall getkey-func))
7012 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7013 tmp)
7014 (error "Invalid key function `%s'" getkey-func)))
7015 (t (error "Invalid sorting type `%c'" sorting-type)))))
7017 (cond
7018 ((= dcst ?a) 'string<)
7019 ((= dcst ?t) 'time-less-p)
7020 (t nil)))))
7021 (message "Sorting entries...done")))
7023 (defun org-do-sort (table what &optional with-case sorting-type)
7024 "Sort TABLE of WHAT according to SORTING-TYPE.
7025 The user will be prompted for the SORTING-TYPE if the call to this
7026 function does not specify it. WHAT is only for the prompt, to indicate
7027 what is being sorted. The sorting key will be extracted from
7028 the car of the elements of the table.
7029 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7030 (unless sorting-type
7031 (message
7032 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7033 what)
7034 (setq sorting-type (read-char-exclusive)))
7035 (let ((dcst (downcase sorting-type))
7036 extractfun comparefun)
7037 ;; Define the appropriate functions
7038 (cond
7039 ((= dcst ?n)
7040 (setq extractfun 'string-to-number
7041 comparefun (if (= dcst sorting-type) '< '>)))
7042 ((= dcst ?a)
7043 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7044 (lambda(x) (downcase (org-sort-remove-invisible x))))
7045 comparefun (if (= dcst sorting-type)
7046 'string<
7047 (lambda (a b) (and (not (string< a b))
7048 (not (string= a b)))))))
7049 ((= dcst ?t)
7050 (setq extractfun
7051 (lambda (x)
7052 (if (string-match org-ts-regexp x)
7053 (time-to-seconds
7054 (org-time-string-to-time (match-string 0 x)))
7056 comparefun (if (= dcst sorting-type) '< '>)))
7057 (t (error "Invalid sorting type `%c'" sorting-type)))
7059 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7060 table)
7061 (lambda (a b) (funcall comparefun (car a) (car b))))))
7063 ;;;; Plain list items, including checkboxes
7065 ;;; Plain list items
7067 (defun org-at-item-p ()
7068 "Is point in a line starting a hand-formatted item?"
7069 (let ((llt org-plain-list-ordered-item-terminator))
7070 (save-excursion
7071 (goto-char (point-at-bol))
7072 (looking-at
7073 (cond
7074 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7075 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7076 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7077 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7079 (defun org-in-item-p ()
7080 "It the cursor inside a plain list item.
7081 Does not have to be the first line."
7082 (save-excursion
7083 (condition-case nil
7084 (progn
7085 (org-beginning-of-item)
7086 (org-at-item-p)
7088 (error nil))))
7090 (defun org-insert-item (&optional checkbox)
7091 "Insert a new item at the current level.
7092 Return t when things worked, nil when we are not in an item."
7093 (when (save-excursion
7094 (condition-case nil
7095 (progn
7096 (org-beginning-of-item)
7097 (org-at-item-p)
7098 (if (org-invisible-p) (error "Invisible item"))
7100 (error nil)))
7101 (let* ((bul (match-string 0))
7102 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7103 (match-end 0)))
7104 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7105 pos)
7106 (cond
7107 ((and (org-at-item-p) (<= (point) eow))
7108 ;; before the bullet
7109 (beginning-of-line 1)
7110 (open-line (if blank 2 1)))
7111 ((<= (point) eow)
7112 (beginning-of-line 1))
7114 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7115 (end-of-line 1)
7116 (delete-horizontal-space))
7117 (newline (if blank 2 1))))
7118 (insert bul (if checkbox "[ ]" ""))
7119 (just-one-space)
7120 (setq pos (point))
7121 (end-of-line 1)
7122 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7123 (org-maybe-renumber-ordered-list)
7124 (and checkbox (org-update-checkbox-count-maybe))
7127 ;;; Checkboxes
7129 (defun org-at-item-checkbox-p ()
7130 "Is point at a line starting a plain-list item with a checklet?"
7131 (and (org-at-item-p)
7132 (save-excursion
7133 (goto-char (match-end 0))
7134 (skip-chars-forward " \t")
7135 (looking-at "\\[[- X]\\]"))))
7137 (defun org-toggle-checkbox (&optional arg)
7138 "Toggle the checkbox in the current line."
7139 (interactive "P")
7140 (catch 'exit
7141 (let (beg end status (firstnew 'unknown))
7142 (cond
7143 ((org-region-active-p)
7144 (setq beg (region-beginning) end (region-end)))
7145 ((org-on-heading-p)
7146 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7147 ((org-at-item-checkbox-p)
7148 (let ((pos (point)))
7149 (replace-match
7150 (cond (arg "[-]")
7151 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7152 (t "[ ]"))
7153 t t)
7154 (goto-char pos))
7155 (throw 'exit t))
7156 (t (error "Not at a checkbox or heading, and no active region")))
7157 (save-excursion
7158 (goto-char beg)
7159 (while (< (point) end)
7160 (when (org-at-item-checkbox-p)
7161 (setq status (equal (match-string 0) "[X]"))
7162 (when (eq firstnew 'unknown)
7163 (setq firstnew (not status)))
7164 (replace-match
7165 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7166 (beginning-of-line 2)))))
7167 (org-update-checkbox-count-maybe))
7169 (defun org-update-checkbox-count-maybe ()
7170 "Update checkbox statistics unless turned off by user."
7171 (when org-provide-checkbox-statistics
7172 (org-update-checkbox-count)))
7174 (defun org-update-checkbox-count (&optional all)
7175 "Update the checkbox statistics in the current section.
7176 This will find all statistic cookies like [57%] and [6/12] and update them
7177 with the current numbers. With optional prefix argument ALL, do this for
7178 the whole buffer."
7179 (interactive "P")
7180 (save-excursion
7181 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7182 (beg (condition-case nil
7183 (progn (outline-back-to-heading) (point))
7184 (error (point-min))))
7185 (end (move-marker (make-marker)
7186 (progn (outline-next-heading) (point))))
7187 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7188 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7189 (re-find (concat re "\\|" re-box))
7190 beg-cookie end-cookie is-percent c-on c-off lim
7191 eline curr-ind next-ind continue-from startsearch
7192 (cstat 0)
7194 (when all
7195 (goto-char (point-min))
7196 (outline-next-heading)
7197 (setq beg (point) end (point-max)))
7198 (goto-char end)
7199 ;; find each statistic cookie
7200 (while (re-search-backward re-find beg t)
7201 (setq beg-cookie (match-beginning 1)
7202 end-cookie (match-end 1)
7203 cstat (+ cstat (if end-cookie 1 0))
7204 startsearch (point-at-eol)
7205 continue-from (point-at-bol)
7206 is-percent (match-beginning 2)
7207 lim (cond
7208 ((org-on-heading-p) (outline-next-heading) (point))
7209 ((org-at-item-p) (org-end-of-item) (point))
7210 (t nil))
7211 c-on 0
7212 c-off 0)
7213 (when lim
7214 ;; find first checkbox for this cookie and gather
7215 ;; statistics from all that are at this indentation level
7216 (goto-char startsearch)
7217 (if (re-search-forward re-box lim t)
7218 (progn
7219 (org-beginning-of-item)
7220 (setq curr-ind (org-get-indentation))
7221 (setq next-ind curr-ind)
7222 (while (= curr-ind next-ind)
7223 (save-excursion (end-of-line) (setq eline (point)))
7224 (if (re-search-forward re-box eline t)
7225 (if (member (match-string 2) '("[ ]" "[-]"))
7226 (setq c-off (1+ c-off))
7227 (setq c-on (1+ c-on))
7230 (org-end-of-item)
7231 (setq next-ind (org-get-indentation))
7233 (goto-char continue-from)
7234 ;; update cookie
7235 (when end-cookie
7236 (delete-region beg-cookie end-cookie)
7237 (goto-char beg-cookie)
7238 (insert
7239 (if is-percent
7240 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7241 (format "[%d/%d]" c-on (+ c-on c-off)))))
7242 ;; update items checkbox if it has one
7243 (when (org-at-item-p)
7244 (org-beginning-of-item)
7245 (when (and (> (+ c-on c-off) 0)
7246 (re-search-forward re-box (point-at-eol) t))
7247 (setq beg-cookie (match-beginning 2)
7248 end-cookie (match-end 2))
7249 (delete-region beg-cookie end-cookie)
7250 (goto-char beg-cookie)
7251 (cond ((= c-off 0) (insert "[X]"))
7252 ((= c-on 0) (insert "[ ]"))
7253 (t (insert "[-]")))
7255 (goto-char continue-from))
7256 (when (interactive-p)
7257 (message "Checkbox satistics updated %s (%d places)"
7258 (if all "in entire file" "in current outline entry") cstat)))))
7260 (defun org-get-checkbox-statistics-face ()
7261 "Select the face for checkbox statistics.
7262 The face will be `org-done' when all relevant boxes are checked. Otherwise
7263 it will be `org-todo'."
7264 (if (match-end 1)
7265 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7266 (if (and (> (match-end 2) (match-beginning 2))
7267 (equal (match-string 2) (match-string 3)))
7268 'org-done
7269 'org-todo)))
7271 (defun org-get-indentation (&optional line)
7272 "Get the indentation of the current line, interpreting tabs.
7273 When LINE is given, assume it represents a line and compute its indentation."
7274 (if line
7275 (if (string-match "^ *" (org-remove-tabs line))
7276 (match-end 0))
7277 (save-excursion
7278 (beginning-of-line 1)
7279 (skip-chars-forward " \t")
7280 (current-column))))
7282 (defun org-remove-tabs (s &optional width)
7283 "Replace tabulators in S with spaces.
7284 Assumes that s is a single line, starting in column 0."
7285 (setq width (or width tab-width))
7286 (while (string-match "\t" s)
7287 (setq s (replace-match
7288 (make-string
7289 (- (* width (/ (+ (match-beginning 0) width) width))
7290 (match-beginning 0)) ?\ )
7291 t t s)))
7294 (defun org-fix-indentation (line ind)
7295 "Fix indentation in LINE.
7296 IND is a cons cell with target and minimum indentation.
7297 If the current indenation in LINE is smaller than the minimum,
7298 leave it alone. If it is larger than ind, set it to the target."
7299 (let* ((l (org-remove-tabs line))
7300 (i (org-get-indentation l))
7301 (i1 (car ind)) (i2 (cdr ind)))
7302 (if (>= i i2) (setq l (substring line i2)))
7303 (if (> i1 0)
7304 (concat (make-string i1 ?\ ) l)
7305 l)))
7307 (defcustom org-empty-line-terminates-plain-lists nil
7308 "Non-nil means, an empty line ends all plain list levels.
7309 When nil, empty lines are part of the preceeding item."
7310 :group 'org-plain-lists
7311 :type 'boolean)
7313 (defun org-beginning-of-item ()
7314 "Go to the beginning of the current hand-formatted item.
7315 If the cursor is not in an item, throw an error."
7316 (interactive)
7317 (let ((pos (point))
7318 (limit (save-excursion
7319 (condition-case nil
7320 (progn
7321 (org-back-to-heading)
7322 (beginning-of-line 2) (point))
7323 (error (point-min)))))
7324 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7325 ind ind1)
7326 (if (org-at-item-p)
7327 (beginning-of-line 1)
7328 (beginning-of-line 1)
7329 (skip-chars-forward " \t")
7330 (setq ind (current-column))
7331 (if (catch 'exit
7332 (while t
7333 (beginning-of-line 0)
7334 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7336 (if (looking-at "[ \t]*$")
7337 (setq ind1 ind-empty)
7338 (skip-chars-forward " \t")
7339 (setq ind1 (current-column)))
7340 (if (< ind1 ind)
7341 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7343 (goto-char pos)
7344 (error "Not in an item")))))
7346 (defun org-end-of-item ()
7347 "Go to the end of the current hand-formatted item.
7348 If the cursor is not in an item, throw an error."
7349 (interactive)
7350 (let* ((pos (point))
7351 ind1
7352 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7353 (limit (save-excursion (outline-next-heading) (point)))
7354 (ind (save-excursion
7355 (org-beginning-of-item)
7356 (skip-chars-forward " \t")
7357 (current-column)))
7358 (end (catch 'exit
7359 (while t
7360 (beginning-of-line 2)
7361 (if (eobp) (throw 'exit (point)))
7362 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7363 (if (looking-at "[ \t]*$")
7364 (setq ind1 ind-empty)
7365 (skip-chars-forward " \t")
7366 (setq ind1 (current-column)))
7367 (if (<= ind1 ind)
7368 (throw 'exit (point-at-bol)))))))
7369 (if end
7370 (goto-char end)
7371 (goto-char pos)
7372 (error "Not in an item"))))
7374 (defun org-next-item ()
7375 "Move to the beginning of the next item in the current plain list.
7376 Error if not at a plain list, or if this is the last item in the list."
7377 (interactive)
7378 (let (ind ind1 (pos (point)))
7379 (org-beginning-of-item)
7380 (setq ind (org-get-indentation))
7381 (org-end-of-item)
7382 (setq ind1 (org-get-indentation))
7383 (unless (and (org-at-item-p) (= ind ind1))
7384 (goto-char pos)
7385 (error "On last item"))))
7387 (defun org-previous-item ()
7388 "Move to the beginning of the previous item in the current plain list.
7389 Error if not at a plain list, or if this is the first item in the list."
7390 (interactive)
7391 (let (beg ind ind1 (pos (point)))
7392 (org-beginning-of-item)
7393 (setq beg (point))
7394 (setq ind (org-get-indentation))
7395 (goto-char beg)
7396 (catch 'exit
7397 (while t
7398 (beginning-of-line 0)
7399 (if (looking-at "[ \t]*$")
7401 (if (<= (setq ind1 (org-get-indentation)) ind)
7402 (throw 'exit t)))))
7403 (condition-case nil
7404 (if (or (not (org-at-item-p))
7405 (< ind1 (1- ind)))
7406 (error "")
7407 (org-beginning-of-item))
7408 (error (goto-char pos)
7409 (error "On first item")))))
7411 (defun org-first-list-item-p ()
7412 "Is this heading the item in a plain list?"
7413 (unless (org-at-item-p)
7414 (error "Not at a plain list item"))
7415 (org-beginning-of-item)
7416 (= (point) (save-excursion (org-beginning-of-item-list))))
7418 (defun org-move-item-down ()
7419 "Move the plain list item at point down, i.e. swap with following item.
7420 Subitems (items with larger indentation) are considered part of the item,
7421 so this really moves item trees."
7422 (interactive)
7423 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7424 (org-beginning-of-item)
7425 (setq beg0 (point))
7426 (save-excursion
7427 (setq ne-beg (org-back-over-empty-lines))
7428 (setq beg (point)))
7429 (goto-char beg0)
7430 (setq ind (org-get-indentation))
7431 (org-end-of-item)
7432 (setq end0 (point))
7433 (setq ind1 (org-get-indentation))
7434 (setq ne-end (org-back-over-empty-lines))
7435 (setq end (point))
7436 (goto-char beg0)
7437 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7438 ;; include less whitespace
7439 (save-excursion
7440 (goto-char beg)
7441 (forward-line (- ne-beg ne-end))
7442 (setq beg (point))))
7443 (goto-char end0)
7444 (if (and (org-at-item-p) (= ind ind1))
7445 (progn
7446 (org-end-of-item)
7447 (org-back-over-empty-lines)
7448 (setq txt (buffer-substring beg end))
7449 (save-excursion
7450 (delete-region beg end))
7451 (setq pos (point))
7452 (insert txt)
7453 (goto-char pos) (org-skip-whitespace)
7454 (org-maybe-renumber-ordered-list))
7455 (goto-char pos)
7456 (error "Cannot move this item further down"))))
7458 (defun org-move-item-up (arg)
7459 "Move the plain list item at point up, i.e. swap with previous item.
7460 Subitems (items with larger indentation) are considered part of the item,
7461 so this really moves item trees."
7462 (interactive "p")
7463 (let (beg beg0 end ind ind1 (pos (point)) txt
7464 ne-beg ne-ins ins-end)
7465 (org-beginning-of-item)
7466 (setq beg0 (point))
7467 (setq ind (org-get-indentation))
7468 (save-excursion
7469 (setq ne-beg (org-back-over-empty-lines))
7470 (setq beg (point)))
7471 (goto-char beg0)
7472 (org-end-of-item)
7473 (setq end (point))
7474 (goto-char beg0)
7475 (catch 'exit
7476 (while t
7477 (beginning-of-line 0)
7478 (if (looking-at "[ \t]*$")
7479 (if org-empty-line-terminates-plain-lists
7480 (progn
7481 (goto-char pos)
7482 (error "Cannot move this item further up"))
7483 nil)
7484 (if (<= (setq ind1 (org-get-indentation)) ind)
7485 (throw 'exit t)))))
7486 (condition-case nil
7487 (org-beginning-of-item)
7488 (error (goto-char beg)
7489 (error "Cannot move this item further up")))
7490 (setq ind1 (org-get-indentation))
7491 (if (and (org-at-item-p) (= ind ind1))
7492 (progn
7493 (setq ne-ins (org-back-over-empty-lines))
7494 (setq txt (buffer-substring beg end))
7495 (save-excursion
7496 (delete-region beg end))
7497 (setq pos (point))
7498 (insert txt)
7499 (setq ins-end (point))
7500 (goto-char pos) (org-skip-whitespace)
7502 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7503 ;; Move whitespace back to beginning
7504 (save-excursion
7505 (goto-char ins-end)
7506 (let ((kill-whole-line t))
7507 (kill-line (- ne-ins ne-beg)) (point)))
7508 (insert (make-string (- ne-ins ne-beg) ?\n)))
7510 (org-maybe-renumber-ordered-list))
7511 (goto-char pos)
7512 (error "Cannot move this item further up"))))
7514 (defun org-maybe-renumber-ordered-list ()
7515 "Renumber the ordered list at point if setup allows it.
7516 This tests the user option `org-auto-renumber-ordered-lists' before
7517 doing the renumbering."
7518 (interactive)
7519 (when (and org-auto-renumber-ordered-lists
7520 (org-at-item-p))
7521 (if (match-beginning 3)
7522 (org-renumber-ordered-list 1)
7523 (org-fix-bullet-type))))
7525 (defun org-maybe-renumber-ordered-list-safe ()
7526 (condition-case nil
7527 (save-excursion
7528 (org-maybe-renumber-ordered-list))
7529 (error nil)))
7531 (defun org-cycle-list-bullet (&optional which)
7532 "Cycle through the different itemize/enumerate bullets.
7533 This cycle the entire list level through the sequence:
7535 `-' -> `+' -> `*' -> `1.' -> `1)'
7537 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7538 0 meand `-', 1 means `+' etc."
7539 (interactive "P")
7540 (org-preserve-lc
7541 (org-beginning-of-item-list)
7542 (org-at-item-p)
7543 (beginning-of-line 1)
7544 (let ((current (match-string 0))
7545 (prevp (eq which 'previous))
7546 new)
7547 (setq new (cond
7548 ((and (numberp which)
7549 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7550 ((string-match "-" current) (if prevp "1)" "+"))
7551 ((string-match "\\+" current)
7552 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7553 ((string-match "\\*" current) (if prevp "+" "1."))
7554 ((string-match "\\." current) (if prevp "*" "1)"))
7555 ((string-match ")" current) (if prevp "1." "-"))
7556 (t (error "This should not happen"))))
7557 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7558 (org-fix-bullet-type)
7559 (org-maybe-renumber-ordered-list))))
7561 (defun org-get-string-indentation (s)
7562 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7563 (let ((n -1) (i 0) (w tab-width) c)
7564 (catch 'exit
7565 (while (< (setq n (1+ n)) (length s))
7566 (setq c (aref s n))
7567 (cond ((= c ?\ ) (setq i (1+ i)))
7568 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7569 (t (throw 'exit t)))))
7572 (defun org-renumber-ordered-list (arg)
7573 "Renumber an ordered plain list.
7574 Cursor needs to be in the first line of an item, the line that starts
7575 with something like \"1.\" or \"2)\"."
7576 (interactive "p")
7577 (unless (and (org-at-item-p)
7578 (match-beginning 3))
7579 (error "This is not an ordered list"))
7580 (let ((line (org-current-line))
7581 (col (current-column))
7582 (ind (org-get-string-indentation
7583 (buffer-substring (point-at-bol) (match-beginning 3))))
7584 ;; (term (substring (match-string 3) -1))
7585 ind1 (n (1- arg))
7586 fmt)
7587 ;; find where this list begins
7588 (org-beginning-of-item-list)
7589 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7590 (setq fmt (concat "%d" (match-string 1)))
7591 (beginning-of-line 0)
7592 ;; walk forward and replace these numbers
7593 (catch 'exit
7594 (while t
7595 (catch 'next
7596 (beginning-of-line 2)
7597 (if (eobp) (throw 'exit nil))
7598 (if (looking-at "[ \t]*$") (throw 'next nil))
7599 (skip-chars-forward " \t") (setq ind1 (current-column))
7600 (if (> ind1 ind) (throw 'next t))
7601 (if (< ind1 ind) (throw 'exit t))
7602 (if (not (org-at-item-p)) (throw 'exit nil))
7603 (delete-region (match-beginning 2) (match-end 2))
7604 (goto-char (match-beginning 2))
7605 (insert (format fmt (setq n (1+ n)))))))
7606 (goto-line line)
7607 (move-to-column col)))
7609 (defun org-fix-bullet-type ()
7610 "Make sure all items in this list have the same bullet as the firsst item."
7611 (interactive)
7612 (unless (org-at-item-p) (error "This is not a list"))
7613 (let ((line (org-current-line))
7614 (col (current-column))
7615 (ind (current-indentation))
7616 ind1 bullet)
7617 ;; find where this list begins
7618 (org-beginning-of-item-list)
7619 (beginning-of-line 1)
7620 ;; find out what the bullet type is
7621 (looking-at "[ \t]*\\(\\S-+\\)")
7622 (setq bullet (match-string 1))
7623 ;; walk forward and replace these numbers
7624 (beginning-of-line 0)
7625 (catch 'exit
7626 (while t
7627 (catch 'next
7628 (beginning-of-line 2)
7629 (if (eobp) (throw 'exit nil))
7630 (if (looking-at "[ \t]*$") (throw 'next nil))
7631 (skip-chars-forward " \t") (setq ind1 (current-column))
7632 (if (> ind1 ind) (throw 'next t))
7633 (if (< ind1 ind) (throw 'exit t))
7634 (if (not (org-at-item-p)) (throw 'exit nil))
7635 (skip-chars-forward " \t")
7636 (looking-at "\\S-+")
7637 (replace-match bullet))))
7638 (goto-line line)
7639 (move-to-column col)
7640 (if (string-match "[0-9]" bullet)
7641 (org-renumber-ordered-list 1))))
7643 (defun org-beginning-of-item-list ()
7644 "Go to the beginning of the current item list.
7645 I.e. to the first item in this list."
7646 (interactive)
7647 (org-beginning-of-item)
7648 (let ((pos (point-at-bol))
7649 (ind (org-get-indentation))
7650 ind1)
7651 ;; find where this list begins
7652 (catch 'exit
7653 (while t
7654 (catch 'next
7655 (beginning-of-line 0)
7656 (if (looking-at "[ \t]*$")
7657 (throw (if (bobp) 'exit 'next) t))
7658 (skip-chars-forward " \t") (setq ind1 (current-column))
7659 (if (or (< ind1 ind)
7660 (and (= ind1 ind)
7661 (not (org-at-item-p)))
7662 (bobp))
7663 (throw 'exit t)
7664 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7665 (goto-char pos)))
7668 (defun org-end-of-item-list ()
7669 "Go to the end of the current item list.
7670 I.e. to the text after the last item."
7671 (interactive)
7672 (org-beginning-of-item)
7673 (let ((pos (point-at-bol))
7674 (ind (org-get-indentation))
7675 ind1)
7676 ;; find where this list begins
7677 (catch 'exit
7678 (while t
7679 (catch 'next
7680 (beginning-of-line 2)
7681 (if (looking-at "[ \t]*$")
7682 (throw (if (eobp) 'exit 'next) t))
7683 (skip-chars-forward " \t") (setq ind1 (current-column))
7684 (if (or (< ind1 ind)
7685 (and (= ind1 ind)
7686 (not (org-at-item-p)))
7687 (eobp))
7688 (progn
7689 (setq pos (point-at-bol))
7690 (throw 'exit t))))))
7691 (goto-char pos)))
7694 (defvar org-last-indent-begin-marker (make-marker))
7695 (defvar org-last-indent-end-marker (make-marker))
7697 (defun org-outdent-item (arg)
7698 "Outdent a local list item."
7699 (interactive "p")
7700 (org-indent-item (- arg)))
7702 (defun org-indent-item (arg)
7703 "Indent a local list item."
7704 (interactive "p")
7705 (unless (org-at-item-p)
7706 (error "Not on an item"))
7707 (save-excursion
7708 (let (beg end ind ind1 tmp delta ind-down ind-up)
7709 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7710 (setq beg org-last-indent-begin-marker
7711 end org-last-indent-end-marker)
7712 (org-beginning-of-item)
7713 (setq beg (move-marker org-last-indent-begin-marker (point)))
7714 (org-end-of-item)
7715 (setq end (move-marker org-last-indent-end-marker (point))))
7716 (goto-char beg)
7717 (setq tmp (org-item-indent-positions)
7718 ind (car tmp)
7719 ind-down (nth 2 tmp)
7720 ind-up (nth 1 tmp)
7721 delta (if (> arg 0)
7722 (if ind-down (- ind-down ind) 2)
7723 (if ind-up (- ind-up ind) -2)))
7724 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7725 (while (< (point) end)
7726 (beginning-of-line 1)
7727 (skip-chars-forward " \t") (setq ind1 (current-column))
7728 (delete-region (point-at-bol) (point))
7729 (or (eolp) (indent-to-column (+ ind1 delta)))
7730 (beginning-of-line 2))))
7731 (org-fix-bullet-type)
7732 (org-maybe-renumber-ordered-list-safe)
7733 (save-excursion
7734 (beginning-of-line 0)
7735 (condition-case nil (org-beginning-of-item) (error nil))
7736 (org-maybe-renumber-ordered-list-safe)))
7738 (defun org-item-indent-positions ()
7739 "Return indentation for plain list items.
7740 This returns a list with three values: The current indentation, the
7741 parent indentation and the indentation a child should habe.
7742 Assumes cursor in item line."
7743 (let* ((bolpos (point-at-bol))
7744 (ind (org-get-indentation))
7745 ind-down ind-up pos)
7746 (save-excursion
7747 (org-beginning-of-item-list)
7748 (skip-chars-backward "\n\r \t")
7749 (when (org-in-item-p)
7750 (org-beginning-of-item)
7751 (setq ind-up (org-get-indentation))))
7752 (setq pos (point))
7753 (save-excursion
7754 (cond
7755 ((and (condition-case nil (progn (org-previous-item) t)
7756 (error nil))
7757 (or (forward-char 1) t)
7758 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7759 (setq ind-down (org-get-indentation)))
7760 ((and (goto-char pos)
7761 (org-at-item-p))
7762 (goto-char (match-end 0))
7763 (skip-chars-forward " \t")
7764 (setq ind-down (current-column)))))
7765 (list ind ind-up ind-down)))
7767 ;;; The orgstruct minor mode
7769 ;; Define a minor mode which can be used in other modes in order to
7770 ;; integrate the org-mode structure editing commands.
7772 ;; This is really a hack, because the org-mode structure commands use
7773 ;; keys which normally belong to the major mode. Here is how it
7774 ;; works: The minor mode defines all the keys necessary to operate the
7775 ;; structure commands, but wraps the commands into a function which
7776 ;; tests if the cursor is currently at a headline or a plain list
7777 ;; item. If that is the case, the structure command is used,
7778 ;; temporarily setting many Org-mode variables like regular
7779 ;; expressions for filling etc. However, when any of those keys is
7780 ;; used at a different location, function uses `key-binding' to look
7781 ;; up if the key has an associated command in another currently active
7782 ;; keymap (minor modes, major mode, global), and executes that
7783 ;; command. There might be problems if any of the keys is otherwise
7784 ;; used as a prefix key.
7786 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7787 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7788 ;; addresses this by checking explicitly for both bindings.
7790 (defvar orgstruct-mode-map (make-sparse-keymap)
7791 "Keymap for the minor `orgstruct-mode'.")
7793 (defvar org-local-vars nil
7794 "List of local variables, for use by `orgstruct-mode'")
7796 ;;;###autoload
7797 (define-minor-mode orgstruct-mode
7798 "Toggle the minor more `orgstruct-mode'.
7799 This mode is for using Org-mode structure commands in other modes.
7800 The following key behave as if Org-mode was active, if the cursor
7801 is on a headline, or on a plain list item (both in the definition
7802 of Org-mode).
7804 M-up Move entry/item up
7805 M-down Move entry/item down
7806 M-left Promote
7807 M-right Demote
7808 M-S-up Move entry/item up
7809 M-S-down Move entry/item down
7810 M-S-left Promote subtree
7811 M-S-right Demote subtree
7812 M-q Fill paragraph and items like in Org-mode
7813 C-c ^ Sort entries
7814 C-c - Cycle list bullet
7815 TAB Cycle item visibility
7816 M-RET Insert new heading/item
7817 S-M-RET Insert new TODO heading / Chekbox item
7818 C-c C-c Set tags / toggle checkbox"
7819 nil " OrgStruct" nil
7820 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7822 ;;;###autoload
7823 (defun turn-on-orgstruct ()
7824 "Unconditionally turn on `orgstruct-mode'."
7825 (orgstruct-mode 1))
7827 ;;;###autoload
7828 (defun turn-on-orgstruct++ ()
7829 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7830 In addition to setting orgstruct-mode, this also exports all indentation and
7831 autofilling variables from org-mode into the buffer. Note that turning
7832 off orgstruct-mode will *not* remove these additional settings."
7833 (orgstruct-mode 1)
7834 (let (var val)
7835 (mapc
7836 (lambda (x)
7837 (when (string-match
7838 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7839 (symbol-name (car x)))
7840 (setq var (car x) val (nth 1 x))
7841 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7842 org-local-vars)))
7844 (defun orgstruct-error ()
7845 "Error when there is no default binding for a structure key."
7846 (interactive)
7847 (error "This key has no function outside structure elements"))
7849 (defun orgstruct-setup ()
7850 "Setup orgstruct keymaps."
7851 (let ((nfunc 0)
7852 (bindings
7853 (list
7854 '([(meta up)] org-metaup)
7855 '([(meta down)] org-metadown)
7856 '([(meta left)] org-metaleft)
7857 '([(meta right)] org-metaright)
7858 '([(meta shift up)] org-shiftmetaup)
7859 '([(meta shift down)] org-shiftmetadown)
7860 '([(meta shift left)] org-shiftmetaleft)
7861 '([(meta shift right)] org-shiftmetaright)
7862 '([(shift up)] org-shiftup)
7863 '([(shift down)] org-shiftdown)
7864 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7865 '("\M-q" fill-paragraph)
7866 '("\C-c^" org-sort)
7867 '("\C-c-" org-cycle-list-bullet)))
7868 elt key fun cmd)
7869 (while (setq elt (pop bindings))
7870 (setq nfunc (1+ nfunc))
7871 (setq key (org-key (car elt))
7872 fun (nth 1 elt)
7873 cmd (orgstruct-make-binding fun nfunc key))
7874 (org-defkey orgstruct-mode-map key cmd))
7876 ;; Special treatment needed for TAB and RET
7877 (org-defkey orgstruct-mode-map [(tab)]
7878 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7879 (org-defkey orgstruct-mode-map "\C-i"
7880 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7882 (org-defkey orgstruct-mode-map "\M-\C-m"
7883 (orgstruct-make-binding 'org-insert-heading 105
7884 "\M-\C-m" [(meta return)]))
7885 (org-defkey orgstruct-mode-map [(meta return)]
7886 (orgstruct-make-binding 'org-insert-heading 106
7887 [(meta return)] "\M-\C-m"))
7889 (org-defkey orgstruct-mode-map [(shift meta return)]
7890 (orgstruct-make-binding 'org-insert-todo-heading 107
7891 [(meta return)] "\M-\C-m"))
7893 (unless org-local-vars
7894 (setq org-local-vars (org-get-local-variables)))
7898 (defun orgstruct-make-binding (fun n &rest keys)
7899 "Create a function for binding in the structure minor mode.
7900 FUN is the command to call inside a table. N is used to create a unique
7901 command name. KEYS are keys that should be checked in for a command
7902 to execute outside of tables."
7903 (eval
7904 (list 'defun
7905 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7906 '(arg)
7907 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7908 "Outside of structure, run the binding of `"
7909 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7910 "'.")
7911 '(interactive "p")
7912 (list 'if
7913 '(org-context-p 'headline 'item)
7914 (list 'org-run-like-in-org-mode (list 'quote fun))
7915 (list 'let '(orgstruct-mode)
7916 (list 'call-interactively
7917 (append '(or)
7918 (mapcar (lambda (k)
7919 (list 'key-binding k))
7920 keys)
7921 '('orgstruct-error))))))))
7923 (defun org-context-p (&rest contexts)
7924 "Check if local context is and of CONTEXTS.
7925 Possible values in the list of contexts are `table', `headline', and `item'."
7926 (let ((pos (point)))
7927 (goto-char (point-at-bol))
7928 (prog1 (or (and (memq 'table contexts)
7929 (looking-at "[ \t]*|"))
7930 (and (memq 'headline contexts)
7931 (looking-at "\\*+"))
7932 (and (memq 'item contexts)
7933 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7934 (goto-char pos))))
7936 (defun org-get-local-variables ()
7937 "Return a list of all local variables in an org-mode buffer."
7938 (let (varlist)
7939 (with-current-buffer (get-buffer-create "*Org tmp*")
7940 (erase-buffer)
7941 (org-mode)
7942 (setq varlist (buffer-local-variables)))
7943 (kill-buffer "*Org tmp*")
7944 (delq nil
7945 (mapcar
7946 (lambda (x)
7947 (setq x
7948 (if (symbolp x)
7949 (list x)
7950 (list (car x) (list 'quote (cdr x)))))
7951 (if (string-match
7952 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7953 (symbol-name (car x)))
7954 x nil))
7955 varlist))))
7957 ;;;###autoload
7958 (defun org-run-like-in-org-mode (cmd)
7959 (unless org-local-vars
7960 (setq org-local-vars (org-get-local-variables)))
7961 (eval (list 'let org-local-vars
7962 (list 'call-interactively (list 'quote cmd)))))
7964 ;;;; Archiving
7966 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7968 (defun org-archive-subtree (&optional find-done)
7969 "Move the current subtree to the archive.
7970 The archive can be a certain top-level heading in the current file, or in
7971 a different file. The tree will be moved to that location, the subtree
7972 heading be marked DONE, and the current time will be added.
7974 When called with prefix argument FIND-DONE, find whole trees without any
7975 open TODO items and archive them (after getting confirmation from the user).
7976 If the cursor is not at a headline when this comand is called, try all level
7977 1 trees. If the cursor is on a headline, only try the direct children of
7978 this heading."
7979 (interactive "P")
7980 (if find-done
7981 (org-archive-all-done)
7982 ;; Save all relevant TODO keyword-relatex variables
7984 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7985 (tr-org-todo-keywords-1 org-todo-keywords-1)
7986 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7987 (tr-org-done-keywords org-done-keywords)
7988 (tr-org-todo-regexp org-todo-regexp)
7989 (tr-org-todo-line-regexp org-todo-line-regexp)
7990 (tr-org-odd-levels-only org-odd-levels-only)
7991 (this-buffer (current-buffer))
7992 (org-archive-location org-archive-location)
7993 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7994 ;; start of variables that will be used for saving context
7995 ;; The compiler complains about them - keep them anyway!
7996 (file (abbreviate-file-name (buffer-file-name)))
7997 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
7998 (time (format-time-string
7999 (substring (cdr org-time-stamp-formats) 1 -1)
8000 (current-time)))
8001 afile heading buffer level newfile-p
8002 category todo priority
8003 ;; start of variables that will be used for savind context
8004 ltags itags prop)
8006 ;; Try to find a local archive location
8007 (save-excursion
8008 (save-restriction
8009 (widen)
8010 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
8011 (if (and prop (string-match "\\S-" prop))
8012 (setq org-archive-location prop)
8013 (if (or (re-search-backward re nil t)
8014 (re-search-forward re nil t))
8015 (setq org-archive-location (match-string 1))))))
8017 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
8018 (progn
8019 (setq afile (format (match-string 1 org-archive-location)
8020 (file-name-nondirectory buffer-file-name))
8021 heading (match-string 2 org-archive-location)))
8022 (error "Invalid `org-archive-location'"))
8023 (if (> (length afile) 0)
8024 (setq newfile-p (not (file-exists-p afile))
8025 buffer (find-file-noselect afile))
8026 (setq buffer (current-buffer)))
8027 (unless buffer
8028 (error "Cannot access file \"%s\"" afile))
8029 (if (and (> (length heading) 0)
8030 (string-match "^\\*+" heading))
8031 (setq level (match-end 0))
8032 (setq heading nil level 0))
8033 (save-excursion
8034 (org-back-to-heading t)
8035 ;; Get context information that will be lost by moving the tree
8036 (org-refresh-category-properties)
8037 (setq category (org-get-category)
8038 todo (and (looking-at org-todo-line-regexp)
8039 (match-string 2))
8040 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
8041 ltags (org-get-tags)
8042 itags (org-delete-all ltags (org-get-tags-at)))
8043 (setq ltags (mapconcat 'identity ltags " ")
8044 itags (mapconcat 'identity itags " "))
8045 ;; We first only copy, in case something goes wrong
8046 ;; we need to protect this-command, to avoid kill-region sets it,
8047 ;; which would lead to duplication of subtrees
8048 (let (this-command) (org-copy-subtree))
8049 (set-buffer buffer)
8050 ;; Enforce org-mode for the archive buffer
8051 (if (not (org-mode-p))
8052 ;; Force the mode for future visits.
8053 (let ((org-insert-mode-line-in-empty-file t)
8054 (org-inhibit-startup t))
8055 (call-interactively 'org-mode)))
8056 (when newfile-p
8057 (goto-char (point-max))
8058 (insert (format "\nArchived entries from file %s\n\n"
8059 (buffer-file-name this-buffer))))
8060 ;; Force the TODO keywords of the original buffer
8061 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
8062 (org-todo-keywords-1 tr-org-todo-keywords-1)
8063 (org-todo-kwd-alist tr-org-todo-kwd-alist)
8064 (org-done-keywords tr-org-done-keywords)
8065 (org-todo-regexp tr-org-todo-regexp)
8066 (org-todo-line-regexp tr-org-todo-line-regexp)
8067 (org-odd-levels-only
8068 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8069 org-odd-levels-only
8070 tr-org-odd-levels-only)))
8071 (goto-char (point-min))
8072 (show-all)
8073 (if heading
8074 (progn
8075 (if (re-search-forward
8076 (concat "^" (regexp-quote heading)
8077 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8078 nil t)
8079 (goto-char (match-end 0))
8080 ;; Heading not found, just insert it at the end
8081 (goto-char (point-max))
8082 (or (bolp) (insert "\n"))
8083 (insert "\n" heading "\n")
8084 (end-of-line 0))
8085 ;; Make the subtree visible
8086 (show-subtree)
8087 (org-end-of-subtree t)
8088 (skip-chars-backward " \t\r\n")
8089 (and (looking-at "[ \t\r\n]*")
8090 (replace-match "\n\n")))
8091 ;; No specific heading, just go to end of file.
8092 (goto-char (point-max)) (insert "\n"))
8093 ;; Paste
8094 (org-paste-subtree (org-get-legal-level level 1))
8096 ;; Mark the entry as done
8097 (when (and org-archive-mark-done
8098 (looking-at org-todo-line-regexp)
8099 (or (not (match-end 2))
8100 (not (member (match-string 2) org-done-keywords))))
8101 (let (org-log-done org-todo-log-states)
8102 (org-todo
8103 (car (or (member org-archive-mark-done org-done-keywords)
8104 org-done-keywords)))))
8106 ;; Add the context info
8107 (when org-archive-save-context-info
8108 (let ((l org-archive-save-context-info) e n v)
8109 (while (setq e (pop l))
8110 (when (and (setq v (symbol-value e))
8111 (stringp v) (string-match "\\S-" v))
8112 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8113 (org-entry-put (point) n v)))))
8115 ;; Save and kill the buffer, if it is not the same buffer.
8116 (if (not (eq this-buffer buffer))
8117 (progn (save-buffer) (kill-buffer buffer)))))
8118 ;; Here we are back in the original buffer. Everything seems to have
8119 ;; worked. So now cut the tree and finish up.
8120 (let (this-command) (org-cut-subtree))
8121 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8122 (message "Subtree archived %s"
8123 (if (eq this-buffer buffer)
8124 (concat "under heading: " heading)
8125 (concat "in file: " (abbreviate-file-name afile)))))))
8127 (defun org-refresh-category-properties ()
8128 "Refresh category text properties in teh buffer."
8129 (let ((def-cat (cond
8130 ((null org-category)
8131 (if buffer-file-name
8132 (file-name-sans-extension
8133 (file-name-nondirectory buffer-file-name))
8134 "???"))
8135 ((symbolp org-category) (symbol-name org-category))
8136 (t org-category)))
8137 beg end cat pos optionp)
8138 (org-unmodified
8139 (save-excursion
8140 (save-restriction
8141 (widen)
8142 (goto-char (point-min))
8143 (put-text-property (point) (point-max) 'org-category def-cat)
8144 (while (re-search-forward
8145 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8146 (setq pos (match-end 0)
8147 optionp (equal (char-after (match-beginning 0)) ?#)
8148 cat (org-trim (match-string 2)))
8149 (if optionp
8150 (setq beg (point-at-bol) end (point-max))
8151 (org-back-to-heading t)
8152 (setq beg (point) end (org-end-of-subtree t t)))
8153 (put-text-property beg end 'org-category cat)
8154 (goto-char pos)))))))
8156 (defun org-archive-all-done (&optional tag)
8157 "Archive sublevels of the current tree without open TODO items.
8158 If the cursor is not on a headline, try all level 1 trees. If
8159 it is on a headline, try all direct children.
8160 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8161 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8162 (rea (concat ".*:" org-archive-tag ":"))
8163 (begm (make-marker))
8164 (endm (make-marker))
8165 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8166 "Move subtree to archive (no open TODO items)? "))
8167 beg end (cntarch 0))
8168 (if (org-on-heading-p)
8169 (progn
8170 (setq re1 (concat "^" (regexp-quote
8171 (make-string
8172 (1+ (- (match-end 0) (match-beginning 0) 1))
8173 ?*))
8174 " "))
8175 (move-marker begm (point))
8176 (move-marker endm (org-end-of-subtree t)))
8177 (setq re1 "^* ")
8178 (move-marker begm (point-min))
8179 (move-marker endm (point-max)))
8180 (save-excursion
8181 (goto-char begm)
8182 (while (re-search-forward re1 endm t)
8183 (setq beg (match-beginning 0)
8184 end (save-excursion (org-end-of-subtree t) (point)))
8185 (goto-char beg)
8186 (if (re-search-forward re end t)
8187 (goto-char end)
8188 (goto-char beg)
8189 (if (and (or (not tag) (not (looking-at rea)))
8190 (y-or-n-p question))
8191 (progn
8192 (if tag
8193 (org-toggle-tag org-archive-tag 'on)
8194 (org-archive-subtree))
8195 (setq cntarch (1+ cntarch)))
8196 (goto-char end)))))
8197 (message "%d trees archived" cntarch)))
8199 (defun org-cycle-hide-drawers (state)
8200 "Re-hide all drawers after a visibility state change."
8201 (when (and (org-mode-p)
8202 (not (memq state '(overview folded))))
8203 (save-excursion
8204 (let* ((globalp (memq state '(contents all)))
8205 (beg (if globalp (point-min) (point)))
8206 (end (if globalp (point-max) (org-end-of-subtree t))))
8207 (goto-char beg)
8208 (while (re-search-forward org-drawer-regexp end t)
8209 (org-flag-drawer t))))))
8211 (defun org-flag-drawer (flag)
8212 (save-excursion
8213 (beginning-of-line 1)
8214 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8215 (let ((b (match-end 0))
8216 (outline-regexp org-outline-regexp))
8217 (if (re-search-forward
8218 "^[ \t]*:END:"
8219 (save-excursion (outline-next-heading) (point)) t)
8220 (outline-flag-region b (point-at-eol) flag)
8221 (error ":END: line missing"))))))
8223 (defun org-cycle-hide-archived-subtrees (state)
8224 "Re-hide all archived subtrees after a visibility state change."
8225 (when (and (not org-cycle-open-archived-trees)
8226 (not (memq state '(overview folded))))
8227 (save-excursion
8228 (let* ((globalp (memq state '(contents all)))
8229 (beg (if globalp (point-min) (point)))
8230 (end (if globalp (point-max) (org-end-of-subtree t))))
8231 (org-hide-archived-subtrees beg end)
8232 (goto-char beg)
8233 (if (looking-at (concat ".*:" org-archive-tag ":"))
8234 (message "%s" (substitute-command-keys
8235 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8237 (defun org-force-cycle-archived ()
8238 "Cycle subtree even if it is archived."
8239 (interactive)
8240 (setq this-command 'org-cycle)
8241 (let ((org-cycle-open-archived-trees t))
8242 (call-interactively 'org-cycle)))
8244 (defun org-hide-archived-subtrees (beg end)
8245 "Re-hide all archived subtrees after a visibility state change."
8246 (save-excursion
8247 (let* ((re (concat ":" org-archive-tag ":")))
8248 (goto-char beg)
8249 (while (re-search-forward re end t)
8250 (and (org-on-heading-p) (hide-subtree))
8251 (org-end-of-subtree t)))))
8253 (defun org-toggle-tag (tag &optional onoff)
8254 "Toggle the tag TAG for the current line.
8255 If ONOFF is `on' or `off', don't toggle but set to this state."
8256 (unless (org-on-heading-p t) (error "Not on headling"))
8257 (let (res current)
8258 (save-excursion
8259 (beginning-of-line)
8260 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8261 (point-at-eol) t)
8262 (progn
8263 (setq current (match-string 1))
8264 (replace-match ""))
8265 (setq current ""))
8266 (setq current (nreverse (org-split-string current ":")))
8267 (cond
8268 ((eq onoff 'on)
8269 (setq res t)
8270 (or (member tag current) (push tag current)))
8271 ((eq onoff 'off)
8272 (or (not (member tag current)) (setq current (delete tag current))))
8273 (t (if (member tag current)
8274 (setq current (delete tag current))
8275 (setq res t)
8276 (push tag current))))
8277 (end-of-line 1)
8278 (if current
8279 (progn
8280 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8281 (org-set-tags nil t))
8282 (delete-horizontal-space))
8283 (run-hooks 'org-after-tags-change-hook))
8284 res))
8286 (defun org-toggle-archive-tag (&optional arg)
8287 "Toggle the archive tag for the current headline.
8288 With prefix ARG, check all children of current headline and offer tagging
8289 the children that do not contain any open TODO items."
8290 (interactive "P")
8291 (if arg
8292 (org-archive-all-done 'tag)
8293 (let (set)
8294 (save-excursion
8295 (org-back-to-heading t)
8296 (setq set (org-toggle-tag org-archive-tag))
8297 (when set (hide-subtree)))
8298 (and set (beginning-of-line 1))
8299 (message "Subtree %s" (if set "archived" "unarchived")))))
8302 ;;;; Tables
8304 ;;; The table editor
8306 ;; Watch out: Here we are talking about two different kind of tables.
8307 ;; Most of the code is for the tables created with the Org-mode table editor.
8308 ;; Sometimes, we talk about tables created and edited with the table.el
8309 ;; Emacs package. We call the former org-type tables, and the latter
8310 ;; table.el-type tables.
8312 (defun org-before-change-function (beg end)
8313 "Every change indicates that a table might need an update."
8314 (setq org-table-may-need-update t))
8316 (defconst org-table-line-regexp "^[ \t]*|"
8317 "Detects an org-type table line.")
8318 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8319 "Detects an org-type table line.")
8320 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8321 "Detects a table line marked for automatic recalculation.")
8322 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8323 "Detects a table line marked for automatic recalculation.")
8324 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8325 "Detects a table line marked for automatic recalculation.")
8326 (defconst org-table-hline-regexp "^[ \t]*|-"
8327 "Detects an org-type table hline.")
8328 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8329 "Detects a table-type table hline.")
8330 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8331 "Detects an org-type or table-type table.")
8332 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8333 "Searching from within a table (any type) this finds the first line
8334 outside the table.")
8335 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8336 "Searching from within a table (any type) this finds the first line
8337 outside the table.")
8339 (defvar org-table-last-highlighted-reference nil)
8340 (defvar org-table-formula-history nil)
8342 (defvar org-table-column-names nil
8343 "Alist with column names, derived from the `!' line.")
8344 (defvar org-table-column-name-regexp nil
8345 "Regular expression matching the current column names.")
8346 (defvar org-table-local-parameters nil
8347 "Alist with parameter names, derived from the `$' line.")
8348 (defvar org-table-named-field-locations nil
8349 "Alist with locations of named fields.")
8351 (defvar org-table-current-line-types nil
8352 "Table row types, non-nil only for the duration of a comand.")
8353 (defvar org-table-current-begin-line nil
8354 "Table begin line, non-nil only for the duration of a comand.")
8355 (defvar org-table-current-begin-pos nil
8356 "Table begin position, non-nil only for the duration of a comand.")
8357 (defvar org-table-dlines nil
8358 "Vector of data line line numbers in the current table.")
8359 (defvar org-table-hlines nil
8360 "Vector of hline line numbers in the current table.")
8362 (defconst org-table-range-regexp
8363 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8364 ;; 1 2 3 4 5
8365 "Regular expression for matching ranges in formulas.")
8367 (defconst org-table-range-regexp2
8368 (concat
8369 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8370 "\\.\\."
8371 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8372 "Match a range for reference display.")
8374 (defconst org-table-translate-regexp
8375 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8376 "Match a reference that needs translation, for reference display.")
8378 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8380 (defun org-table-create-with-table.el ()
8381 "Use the table.el package to insert a new table.
8382 If there is already a table at point, convert between Org-mode tables
8383 and table.el tables."
8384 (interactive)
8385 (require 'table)
8386 (cond
8387 ((org-at-table.el-p)
8388 (if (y-or-n-p "Convert table to Org-mode table? ")
8389 (org-table-convert)))
8390 ((org-at-table-p)
8391 (if (y-or-n-p "Convert table to table.el table? ")
8392 (org-table-convert)))
8393 (t (call-interactively 'table-insert))))
8395 (defun org-table-create-or-convert-from-region (arg)
8396 "Convert region to table, or create an empty table.
8397 If there is an active region, convert it to a table, using the function
8398 `org-table-convert-region'. See the documentation of that function
8399 to learn how the prefix argument is interpreted to determine the field
8400 separator.
8401 If there is no such region, create an empty table with `org-table-create'."
8402 (interactive "P")
8403 (if (org-region-active-p)
8404 (org-table-convert-region (region-beginning) (region-end) arg)
8405 (org-table-create arg)))
8407 (defun org-table-create (&optional size)
8408 "Query for a size and insert a table skeleton.
8409 SIZE is a string Columns x Rows like for example \"3x2\"."
8410 (interactive "P")
8411 (unless size
8412 (setq size (read-string
8413 (concat "Table size Columns x Rows [e.g. "
8414 org-table-default-size "]: ")
8415 "" nil org-table-default-size)))
8417 (let* ((pos (point))
8418 (indent (make-string (current-column) ?\ ))
8419 (split (org-split-string size " *x *"))
8420 (rows (string-to-number (nth 1 split)))
8421 (columns (string-to-number (car split)))
8422 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8423 "\n")))
8424 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8425 (point-at-bol) (point)))
8426 (beginning-of-line 1)
8427 (newline))
8428 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8429 (dotimes (i rows) (insert line))
8430 (goto-char pos)
8431 (if (> rows 1)
8432 ;; Insert a hline after the first row.
8433 (progn
8434 (end-of-line 1)
8435 (insert "\n|-")
8436 (goto-char pos)))
8437 (org-table-align)))
8439 (defun org-table-convert-region (beg0 end0 &optional separator)
8440 "Convert region to a table.
8441 The region goes from BEG0 to END0, but these borders will be moved
8442 slightly, to make sure a beginning of line in the first line is included.
8444 SEPARATOR specifies the field separator in the lines. It can have the
8445 following values:
8447 '(4) Use the comma as a field separator
8448 '(16) Use a TAB as field separator
8449 integer When a number, use that many spaces as field separator
8450 nil When nil, the command tries to be smart and figure out the
8451 separator in the following way:
8452 - when each line contains a TAB, assume TAB-separated material
8453 - when each line contains a comme, assume CSV material
8454 - else, assume one or more SPACE charcters as separator."
8455 (interactive "rP")
8456 (let* ((beg (min beg0 end0))
8457 (end (max beg0 end0))
8459 (goto-char beg)
8460 (beginning-of-line 1)
8461 (setq beg (move-marker (make-marker) (point)))
8462 (goto-char end)
8463 (if (bolp) (backward-char 1) (end-of-line 1))
8464 (setq end (move-marker (make-marker) (point)))
8465 ;; Get the right field separator
8466 (unless separator
8467 (goto-char beg)
8468 (setq separator
8469 (cond
8470 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8471 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8472 (t 1))))
8473 (setq re (cond
8474 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8475 ((equal separator '(16)) "^\\|\t")
8476 ((integerp separator)
8477 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8478 (t (error "This should not happen"))))
8479 (goto-char beg)
8480 (while (re-search-forward re end t)
8481 (replace-match "| " t t))
8482 (goto-char beg)
8483 (insert " ")
8484 (org-table-align)))
8486 (defun org-table-import (file arg)
8487 "Import FILE as a table.
8488 The file is assumed to be tab-separated. Such files can be produced by most
8489 spreadsheet and database applications. If no tabs (at least one per line)
8490 are found, lines will be split on whitespace into fields."
8491 (interactive "f\nP")
8492 (or (bolp) (newline))
8493 (let ((beg (point))
8494 (pm (point-max)))
8495 (insert-file-contents file)
8496 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8498 (defun org-table-export ()
8499 "Export table as a tab-separated file.
8500 Such a file can be imported into a spreadsheet program like Excel."
8501 (interactive)
8502 (let* ((beg (org-table-begin))
8503 (end (org-table-end))
8504 (table (buffer-substring beg end))
8505 (file (read-file-name "Export table to: "))
8506 buf)
8507 (unless (or (not (file-exists-p file))
8508 (y-or-n-p (format "Overwrite file %s? " file)))
8509 (error "Abort"))
8510 (with-current-buffer (find-file-noselect file)
8511 (setq buf (current-buffer))
8512 (erase-buffer)
8513 (fundamental-mode)
8514 (insert table)
8515 (goto-char (point-min))
8516 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8517 (replace-match "" t t)
8518 (end-of-line 1))
8519 (goto-char (point-min))
8520 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8521 (replace-match "" t t)
8522 (goto-char (min (1+ (point)) (point-max))))
8523 (goto-char (point-min))
8524 (while (re-search-forward "^-[-+]*$" nil t)
8525 (replace-match "")
8526 (if (looking-at "\n")
8527 (delete-char 1)))
8528 (goto-char (point-min))
8529 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8530 (replace-match "\t" t t))
8531 (save-buffer))
8532 (kill-buffer buf)))
8534 (defvar org-table-aligned-begin-marker (make-marker)
8535 "Marker at the beginning of the table last aligned.
8536 Used to check if cursor still is in that table, to minimize realignment.")
8537 (defvar org-table-aligned-end-marker (make-marker)
8538 "Marker at the end of the table last aligned.
8539 Used to check if cursor still is in that table, to minimize realignment.")
8540 (defvar org-table-last-alignment nil
8541 "List of flags for flushright alignment, from the last re-alignment.
8542 This is being used to correctly align a single field after TAB or RET.")
8543 (defvar org-table-last-column-widths nil
8544 "List of max width of fields in each column.
8545 This is being used to correctly align a single field after TAB or RET.")
8546 (defvar org-table-overlay-coordinates nil
8547 "Overlay coordinates after each align of a table.")
8548 (make-variable-buffer-local 'org-table-overlay-coordinates)
8550 (defvar org-last-recalc-line nil)
8551 (defconst org-narrow-column-arrow "=>"
8552 "Used as display property in narrowed table columns.")
8554 (defun org-table-align ()
8555 "Align the table at point by aligning all vertical bars."
8556 (interactive)
8557 (let* (
8558 ;; Limits of table
8559 (beg (org-table-begin))
8560 (end (org-table-end))
8561 ;; Current cursor position
8562 (linepos (org-current-line))
8563 (colpos (org-table-current-column))
8564 (winstart (window-start))
8565 (winstartline (org-current-line (min winstart (1- (point-max)))))
8566 lines (new "") lengths l typenums ty fields maxfields i
8567 column
8568 (indent "") cnt frac
8569 rfmt hfmt
8570 (spaces '(1 . 1))
8571 (sp1 (car spaces))
8572 (sp2 (cdr spaces))
8573 (rfmt1 (concat
8574 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8575 (hfmt1 (concat
8576 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8577 emptystrings links dates emph narrow fmax f1 len c e)
8578 (untabify beg end)
8579 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8580 ;; Check if we have links or dates
8581 (goto-char beg)
8582 (setq links (re-search-forward org-bracket-link-regexp end t))
8583 (goto-char beg)
8584 (setq emph (and org-hide-emphasis-markers
8585 (re-search-forward org-emph-re end t)))
8586 (goto-char beg)
8587 (setq dates (and org-display-custom-times
8588 (re-search-forward org-ts-regexp-both end t)))
8589 ;; Make sure the link properties are right
8590 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8591 ;; Make sure the date properties are right
8592 (when dates (goto-char beg) (while (org-activate-dates end)))
8593 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8595 ;; Check if we are narrowing any columns
8596 (goto-char beg)
8597 (setq narrow (and org-format-transports-properties-p
8598 (re-search-forward "<[0-9]+>" end t)))
8599 ;; Get the rows
8600 (setq lines (org-split-string
8601 (buffer-substring beg end) "\n"))
8602 ;; Store the indentation of the first line
8603 (if (string-match "^ *" (car lines))
8604 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8605 ;; Mark the hlines by setting the corresponding element to nil
8606 ;; At the same time, we remove trailing space.
8607 (setq lines (mapcar (lambda (l)
8608 (if (string-match "^ *|-" l)
8610 (if (string-match "[ \t]+$" l)
8611 (substring l 0 (match-beginning 0))
8612 l)))
8613 lines))
8614 ;; Get the data fields by splitting the lines.
8615 (setq fields (mapcar
8616 (lambda (l)
8617 (org-split-string l " *| *"))
8618 (delq nil (copy-sequence lines))))
8619 ;; How many fields in the longest line?
8620 (condition-case nil
8621 (setq maxfields (apply 'max (mapcar 'length fields)))
8622 (error
8623 (kill-region beg end)
8624 (org-table-create org-table-default-size)
8625 (error "Empty table - created default table")))
8626 ;; A list of empty strings to fill any short rows on output
8627 (setq emptystrings (make-list maxfields ""))
8628 ;; Check for special formatting.
8629 (setq i -1)
8630 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8631 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8632 ;; Check if there is an explicit width specified
8633 (when narrow
8634 (setq c column fmax nil)
8635 (while c
8636 (setq e (pop c))
8637 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8638 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8639 ;; Find fields that are wider than fmax, and shorten them
8640 (when fmax
8641 (loop for xx in column do
8642 (when (and (stringp xx)
8643 (> (org-string-width xx) fmax))
8644 (org-add-props xx nil
8645 'help-echo
8646 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8647 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8648 (unless (> f1 1)
8649 (error "Cannot narrow field starting with wide link \"%s\""
8650 (match-string 0 xx)))
8651 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8652 (add-text-properties (- f1 2) f1
8653 (list 'display org-narrow-column-arrow)
8654 xx)))))
8655 ;; Get the maximum width for each column
8656 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8657 ;; Get the fraction of numbers, to decide about alignment of the column
8658 (setq cnt 0 frac 0.0)
8659 (loop for x in column do
8660 (if (equal x "")
8662 (setq frac ( / (+ (* frac cnt)
8663 (if (string-match org-table-number-regexp x) 1 0))
8664 (setq cnt (1+ cnt))))))
8665 (push (>= frac org-table-number-fraction) typenums))
8666 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8668 ;; Store the alignment of this table, for later editing of single fields
8669 (setq org-table-last-alignment typenums
8670 org-table-last-column-widths lengths)
8672 ;; With invisible characters, `format' does not get the field width right
8673 ;; So we need to make these fields wide by hand.
8674 (when (or links emph)
8675 (loop for i from 0 upto (1- maxfields) do
8676 (setq len (nth i lengths))
8677 (loop for j from 0 upto (1- (length fields)) do
8678 (setq c (nthcdr i (car (nthcdr j fields))))
8679 (if (and (stringp (car c))
8680 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8681 ; (string-match org-bracket-link-regexp (car c))
8682 (< (org-string-width (car c)) len))
8683 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8685 ;; Compute the formats needed for output of the table
8686 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8687 (while (setq l (pop lengths))
8688 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8689 (setq rfmt (concat rfmt (format rfmt1 ty l))
8690 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8691 (setq rfmt (concat rfmt "\n")
8692 hfmt (concat (substring hfmt 0 -1) "|\n"))
8694 (setq new (mapconcat
8695 (lambda (l)
8696 (if l (apply 'format rfmt
8697 (append (pop fields) emptystrings))
8698 hfmt))
8699 lines ""))
8700 ;; Replace the old one
8701 (delete-region beg end)
8702 (move-marker end nil)
8703 (move-marker org-table-aligned-begin-marker (point))
8704 (insert new)
8705 (move-marker org-table-aligned-end-marker (point))
8706 (when (and orgtbl-mode (not (org-mode-p)))
8707 (goto-char org-table-aligned-begin-marker)
8708 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8709 ;; Try to move to the old location
8710 (goto-line winstartline)
8711 (setq winstart (point-at-bol))
8712 (goto-line linepos)
8713 (set-window-start (selected-window) winstart 'noforce)
8714 (org-table-goto-column colpos)
8715 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8716 (setq org-table-may-need-update nil)
8719 (defun org-string-width (s)
8720 "Compute width of string, ignoring invisible characters.
8721 This ignores character with invisibility property `org-link', and also
8722 characters with property `org-cwidth', because these will become invisible
8723 upon the next fontification round."
8724 (let (b l)
8725 (when (or (eq t buffer-invisibility-spec)
8726 (assq 'org-link buffer-invisibility-spec))
8727 (while (setq b (text-property-any 0 (length s)
8728 'invisible 'org-link s))
8729 (setq s (concat (substring s 0 b)
8730 (substring s (or (next-single-property-change
8731 b 'invisible s) (length s)))))))
8732 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8733 (setq s (concat (substring s 0 b)
8734 (substring s (or (next-single-property-change
8735 b 'org-cwidth s) (length s))))))
8736 (setq l (string-width s) b -1)
8737 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8738 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8741 (defun org-table-begin (&optional table-type)
8742 "Find the beginning of the table and return its position.
8743 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8744 (save-excursion
8745 (if (not (re-search-backward
8746 (if table-type org-table-any-border-regexp
8747 org-table-border-regexp)
8748 nil t))
8749 (progn (goto-char (point-min)) (point))
8750 (goto-char (match-beginning 0))
8751 (beginning-of-line 2)
8752 (point))))
8754 (defun org-table-end (&optional table-type)
8755 "Find the end of the table and return its position.
8756 With argument TABLE-TYPE, go to the end of a table.el-type table."
8757 (save-excursion
8758 (if (not (re-search-forward
8759 (if table-type org-table-any-border-regexp
8760 org-table-border-regexp)
8761 nil t))
8762 (goto-char (point-max))
8763 (goto-char (match-beginning 0)))
8764 (point-marker)))
8766 (defun org-table-justify-field-maybe (&optional new)
8767 "Justify the current field, text to left, number to right.
8768 Optional argument NEW may specify text to replace the current field content."
8769 (cond
8770 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8771 ((org-at-table-hline-p))
8772 ((and (not new)
8773 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8774 (current-buffer)))
8775 (< (point) org-table-aligned-begin-marker)
8776 (>= (point) org-table-aligned-end-marker)))
8777 ;; This is not the same table, force a full re-align
8778 (setq org-table-may-need-update t))
8779 (t ;; realign the current field, based on previous full realign
8780 (let* ((pos (point)) s
8781 (col (org-table-current-column))
8782 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8783 l f n o e)
8784 (when (> col 0)
8785 (skip-chars-backward "^|\n")
8786 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8787 (progn
8788 (setq s (match-string 1)
8789 o (match-string 0)
8790 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8791 e (not (= (match-beginning 2) (match-end 2))))
8792 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8793 l (if e "|" (setq org-table-may-need-update t) ""))
8794 n (format f s))
8795 (if new
8796 (if (<= (length new) l) ;; FIXME: length -> str-width?
8797 (setq n (format f new))
8798 (setq n (concat new "|") org-table-may-need-update t)))
8799 (or (equal n o)
8800 (let (org-table-may-need-update)
8801 (replace-match n t t))))
8802 (setq org-table-may-need-update t))
8803 (goto-char pos))))))
8805 (defun org-table-next-field ()
8806 "Go to the next field in the current table, creating new lines as needed.
8807 Before doing so, re-align the table if necessary."
8808 (interactive)
8809 (org-table-maybe-eval-formula)
8810 (org-table-maybe-recalculate-line)
8811 (if (and org-table-automatic-realign
8812 org-table-may-need-update)
8813 (org-table-align))
8814 (let ((end (org-table-end)))
8815 (if (org-at-table-hline-p)
8816 (end-of-line 1))
8817 (condition-case nil
8818 (progn
8819 (re-search-forward "|" end)
8820 (if (looking-at "[ \t]*$")
8821 (re-search-forward "|" end))
8822 (if (and (looking-at "-")
8823 org-table-tab-jumps-over-hlines
8824 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8825 (goto-char (match-beginning 1)))
8826 (if (looking-at "-")
8827 (progn
8828 (beginning-of-line 0)
8829 (org-table-insert-row 'below))
8830 (if (looking-at " ") (forward-char 1))))
8831 (error
8832 (org-table-insert-row 'below)))))
8834 (defun org-table-previous-field ()
8835 "Go to the previous field in the table.
8836 Before doing so, re-align the table if necessary."
8837 (interactive)
8838 (org-table-justify-field-maybe)
8839 (org-table-maybe-recalculate-line)
8840 (if (and org-table-automatic-realign
8841 org-table-may-need-update)
8842 (org-table-align))
8843 (if (org-at-table-hline-p)
8844 (end-of-line 1))
8845 (re-search-backward "|" (org-table-begin))
8846 (re-search-backward "|" (org-table-begin))
8847 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8848 (re-search-backward "|" (org-table-begin)))
8849 (if (looking-at "| ?")
8850 (goto-char (match-end 0))))
8852 (defun org-table-next-row ()
8853 "Go to the next row (same column) in the current table.
8854 Before doing so, re-align the table if necessary."
8855 (interactive)
8856 (org-table-maybe-eval-formula)
8857 (org-table-maybe-recalculate-line)
8858 (if (or (looking-at "[ \t]*$")
8859 (save-excursion (skip-chars-backward " \t") (bolp)))
8860 (newline)
8861 (if (and org-table-automatic-realign
8862 org-table-may-need-update)
8863 (org-table-align))
8864 (let ((col (org-table-current-column)))
8865 (beginning-of-line 2)
8866 (if (or (not (org-at-table-p))
8867 (org-at-table-hline-p))
8868 (progn
8869 (beginning-of-line 0)
8870 (org-table-insert-row 'below)))
8871 (org-table-goto-column col)
8872 (skip-chars-backward "^|\n\r")
8873 (if (looking-at " ") (forward-char 1)))))
8875 (defun org-table-copy-down (n)
8876 "Copy a field down in the current column.
8877 If the field at the cursor is empty, copy into it the content of the nearest
8878 non-empty field above. With argument N, use the Nth non-empty field.
8879 If the current field is not empty, it is copied down to the next row, and
8880 the cursor is moved with it. Therefore, repeating this command causes the
8881 column to be filled row-by-row.
8882 If the variable `org-table-copy-increment' is non-nil and the field is an
8883 integer or a timestamp, it will be incremented while copying. In the case of
8884 a timestamp, if the cursor is on the year, change the year. If it is on the
8885 month or the day, change that. Point will stay on the current date field
8886 in order to easily repeat the interval."
8887 (interactive "p")
8888 (let* ((colpos (org-table-current-column))
8889 (col (current-column))
8890 (field (org-table-get-field))
8891 (non-empty (string-match "[^ \t]" field))
8892 (beg (org-table-begin))
8893 txt)
8894 (org-table-check-inside-data-field)
8895 (if non-empty
8896 (progn
8897 (setq txt (org-trim field))
8898 (org-table-next-row)
8899 (org-table-blank-field))
8900 (save-excursion
8901 (setq txt
8902 (catch 'exit
8903 (while (progn (beginning-of-line 1)
8904 (re-search-backward org-table-dataline-regexp
8905 beg t))
8906 (org-table-goto-column colpos t)
8907 (if (and (looking-at
8908 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8909 (= (setq n (1- n)) 0))
8910 (throw 'exit (match-string 1))))))))
8911 (if txt
8912 (progn
8913 (if (and org-table-copy-increment
8914 (string-match "^[0-9]+$" txt))
8915 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8916 (insert txt)
8917 (move-to-column col)
8918 (if (and org-table-copy-increment (org-at-timestamp-p t))
8919 (org-timestamp-up 1)
8920 (org-table-maybe-recalculate-line))
8921 (org-table-align)
8922 (move-to-column col))
8923 (error "No non-empty field found"))))
8925 (defun org-table-check-inside-data-field ()
8926 "Is point inside a table data field?
8927 I.e. not on a hline or before the first or after the last column?
8928 This actually throws an error, so it aborts the current command."
8929 (if (or (not (org-at-table-p))
8930 (= (org-table-current-column) 0)
8931 (org-at-table-hline-p)
8932 (looking-at "[ \t]*$"))
8933 (error "Not in table data field")))
8935 (defvar org-table-clip nil
8936 "Clipboard for table regions.")
8938 (defun org-table-blank-field ()
8939 "Blank the current table field or active region."
8940 (interactive)
8941 (org-table-check-inside-data-field)
8942 (if (and (interactive-p) (org-region-active-p))
8943 (let (org-table-clip)
8944 (org-table-cut-region (region-beginning) (region-end)))
8945 (skip-chars-backward "^|")
8946 (backward-char 1)
8947 (if (looking-at "|[^|\n]+")
8948 (let* ((pos (match-beginning 0))
8949 (match (match-string 0))
8950 (len (org-string-width match)))
8951 (replace-match (concat "|" (make-string (1- len) ?\ )))
8952 (goto-char (+ 2 pos))
8953 (substring match 1)))))
8955 (defun org-table-get-field (&optional n replace)
8956 "Return the value of the field in column N of current row.
8957 N defaults to current field.
8958 If REPLACE is a string, replace field with this value. The return value
8959 is always the old value."
8960 (and n (org-table-goto-column n))
8961 (skip-chars-backward "^|\n")
8962 (backward-char 1)
8963 (if (looking-at "|[^|\r\n]*")
8964 (let* ((pos (match-beginning 0))
8965 (val (buffer-substring (1+ pos) (match-end 0))))
8966 (if replace
8967 (replace-match (concat "|" replace) t t))
8968 (goto-char (min (point-at-eol) (+ 2 pos)))
8969 val)
8970 (forward-char 1) ""))
8972 (defun org-table-field-info (arg)
8973 "Show info about the current field, and highlight any reference at point."
8974 (interactive "P")
8975 (org-table-get-specials)
8976 (save-excursion
8977 (let* ((pos (point))
8978 (col (org-table-current-column))
8979 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8980 (name (car (rassoc (list (org-current-line) col)
8981 org-table-named-field-locations)))
8982 (eql (org-table-get-stored-formulas))
8983 (dline (org-table-current-dline))
8984 (ref (format "@%d$%d" dline col))
8985 (ref1 (org-table-convert-refs-to-an ref))
8986 (fequation (or (assoc name eql) (assoc ref eql)))
8987 (cequation (assoc (int-to-string col) eql))
8988 (eqn (or fequation cequation)))
8989 (goto-char pos)
8990 (condition-case nil
8991 (org-table-show-reference 'local)
8992 (error nil))
8993 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8994 dline col
8995 (if cname (concat " or $" cname) "")
8996 dline col ref1
8997 (if name (concat " or $" name) "")
8998 ;; FIXME: formula info not correct if special table line
8999 (if eqn
9000 (concat ", formula: "
9001 (org-table-formula-to-user
9002 (concat
9003 (if (string-match "^[$@]"(car eqn)) "" "$")
9004 (car eqn) "=" (cdr eqn))))
9005 "")))))
9007 (defun org-table-current-column ()
9008 "Find out which column we are in.
9009 When called interactively, column is also displayed in echo area."
9010 (interactive)
9011 (if (interactive-p) (org-table-check-inside-data-field))
9012 (save-excursion
9013 (let ((cnt 0) (pos (point)))
9014 (beginning-of-line 1)
9015 (while (search-forward "|" pos t)
9016 (setq cnt (1+ cnt)))
9017 (if (interactive-p) (message "This is table column %d" cnt))
9018 cnt)))
9020 (defun org-table-current-dline ()
9021 "Find out what table data line we are in.
9022 Only datalins count for this."
9023 (interactive)
9024 (if (interactive-p) (org-table-check-inside-data-field))
9025 (save-excursion
9026 (let ((cnt 0) (pos (point)))
9027 (goto-char (org-table-begin))
9028 (while (<= (point) pos)
9029 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
9030 (beginning-of-line 2))
9031 (if (interactive-p) (message "This is table line %d" cnt))
9032 cnt)))
9034 (defun org-table-goto-column (n &optional on-delim force)
9035 "Move the cursor to the Nth column in the current table line.
9036 With optional argument ON-DELIM, stop with point before the left delimiter
9037 of the field.
9038 If there are less than N fields, just go to after the last delimiter.
9039 However, when FORCE is non-nil, create new columns if necessary."
9040 (interactive "p")
9041 (let ((pos (point-at-eol)))
9042 (beginning-of-line 1)
9043 (when (> n 0)
9044 (while (and (> (setq n (1- n)) -1)
9045 (or (search-forward "|" pos t)
9046 (and force
9047 (progn (end-of-line 1)
9048 (skip-chars-backward "^|")
9049 (insert " | "))))))
9050 ; (backward-char 2) t)))))
9051 (when (and force (not (looking-at ".*|")))
9052 (save-excursion (end-of-line 1) (insert " | ")))
9053 (if on-delim
9054 (backward-char 1)
9055 (if (looking-at " ") (forward-char 1))))))
9057 (defun org-at-table-p (&optional table-type)
9058 "Return t if the cursor is inside an org-type table.
9059 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9060 (if org-enable-table-editor
9061 (save-excursion
9062 (beginning-of-line 1)
9063 (looking-at (if table-type org-table-any-line-regexp
9064 org-table-line-regexp)))
9065 nil))
9067 (defun org-at-table.el-p ()
9068 "Return t if and only if we are at a table.el table."
9069 (and (org-at-table-p 'any)
9070 (save-excursion
9071 (goto-char (org-table-begin 'any))
9072 (looking-at org-table1-hline-regexp))))
9074 (defun org-table-recognize-table.el ()
9075 "If there is a table.el table nearby, recognize it and move into it."
9076 (if org-table-tab-recognizes-table.el
9077 (if (org-at-table.el-p)
9078 (progn
9079 (beginning-of-line 1)
9080 (if (looking-at org-table-dataline-regexp)
9082 (if (looking-at org-table1-hline-regexp)
9083 (progn
9084 (beginning-of-line 2)
9085 (if (looking-at org-table-any-border-regexp)
9086 (beginning-of-line -1)))))
9087 (if (re-search-forward "|" (org-table-end t) t)
9088 (progn
9089 (require 'table)
9090 (if (table--at-cell-p (point))
9092 (message "recognizing table.el table...")
9093 (table-recognize-table)
9094 (message "recognizing table.el table...done")))
9095 (error "This should not happen..."))
9097 nil)
9098 nil))
9100 (defun org-at-table-hline-p ()
9101 "Return t if the cursor is inside a hline in a table."
9102 (if org-enable-table-editor
9103 (save-excursion
9104 (beginning-of-line 1)
9105 (looking-at org-table-hline-regexp))
9106 nil))
9108 (defun org-table-insert-column ()
9109 "Insert a new column into the table."
9110 (interactive)
9111 (if (not (org-at-table-p))
9112 (error "Not at a table"))
9113 (org-table-find-dataline)
9114 (let* ((col (max 1 (org-table-current-column)))
9115 (beg (org-table-begin))
9116 (end (org-table-end))
9117 ;; Current cursor position
9118 (linepos (org-current-line))
9119 (colpos col))
9120 (goto-char beg)
9121 (while (< (point) end)
9122 (if (org-at-table-hline-p)
9124 (org-table-goto-column col t)
9125 (insert "| "))
9126 (beginning-of-line 2))
9127 (move-marker end nil)
9128 (goto-line linepos)
9129 (org-table-goto-column colpos)
9130 (org-table-align)
9131 (org-table-fix-formulas "$" nil (1- col) 1)))
9133 (defun org-table-find-dataline ()
9134 "Find a dataline in the current table, which is needed for column commands."
9135 (if (and (org-at-table-p)
9136 (not (org-at-table-hline-p)))
9138 (let ((col (current-column))
9139 (end (org-table-end)))
9140 (move-to-column col)
9141 (while (and (< (point) end)
9142 (or (not (= (current-column) col))
9143 (org-at-table-hline-p)))
9144 (beginning-of-line 2)
9145 (move-to-column col))
9146 (if (and (org-at-table-p)
9147 (not (org-at-table-hline-p)))
9149 (error
9150 "Please position cursor in a data line for column operations")))))
9152 (defun org-table-delete-column ()
9153 "Delete a column from the table."
9154 (interactive)
9155 (if (not (org-at-table-p))
9156 (error "Not at a table"))
9157 (org-table-find-dataline)
9158 (org-table-check-inside-data-field)
9159 (let* ((col (org-table-current-column))
9160 (beg (org-table-begin))
9161 (end (org-table-end))
9162 ;; Current cursor position
9163 (linepos (org-current-line))
9164 (colpos col))
9165 (goto-char beg)
9166 (while (< (point) end)
9167 (if (org-at-table-hline-p)
9169 (org-table-goto-column col t)
9170 (and (looking-at "|[^|\n]+|")
9171 (replace-match "|")))
9172 (beginning-of-line 2))
9173 (move-marker end nil)
9174 (goto-line linepos)
9175 (org-table-goto-column colpos)
9176 (org-table-align)
9177 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9178 col -1 col)))
9180 (defun org-table-move-column-right ()
9181 "Move column to the right."
9182 (interactive)
9183 (org-table-move-column nil))
9184 (defun org-table-move-column-left ()
9185 "Move column to the left."
9186 (interactive)
9187 (org-table-move-column 'left))
9189 (defun org-table-move-column (&optional left)
9190 "Move the current column to the right. With arg LEFT, move to the left."
9191 (interactive "P")
9192 (if (not (org-at-table-p))
9193 (error "Not at a table"))
9194 (org-table-find-dataline)
9195 (org-table-check-inside-data-field)
9196 (let* ((col (org-table-current-column))
9197 (col1 (if left (1- col) col))
9198 (beg (org-table-begin))
9199 (end (org-table-end))
9200 ;; Current cursor position
9201 (linepos (org-current-line))
9202 (colpos (if left (1- col) (1+ col))))
9203 (if (and left (= col 1))
9204 (error "Cannot move column further left"))
9205 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9206 (error "Cannot move column further right"))
9207 (goto-char beg)
9208 (while (< (point) end)
9209 (if (org-at-table-hline-p)
9211 (org-table-goto-column col1 t)
9212 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9213 (replace-match "|\\2|\\1|")))
9214 (beginning-of-line 2))
9215 (move-marker end nil)
9216 (goto-line linepos)
9217 (org-table-goto-column colpos)
9218 (org-table-align)
9219 (org-table-fix-formulas
9220 "$" (list (cons (number-to-string col) (number-to-string colpos))
9221 (cons (number-to-string colpos) (number-to-string col))))))
9223 (defun org-table-move-row-down ()
9224 "Move table row down."
9225 (interactive)
9226 (org-table-move-row nil))
9227 (defun org-table-move-row-up ()
9228 "Move table row up."
9229 (interactive)
9230 (org-table-move-row 'up))
9232 (defun org-table-move-row (&optional up)
9233 "Move the current table line down. With arg UP, move it up."
9234 (interactive "P")
9235 (let* ((col (current-column))
9236 (pos (point))
9237 (hline1p (save-excursion (beginning-of-line 1)
9238 (looking-at org-table-hline-regexp)))
9239 (dline1 (org-table-current-dline))
9240 (dline2 (+ dline1 (if up -1 1)))
9241 (tonew (if up 0 2))
9242 txt hline2p)
9243 (beginning-of-line tonew)
9244 (unless (org-at-table-p)
9245 (goto-char pos)
9246 (error "Cannot move row further"))
9247 (setq hline2p (looking-at org-table-hline-regexp))
9248 (goto-char pos)
9249 (beginning-of-line 1)
9250 (setq pos (point))
9251 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9252 (delete-region (point) (1+ (point-at-eol)))
9253 (beginning-of-line tonew)
9254 (insert txt)
9255 (beginning-of-line 0)
9256 (move-to-column col)
9257 (unless (or hline1p hline2p)
9258 (org-table-fix-formulas
9259 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9260 (cons (number-to-string dline2) (number-to-string dline1)))))))
9262 (defun org-table-insert-row (&optional arg)
9263 "Insert a new row above the current line into the table.
9264 With prefix ARG, insert below the current line."
9265 (interactive "P")
9266 (if (not (org-at-table-p))
9267 (error "Not at a table"))
9268 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9269 (new (org-table-clean-line line)))
9270 ;; Fix the first field if necessary
9271 (if (string-match "^[ \t]*| *[#$] *|" line)
9272 (setq new (replace-match (match-string 0 line) t t new)))
9273 (beginning-of-line (if arg 2 1))
9274 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9275 (beginning-of-line 0)
9276 (re-search-forward "| ?" (point-at-eol) t)
9277 (and (or org-table-may-need-update org-table-overlay-coordinates)
9278 (org-table-align))
9279 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9281 (defun org-table-insert-hline (&optional above)
9282 "Insert a horizontal-line below the current line into the table.
9283 With prefix ABOVE, insert above the current line."
9284 (interactive "P")
9285 (if (not (org-at-table-p))
9286 (error "Not at a table"))
9287 (let ((line (org-table-clean-line
9288 (buffer-substring (point-at-bol) (point-at-eol))))
9289 (col (current-column)))
9290 (while (string-match "|\\( +\\)|" line)
9291 (setq line (replace-match
9292 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9293 ?-) "|") t t line)))
9294 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9295 (beginning-of-line (if above 1 2))
9296 (insert line "\n")
9297 (beginning-of-line (if above 1 -1))
9298 (move-to-column col)
9299 (and org-table-overlay-coordinates (org-table-align))))
9301 (defun org-table-hline-and-move (&optional same-column)
9302 "Insert a hline and move to the row below that line."
9303 (interactive "P")
9304 (let ((col (org-table-current-column)))
9305 (org-table-maybe-eval-formula)
9306 (org-table-maybe-recalculate-line)
9307 (org-table-insert-hline)
9308 (end-of-line 2)
9309 (if (looking-at "\n[ \t]*|-")
9310 (progn (insert "\n|") (org-table-align))
9311 (org-table-next-field))
9312 (if same-column (org-table-goto-column col))))
9314 (defun org-table-clean-line (s)
9315 "Convert a table line S into a string with only \"|\" and space.
9316 In particular, this does handle wide and invisible characters."
9317 (if (string-match "^[ \t]*|-" s)
9318 ;; It's a hline, just map the characters
9319 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9320 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9321 (setq s (replace-match
9322 (concat "|" (make-string (org-string-width (match-string 1 s))
9323 ?\ ) "|")
9324 t t s)))
9327 (defun org-table-kill-row ()
9328 "Delete the current row or horizontal line from the table."
9329 (interactive)
9330 (if (not (org-at-table-p))
9331 (error "Not at a table"))
9332 (let ((col (current-column))
9333 (dline (org-table-current-dline)))
9334 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9335 (if (not (org-at-table-p)) (beginning-of-line 0))
9336 (move-to-column col)
9337 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9338 dline -1 dline)))
9340 (defun org-table-sort-lines (with-case &optional sorting-type)
9341 "Sort table lines according to the column at point.
9343 The position of point indicates the column to be used for
9344 sorting, and the range of lines is the range between the nearest
9345 horizontal separator lines, or the entire table of no such lines
9346 exist. If point is before the first column, you will be prompted
9347 for the sorting column. If there is an active region, the mark
9348 specifies the first line and the sorting column, while point
9349 should be in the last line to be included into the sorting.
9351 The command then prompts for the sorting type which can be
9352 alphabetically, numerically, or by time (as given in a time stamp
9353 in the field). Sorting in reverse order is also possible.
9355 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9357 If SORTING-TYPE is specified when this function is called from a Lisp
9358 program, no prompting will take place. SORTING-TYPE must be a character,
9359 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9360 should be done in reverse order."
9361 (interactive "P")
9362 (let* ((thisline (org-current-line))
9363 (thiscol (org-table-current-column))
9364 beg end bcol ecol tend tbeg column lns pos)
9365 (when (equal thiscol 0)
9366 (if (interactive-p)
9367 (setq thiscol
9368 (string-to-number
9369 (read-string "Use column N for sorting: ")))
9370 (setq thiscol 1))
9371 (org-table-goto-column thiscol))
9372 (org-table-check-inside-data-field)
9373 (if (org-region-active-p)
9374 (progn
9375 (setq beg (region-beginning) end (region-end))
9376 (goto-char beg)
9377 (setq column (org-table-current-column)
9378 beg (point-at-bol))
9379 (goto-char end)
9380 (setq end (point-at-bol 2)))
9381 (setq column (org-table-current-column)
9382 pos (point)
9383 tbeg (org-table-begin)
9384 tend (org-table-end))
9385 (if (re-search-backward org-table-hline-regexp tbeg t)
9386 (setq beg (point-at-bol 2))
9387 (goto-char tbeg)
9388 (setq beg (point-at-bol 1)))
9389 (goto-char pos)
9390 (if (re-search-forward org-table-hline-regexp tend t)
9391 (setq end (point-at-bol 1))
9392 (goto-char tend)
9393 (setq end (point-at-bol))))
9394 (setq beg (move-marker (make-marker) beg)
9395 end (move-marker (make-marker) end))
9396 (untabify beg end)
9397 (goto-char beg)
9398 (org-table-goto-column column)
9399 (skip-chars-backward "^|")
9400 (setq bcol (current-column))
9401 (org-table-goto-column (1+ column))
9402 (skip-chars-backward "^|")
9403 (setq ecol (1- (current-column)))
9404 (org-table-goto-column column)
9405 (setq lns (mapcar (lambda(x) (cons
9406 (org-sort-remove-invisible
9407 (nth (1- column)
9408 (org-split-string x "[ \t]*|[ \t]*")))
9410 (org-split-string (buffer-substring beg end) "\n")))
9411 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9412 (delete-region beg end)
9413 (move-marker beg nil)
9414 (move-marker end nil)
9415 (insert (mapconcat 'cdr lns "\n") "\n")
9416 (goto-line thisline)
9417 (org-table-goto-column thiscol)
9418 (message "%d lines sorted, based on column %d" (length lns) column)))
9420 ;; FIXME: maybe we will not need this? Table sorting is broken....
9421 (defun org-sort-remove-invisible (s)
9422 (remove-text-properties 0 (length s) org-rm-props s)
9423 (while (string-match org-bracket-link-regexp s)
9424 (setq s (replace-match (if (match-end 2)
9425 (match-string 3 s)
9426 (match-string 1 s)) t t s)))
9429 (defun org-table-cut-region (beg end)
9430 "Copy region in table to the clipboard and blank all relevant fields."
9431 (interactive "r")
9432 (org-table-copy-region beg end 'cut))
9434 (defun org-table-copy-region (beg end &optional cut)
9435 "Copy rectangular region in table to clipboard.
9436 A special clipboard is used which can only be accessed
9437 with `org-table-paste-rectangle'."
9438 (interactive "rP")
9439 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9440 region cols
9441 (rpl (if cut " " nil)))
9442 (goto-char beg)
9443 (org-table-check-inside-data-field)
9444 (setq l01 (org-current-line)
9445 c01 (org-table-current-column))
9446 (goto-char end)
9447 (org-table-check-inside-data-field)
9448 (setq l02 (org-current-line)
9449 c02 (org-table-current-column))
9450 (setq l1 (min l01 l02) l2 (max l01 l02)
9451 c1 (min c01 c02) c2 (max c01 c02))
9452 (catch 'exit
9453 (while t
9454 (catch 'nextline
9455 (if (> l1 l2) (throw 'exit t))
9456 (goto-line l1)
9457 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9458 (setq cols nil ic1 c1 ic2 c2)
9459 (while (< ic1 (1+ ic2))
9460 (push (org-table-get-field ic1 rpl) cols)
9461 (setq ic1 (1+ ic1)))
9462 (push (nreverse cols) region)
9463 (setq l1 (1+ l1)))))
9464 (setq org-table-clip (nreverse region))
9465 (if cut (org-table-align))
9466 org-table-clip))
9468 (defun org-table-paste-rectangle ()
9469 "Paste a rectangular region into a table.
9470 The upper right corner ends up in the current field. All involved fields
9471 will be overwritten. If the rectangle does not fit into the present table,
9472 the table is enlarged as needed. The process ignores horizontal separator
9473 lines."
9474 (interactive)
9475 (unless (and org-table-clip (listp org-table-clip))
9476 (error "First cut/copy a region to paste!"))
9477 (org-table-check-inside-data-field)
9478 (let* ((clip org-table-clip)
9479 (line (org-current-line))
9480 (col (org-table-current-column))
9481 (org-enable-table-editor t)
9482 (org-table-automatic-realign nil)
9483 c cols field)
9484 (while (setq cols (pop clip))
9485 (while (org-at-table-hline-p) (beginning-of-line 2))
9486 (if (not (org-at-table-p))
9487 (progn (end-of-line 0) (org-table-next-field)))
9488 (setq c col)
9489 (while (setq field (pop cols))
9490 (org-table-goto-column c nil 'force)
9491 (org-table-get-field nil field)
9492 (setq c (1+ c)))
9493 (beginning-of-line 2))
9494 (goto-line line)
9495 (org-table-goto-column col)
9496 (org-table-align)))
9498 (defun org-table-convert ()
9499 "Convert from `org-mode' table to table.el and back.
9500 Obviously, this only works within limits. When an Org-mode table is
9501 converted to table.el, all horizontal separator lines get lost, because
9502 table.el uses these as cell boundaries and has no notion of horizontal lines.
9503 A table.el table can be converted to an Org-mode table only if it does not
9504 do row or column spanning. Multiline cells will become multiple cells.
9505 Beware, Org-mode does not test if the table can be successfully converted - it
9506 blindly applies a recipe that works for simple tables."
9507 (interactive)
9508 (require 'table)
9509 (if (org-at-table.el-p)
9510 ;; convert to Org-mode table
9511 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9512 (end (move-marker (make-marker) (org-table-end t))))
9513 (table-unrecognize-region beg end)
9514 (goto-char beg)
9515 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9516 (replace-match ""))
9517 (goto-char beg))
9518 (if (org-at-table-p)
9519 ;; convert to table.el table
9520 (let ((beg (move-marker (make-marker) (org-table-begin)))
9521 (end (move-marker (make-marker) (org-table-end))))
9522 ;; first, get rid of all horizontal lines
9523 (goto-char beg)
9524 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9525 (replace-match ""))
9526 ;; insert a hline before first
9527 (goto-char beg)
9528 (org-table-insert-hline 'above)
9529 (beginning-of-line -1)
9530 ;; insert a hline after each line
9531 (while (progn (beginning-of-line 3) (< (point) end))
9532 (org-table-insert-hline))
9533 (goto-char beg)
9534 (setq end (move-marker end (org-table-end)))
9535 ;; replace "+" at beginning and ending of hlines
9536 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9537 (replace-match "\\1+-"))
9538 (goto-char beg)
9539 (while (re-search-forward "-|[ \t]*$" end t)
9540 (replace-match "-+"))
9541 (goto-char beg)))))
9543 (defun org-table-wrap-region (arg)
9544 "Wrap several fields in a column like a paragraph.
9545 This is useful if you'd like to spread the contents of a field over several
9546 lines, in order to keep the table compact.
9548 If there is an active region, and both point and mark are in the same column,
9549 the text in the column is wrapped to minimum width for the given number of
9550 lines. Generally, this makes the table more compact. A prefix ARG may be
9551 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9552 formats the selected text to two lines. If the region was longer than two
9553 lines, the remaining lines remain empty. A negative prefix argument reduces
9554 the current number of lines by that amount. The wrapped text is pasted back
9555 into the table. If you formatted it to more lines than it was before, fields
9556 further down in the table get overwritten - so you might need to make space in
9557 the table first.
9559 If there is no region, the current field is split at the cursor position and
9560 the text fragment to the right of the cursor is prepended to the field one
9561 line down.
9563 If there is no region, but you specify a prefix ARG, the current field gets
9564 blank, and the content is appended to the field above."
9565 (interactive "P")
9566 (org-table-check-inside-data-field)
9567 (if (org-region-active-p)
9568 ;; There is a region: fill as a paragraph
9569 (let* ((beg (region-beginning))
9570 (cline (save-excursion (goto-char beg) (org-current-line)))
9571 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9572 nlines)
9573 (org-table-cut-region (region-beginning) (region-end))
9574 (if (> (length (car org-table-clip)) 1)
9575 (error "Region must be limited to single column"))
9576 (setq nlines (if arg
9577 (if (< arg 1)
9578 (+ (length org-table-clip) arg)
9579 arg)
9580 (length org-table-clip)))
9581 (setq org-table-clip
9582 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9583 nil nlines)))
9584 (goto-line cline)
9585 (org-table-goto-column ccol)
9586 (org-table-paste-rectangle))
9587 ;; No region, split the current field at point
9588 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9589 (skip-chars-forward "^\r\n|"))
9590 (if arg
9591 ;; combine with field above
9592 (let ((s (org-table-blank-field))
9593 (col (org-table-current-column)))
9594 (beginning-of-line 0)
9595 (while (org-at-table-hline-p) (beginning-of-line 0))
9596 (org-table-goto-column col)
9597 (skip-chars-forward "^|")
9598 (skip-chars-backward " ")
9599 (insert " " (org-trim s))
9600 (org-table-align))
9601 ;; split field
9602 (if (looking-at "\\([^|]+\\)+|")
9603 (let ((s (match-string 1)))
9604 (replace-match " |")
9605 (goto-char (match-beginning 0))
9606 (org-table-next-row)
9607 (insert (org-trim s) " ")
9608 (org-table-align))
9609 (org-table-next-row)))))
9611 (defvar org-field-marker nil)
9613 (defun org-table-edit-field (arg)
9614 "Edit table field in a different window.
9615 This is mainly useful for fields that contain hidden parts.
9616 When called with a \\[universal-argument] prefix, just make the full field visible so that
9617 it can be edited in place."
9618 (interactive "P")
9619 (if arg
9620 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9621 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9622 (remove-text-properties b e '(org-cwidth t invisible t
9623 display t intangible t))
9624 (if (and (boundp 'font-lock-mode) font-lock-mode)
9625 (font-lock-fontify-block)))
9626 (let ((pos (move-marker (make-marker) (point)))
9627 (field (org-table-get-field))
9628 (cw (current-window-configuration))
9630 (org-switch-to-buffer-other-window "*Org tmp*")
9631 (erase-buffer)
9632 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9633 (let ((org-inhibit-startup t)) (org-mode))
9634 (goto-char (setq p (point-max)))
9635 (insert (org-trim field))
9636 (remove-text-properties p (point-max)
9637 '(invisible t org-cwidth t display t
9638 intangible t))
9639 (goto-char p)
9640 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9641 (org-set-local 'org-window-configuration cw)
9642 (org-set-local 'org-field-marker pos)
9643 (message "Edit and finish with C-c C-c"))))
9645 (defun org-table-finish-edit-field ()
9646 "Finish editing a table data field.
9647 Remove all newline characters, insert the result into the table, realign
9648 the table and kill the editing buffer."
9649 (let ((pos org-field-marker)
9650 (cw org-window-configuration)
9651 (cb (current-buffer))
9652 text)
9653 (goto-char (point-min))
9654 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9655 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9656 (replace-match " "))
9657 (setq text (org-trim (buffer-string)))
9658 (set-window-configuration cw)
9659 (kill-buffer cb)
9660 (select-window (get-buffer-window (marker-buffer pos)))
9661 (goto-char pos)
9662 (move-marker pos nil)
9663 (org-table-check-inside-data-field)
9664 (org-table-get-field nil text)
9665 (org-table-align)
9666 (message "New field value inserted")))
9668 (defun org-trim (s)
9669 "Remove whitespace at beginning and end of string."
9670 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9671 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9674 (defun org-wrap (string &optional width lines)
9675 "Wrap string to either a number of lines, or a width in characters.
9676 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9677 that costs. If there is a word longer than WIDTH, the text is actually
9678 wrapped to the length of that word.
9679 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9680 many lines, whatever width that takes.
9681 The return value is a list of lines, without newlines at the end."
9682 (let* ((words (org-split-string string "[ \t\n]+"))
9683 (maxword (apply 'max (mapcar 'org-string-width words)))
9684 w ll)
9685 (cond (width
9686 (org-do-wrap words (max maxword width)))
9687 (lines
9688 (setq w maxword)
9689 (setq ll (org-do-wrap words maxword))
9690 (if (<= (length ll) lines)
9692 (setq ll words)
9693 (while (> (length ll) lines)
9694 (setq w (1+ w))
9695 (setq ll (org-do-wrap words w)))
9696 ll))
9697 (t (error "Cannot wrap this")))))
9700 (defun org-do-wrap (words width)
9701 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9702 (let (lines line)
9703 (while words
9704 (setq line (pop words))
9705 (while (and words (< (+ (length line) (length (car words))) width))
9706 (setq line (concat line " " (pop words))))
9707 (setq lines (push line lines)))
9708 (nreverse lines)))
9710 (defun org-split-string (string &optional separators)
9711 "Splits STRING into substrings at SEPARATORS.
9712 No empty strings are returned if there are matches at the beginning
9713 and end of string."
9714 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9715 (start 0)
9716 notfirst
9717 (list nil))
9718 (while (and (string-match rexp string
9719 (if (and notfirst
9720 (= start (match-beginning 0))
9721 (< start (length string)))
9722 (1+ start) start))
9723 (< (match-beginning 0) (length string)))
9724 (setq notfirst t)
9725 (or (eq (match-beginning 0) 0)
9726 (and (eq (match-beginning 0) (match-end 0))
9727 (eq (match-beginning 0) start))
9728 (setq list
9729 (cons (substring string start (match-beginning 0))
9730 list)))
9731 (setq start (match-end 0)))
9732 (or (eq start (length string))
9733 (setq list
9734 (cons (substring string start)
9735 list)))
9736 (nreverse list)))
9738 (defun org-table-map-tables (function)
9739 "Apply FUNCTION to the start of all tables in the buffer."
9740 (save-excursion
9741 (save-restriction
9742 (widen)
9743 (goto-char (point-min))
9744 (while (re-search-forward org-table-any-line-regexp nil t)
9745 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9746 (beginning-of-line 1)
9747 (if (looking-at org-table-line-regexp)
9748 (save-excursion (funcall function)))
9749 (re-search-forward org-table-any-border-regexp nil 1))))
9750 (message "Mapping tables: done"))
9752 (defvar org-timecnt) ; dynamically scoped parameter
9754 (defun org-table-sum (&optional beg end nlast)
9755 "Sum numbers in region of current table column.
9756 The result will be displayed in the echo area, and will be available
9757 as kill to be inserted with \\[yank].
9759 If there is an active region, it is interpreted as a rectangle and all
9760 numbers in that rectangle will be summed. If there is no active
9761 region and point is located in a table column, sum all numbers in that
9762 column.
9764 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9765 numbers are assumed to be times as well (in decimal hours) and the
9766 numbers are added as such.
9768 If NLAST is a number, only the NLAST fields will actually be summed."
9769 (interactive)
9770 (save-excursion
9771 (let (col (org-timecnt 0) diff h m s org-table-clip)
9772 (cond
9773 ((and beg end)) ; beg and end given explicitly
9774 ((org-region-active-p)
9775 (setq beg (region-beginning) end (region-end)))
9777 (setq col (org-table-current-column))
9778 (goto-char (org-table-begin))
9779 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9780 (error "No table data"))
9781 (org-table-goto-column col)
9782 (setq beg (point))
9783 (goto-char (org-table-end))
9784 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9785 (error "No table data"))
9786 (org-table-goto-column col)
9787 (setq end (point))))
9788 (let* ((items (apply 'append (org-table-copy-region beg end)))
9789 (items1 (cond ((not nlast) items)
9790 ((>= nlast (length items)) items)
9791 (t (setq items (reverse items))
9792 (setcdr (nthcdr (1- nlast) items) nil)
9793 (nreverse items))))
9794 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9795 items1)))
9796 (res (apply '+ numbers))
9797 (sres (if (= org-timecnt 0)
9798 (format "%g" res)
9799 (setq diff (* 3600 res)
9800 h (floor (/ diff 3600)) diff (mod diff 3600)
9801 m (floor (/ diff 60)) diff (mod diff 60)
9802 s diff)
9803 (format "%d:%02d:%02d" h m s))))
9804 (kill-new sres)
9805 (if (interactive-p)
9806 (message "%s"
9807 (substitute-command-keys
9808 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9809 (length numbers) sres))))
9810 sres))))
9812 (defun org-table-get-number-for-summing (s)
9813 (let (n)
9814 (if (string-match "^ *|? *" s)
9815 (setq s (replace-match "" nil nil s)))
9816 (if (string-match " *|? *$" s)
9817 (setq s (replace-match "" nil nil s)))
9818 (setq n (string-to-number s))
9819 (cond
9820 ((and (string-match "0" s)
9821 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9822 ((string-match "\\`[ \t]+\\'" s) nil)
9823 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9824 (let ((h (string-to-number (or (match-string 1 s) "0")))
9825 (m (string-to-number (or (match-string 2 s) "0")))
9826 (s (string-to-number (or (match-string 4 s) "0"))))
9827 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9828 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9829 ((equal n 0) nil)
9830 (t n))))
9832 (defun org-table-current-field-formula (&optional key noerror)
9833 "Return the formula active for the current field.
9834 Assumes that specials are in place.
9835 If KEY is given, return the key to this formula.
9836 Otherwise return the formula preceeded with \"=\" or \":=\"."
9837 (let* ((name (car (rassoc (list (org-current-line)
9838 (org-table-current-column))
9839 org-table-named-field-locations)))
9840 (col (org-table-current-column))
9841 (scol (int-to-string col))
9842 (ref (format "@%d$%d" (org-table-current-dline) col))
9843 (stored-list (org-table-get-stored-formulas noerror))
9844 (ass (or (assoc name stored-list)
9845 (assoc ref stored-list)
9846 (assoc scol stored-list))))
9847 (if key
9848 (car ass)
9849 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9850 (cdr ass))))))
9852 (defun org-table-get-formula (&optional equation named)
9853 "Read a formula from the minibuffer, offer stored formula as default.
9854 When NAMED is non-nil, look for a named equation."
9855 (let* ((stored-list (org-table-get-stored-formulas))
9856 (name (car (rassoc (list (org-current-line)
9857 (org-table-current-column))
9858 org-table-named-field-locations)))
9859 (ref (format "@%d$%d" (org-table-current-dline)
9860 (org-table-current-column)))
9861 (refass (assoc ref stored-list))
9862 (scol (if named
9863 (if name name ref)
9864 (int-to-string (org-table-current-column))))
9865 (dummy (and (or name refass) (not named)
9866 (not (y-or-n-p "Replace field formula with column formula? " ))
9867 (error "Abort")))
9868 (name (or name ref))
9869 (org-table-may-need-update nil)
9870 (stored (cdr (assoc scol stored-list)))
9871 (eq (cond
9872 ((and stored equation (string-match "^ *=? *$" equation))
9873 stored)
9874 ((stringp equation)
9875 equation)
9876 (t (org-table-formula-from-user
9877 (read-string
9878 (org-table-formula-to-user
9879 (format "%s formula %s%s="
9880 (if named "Field" "Column")
9881 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9882 scol))
9883 (if stored (org-table-formula-to-user stored) "")
9884 'org-table-formula-history
9885 )))))
9886 mustsave)
9887 (when (not (string-match "\\S-" eq))
9888 ;; remove formula
9889 (setq stored-list (delq (assoc scol stored-list) stored-list))
9890 (org-table-store-formulas stored-list)
9891 (error "Formula removed"))
9892 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9893 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9894 (if (and name (not named))
9895 ;; We set the column equation, delete the named one.
9896 (setq stored-list (delq (assoc name stored-list) stored-list)
9897 mustsave t))
9898 (if stored
9899 (setcdr (assoc scol stored-list) eq)
9900 (setq stored-list (cons (cons scol eq) stored-list)))
9901 (if (or mustsave (not (equal stored eq)))
9902 (org-table-store-formulas stored-list))
9903 eq))
9905 (defun org-table-store-formulas (alist)
9906 "Store the list of formulas below the current table."
9907 (setq alist (sort alist 'org-table-formula-less-p))
9908 (save-excursion
9909 (goto-char (org-table-end))
9910 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9911 (progn
9912 ;; don't overwrite TBLFM, we might use text properties to store stuff
9913 (goto-char (match-beginning 2))
9914 (delete-region (match-beginning 2) (match-end 0)))
9915 (insert "#+TBLFM:"))
9916 (insert " "
9917 (mapconcat (lambda (x)
9918 (concat
9919 (if (equal (string-to-char (car x)) ?@) "" "$")
9920 (car x) "=" (cdr x)))
9921 alist "::")
9922 "\n")))
9924 (defsubst org-table-formula-make-cmp-string (a)
9925 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9926 (concat
9927 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9928 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9929 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9931 (defun org-table-formula-less-p (a b)
9932 "Compare two formulas for sorting."
9933 (let ((as (org-table-formula-make-cmp-string (car a)))
9934 (bs (org-table-formula-make-cmp-string (car b))))
9935 (and as bs (string< as bs))))
9937 (defun org-table-get-stored-formulas (&optional noerror)
9938 "Return an alist with the stored formulas directly after current table."
9939 (interactive)
9940 (let (scol eq eq-alist strings string seen)
9941 (save-excursion
9942 (goto-char (org-table-end))
9943 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9944 (setq strings (org-split-string (match-string 2) " *:: *"))
9945 (while (setq string (pop strings))
9946 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9947 (setq scol (if (match-end 2)
9948 (match-string 2 string)
9949 (match-string 1 string))
9950 eq (match-string 3 string)
9951 eq-alist (cons (cons scol eq) eq-alist))
9952 (if (member scol seen)
9953 (if noerror
9954 (progn
9955 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9956 (ding)
9957 (sit-for 2))
9958 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9959 (push scol seen))))))
9960 (nreverse eq-alist)))
9962 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9963 "Modify the equations after the table structure has been edited.
9964 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9965 For all numbers larger than LIMIT, shift them by DELTA."
9966 (save-excursion
9967 (goto-char (org-table-end))
9968 (when (looking-at "#\\+TBLFM:")
9969 (let ((re (concat key "\\([0-9]+\\)"))
9970 (re2
9971 (when remove
9972 (if (equal key "$")
9973 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9974 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9975 s n a)
9976 (when remove
9977 (while (re-search-forward re2 (point-at-eol) t)
9978 (replace-match "")))
9979 (while (re-search-forward re (point-at-eol) t)
9980 (setq s (match-string 1) n (string-to-number s))
9981 (cond
9982 ((setq a (assoc s replace))
9983 (replace-match (concat key (cdr a)) t t))
9984 ((and limit (> n limit))
9985 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9987 (defun org-table-get-specials ()
9988 "Get the column names and local parameters for this table."
9989 (save-excursion
9990 (let ((beg (org-table-begin)) (end (org-table-end))
9991 names name fields fields1 field cnt
9992 c v l line col types dlines hlines)
9993 (setq org-table-column-names nil
9994 org-table-local-parameters nil
9995 org-table-named-field-locations nil
9996 org-table-current-begin-line nil
9997 org-table-current-begin-pos nil
9998 org-table-current-line-types nil)
9999 (goto-char beg)
10000 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10001 (setq names (org-split-string (match-string 1) " *| *")
10002 cnt 1)
10003 (while (setq name (pop names))
10004 (setq cnt (1+ cnt))
10005 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10006 (push (cons name (int-to-string cnt)) org-table-column-names))))
10007 (setq org-table-column-names (nreverse org-table-column-names))
10008 (setq org-table-column-name-regexp
10009 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10010 (goto-char beg)
10011 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10012 (setq fields (org-split-string (match-string 1) " *| *"))
10013 (while (setq field (pop fields))
10014 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10015 (push (cons (match-string 1 field) (match-string 2 field))
10016 org-table-local-parameters))))
10017 (goto-char beg)
10018 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10019 (setq c (match-string 1)
10020 fields (org-split-string (match-string 2) " *| *"))
10021 (save-excursion
10022 (beginning-of-line (if (equal c "_") 2 0))
10023 (setq line (org-current-line) col 1)
10024 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10025 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10026 (while (and fields1 (setq field (pop fields)))
10027 (setq v (pop fields1) col (1+ col))
10028 (when (and (stringp field) (stringp v)
10029 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10030 (push (cons field v) org-table-local-parameters)
10031 (push (list field line col) org-table-named-field-locations))))
10032 ;; Analyse the line types
10033 (goto-char beg)
10034 (setq org-table-current-begin-line (org-current-line)
10035 org-table-current-begin-pos (point)
10036 l org-table-current-begin-line)
10037 (while (looking-at "[ \t]*|\\(-\\)?")
10038 (push (if (match-end 1) 'hline 'dline) types)
10039 (if (match-end 1) (push l hlines) (push l dlines))
10040 (beginning-of-line 2)
10041 (setq l (1+ l)))
10042 (setq org-table-current-line-types (apply 'vector (nreverse types))
10043 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
10044 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
10046 (defun org-table-maybe-eval-formula ()
10047 "Check if the current field starts with \"=\" or \":=\".
10048 If yes, store the formula and apply it."
10049 ;; We already know we are in a table. Get field will only return a formula
10050 ;; when appropriate. It might return a separator line, but no problem.
10051 (when org-table-formula-evaluate-inline
10052 (let* ((field (org-trim (or (org-table-get-field) "")))
10053 named eq)
10054 (when (string-match "^:?=\\(.*\\)" field)
10055 (setq named (equal (string-to-char field) ?:)
10056 eq (match-string 1 field))
10057 (if (or (fboundp 'calc-eval)
10058 (equal (substring eq 0 (min 2 (length eq))) "'("))
10059 (org-table-eval-formula (if named '(4) nil)
10060 (org-table-formula-from-user eq))
10061 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10063 (defvar org-recalc-commands nil
10064 "List of commands triggering the recalculation of a line.
10065 Will be filled automatically during use.")
10067 (defvar org-recalc-marks
10068 '((" " . "Unmarked: no special line, no automatic recalculation")
10069 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10070 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10071 ("!" . "Column name definition line. Reference in formula as $name.")
10072 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10073 ("_" . "Names for values in row below this one.")
10074 ("^" . "Names for values in row above this one.")))
10076 (defun org-table-rotate-recalc-marks (&optional newchar)
10077 "Rotate the recalculation mark in the first column.
10078 If in any row, the first field is not consistent with a mark,
10079 insert a new column for the markers.
10080 When there is an active region, change all the lines in the region,
10081 after prompting for the marking character.
10082 After each change, a message will be displayed indicating the meaning
10083 of the new mark."
10084 (interactive)
10085 (unless (org-at-table-p) (error "Not at a table"))
10086 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10087 (beg (org-table-begin))
10088 (end (org-table-end))
10089 (l (org-current-line))
10090 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10091 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10092 (have-col
10093 (save-excursion
10094 (goto-char beg)
10095 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10096 (col (org-table-current-column))
10097 (forcenew (car (assoc newchar org-recalc-marks)))
10098 epos new)
10099 (when l1
10100 (message "Change region to what mark? Type # * ! $ or SPC: ")
10101 (setq newchar (char-to-string (read-char-exclusive))
10102 forcenew (car (assoc newchar org-recalc-marks))))
10103 (if (and newchar (not forcenew))
10104 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10105 newchar))
10106 (if l1 (goto-line l1))
10107 (save-excursion
10108 (beginning-of-line 1)
10109 (unless (looking-at org-table-dataline-regexp)
10110 (error "Not at a table data line")))
10111 (unless have-col
10112 (org-table-goto-column 1)
10113 (org-table-insert-column)
10114 (org-table-goto-column (1+ col)))
10115 (setq epos (point-at-eol))
10116 (save-excursion
10117 (beginning-of-line 1)
10118 (org-table-get-field
10119 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10120 (concat " "
10121 (setq new (or forcenew
10122 (cadr (member (match-string 1) marks))))
10123 " ")
10124 " # ")))
10125 (if (and l1 l2)
10126 (progn
10127 (goto-line l1)
10128 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10129 (and (looking-at org-table-dataline-regexp)
10130 (org-table-get-field 1 (concat " " new " "))))
10131 (goto-line l1)))
10132 (if (not (= epos (point-at-eol))) (org-table-align))
10133 (goto-line l)
10134 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10136 (defun org-table-maybe-recalculate-line ()
10137 "Recompute the current line if marked for it, and if we haven't just done it."
10138 (interactive)
10139 (and org-table-allow-automatic-line-recalculation
10140 (not (and (memq last-command org-recalc-commands)
10141 (equal org-last-recalc-line (org-current-line))))
10142 (save-excursion (beginning-of-line 1)
10143 (looking-at org-table-auto-recalculate-regexp))
10144 (org-table-recalculate) t))
10146 (defvar org-table-formula-debug nil
10147 "Non-nil means, debug table formulas.
10148 When nil, simply write \"#ERROR\" in corrupted fields.")
10149 (make-variable-buffer-local 'org-table-formula-debug)
10151 (defvar modes)
10152 (defsubst org-set-calc-mode (var &optional value)
10153 (if (stringp var)
10154 (setq var (assoc var '(("D" calc-angle-mode deg)
10155 ("R" calc-angle-mode rad)
10156 ("F" calc-prefer-frac t)
10157 ("S" calc-symbolic-mode t)))
10158 value (nth 2 var) var (nth 1 var)))
10159 (if (memq var modes)
10160 (setcar (cdr (memq var modes)) value)
10161 (cons var (cons value modes)))
10162 modes)
10164 (defun org-table-eval-formula (&optional arg equation
10165 suppress-align suppress-const
10166 suppress-store suppress-analysis)
10167 "Replace the table field value at the cursor by the result of a calculation.
10169 This function makes use of Dave Gillespie's Calc package, in my view the
10170 most exciting program ever written for GNU Emacs. So you need to have Calc
10171 installed in order to use this function.
10173 In a table, this command replaces the value in the current field with the
10174 result of a formula. It also installs the formula as the \"current\" column
10175 formula, by storing it in a special line below the table. When called
10176 with a `C-u' prefix, the current field must ba a named field, and the
10177 formula is installed as valid in only this specific field.
10179 When called with two `C-u' prefixes, insert the active equation
10180 for the field back into the current field, so that it can be
10181 edited there. This is useful in order to use \\[org-table-show-reference]
10182 to check the referenced fields.
10184 When called, the command first prompts for a formula, which is read in
10185 the minibuffer. Previously entered formulas are available through the
10186 history list, and the last used formula is offered as a default.
10187 These stored formulas are adapted correctly when moving, inserting, or
10188 deleting columns with the corresponding commands.
10190 The formula can be any algebraic expression understood by the Calc package.
10191 For details, see the Org-mode manual.
10193 This function can also be called from Lisp programs and offers
10194 additional arguments: EQUATION can be the formula to apply. If this
10195 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10196 used to speed-up recursive calls by by-passing unnecessary aligns.
10197 SUPPRESS-CONST suppresses the interpretation of constants in the
10198 formula, assuming that this has been done already outside the function.
10199 SUPPRESS-STORE means the formula should not be stored, either because
10200 it is already stored, or because it is a modified equation that should
10201 not overwrite the stored one."
10202 (interactive "P")
10203 (org-table-check-inside-data-field)
10204 (or suppress-analysis (org-table-get-specials))
10205 (if (equal arg '(16))
10206 (let ((eq (org-table-current-field-formula)))
10207 (or eq (error "No equation active for current field"))
10208 (org-table-get-field nil eq)
10209 (org-table-align)
10210 (setq org-table-may-need-update t))
10211 (let* (fields
10212 (ndown (if (integerp arg) arg 1))
10213 (org-table-automatic-realign nil)
10214 (case-fold-search nil)
10215 (down (> ndown 1))
10216 (formula (if (and equation suppress-store)
10217 equation
10218 (org-table-get-formula equation (equal arg '(4)))))
10219 (n0 (org-table-current-column))
10220 (modes (copy-sequence org-calc-default-modes))
10221 (numbers nil) ; was a variable, now fixed default
10222 (keep-empty nil)
10223 n form form0 bw fmt x ev orig c lispp literal)
10224 ;; Parse the format string. Since we have a lot of modes, this is
10225 ;; a lot of work. However, I think calc still uses most of the time.
10226 (if (string-match ";" formula)
10227 (let ((tmp (org-split-string formula ";")))
10228 (setq formula (car tmp)
10229 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10230 (nth 1 tmp)))
10231 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10232 (setq c (string-to-char (match-string 1 fmt))
10233 n (string-to-number (match-string 2 fmt)))
10234 (if (= c ?p)
10235 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10236 (setq modes (org-set-calc-mode
10237 'calc-float-format
10238 (list (cdr (assoc c '((?n . float) (?f . fix)
10239 (?s . sci) (?e . eng))))
10240 n))))
10241 (setq fmt (replace-match "" t t fmt)))
10242 (if (string-match "[NT]" fmt)
10243 (setq numbers (equal (match-string 0 fmt) "N")
10244 fmt (replace-match "" t t fmt)))
10245 (if (string-match "L" fmt)
10246 (setq literal t
10247 fmt (replace-match "" t t fmt)))
10248 (if (string-match "E" fmt)
10249 (setq keep-empty t
10250 fmt (replace-match "" t t fmt)))
10251 (while (string-match "[DRFS]" fmt)
10252 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10253 (setq fmt (replace-match "" t t fmt)))
10254 (unless (string-match "\\S-" fmt)
10255 (setq fmt nil))))
10256 (if (and (not suppress-const) org-table-formula-use-constants)
10257 (setq formula (org-table-formula-substitute-names formula)))
10258 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10259 (while (> ndown 0)
10260 (setq fields (org-split-string
10261 (org-no-properties
10262 (buffer-substring (point-at-bol) (point-at-eol)))
10263 " *| *"))
10264 (if (eq numbers t)
10265 (setq fields (mapcar
10266 (lambda (x) (number-to-string (string-to-number x)))
10267 fields)))
10268 (setq ndown (1- ndown))
10269 (setq form (copy-sequence formula)
10270 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10271 (if (and lispp literal) (setq lispp 'literal))
10272 ;; Check for old vertical references
10273 (setq form (org-rewrite-old-row-references form))
10274 ;; Insert complex ranges
10275 (while (string-match org-table-range-regexp form)
10276 (setq form
10277 (replace-match
10278 (save-match-data
10279 (org-table-make-reference
10280 (org-table-get-range (match-string 0 form) nil n0)
10281 keep-empty numbers lispp))
10282 t t form)))
10283 ;; Insert simple ranges
10284 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10285 (setq form
10286 (replace-match
10287 (save-match-data
10288 (org-table-make-reference
10289 (org-sublist
10290 fields (string-to-number (match-string 1 form))
10291 (string-to-number (match-string 2 form)))
10292 keep-empty numbers lispp))
10293 t t form)))
10294 (setq form0 form)
10295 ;; Insert the references to fields in same row
10296 (while (string-match "\\$\\([0-9]+\\)" form)
10297 (setq n (string-to-number (match-string 1 form))
10298 x (nth (1- (if (= n 0) n0 n)) fields))
10299 (unless x (error "Invalid field specifier \"%s\""
10300 (match-string 0 form)))
10301 (setq form (replace-match
10302 (save-match-data
10303 (org-table-make-reference x nil numbers lispp))
10304 t t form)))
10306 (if lispp
10307 (setq ev (condition-case nil
10308 (eval (eval (read form)))
10309 (error "#ERROR"))
10310 ev (if (numberp ev) (number-to-string ev) ev))
10311 (or (fboundp 'calc-eval)
10312 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10313 (setq ev (calc-eval (cons form modes)
10314 (if numbers 'num))))
10316 (when org-table-formula-debug
10317 (with-output-to-temp-buffer "*Substitution History*"
10318 (princ (format "Substitution history of formula
10319 Orig: %s
10320 $xyz-> %s
10321 @r$c-> %s
10322 $1-> %s\n" orig formula form0 form))
10323 (if (listp ev)
10324 (princ (format " %s^\nError: %s"
10325 (make-string (car ev) ?\-) (nth 1 ev)))
10326 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10327 ev (or fmt "NONE")
10328 (if fmt (format fmt (string-to-number ev)) ev)))))
10329 (setq bw (get-buffer-window "*Substitution History*"))
10330 (shrink-window-if-larger-than-buffer bw)
10331 (unless (and (interactive-p) (not ndown))
10332 (unless (let (inhibit-redisplay)
10333 (y-or-n-p "Debugging Formula. Continue to next? "))
10334 (org-table-align)
10335 (error "Abort"))
10336 (delete-window bw)
10337 (message "")))
10338 (if (listp ev) (setq fmt nil ev "#ERROR"))
10339 (org-table-justify-field-maybe
10340 (if fmt (format fmt (string-to-number ev)) ev))
10341 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10342 (call-interactively 'org-return)
10343 (setq ndown 0)))
10344 (and down (org-table-maybe-recalculate-line))
10345 (or suppress-align (and org-table-may-need-update
10346 (org-table-align))))))
10348 (defun org-table-put-field-property (prop value)
10349 (save-excursion
10350 (put-text-property (progn (skip-chars-backward "^|") (point))
10351 (progn (skip-chars-forward "^|") (point))
10352 prop value)))
10354 (defun org-table-get-range (desc &optional tbeg col highlight)
10355 "Get a calc vector from a column, accorting to descriptor DESC.
10356 Optional arguments TBEG and COL can give the beginning of the table and
10357 the current column, to avoid unnecessary parsing.
10358 HIGHLIGHT means, just highlight the range."
10359 (if (not (equal (string-to-char desc) ?@))
10360 (setq desc (concat "@" desc)))
10361 (save-excursion
10362 (or tbeg (setq tbeg (org-table-begin)))
10363 (or col (setq col (org-table-current-column)))
10364 (let ((thisline (org-current-line))
10365 beg end c1 c2 r1 r2 rangep tmp)
10366 (unless (string-match org-table-range-regexp desc)
10367 (error "Invalid table range specifier `%s'" desc))
10368 (setq rangep (match-end 3)
10369 r1 (and (match-end 1) (match-string 1 desc))
10370 r2 (and (match-end 4) (match-string 4 desc))
10371 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10372 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10374 (and c1 (setq c1 (+ (string-to-number c1)
10375 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10376 (and c2 (setq c2 (+ (string-to-number c2)
10377 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10378 (if (equal r1 "") (setq r1 nil))
10379 (if (equal r2 "") (setq r2 nil))
10380 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10381 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10382 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10383 (if (not r1) (setq r1 thisline))
10384 (if (not r2) (setq r2 thisline))
10385 (if (not c1) (setq c1 col))
10386 (if (not c2) (setq c2 col))
10387 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10388 ;; just one field
10389 (progn
10390 (goto-line r1)
10391 (while (not (looking-at org-table-dataline-regexp))
10392 (beginning-of-line 2))
10393 (prog1 (org-trim (org-table-get-field c1))
10394 (if highlight (org-table-highlight-rectangle (point) (point)))))
10395 ;; A range, return a vector
10396 ;; First sort the numbers to get a regular ractangle
10397 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10398 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10399 (goto-line r1)
10400 (while (not (looking-at org-table-dataline-regexp))
10401 (beginning-of-line 2))
10402 (org-table-goto-column c1)
10403 (setq beg (point))
10404 (goto-line r2)
10405 (while (not (looking-at org-table-dataline-regexp))
10406 (beginning-of-line 0))
10407 (org-table-goto-column c2)
10408 (setq end (point))
10409 (if highlight
10410 (org-table-highlight-rectangle
10411 beg (progn (skip-chars-forward "^|\n") (point))))
10412 ;; return string representation of calc vector
10413 (mapcar 'org-trim
10414 (apply 'append (org-table-copy-region beg end)))))))
10416 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10417 "Analyze descriptor DESC and retrieve the corresponding line number.
10418 The cursor is currently in line CLINE, the table begins in line BLINE,
10419 and TABLE is a vector with line types."
10420 (if (string-match "^[0-9]+$" desc)
10421 (aref org-table-dlines (string-to-number desc))
10422 (setq cline (or cline (org-current-line))
10423 bline (or bline org-table-current-begin-line)
10424 table (or table org-table-current-line-types))
10425 (if (or
10426 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10427 ;; 1 2 3 4 5 6
10428 (and (not (match-end 3)) (not (match-end 6)))
10429 (and (match-end 3) (match-end 6) (not (match-end 5))))
10430 (error "invalid row descriptor `%s'" desc))
10431 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10432 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10433 (odir (and (match-end 5) (match-string 5 desc)))
10434 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10435 (i (- cline bline))
10436 (rel (and (match-end 6)
10437 (or (and (match-end 1) (not (match-end 3)))
10438 (match-end 5)))))
10439 (if (and hn (not hdir))
10440 (progn
10441 (setq i 0 hdir "+")
10442 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10443 (if (and (not hn) on (not odir))
10444 (error "should never happen");;(aref org-table-dlines on)
10445 (if (and hn (> hn 0))
10446 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10447 (if on
10448 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10449 (+ bline i)))))
10451 (defun org-find-row-type (table i type backwards relative n)
10452 (let ((l (length table)))
10453 (while (> n 0)
10454 (while (and (setq i (+ i (if backwards -1 1)))
10455 (>= i 0) (< i l)
10456 (not (eq (aref table i) type))
10457 (if (and relative (eq (aref table i) 'hline))
10458 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10459 t)))
10460 (setq n (1- n)))
10461 (if (or (< i 0) (>= i l))
10462 (error "Row descriptior leads outside table")
10463 i)))
10465 (defun org-rewrite-old-row-references (s)
10466 (if (string-match "&[-+0-9I]" s)
10467 (error "Formula contains old &row reference, please rewrite using @-syntax")
10470 (defun org-table-make-reference (elements keep-empty numbers lispp)
10471 "Convert list ELEMENTS to something appropriate to insert into formula.
10472 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10473 NUMBERS indicates that everything should be converted to numbers.
10474 LISPP means to return something appropriate for a Lisp list."
10475 (if (stringp elements) ; just a single val
10476 (if lispp
10477 (if (eq lispp 'literal)
10478 elements
10479 (prin1-to-string (if numbers (string-to-number elements) elements)))
10480 (if (equal elements "") (setq elements "0"))
10481 (if numbers (number-to-string (string-to-number elements)) elements))
10482 (unless keep-empty
10483 (setq elements
10484 (delq nil
10485 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10486 elements))))
10487 (setq elements (or elements '("0")))
10488 (if lispp
10489 (mapconcat
10490 (lambda (x)
10491 (if (eq lispp 'literal)
10493 (prin1-to-string (if numbers (string-to-number x) x))))
10494 elements " ")
10495 (concat "[" (mapconcat
10496 (lambda (x)
10497 (if numbers (number-to-string (string-to-number x)) x))
10498 elements
10499 ",") "]"))))
10501 (defun org-table-recalculate (&optional all noalign)
10502 "Recalculate the current table line by applying all stored formulas.
10503 With prefix arg ALL, do this for all lines in the table."
10504 (interactive "P")
10505 (or (memq this-command org-recalc-commands)
10506 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10507 (unless (org-at-table-p) (error "Not at a table"))
10508 (if (equal all '(16))
10509 (org-table-iterate)
10510 (org-table-get-specials)
10511 (let* ((eqlist (sort (org-table-get-stored-formulas)
10512 (lambda (a b) (string< (car a) (car b)))))
10513 (inhibit-redisplay (not debug-on-error))
10514 (line-re org-table-dataline-regexp)
10515 (thisline (org-current-line))
10516 (thiscol (org-table-current-column))
10517 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10518 ;; Insert constants in all formulas
10519 (setq eqlist
10520 (mapcar (lambda (x)
10521 (setcdr x (org-table-formula-substitute-names (cdr x)))
10523 eqlist))
10524 ;; Split the equation list
10525 (while (setq eq (pop eqlist))
10526 (if (<= (string-to-char (car eq)) ?9)
10527 (push eq eqlnum)
10528 (push eq eqlname)))
10529 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10530 (if all
10531 (progn
10532 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10533 (goto-char (setq beg (org-table-begin)))
10534 (if (re-search-forward org-table-calculate-mark-regexp end t)
10535 ;; This is a table with marked lines, compute selected lines
10536 (setq line-re org-table-recalculate-regexp)
10537 ;; Move forward to the first non-header line
10538 (if (and (re-search-forward org-table-dataline-regexp end t)
10539 (re-search-forward org-table-hline-regexp end t)
10540 (re-search-forward org-table-dataline-regexp end t))
10541 (setq beg (match-beginning 0))
10542 nil))) ;; just leave beg where it is
10543 (setq beg (point-at-bol)
10544 end (move-marker (make-marker) (1+ (point-at-eol)))))
10545 (goto-char beg)
10546 (and all (message "Re-applying formulas to full table..."))
10548 ;; First find the named fields, and mark them untouchanble
10549 (remove-text-properties beg end '(org-untouchable t))
10550 (while (setq eq (pop eqlname))
10551 (setq name (car eq)
10552 a (assoc name org-table-named-field-locations))
10553 (and (not a)
10554 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10555 (setq a (list name
10556 (aref org-table-dlines
10557 (string-to-number (match-string 1 name)))
10558 (string-to-number (match-string 2 name)))))
10559 (when (and a (or all (equal (nth 1 a) thisline)))
10560 (message "Re-applying formula to field: %s" name)
10561 (goto-line (nth 1 a))
10562 (org-table-goto-column (nth 2 a))
10563 (push (append a (list (cdr eq))) eqlname1)
10564 (org-table-put-field-property :org-untouchable t)))
10566 ;; Now evauluate the column formulas, but skip fields covered by
10567 ;; field formulas
10568 (goto-char beg)
10569 (while (re-search-forward line-re end t)
10570 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10571 ;; Unprotected line, recalculate
10572 (and all (message "Re-applying formulas to full table...(line %d)"
10573 (setq cnt (1+ cnt))))
10574 (setq org-last-recalc-line (org-current-line))
10575 (setq eql eqlnum)
10576 (while (setq entry (pop eql))
10577 (goto-line org-last-recalc-line)
10578 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10579 (unless (get-text-property (point) :org-untouchable)
10580 (org-table-eval-formula nil (cdr entry)
10581 'noalign 'nocst 'nostore 'noanalysis)))))
10583 ;; Now evaluate the field formulas
10584 (while (setq eq (pop eqlname1))
10585 (message "Re-applying formula to field: %s" (car eq))
10586 (goto-line (nth 1 eq))
10587 (org-table-goto-column (nth 2 eq))
10588 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10589 'nostore 'noanalysis))
10591 (goto-line thisline)
10592 (org-table-goto-column thiscol)
10593 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10594 (or noalign (and org-table-may-need-update (org-table-align))
10595 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10597 ;; back to initial position
10598 (message "Re-applying formulas...done")
10599 (goto-line thisline)
10600 (org-table-goto-column thiscol)
10601 (or noalign (and org-table-may-need-update (org-table-align))
10602 (and all (message "Re-applying formulas...done"))))))
10604 (defun org-table-iterate (&optional arg)
10605 "Recalculate the table until it does not change anymore."
10606 (interactive "P")
10607 (let ((imax (if arg (prefix-numeric-value arg) 10))
10608 (i 0)
10609 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10610 thistbl)
10611 (catch 'exit
10612 (while (< i imax)
10613 (setq i (1+ i))
10614 (org-table-recalculate 'all)
10615 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10616 (if (not (string= lasttbl thistbl))
10617 (setq lasttbl thistbl)
10618 (if (> i 1)
10619 (message "Convergence after %d iterations" i)
10620 (message "Table was already stable"))
10621 (throw 'exit t)))
10622 (error "No convergence after %d iterations" i))))
10624 (defun org-table-formula-substitute-names (f)
10625 "Replace $const with values in string F."
10626 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10627 ;; First, check for column names
10628 (while (setq start (string-match org-table-column-name-regexp f start))
10629 (setq start (1+ start))
10630 (setq a (assoc (match-string 1 f) org-table-column-names))
10631 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10632 ;; Parameters and constants
10633 (setq start 0)
10634 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10635 (setq start (1+ start))
10636 (if (setq a (save-match-data
10637 (org-table-get-constant (match-string 1 f))))
10638 (setq f (replace-match
10639 (concat (if pp "(") a (if pp ")")) t t f))))
10640 (if org-table-formula-debug
10641 (put-text-property 0 (length f) :orig-formula f1 f))
10644 (defun org-table-get-constant (const)
10645 "Find the value for a parameter or constant in a formula.
10646 Parameters get priority."
10647 (or (cdr (assoc const org-table-local-parameters))
10648 (cdr (assoc const org-table-formula-constants-local))
10649 (cdr (assoc const org-table-formula-constants))
10650 (and (fboundp 'constants-get) (constants-get const))
10651 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10652 (org-entry-get nil (substring const 5) 'inherit))
10653 "#UNDEFINED_NAME"))
10655 (defvar org-table-fedit-map
10656 (let ((map (make-sparse-keymap)))
10657 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10658 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10659 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10660 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10661 (org-defkey map "\C-c?" 'org-table-show-reference)
10662 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10663 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10664 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10665 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10666 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10667 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10668 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10669 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10670 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10671 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10672 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10673 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10674 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10675 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10676 map))
10678 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10679 '("Edit-Formulas"
10680 ["Finish and Install" org-table-fedit-finish t]
10681 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10682 ["Abort" org-table-fedit-abort t]
10683 "--"
10684 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10685 ["Complete Lisp Symbol" lisp-complete-symbol t]
10686 "--"
10687 "Shift Reference at Point"
10688 ["Up" org-table-fedit-ref-up t]
10689 ["Down" org-table-fedit-ref-down t]
10690 ["Left" org-table-fedit-ref-left t]
10691 ["Right" org-table-fedit-ref-right t]
10693 "Change Test Row for Column Formulas"
10694 ["Up" org-table-fedit-line-up t]
10695 ["Down" org-table-fedit-line-down t]
10696 "--"
10697 ["Scroll Table Window" org-table-fedit-scroll t]
10698 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10699 ["Show Table Grid" org-table-fedit-toggle-coordinates
10700 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10701 org-table-overlay-coordinates)]
10702 "--"
10703 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10704 :style toggle :selected org-table-buffer-is-an]))
10706 (defvar org-pos)
10708 (defun org-table-edit-formulas ()
10709 "Edit the formulas of the current table in a separate buffer."
10710 (interactive)
10711 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10712 (beginning-of-line 0))
10713 (unless (org-at-table-p) (error "Not at a table"))
10714 (org-table-get-specials)
10715 (let ((key (org-table-current-field-formula 'key 'noerror))
10716 (eql (sort (org-table-get-stored-formulas 'noerror)
10717 'org-table-formula-less-p))
10718 (pos (move-marker (make-marker) (point)))
10719 (startline 1)
10720 (wc (current-window-configuration))
10721 (titles '((column . "# Column Formulas\n")
10722 (field . "# Field Formulas\n")
10723 (named . "# Named Field Formulas\n")))
10724 entry s type title)
10725 (org-switch-to-buffer-other-window "*Edit Formulas*")
10726 (erase-buffer)
10727 ;; Keep global-font-lock-mode from turning on font-lock-mode
10728 (let ((font-lock-global-modes '(not fundamental-mode)))
10729 (fundamental-mode))
10730 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10731 (org-set-local 'org-pos pos)
10732 (org-set-local 'org-window-configuration wc)
10733 (use-local-map org-table-fedit-map)
10734 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10735 (easy-menu-add org-table-fedit-menu)
10736 (setq startline (org-current-line))
10737 (while (setq entry (pop eql))
10738 (setq type (cond
10739 ((equal (string-to-char (car entry)) ?@) 'field)
10740 ((string-match "^[0-9]" (car entry)) 'column)
10741 (t 'named)))
10742 (when (setq title (assq type titles))
10743 (or (bobp) (insert "\n"))
10744 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10745 (setq titles (delq title titles)))
10746 (if (equal key (car entry)) (setq startline (org-current-line)))
10747 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10748 (car entry) " = " (cdr entry) "\n"))
10749 (remove-text-properties 0 (length s) '(face nil) s)
10750 (insert s))
10751 (if (eq org-table-use-standard-references t)
10752 (org-table-fedit-toggle-ref-type))
10753 (goto-line startline)
10754 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10756 (defun org-table-fedit-post-command ()
10757 (when (not (memq this-command '(lisp-complete-symbol)))
10758 (let ((win (selected-window)))
10759 (save-excursion
10760 (condition-case nil
10761 (org-table-show-reference)
10762 (error nil))
10763 (select-window win)))))
10765 (defun org-table-formula-to-user (s)
10766 "Convert a formula from internal to user representation."
10767 (if (eq org-table-use-standard-references t)
10768 (org-table-convert-refs-to-an s)
10771 (defun org-table-formula-from-user (s)
10772 "Convert a formula from user to internal representation."
10773 (if org-table-use-standard-references
10774 (org-table-convert-refs-to-rc s)
10777 (defun org-table-convert-refs-to-rc (s)
10778 "Convert spreadsheet references from AB7 to @7$28.
10779 Works for single references, but also for entire formulas and even the
10780 full TBLFM line."
10781 (let ((start 0))
10782 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10783 (cond
10784 ((match-end 3)
10785 ;; format match, just advance
10786 (setq start (match-end 0)))
10787 ((and (> (match-beginning 0) 0)
10788 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10789 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10790 ;; 3.e5 or something like this.
10791 (setq start (match-end 0)))
10793 (setq start (match-beginning 0)
10794 s (replace-match
10795 (if (equal (match-string 2 s) "&")
10796 (format "$%d" (org-letters-to-number (match-string 1 s)))
10797 (format "@%d$%d"
10798 (string-to-number (match-string 2 s))
10799 (org-letters-to-number (match-string 1 s))))
10800 t t s)))))
10803 (defun org-table-convert-refs-to-an (s)
10804 "Convert spreadsheet references from to @7$28 to AB7.
10805 Works for single references, but also for entire formulas and even the
10806 full TBLFM line."
10807 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10808 (setq s (replace-match
10809 (format "%s%d"
10810 (org-number-to-letters
10811 (string-to-number (match-string 2 s)))
10812 (string-to-number (match-string 1 s)))
10813 t t s)))
10814 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10815 (setq s (replace-match (concat "\\1"
10816 (org-number-to-letters
10817 (string-to-number (match-string 2 s))) "&")
10818 t nil s)))
10821 (defun org-letters-to-number (s)
10822 "Convert a base 26 number represented by letters into an integer.
10823 For example: AB -> 28."
10824 (let ((n 0))
10825 (setq s (upcase s))
10826 (while (> (length s) 0)
10827 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10828 s (substring s 1)))
10831 (defun org-number-to-letters (n)
10832 "Convert an integer into a base 26 number represented by letters.
10833 For example: 28 -> AB."
10834 (let ((s ""))
10835 (while (> n 0)
10836 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10837 n (/ (1- n) 26)))
10840 (defun org-table-fedit-convert-buffer (function)
10841 "Convert all references in this buffer, using FUNTION."
10842 (let ((line (org-current-line)))
10843 (goto-char (point-min))
10844 (while (not (eobp))
10845 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10846 (delete-region (point) (point-at-eol))
10847 (or (eobp) (forward-char 1)))
10848 (goto-line line)))
10850 (defun org-table-fedit-toggle-ref-type ()
10851 "Convert all references in the buffer from B3 to @3$2 and back."
10852 (interactive)
10853 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10854 (org-table-fedit-convert-buffer
10855 (if org-table-buffer-is-an
10856 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10857 (message "Reference type switched to %s"
10858 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10860 (defun org-table-fedit-ref-up ()
10861 "Shift the reference at point one row/hline up."
10862 (interactive)
10863 (org-table-fedit-shift-reference 'up))
10864 (defun org-table-fedit-ref-down ()
10865 "Shift the reference at point one row/hline down."
10866 (interactive)
10867 (org-table-fedit-shift-reference 'down))
10868 (defun org-table-fedit-ref-left ()
10869 "Shift the reference at point one field to the left."
10870 (interactive)
10871 (org-table-fedit-shift-reference 'left))
10872 (defun org-table-fedit-ref-right ()
10873 "Shift the reference at point one field to the right."
10874 (interactive)
10875 (org-table-fedit-shift-reference 'right))
10877 (defun org-table-fedit-shift-reference (dir)
10878 (cond
10879 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10880 (if (memq dir '(left right))
10881 (org-rematch-and-replace 1 (eq dir 'left))
10882 (error "Cannot shift reference in this direction")))
10883 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10884 ;; A B3-like reference
10885 (if (memq dir '(up down))
10886 (org-rematch-and-replace 2 (eq dir 'up))
10887 (org-rematch-and-replace 1 (eq dir 'left))))
10888 ((org-at-regexp-p
10889 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10890 ;; An internal reference
10891 (if (memq dir '(up down))
10892 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10893 (org-rematch-and-replace 5 (eq dir 'left))))))
10895 (defun org-rematch-and-replace (n &optional decr hline)
10896 "Re-match the group N, and replace it with the shifted refrence."
10897 (or (match-end n) (error "Cannot shift reference in this direction"))
10898 (goto-char (match-beginning n))
10899 (and (looking-at (regexp-quote (match-string n)))
10900 (replace-match (org-shift-refpart (match-string 0) decr hline)
10901 t t)))
10903 (defun org-shift-refpart (ref &optional decr hline)
10904 "Shift a refrence part REF.
10905 If DECR is set, decrease the references row/column, else increase.
10906 If HLINE is set, this may be a hline reference, it certainly is not
10907 a translation reference."
10908 (save-match-data
10909 (let* ((sign (string-match "^[-+]" ref)) n)
10911 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10912 (cond
10913 ((and hline (string-match "^I+" ref))
10914 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10915 (setq n (+ n (if decr -1 1)))
10916 (if (= n 0) (setq n (+ n (if decr -1 1))))
10917 (if sign
10918 (setq sign (if (< n 0) "-" "+") n (abs n))
10919 (setq n (max 1 n)))
10920 (concat sign (make-string n ?I)))
10922 ((string-match "^[0-9]+" ref)
10923 (setq n (string-to-number (concat sign ref)))
10924 (setq n (+ n (if decr -1 1)))
10925 (if sign
10926 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10927 (number-to-string (max 1 n))))
10929 ((string-match "^[a-zA-Z]+" ref)
10930 (org-number-to-letters
10931 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10933 (t (error "Cannot shift reference"))))))
10935 (defun org-table-fedit-toggle-coordinates ()
10936 "Toggle the display of coordinates in the refrenced table."
10937 (interactive)
10938 (let ((pos (marker-position org-pos)))
10939 (with-current-buffer (marker-buffer org-pos)
10940 (save-excursion
10941 (goto-char pos)
10942 (org-table-toggle-coordinate-overlays)))))
10944 (defun org-table-fedit-finish (&optional arg)
10945 "Parse the buffer for formula definitions and install them.
10946 With prefix ARG, apply the new formulas to the table."
10947 (interactive "P")
10948 (org-table-remove-rectangle-highlight)
10949 (if org-table-use-standard-references
10950 (progn
10951 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10952 (setq org-table-buffer-is-an nil)))
10953 (let ((pos org-pos) eql var form)
10954 (goto-char (point-min))
10955 (while (re-search-forward
10956 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10957 nil t)
10958 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10959 form (match-string 3))
10960 (setq form (org-trim form))
10961 (when (not (equal form ""))
10962 (while (string-match "[ \t]*\n[ \t]*" form)
10963 (setq form (replace-match " " t t form)))
10964 (when (assoc var eql)
10965 (error "Double formulas for %s" var))
10966 (push (cons var form) eql)))
10967 (setq org-pos nil)
10968 (set-window-configuration org-window-configuration)
10969 (select-window (get-buffer-window (marker-buffer pos)))
10970 (goto-char pos)
10971 (unless (org-at-table-p)
10972 (error "Lost table position - cannot install formulae"))
10973 (org-table-store-formulas eql)
10974 (move-marker pos nil)
10975 (kill-buffer "*Edit Formulas*")
10976 (if arg
10977 (org-table-recalculate 'all)
10978 (message "New formulas installed - press C-u C-c C-c to apply."))))
10980 (defun org-table-fedit-abort ()
10981 "Abort editing formulas, without installing the changes."
10982 (interactive)
10983 (org-table-remove-rectangle-highlight)
10984 (let ((pos org-pos))
10985 (set-window-configuration org-window-configuration)
10986 (select-window (get-buffer-window (marker-buffer pos)))
10987 (goto-char pos)
10988 (move-marker pos nil)
10989 (message "Formula editing aborted without installing changes")))
10991 (defun org-table-fedit-lisp-indent ()
10992 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10993 (interactive)
10994 (let ((pos (point)) beg end ind)
10995 (beginning-of-line 1)
10996 (cond
10997 ((looking-at "[ \t]")
10998 (goto-char pos)
10999 (call-interactively 'lisp-indent-line))
11000 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
11001 ((not (fboundp 'pp-buffer))
11002 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
11003 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
11004 (goto-char (- (match-end 0) 2))
11005 (setq beg (point))
11006 (setq ind (make-string (current-column) ?\ ))
11007 (condition-case nil (forward-sexp 1)
11008 (error
11009 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
11010 (setq end (point))
11011 (save-restriction
11012 (narrow-to-region beg end)
11013 (if (eq last-command this-command)
11014 (progn
11015 (goto-char (point-min))
11016 (setq this-command nil)
11017 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
11018 (replace-match " ")))
11019 (pp-buffer)
11020 (untabify (point-min) (point-max))
11021 (goto-char (1+ (point-min)))
11022 (while (re-search-forward "^." nil t)
11023 (beginning-of-line 1)
11024 (insert ind))
11025 (goto-char (point-max))
11026 (backward-delete-char 1)))
11027 (goto-char beg))
11028 (t nil))))
11030 (defvar org-show-positions nil)
11032 (defun org-table-show-reference (&optional local)
11033 "Show the location/value of the $ expression at point."
11034 (interactive)
11035 (org-table-remove-rectangle-highlight)
11036 (catch 'exit
11037 (let ((pos (if local (point) org-pos))
11038 (face2 'highlight)
11039 (org-inhibit-highlight-removal t)
11040 (win (selected-window))
11041 (org-show-positions nil)
11042 var name e what match dest)
11043 (if local (org-table-get-specials))
11044 (setq what (cond
11045 ((or (org-at-regexp-p org-table-range-regexp2)
11046 (org-at-regexp-p org-table-translate-regexp)
11047 (org-at-regexp-p org-table-range-regexp))
11048 (setq match
11049 (save-match-data
11050 (org-table-convert-refs-to-rc (match-string 0))))
11051 'range)
11052 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11053 ((org-at-regexp-p "\\$[0-9]+") 'column)
11054 ((not local) nil)
11055 (t (error "No reference at point")))
11056 match (and what (or match (match-string 0))))
11057 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11058 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11059 'secondary-selection))
11060 (org-add-hook 'before-change-functions
11061 'org-table-remove-rectangle-highlight)
11062 (if (eq what 'name) (setq var (substring match 1)))
11063 (when (eq what 'range)
11064 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11065 (setq match (org-table-formula-substitute-names match)))
11066 (unless local
11067 (save-excursion
11068 (end-of-line 1)
11069 (re-search-backward "^\\S-" nil t)
11070 (beginning-of-line 1)
11071 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11072 (setq dest
11073 (save-match-data
11074 (org-table-convert-refs-to-rc (match-string 1))))
11075 (org-table-add-rectangle-overlay
11076 (match-beginning 1) (match-end 1) face2))))
11077 (if (and (markerp pos) (marker-buffer pos))
11078 (if (get-buffer-window (marker-buffer pos))
11079 (select-window (get-buffer-window (marker-buffer pos)))
11080 (org-switch-to-buffer-other-window (get-buffer-window
11081 (marker-buffer pos)))))
11082 (goto-char pos)
11083 (org-table-force-dataline)
11084 (when dest
11085 (setq name (substring dest 1))
11086 (cond
11087 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11088 (setq e (assoc name org-table-named-field-locations))
11089 (goto-line (nth 1 e))
11090 (org-table-goto-column (nth 2 e)))
11091 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11092 (let ((l (string-to-number (match-string 1 dest)))
11093 (c (string-to-number (match-string 2 dest))))
11094 (goto-line (aref org-table-dlines l))
11095 (org-table-goto-column c)))
11096 (t (org-table-goto-column (string-to-number name))))
11097 (move-marker pos (point))
11098 (org-table-highlight-rectangle nil nil face2))
11099 (cond
11100 ((equal dest match))
11101 ((not match))
11102 ((eq what 'range)
11103 (condition-case nil
11104 (save-excursion
11105 (org-table-get-range match nil nil 'highlight))
11106 (error nil)))
11107 ((setq e (assoc var org-table-named-field-locations))
11108 (goto-line (nth 1 e))
11109 (org-table-goto-column (nth 2 e))
11110 (org-table-highlight-rectangle (point) (point))
11111 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11112 ((setq e (assoc var org-table-column-names))
11113 (org-table-goto-column (string-to-number (cdr e)))
11114 (org-table-highlight-rectangle (point) (point))
11115 (goto-char (org-table-begin))
11116 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11117 (org-table-end) t)
11118 (progn
11119 (goto-char (match-beginning 1))
11120 (org-table-highlight-rectangle)
11121 (message "Named column (column %s)" (cdr e)))
11122 (error "Column name not found")))
11123 ((eq what 'column)
11124 ;; column number
11125 (org-table-goto-column (string-to-number (substring match 1)))
11126 (org-table-highlight-rectangle (point) (point))
11127 (message "Column %s" (substring match 1)))
11128 ((setq e (assoc var org-table-local-parameters))
11129 (goto-char (org-table-begin))
11130 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11131 (progn
11132 (goto-char (match-beginning 1))
11133 (org-table-highlight-rectangle)
11134 (message "Local parameter."))
11135 (error "Parameter not found")))
11137 (cond
11138 ((not var) (error "No reference at point"))
11139 ((setq e (assoc var org-table-formula-constants-local))
11140 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11141 var (cdr e)))
11142 ((setq e (assoc var org-table-formula-constants))
11143 (message "Constant: $%s=%s in `org-table-formula-constants'."
11144 var (cdr e)))
11145 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11146 (message "Constant: $%s=%s, from `constants.el'%s."
11147 var e (format " (%s units)" constants-unit-system)))
11148 (t (error "Undefined name $%s" var)))))
11149 (goto-char pos)
11150 (when (and org-show-positions
11151 (not (memq this-command '(org-table-fedit-scroll
11152 org-table-fedit-scroll-down))))
11153 (push pos org-show-positions)
11154 (push org-table-current-begin-pos org-show-positions)
11155 (let ((min (apply 'min org-show-positions))
11156 (max (apply 'max org-show-positions)))
11157 (goto-char min) (recenter 0)
11158 (goto-char max)
11159 (or (pos-visible-in-window-p max) (recenter -1))))
11160 (select-window win))))
11162 (defun org-table-force-dataline ()
11163 "Make sure the cursor is in a dataline in a table."
11164 (unless (save-excursion
11165 (beginning-of-line 1)
11166 (looking-at org-table-dataline-regexp))
11167 (let* ((re org-table-dataline-regexp)
11168 (p1 (save-excursion (re-search-forward re nil 'move)))
11169 (p2 (save-excursion (re-search-backward re nil 'move))))
11170 (cond ((and p1 p2)
11171 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11172 p1 p2)))
11173 ((or p1 p2) (goto-char (or p1 p2)))
11174 (t (error "No table dataline around here"))))))
11176 (defun org-table-fedit-line-up ()
11177 "Move cursor one line up in the window showing the table."
11178 (interactive)
11179 (org-table-fedit-move 'previous-line))
11181 (defun org-table-fedit-line-down ()
11182 "Move cursor one line down in the window showing the table."
11183 (interactive)
11184 (org-table-fedit-move 'next-line))
11186 (defun org-table-fedit-move (command)
11187 "Move the cursor in the window shoinw the table.
11188 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11189 (let ((org-table-allow-automatic-line-recalculation nil)
11190 (pos org-pos) (win (selected-window)) p)
11191 (select-window (get-buffer-window (marker-buffer org-pos)))
11192 (setq p (point))
11193 (call-interactively command)
11194 (while (and (org-at-table-p)
11195 (org-at-table-hline-p))
11196 (call-interactively command))
11197 (or (org-at-table-p) (goto-char p))
11198 (move-marker pos (point))
11199 (select-window win)))
11201 (defun org-table-fedit-scroll (N)
11202 (interactive "p")
11203 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11204 (scroll-other-window N)))
11206 (defun org-table-fedit-scroll-down (N)
11207 (interactive "p")
11208 (org-table-fedit-scroll (- N)))
11210 (defvar org-table-rectangle-overlays nil)
11212 (defun org-table-add-rectangle-overlay (beg end &optional face)
11213 "Add a new overlay."
11214 (let ((ov (org-make-overlay beg end)))
11215 (org-overlay-put ov 'face (or face 'secondary-selection))
11216 (push ov org-table-rectangle-overlays)))
11218 (defun org-table-highlight-rectangle (&optional beg end face)
11219 "Highlight rectangular region in a table."
11220 (setq beg (or beg (point)) end (or end (point)))
11221 (let ((b (min beg end))
11222 (e (max beg end))
11223 l1 c1 l2 c2 tmp)
11224 (and (boundp 'org-show-positions)
11225 (setq org-show-positions (cons b (cons e org-show-positions))))
11226 (goto-char (min beg end))
11227 (setq l1 (org-current-line)
11228 c1 (org-table-current-column))
11229 (goto-char (max beg end))
11230 (setq l2 (org-current-line)
11231 c2 (org-table-current-column))
11232 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11233 (goto-line l1)
11234 (beginning-of-line 1)
11235 (loop for line from l1 to l2 do
11236 (when (looking-at org-table-dataline-regexp)
11237 (org-table-goto-column c1)
11238 (skip-chars-backward "^|\n") (setq beg (point))
11239 (org-table-goto-column c2)
11240 (skip-chars-forward "^|\n") (setq end (point))
11241 (org-table-add-rectangle-overlay beg end face))
11242 (beginning-of-line 2))
11243 (goto-char b))
11244 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11246 (defun org-table-remove-rectangle-highlight (&rest ignore)
11247 "Remove the rectangle overlays."
11248 (unless org-inhibit-highlight-removal
11249 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11250 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11251 (setq org-table-rectangle-overlays nil)))
11253 (defvar org-table-coordinate-overlays nil
11254 "Collects the cooordinate grid overlays, so that they can be removed.")
11255 (make-variable-buffer-local 'org-table-coordinate-overlays)
11257 (defun org-table-overlay-coordinates ()
11258 "Add overlays to the table at point, to show row/column coordinates."
11259 (interactive)
11260 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11261 (setq org-table-coordinate-overlays nil)
11262 (save-excursion
11263 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11264 (goto-char (org-table-begin))
11265 (while (org-at-table-p)
11266 (setq eol (point-at-eol))
11267 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11268 (push ov org-table-coordinate-overlays)
11269 (setq hline (looking-at org-table-hline-regexp))
11270 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11271 (format "%4d" (setq id (1+ id)))))
11272 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11273 (when hline
11274 (setq ic 0)
11275 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11276 (setq beg (1+ (match-beginning 0))
11277 ic (1+ ic)
11278 s1 (concat "$" (int-to-string ic))
11279 s2 (org-number-to-letters ic)
11280 str (if (eq org-table-use-standard-references t) s2 s1))
11281 (setq ov (org-make-overlay beg (+ beg (length str))))
11282 (push ov org-table-coordinate-overlays)
11283 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11284 (beginning-of-line 2)))))
11286 (defun org-table-toggle-coordinate-overlays ()
11287 "Toggle the display of Row/Column numbers in tables."
11288 (interactive)
11289 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11290 (message "Row/Column number display turned %s"
11291 (if org-table-overlay-coordinates "on" "off"))
11292 (if (and (org-at-table-p) org-table-overlay-coordinates)
11293 (org-table-align))
11294 (unless org-table-overlay-coordinates
11295 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11296 (setq org-table-coordinate-overlays nil)))
11298 (defun org-table-toggle-formula-debugger ()
11299 "Toggle the formula debugger in tables."
11300 (interactive)
11301 (setq org-table-formula-debug (not org-table-formula-debug))
11302 (message "Formula debugging has been turned %s"
11303 (if org-table-formula-debug "on" "off")))
11305 ;;; The orgtbl minor mode
11307 ;; Define a minor mode which can be used in other modes in order to
11308 ;; integrate the org-mode table editor.
11310 ;; This is really a hack, because the org-mode table editor uses several
11311 ;; keys which normally belong to the major mode, for example the TAB and
11312 ;; RET keys. Here is how it works: The minor mode defines all the keys
11313 ;; necessary to operate the table editor, but wraps the commands into a
11314 ;; function which tests if the cursor is currently inside a table. If that
11315 ;; is the case, the table editor command is executed. However, when any of
11316 ;; those keys is used outside a table, the function uses `key-binding' to
11317 ;; look up if the key has an associated command in another currently active
11318 ;; keymap (minor modes, major mode, global), and executes that command.
11319 ;; There might be problems if any of the keys used by the table editor is
11320 ;; otherwise used as a prefix key.
11322 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11323 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11324 ;; addresses this by checking explicitly for both bindings.
11326 ;; The optimized version (see variable `orgtbl-optimized') takes over
11327 ;; all keys which are bound to `self-insert-command' in the *global map*.
11328 ;; Some modes bind other commands to simple characters, for example
11329 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11330 ;; active, this binding is ignored inside tables and replaced with a
11331 ;; modified self-insert.
11333 (defvar orgtbl-mode nil
11334 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11335 table editor in arbitrary modes.")
11336 (make-variable-buffer-local 'orgtbl-mode)
11338 (defvar orgtbl-mode-map (make-keymap)
11339 "Keymap for `orgtbl-mode'.")
11341 ;;;###autoload
11342 (defun turn-on-orgtbl ()
11343 "Unconditionally turn on `orgtbl-mode'."
11344 (orgtbl-mode 1))
11346 (defvar org-old-auto-fill-inhibit-regexp nil
11347 "Local variable used by `orgtbl-mode'")
11349 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11350 "Matches a line belonging to an orgtbl.")
11352 (defconst orgtbl-extra-font-lock-keywords
11353 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11354 0 (quote 'org-table) 'prepend))
11355 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11357 ;;;###autoload
11358 (defun orgtbl-mode (&optional arg)
11359 "The `org-mode' table editor as a minor mode for use in other modes."
11360 (interactive)
11361 (if (org-mode-p)
11362 ;; Exit without error, in case some hook functions calls this
11363 ;; by accident in org-mode.
11364 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11365 (setq orgtbl-mode
11366 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11367 (if orgtbl-mode
11368 (progn
11369 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11370 ;; Make sure we are first in minor-mode-map-alist
11371 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11372 (and c (setq minor-mode-map-alist
11373 (cons c (delq c minor-mode-map-alist)))))
11374 (org-set-local (quote org-table-may-need-update) t)
11375 (org-add-hook 'before-change-functions 'org-before-change-function
11376 nil 'local)
11377 (org-set-local 'org-old-auto-fill-inhibit-regexp
11378 auto-fill-inhibit-regexp)
11379 (org-set-local 'auto-fill-inhibit-regexp
11380 (if auto-fill-inhibit-regexp
11381 (concat orgtbl-line-start-regexp "\\|"
11382 auto-fill-inhibit-regexp)
11383 orgtbl-line-start-regexp))
11384 (org-add-to-invisibility-spec '(org-cwidth))
11385 (when (fboundp 'font-lock-add-keywords)
11386 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11387 (org-restart-font-lock))
11388 (easy-menu-add orgtbl-mode-menu)
11389 (run-hooks 'orgtbl-mode-hook))
11390 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11391 (org-cleanup-narrow-column-properties)
11392 (org-remove-from-invisibility-spec '(org-cwidth))
11393 (remove-hook 'before-change-functions 'org-before-change-function t)
11394 (when (fboundp 'font-lock-remove-keywords)
11395 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11396 (org-restart-font-lock))
11397 (easy-menu-remove orgtbl-mode-menu)
11398 (force-mode-line-update 'all))))
11400 (defun org-cleanup-narrow-column-properties ()
11401 "Remove all properties related to narrow-column invisibility."
11402 (let ((s 1))
11403 (while (setq s (text-property-any s (point-max)
11404 'display org-narrow-column-arrow))
11405 (remove-text-properties s (1+ s) '(display t)))
11406 (setq s 1)
11407 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11408 (remove-text-properties s (1+ s) '(org-cwidth t)))
11409 (setq s 1)
11410 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11411 (remove-text-properties s (1+ s) '(invisible t)))))
11413 ;; Install it as a minor mode.
11414 (put 'orgtbl-mode :included t)
11415 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11416 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11418 (defun orgtbl-make-binding (fun n &rest keys)
11419 "Create a function for binding in the table minor mode.
11420 FUN is the command to call inside a table. N is used to create a unique
11421 command name. KEYS are keys that should be checked in for a command
11422 to execute outside of tables."
11423 (eval
11424 (list 'defun
11425 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11426 '(arg)
11427 (concat "In tables, run `" (symbol-name fun) "'.\n"
11428 "Outside of tables, run the binding of `"
11429 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11430 "'.")
11431 '(interactive "p")
11432 (list 'if
11433 '(org-at-table-p)
11434 (list 'call-interactively (list 'quote fun))
11435 (list 'let '(orgtbl-mode)
11436 (list 'call-interactively
11437 (append '(or)
11438 (mapcar (lambda (k)
11439 (list 'key-binding k))
11440 keys)
11441 '('orgtbl-error))))))))
11443 (defun orgtbl-error ()
11444 "Error when there is no default binding for a table key."
11445 (interactive)
11446 (error "This key has no function outside tables"))
11448 (defun orgtbl-setup ()
11449 "Setup orgtbl keymaps."
11450 (let ((nfunc 0)
11451 (bindings
11452 (list
11453 '([(meta shift left)] org-table-delete-column)
11454 '([(meta left)] org-table-move-column-left)
11455 '([(meta right)] org-table-move-column-right)
11456 '([(meta shift right)] org-table-insert-column)
11457 '([(meta shift up)] org-table-kill-row)
11458 '([(meta shift down)] org-table-insert-row)
11459 '([(meta up)] org-table-move-row-up)
11460 '([(meta down)] org-table-move-row-down)
11461 '("\C-c\C-w" org-table-cut-region)
11462 '("\C-c\M-w" org-table-copy-region)
11463 '("\C-c\C-y" org-table-paste-rectangle)
11464 '("\C-c-" org-table-insert-hline)
11465 '("\C-c}" org-table-toggle-coordinate-overlays)
11466 '("\C-c{" org-table-toggle-formula-debugger)
11467 '("\C-m" org-table-next-row)
11468 '([(shift return)] org-table-copy-down)
11469 '("\C-c\C-q" org-table-wrap-region)
11470 '("\C-c?" org-table-field-info)
11471 '("\C-c " org-table-blank-field)
11472 '("\C-c+" org-table-sum)
11473 '("\C-c=" org-table-eval-formula)
11474 '("\C-c'" org-table-edit-formulas)
11475 '("\C-c`" org-table-edit-field)
11476 '("\C-c*" org-table-recalculate)
11477 '("\C-c|" org-table-create-or-convert-from-region)
11478 '("\C-c^" org-table-sort-lines)
11479 '([(control ?#)] org-table-rotate-recalc-marks)))
11480 elt key fun cmd)
11481 (while (setq elt (pop bindings))
11482 (setq nfunc (1+ nfunc))
11483 (setq key (org-key (car elt))
11484 fun (nth 1 elt)
11485 cmd (orgtbl-make-binding fun nfunc key))
11486 (org-defkey orgtbl-mode-map key cmd))
11488 ;; Special treatment needed for TAB and RET
11489 (org-defkey orgtbl-mode-map [(return)]
11490 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11491 (org-defkey orgtbl-mode-map "\C-m"
11492 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11494 (org-defkey orgtbl-mode-map [(tab)]
11495 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11496 (org-defkey orgtbl-mode-map "\C-i"
11497 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11499 (org-defkey orgtbl-mode-map [(shift tab)]
11500 (orgtbl-make-binding 'org-table-previous-field 104
11501 [(shift tab)] [(tab)] "\C-i"))
11503 (org-defkey orgtbl-mode-map "\M-\C-m"
11504 (orgtbl-make-binding 'org-table-wrap-region 105
11505 "\M-\C-m" [(meta return)]))
11506 (org-defkey orgtbl-mode-map [(meta return)]
11507 (orgtbl-make-binding 'org-table-wrap-region 106
11508 [(meta return)] "\M-\C-m"))
11510 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11511 (when orgtbl-optimized
11512 ;; If the user wants maximum table support, we need to hijack
11513 ;; some standard editing functions
11514 (org-remap orgtbl-mode-map
11515 'self-insert-command 'orgtbl-self-insert-command
11516 'delete-char 'org-delete-char
11517 'delete-backward-char 'org-delete-backward-char)
11518 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11519 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11520 '("OrgTbl"
11521 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11522 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11523 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11524 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11525 "--"
11526 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11527 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11528 ["Copy Field from Above"
11529 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11530 "--"
11531 ("Column"
11532 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11533 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11534 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11535 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11536 ("Row"
11537 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11538 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11539 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11540 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11541 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
11542 "--"
11543 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11544 ("Rectangle"
11545 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11546 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11547 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11548 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11549 "--"
11550 ("Radio tables"
11551 ["Insert table template" orgtbl-insert-radio-table
11552 (assq major-mode orgtbl-radio-table-templates)]
11553 ["Comment/uncomment table" orgtbl-toggle-comment t])
11554 "--"
11555 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11556 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11557 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11558 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11559 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11560 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11561 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11562 ["Sum Column/Rectangle" org-table-sum
11563 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11564 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11565 ["Debug Formulas"
11566 org-table-toggle-formula-debugger :active (org-at-table-p)
11567 :keys "C-c {"
11568 :style toggle :selected org-table-formula-debug]
11569 ["Show Col/Row Numbers"
11570 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11571 :keys "C-c }"
11572 :style toggle :selected org-table-overlay-coordinates]
11576 (defun orgtbl-ctrl-c-ctrl-c (arg)
11577 "If the cursor is inside a table, realign the table.
11578 It it is a table to be sent away to a receiver, do it.
11579 With prefix arg, also recompute table."
11580 (interactive "P")
11581 (let ((pos (point)) action)
11582 (save-excursion
11583 (beginning-of-line 1)
11584 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11585 ((looking-at "[ \t]*|") pos)
11586 ((looking-at "#\\+TBLFM:") 'recalc))))
11587 (cond
11588 ((integerp action)
11589 (goto-char action)
11590 (org-table-maybe-eval-formula)
11591 (if arg
11592 (call-interactively 'org-table-recalculate)
11593 (org-table-maybe-recalculate-line))
11594 (call-interactively 'org-table-align)
11595 (orgtbl-send-table 'maybe))
11596 ((eq action 'recalc)
11597 (save-excursion
11598 (beginning-of-line 1)
11599 (skip-chars-backward " \r\n\t")
11600 (if (org-at-table-p)
11601 (org-call-with-arg 'org-table-recalculate t))))
11602 (t (let (orgtbl-mode)
11603 (call-interactively (key-binding "\C-c\C-c")))))))
11605 (defun orgtbl-tab (arg)
11606 "Justification and field motion for `orgtbl-mode'."
11607 (interactive "P")
11608 (if arg (org-table-edit-field t)
11609 (org-table-justify-field-maybe)
11610 (org-table-next-field)))
11612 (defun orgtbl-ret ()
11613 "Justification and field motion for `orgtbl-mode'."
11614 (interactive)
11615 (org-table-justify-field-maybe)
11616 (org-table-next-row))
11618 (defun orgtbl-self-insert-command (N)
11619 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11620 If the cursor is in a table looking at whitespace, the whitespace is
11621 overwritten, and the table is not marked as requiring realignment."
11622 (interactive "p")
11623 (if (and (org-at-table-p)
11625 (and org-table-auto-blank-field
11626 (member last-command
11627 '(orgtbl-hijacker-command-100
11628 orgtbl-hijacker-command-101
11629 orgtbl-hijacker-command-102
11630 orgtbl-hijacker-command-103
11631 orgtbl-hijacker-command-104
11632 orgtbl-hijacker-command-105))
11633 (org-table-blank-field))
11635 (eq N 1)
11636 (looking-at "[^|\n]* +|"))
11637 (let (org-table-may-need-update)
11638 (goto-char (1- (match-end 0)))
11639 (delete-backward-char 1)
11640 (goto-char (match-beginning 0))
11641 (self-insert-command N))
11642 (setq org-table-may-need-update t)
11643 (let (orgtbl-mode)
11644 (call-interactively (key-binding (vector last-input-event))))))
11646 (defun org-force-self-insert (N)
11647 "Needed to enforce self-insert under remapping."
11648 (interactive "p")
11649 (self-insert-command N))
11651 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11652 "Regula expression matching exponentials as produced by calc.")
11654 (defvar org-table-clean-did-remove-column nil)
11656 (defun orgtbl-export (table target)
11657 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11658 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11659 org-table-last-alignment org-table-last-column-widths
11660 maxcol column)
11661 (if (not (fboundp func))
11662 (error "Cannot export orgtbl table to %s" target))
11663 (setq lines (org-table-clean-before-export lines))
11664 (setq table
11665 (mapcar
11666 (lambda (x)
11667 (if (string-match org-table-hline-regexp x)
11668 'hline
11669 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11670 lines))
11671 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11672 table)))
11673 (loop for i from (1- maxcol) downto 0 do
11674 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11675 (setq column (delq nil column))
11676 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11677 (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))
11678 (funcall func table nil)))
11680 (defun orgtbl-send-table (&optional maybe)
11681 "Send a tranformed version of this table to the receiver position.
11682 With argument MAYBE, fail quietly if no transformation is defined for
11683 this table."
11684 (interactive)
11685 (catch 'exit
11686 (unless (org-at-table-p) (error "Not at a table"))
11687 ;; when non-interactive, we assume align has just happened.
11688 (when (interactive-p) (org-table-align))
11689 (save-excursion
11690 (goto-char (org-table-begin))
11691 (beginning-of-line 0)
11692 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11693 (if maybe
11694 (throw 'exit nil)
11695 (error "Don't know how to transform this table."))))
11696 (let* ((name (match-string 1))
11698 (transform (intern (match-string 2)))
11699 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11700 (skip (plist-get params :skip))
11701 (skipcols (plist-get params :skipcols))
11702 (txt (buffer-substring-no-properties
11703 (org-table-begin) (org-table-end)))
11704 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11705 (lines (org-table-clean-before-export lines))
11706 (i0 (if org-table-clean-did-remove-column 2 1))
11707 (table (mapcar
11708 (lambda (x)
11709 (if (string-match org-table-hline-regexp x)
11710 'hline
11711 (org-remove-by-index
11712 (org-split-string (org-trim x) "\\s-*|\\s-*")
11713 skipcols i0)))
11714 lines))
11715 (fun (if (= i0 2) 'cdr 'identity))
11716 (org-table-last-alignment
11717 (org-remove-by-index (funcall fun org-table-last-alignment)
11718 skipcols i0))
11719 (org-table-last-column-widths
11720 (org-remove-by-index (funcall fun org-table-last-column-widths)
11721 skipcols i0)))
11723 (unless (fboundp transform)
11724 (error "No such transformation function %s" transform))
11725 (setq txt (funcall transform table params))
11726 ;; Find the insertion place
11727 (save-excursion
11728 (goto-char (point-min))
11729 (unless (re-search-forward
11730 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11731 (error "Don't know where to insert translated table"))
11732 (goto-char (match-beginning 0))
11733 (beginning-of-line 2)
11734 (setq beg (point))
11735 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11736 (error "Cannot find end of insertion region"))
11737 (beginning-of-line 1)
11738 (delete-region beg (point))
11739 (goto-char beg)
11740 (insert txt "\n"))
11741 (message "Table converted and installed at receiver location"))))
11743 (defun org-remove-by-index (list indices &optional i0)
11744 "Remove the elements in LIST with indices in INDICES.
11745 First element has index 0, or I0 if given."
11746 (if (not indices)
11747 list
11748 (if (integerp indices) (setq indices (list indices)))
11749 (setq i0 (1- (or i0 0)))
11750 (delq :rm (mapcar (lambda (x)
11751 (setq i0 (1+ i0))
11752 (if (memq i0 indices) :rm x))
11753 list))))
11755 (defun orgtbl-toggle-comment ()
11756 "Comment or uncomment the orgtbl at point."
11757 (interactive)
11758 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11759 (re2 (concat "^" orgtbl-line-start-regexp))
11760 (commented (save-excursion (beginning-of-line 1)
11761 (cond ((looking-at re1) t)
11762 ((looking-at re2) nil)
11763 (t (error "Not at an org table")))))
11764 (re (if commented re1 re2))
11765 beg end)
11766 (save-excursion
11767 (beginning-of-line 1)
11768 (while (looking-at re) (beginning-of-line 0))
11769 (beginning-of-line 2)
11770 (setq beg (point))
11771 (while (looking-at re) (beginning-of-line 2))
11772 (setq end (point)))
11773 (comment-region beg end (if commented '(4) nil))))
11775 (defun orgtbl-insert-radio-table ()
11776 "Insert a radio table template appropriate for this major mode."
11777 (interactive)
11778 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11779 (txt (nth 1 e))
11780 name pos)
11781 (unless e (error "No radio table setup defined for %s" major-mode))
11782 (setq name (read-string "Table name: "))
11783 (while (string-match "%n" txt)
11784 (setq txt (replace-match name t t txt)))
11785 (or (bolp) (insert "\n"))
11786 (setq pos (point))
11787 (insert txt)
11788 (goto-char pos)))
11790 (defun org-get-param (params header i sym &optional hsym)
11791 "Get parameter value for symbol SYM.
11792 If this is a header line, actually get the value for the symbol with an
11793 additional \"h\" inserted after the colon.
11794 If the value is a protperty list, get the element for the current column.
11795 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11796 (let ((val (plist-get params sym)))
11797 (and hsym header (setq val (or (plist-get params hsym) val)))
11798 (if (consp val) (plist-get val i) val)))
11800 (defun orgtbl-to-generic (table params)
11801 "Convert the orgtbl-mode TABLE to some other format.
11802 This generic routine can be used for many standard cases.
11803 TABLE is a list, each entry either the symbol `hline' for a horizontal
11804 separator line, or a list of fields for that line.
11805 PARAMS is a property list of parameters that can influence the conversion.
11806 For the generic converter, some parameters are obligatory: You need to
11807 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11808 :splice, you must have :tstart and :tend.
11810 Valid parameters are
11812 :tstart String to start the table. Ignored when :splice is t.
11813 :tend String to end the table. Ignored when :splice is t.
11815 :splice When set to t, return only table body lines, don't wrap
11816 them into :tstart and :tend. Default is nil.
11818 :hline String to be inserted on horizontal separation lines.
11819 May be nil to ignore hlines.
11821 :lstart String to start a new table line.
11822 :lend String to end a table line
11823 :sep Separator between two fields
11824 :lfmt Format for entire line, with enough %s to capture all fields.
11825 If this is present, :lstart, :lend, and :sep are ignored.
11826 :fmt A format to be used to wrap the field, should contain
11827 %s for the original field value. For example, to wrap
11828 everything in dollars, you could use :fmt \"$%s$\".
11829 This may also be a property list with column numbers and
11830 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11832 :hlstart :hlend :hlsep :hlfmt :hfmt
11833 Same as above, specific for the header lines in the table.
11834 All lines before the first hline are treated as header.
11835 If any of these is not present, the data line value is used.
11837 :efmt Use this format to print numbers with exponentials.
11838 The format should have %s twice for inserting mantissa
11839 and exponent, for example \"%s\\\\times10^{%s}\". This
11840 may also be a property list with column numbers and
11841 formats. :fmt will still be applied after :efmt.
11843 In addition to this, the parameters :skip and :skipcols are always handled
11844 directly by `orgtbl-send-table'. See manual."
11845 (interactive)
11846 (let* ((p params)
11847 (splicep (plist-get p :splice))
11848 (hline (plist-get p :hline))
11849 rtn line i fm efm lfmt h)
11851 ;; Do we have a header?
11852 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11853 (setq h t))
11855 ;; Put header
11856 (unless splicep
11857 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11859 ;; Now loop over all lines
11860 (while (setq line (pop table))
11861 (if (eq line 'hline)
11862 ;; A horizontal separator line
11863 (progn (if hline (push hline rtn))
11864 (setq h nil)) ; no longer in header
11865 ;; A normal line. Convert the fields, push line onto the result list
11866 (setq i 0)
11867 (setq line
11868 (mapcar
11869 (lambda (f)
11870 (setq i (1+ i)
11871 fm (org-get-param p h i :fmt :hfmt)
11872 efm (org-get-param p h i :efmt))
11873 (if (and efm (string-match orgtbl-exp-regexp f))
11874 (setq f (format
11875 efm (match-string 1 f) (match-string 2 f))))
11876 (if fm (setq f (format fm f)))
11878 line))
11879 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11880 (push (apply 'format lfmt line) rtn)
11881 (push (concat
11882 (org-get-param p h i :lstart :hlstart)
11883 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11884 (org-get-param p h i :lend :hlend))
11885 rtn))))
11887 (unless splicep
11888 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11890 (mapconcat 'identity (nreverse rtn) "\n")))
11892 (defun orgtbl-to-latex (table params)
11893 "Convert the orgtbl-mode TABLE to LaTeX.
11894 TABLE is a list, each entry either the symbol `hline' for a horizontal
11895 separator line, or a list of fields for that line.
11896 PARAMS is a property list of parameters that can influence the conversion.
11897 Supports all parameters from `orgtbl-to-generic'. Most important for
11898 LaTeX are:
11900 :splice When set to t, return only table body lines, don't wrap
11901 them into a tabular environment. Default is nil.
11903 :fmt A format to be used to wrap the field, should contain %s for the
11904 original field value. For example, to wrap everything in dollars,
11905 use :fmt \"$%s$\". This may also be a property list with column
11906 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11908 :efmt Format for transforming numbers with exponentials. The format
11909 should have %s twice for inserting mantissa and exponent, for
11910 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11911 This may also be a property list with column numbers and formats.
11913 The general parameters :skip and :skipcols have already been applied when
11914 this function is called."
11915 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11916 org-table-last-alignment ""))
11917 (params2
11918 (list
11919 :tstart (concat "\\begin{tabular}{" alignment "}")
11920 :tend "\\end{tabular}"
11921 :lstart "" :lend " \\\\" :sep " & "
11922 :efmt "%s\\,(%s)" :hline "\\hline")))
11923 (orgtbl-to-generic table (org-combine-plists params2 params))))
11925 (defun orgtbl-to-html (table params)
11926 "Convert the orgtbl-mode TABLE to LaTeX.
11927 TABLE is a list, each entry either the symbol `hline' for a horizontal
11928 separator line, or a list of fields for that line.
11929 PARAMS is a property list of parameters that can influence the conversion.
11930 Currently this function recognizes the following parameters:
11932 :splice When set to t, return only table body lines, don't wrap
11933 them into a <table> environment. Default is nil.
11935 The general parameters :skip and :skipcols have already been applied when
11936 this function is called. The function does *not* use `orgtbl-to-generic',
11937 so you cannot specify parameters for it."
11938 (let* ((splicep (plist-get params :splice))
11939 html)
11940 ;; Just call the formatter we already have
11941 ;; We need to make text lines for it, so put the fields back together.
11942 (setq html (org-format-org-table-html
11943 (mapcar
11944 (lambda (x)
11945 (if (eq x 'hline)
11946 "|----+----|"
11947 (concat "| " (mapconcat 'identity x " | ") " |")))
11948 table)
11949 splicep))
11950 (if (string-match "\n+\\'" html)
11951 (setq html (replace-match "" t t html)))
11952 html))
11954 (defun orgtbl-to-texinfo (table params)
11955 "Convert the orgtbl-mode TABLE to TeXInfo.
11956 TABLE is a list, each entry either the symbol `hline' for a horizontal
11957 separator line, or a list of fields for that line.
11958 PARAMS is a property list of parameters that can influence the conversion.
11959 Supports all parameters from `orgtbl-to-generic'. Most important for
11960 TeXInfo are:
11962 :splice nil/t When set to t, return only table body lines, don't wrap
11963 them into a multitable environment. Default is nil.
11965 :fmt fmt A format to be used to wrap the field, should contain
11966 %s for the original field value. For example, to wrap
11967 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11968 This may also be a property list with column numbers and
11969 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11971 :cf \"f1 f2..\" The column fractions for the table. By default these
11972 are computed automatically from the width of the columns
11973 under org-mode.
11975 The general parameters :skip and :skipcols have already been applied when
11976 this function is called."
11977 (let* ((total (float (apply '+ org-table-last-column-widths)))
11978 (colfrac (or (plist-get params :cf)
11979 (mapconcat
11980 (lambda (x) (format "%.3f" (/ (float x) total)))
11981 org-table-last-column-widths " ")))
11982 (params2
11983 (list
11984 :tstart (concat "@multitable @columnfractions " colfrac)
11985 :tend "@end multitable"
11986 :lstart "@item " :lend "" :sep " @tab "
11987 :hlstart "@headitem ")))
11988 (orgtbl-to-generic table (org-combine-plists params2 params))))
11990 ;;;; Link Stuff
11992 ;;; Link abbreviations
11994 (defun org-link-expand-abbrev (link)
11995 "Apply replacements as defined in `org-link-abbrev-alist."
11996 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11997 (let* ((key (match-string 1 link))
11998 (as (or (assoc key org-link-abbrev-alist-local)
11999 (assoc key org-link-abbrev-alist)))
12000 (tag (and (match-end 2) (match-string 3 link)))
12001 rpl)
12002 (if (not as)
12003 link
12004 (setq rpl (cdr as))
12005 (cond
12006 ((symbolp rpl) (funcall rpl tag))
12007 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
12008 (t (concat rpl tag)))))
12009 link))
12011 ;;; Storing and inserting links
12013 (defvar org-insert-link-history nil
12014 "Minibuffer history for links inserted with `org-insert-link'.")
12016 (defvar org-stored-links nil
12017 "Contains the links stored with `org-store-link'.")
12019 (defvar org-store-link-plist nil
12020 "Plist with info about the most recently link created with `org-store-link'.")
12022 (defvar org-link-protocols nil
12023 "Link protocols added to Org-mode using `org-add-link-type'.")
12025 (defvar org-store-link-functions nil
12026 "List of functions that are called to create and store a link.
12027 Each function will be called in turn until one returns a non-nil
12028 value. Each function should check if it is responsible for creating
12029 this link (for example by looking at the major mode).
12030 If not, it must exit and return nil.
12031 If yes, it should return a non-nil value after a calling
12032 `org-store-link-props' with a list of properties and values.
12033 Special properties are:
12035 :type The link prefix. like \"http\". This must be given.
12036 :link The link, like \"http://www.astro.uva.nl/~dominik\".
12037 This is obligatory as well.
12038 :description Optional default description for the second pair
12039 of brackets in an Org-mode link. The user can still change
12040 this when inserting this link into an Org-mode buffer.
12042 In addition to these, any additional properties can be specified
12043 and then used in remember templates.")
12045 (defun org-add-link-type (type &optional follow publish)
12046 "Add TYPE to the list of `org-link-types'.
12047 Re-compute all regular expressions depending on `org-link-types'
12048 FOLLOW and PUBLISH are two functions. Both take the link path as
12049 an argument.
12050 FOLLOW should do whatever is necessary to follow the link, for example
12051 to find a file or display a mail message.
12053 PUBLISH takes the path and retuns the string that should be used when
12054 this document is published. FIMXE: This is actually not yet implemented."
12055 (add-to-list 'org-link-types type t)
12056 (org-make-link-regexps)
12057 (add-to-list 'org-link-protocols
12058 (list type follow publish)))
12060 (defun org-add-agenda-custom-command (entry)
12061 "Replace or add a command in `org-agenda-custom-commands'.
12062 This is mostly for hacking and trying a new command - once the command
12063 works you probably want to add it to `org-agenda-custom-commands' for good."
12064 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12065 (if ass
12066 (setcdr ass (cdr entry))
12067 (push entry org-agenda-custom-commands))))
12069 ;;;###autoload
12070 (defun org-store-link (arg)
12071 "\\<org-mode-map>Store an org-link to the current location.
12072 This link is added to `org-stored-links' and can later be inserted
12073 into an org-buffer with \\[org-insert-link].
12075 For some link types, a prefix arg is interpreted:
12076 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12077 For file links, arg negates `org-context-in-file-links'."
12078 (interactive "P")
12079 (setq org-store-link-plist nil) ; reset
12080 (let (link cpltxt desc description search txt)
12081 (cond
12083 ((run-hook-with-args-until-success 'org-store-link-functions)
12084 (setq link (plist-get org-store-link-plist :link)
12085 desc (or (plist-get org-store-link-plist :description) link)))
12087 ((eq major-mode 'bbdb-mode)
12088 (let ((name (bbdb-record-name (bbdb-current-record)))
12089 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
12090 (setq cpltxt (concat "bbdb:" (or name company))
12091 link (org-make-link cpltxt))
12092 (org-store-link-props :type "bbdb" :name name :company company)))
12094 ((eq major-mode 'Info-mode)
12095 (setq link (org-make-link "info:"
12096 (file-name-nondirectory Info-current-file)
12097 ":" Info-current-node))
12098 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
12099 ":" Info-current-node))
12100 (org-store-link-props :type "info" :file Info-current-file
12101 :node Info-current-node))
12103 ((eq major-mode 'calendar-mode)
12104 (let ((cd (calendar-cursor-to-date)))
12105 (setq link
12106 (format-time-string
12107 (car org-time-stamp-formats)
12108 (apply 'encode-time
12109 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12110 nil nil nil))))
12111 (org-store-link-props :type "calendar" :date cd)))
12113 ((or (eq major-mode 'vm-summary-mode)
12114 (eq major-mode 'vm-presentation-mode))
12115 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
12116 (vm-follow-summary-cursor)
12117 (save-excursion
12118 (vm-select-folder-buffer)
12119 (let* ((message (car vm-message-pointer))
12120 (folder buffer-file-name)
12121 (subject (vm-su-subject message))
12122 (to (vm-get-header-contents message "To"))
12123 (from (vm-get-header-contents message "From"))
12124 (message-id (vm-su-message-id message)))
12125 (org-store-link-props :type "vm" :from from :to to :subject subject
12126 :message-id message-id)
12127 (setq message-id (org-remove-angle-brackets message-id))
12128 (setq folder (abbreviate-file-name folder))
12129 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
12130 folder)
12131 (setq folder (replace-match "" t t folder)))
12132 (setq cpltxt (org-email-link-description))
12133 (setq link (org-make-link "vm:" folder "#" message-id)))))
12135 ((eq major-mode 'wl-summary-mode)
12136 (let* ((msgnum (wl-summary-message-number))
12137 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
12138 msgnum 'message-id))
12139 (wl-message-entity
12140 (if (fboundp 'elmo-message-entity)
12141 (elmo-message-entity
12142 wl-summary-buffer-elmo-folder msgnum)
12143 (elmo-msgdb-overview-get-entity
12144 msgnum (wl-summary-buffer-msgdb))))
12145 (from (wl-summary-line-from))
12146 (to (car (elmo-message-entity-field wl-message-entity 'to)))
12147 (subject (let (wl-thr-indent-string wl-parent-message-entity)
12148 (wl-summary-line-subject))))
12149 (org-store-link-props :type "wl" :from from :to to
12150 :subject subject :message-id message-id)
12151 (setq message-id (org-remove-angle-brackets message-id))
12152 (setq cpltxt (org-email-link-description))
12153 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
12154 "#" message-id))))
12156 ((or (equal major-mode 'mh-folder-mode)
12157 (equal major-mode 'mh-show-mode))
12158 (let ((from (org-mhe-get-header "From:"))
12159 (to (org-mhe-get-header "To:"))
12160 (message-id (org-mhe-get-header "Message-Id:"))
12161 (subject (org-mhe-get-header "Subject:")))
12162 (org-store-link-props :type "mh" :from from :to to
12163 :subject subject :message-id message-id)
12164 (setq cpltxt (org-email-link-description))
12165 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
12166 (org-remove-angle-brackets message-id)))))
12168 ((or (eq major-mode 'rmail-mode)
12169 (eq major-mode 'rmail-summary-mode))
12170 (save-window-excursion
12171 (save-restriction
12172 (when (eq major-mode 'rmail-summary-mode)
12173 (rmail-show-message rmail-current-message))
12174 (rmail-narrow-to-non-pruned-header)
12175 (let ((folder buffer-file-name)
12176 (message-id (mail-fetch-field "message-id"))
12177 (from (mail-fetch-field "from"))
12178 (to (mail-fetch-field "to"))
12179 (subject (mail-fetch-field "subject")))
12180 (org-store-link-props
12181 :type "rmail" :from from :to to
12182 :subject subject :message-id message-id)
12183 (setq message-id (org-remove-angle-brackets message-id))
12184 (setq cpltxt (org-email-link-description))
12185 (setq link (org-make-link "rmail:" folder "#" message-id)))
12186 (rmail-show-message rmail-current-message))))
12188 ((eq major-mode 'gnus-group-mode)
12189 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12190 (gnus-group-group-name)) ; version
12191 ((fboundp 'gnus-group-name)
12192 (gnus-group-name))
12193 (t "???"))))
12194 (unless group (error "Not on a group"))
12195 (org-store-link-props :type "gnus" :group group)
12196 (setq cpltxt (concat
12197 (if (org-xor arg org-usenet-links-prefer-google)
12198 "http://groups.google.com/groups?group="
12199 "gnus:")
12200 group)
12201 link (org-make-link cpltxt))))
12203 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12204 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12205 (let* ((group gnus-newsgroup-name)
12206 (article (gnus-summary-article-number))
12207 (header (gnus-summary-article-header article))
12208 (from (mail-header-from header))
12209 (message-id (mail-header-id header))
12210 (date (mail-header-date header))
12211 (subject (gnus-summary-subject-string)))
12212 (org-store-link-props :type "gnus" :from from :subject subject
12213 :message-id message-id :group group)
12214 (setq cpltxt (org-email-link-description))
12215 (if (org-xor arg org-usenet-links-prefer-google)
12216 (setq link
12217 (concat
12218 cpltxt "\n "
12219 (format "http://groups.google.com/groups?as_umsgid=%s"
12220 (org-fixup-message-id-for-http message-id))))
12221 (setq link (org-make-link "gnus:" group
12222 "#" (number-to-string article))))))
12224 ((eq major-mode 'w3-mode)
12225 (setq cpltxt (url-view-url t)
12226 link (org-make-link cpltxt))
12227 (org-store-link-props :type "w3" :url (url-view-url t)))
12229 ((eq major-mode 'w3m-mode)
12230 (setq cpltxt (or w3m-current-title w3m-current-url)
12231 link (org-make-link w3m-current-url))
12232 (org-store-link-props :type "w3m" :url (url-view-url t)))
12234 ((setq search (run-hook-with-args-until-success
12235 'org-create-file-search-functions))
12236 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12237 "::" search))
12238 (setq cpltxt (or description link)))
12240 ((eq major-mode 'image-mode)
12241 (setq cpltxt (concat "file:"
12242 (abbreviate-file-name buffer-file-name))
12243 link (org-make-link cpltxt))
12244 (org-store-link-props :type "image" :file buffer-file-name))
12246 ((eq major-mode 'dired-mode)
12247 ;; link to the file in the current line
12248 (setq cpltxt (concat "file:"
12249 (abbreviate-file-name
12250 (expand-file-name
12251 (dired-get-filename nil t))))
12252 link (org-make-link cpltxt)))
12254 ((and buffer-file-name (org-mode-p))
12255 ;; Just link to current headline
12256 (setq cpltxt (concat "file:"
12257 (abbreviate-file-name buffer-file-name)))
12258 ;; Add a context search string
12259 (when (org-xor org-context-in-file-links arg)
12260 ;; Check if we are on a target
12261 (if (org-in-regexp "<<\\(.*?\\)>>")
12262 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12263 (setq txt (cond
12264 ((org-on-heading-p) nil)
12265 ((org-region-active-p)
12266 (buffer-substring (region-beginning) (region-end)))
12267 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12268 (when (or (null txt) (string-match "\\S-" txt))
12269 (setq cpltxt
12270 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12271 desc "NONE"))))
12272 (if (string-match "::\\'" cpltxt)
12273 (setq cpltxt (substring cpltxt 0 -2)))
12274 (setq link (org-make-link cpltxt)))
12276 ((buffer-file-name (buffer-base-buffer))
12277 ;; Just link to this file here.
12278 (setq cpltxt (concat "file:"
12279 (abbreviate-file-name
12280 (buffer-file-name (buffer-base-buffer)))))
12281 ;; Add a context string
12282 (when (org-xor org-context-in-file-links arg)
12283 (setq txt (if (org-region-active-p)
12284 (buffer-substring (region-beginning) (region-end))
12285 (buffer-substring (point-at-bol) (point-at-eol))))
12286 ;; Only use search option if there is some text.
12287 (when (string-match "\\S-" txt)
12288 (setq cpltxt
12289 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12290 desc "NONE")))
12291 (setq link (org-make-link cpltxt)))
12293 ((interactive-p)
12294 (error "Cannot link to a buffer which is not visiting a file"))
12296 (t (setq link nil)))
12298 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12299 (setq link (or link cpltxt)
12300 desc (or desc cpltxt))
12301 (if (equal desc "NONE") (setq desc nil))
12303 (if (and (interactive-p) link)
12304 (progn
12305 (setq org-stored-links
12306 (cons (list link desc) org-stored-links))
12307 (message "Stored: %s" (or desc link)))
12308 (and link (org-make-link-string link desc)))))
12310 (defun org-store-link-props (&rest plist)
12311 "Store link properties, extract names and addresses."
12312 (let (x adr)
12313 (when (setq x (plist-get plist :from))
12314 (setq adr (mail-extract-address-components x))
12315 (plist-put plist :fromname (car adr))
12316 (plist-put plist :fromaddress (nth 1 adr)))
12317 (when (setq x (plist-get plist :to))
12318 (setq adr (mail-extract-address-components x))
12319 (plist-put plist :toname (car adr))
12320 (plist-put plist :toaddress (nth 1 adr))))
12321 (let ((from (plist-get plist :from))
12322 (to (plist-get plist :to)))
12323 (when (and from to org-from-is-user-regexp)
12324 (plist-put plist :fromto
12325 (if (string-match org-from-is-user-regexp from)
12326 (concat "to %t")
12327 (concat "from %f")))))
12328 (setq org-store-link-plist plist))
12330 (defun org-email-link-description (&optional fmt)
12331 "Return the description part of an email link.
12332 This takes information from `org-store-link-plist' and formats it
12333 according to FMT (default from `org-email-link-description-format')."
12334 (setq fmt (or fmt org-email-link-description-format))
12335 (let* ((p org-store-link-plist)
12336 (to (plist-get p :toaddress))
12337 (from (plist-get p :fromaddress))
12338 (table
12339 (list
12340 (cons "%c" (plist-get p :fromto))
12341 (cons "%F" (plist-get p :from))
12342 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12343 (cons "%T" (plist-get p :to))
12344 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12345 (cons "%s" (plist-get p :subject))
12346 (cons "%m" (plist-get p :message-id)))))
12347 (when (string-match "%c" fmt)
12348 ;; Check if the user wrote this message
12349 (if (and org-from-is-user-regexp from to
12350 (save-match-data (string-match org-from-is-user-regexp from)))
12351 (setq fmt (replace-match "to %t" t t fmt))
12352 (setq fmt (replace-match "from %f" t t fmt))))
12353 (org-replace-escapes fmt table)))
12355 (defun org-make-org-heading-search-string (&optional string heading)
12356 "Make search string for STRING or current headline."
12357 (interactive)
12358 (let ((s (or string (org-get-heading))))
12359 (unless (and string (not heading))
12360 ;; We are using a headline, clean up garbage in there.
12361 (if (string-match org-todo-regexp s)
12362 (setq s (replace-match "" t t s)))
12363 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12364 (setq s (replace-match "" t t s)))
12365 (setq s (org-trim s))
12366 (if (string-match (concat "^\\(" org-quote-string "\\|"
12367 org-comment-string "\\)") s)
12368 (setq s (replace-match "" t t s)))
12369 (while (string-match org-ts-regexp s)
12370 (setq s (replace-match "" t t s))))
12371 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12372 (setq s (replace-match " " t t s)))
12373 (or string (setq s (concat "*" s))) ; Add * for headlines
12374 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12376 (defun org-make-link (&rest strings)
12377 "Concatenate STRINGS."
12378 (apply 'concat strings))
12380 (defun org-make-link-string (link &optional description)
12381 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12382 (unless (string-match "\\S-" link)
12383 (error "Empty link"))
12384 (when (stringp description)
12385 ;; Remove brackets from the description, they are fatal.
12386 (while (string-match "\\[" description)
12387 (setq description (replace-match "{" t t description)))
12388 (while (string-match "\\]" description)
12389 (setq description (replace-match "}" t t description))))
12390 (when (equal (org-link-escape link) description)
12391 ;; No description needed, it is identical
12392 (setq description nil))
12393 (when (and (not description)
12394 (not (equal link (org-link-escape link))))
12395 (setq description link))
12396 (concat "[[" (org-link-escape link) "]"
12397 (if description (concat "[" description "]") "")
12398 "]"))
12400 (defconst org-link-escape-chars
12401 '((?\ . "%20")
12402 (?\[ . "%5B")
12403 (?\] . "%5D")
12404 (?\340 . "%E0") ; `a
12405 (?\342 . "%E2") ; ^a
12406 (?\347 . "%E7") ; ,c
12407 (?\350 . "%E8") ; `e
12408 (?\351 . "%E9") ; 'e
12409 (?\352 . "%EA") ; ^e
12410 (?\356 . "%EE") ; ^i
12411 (?\364 . "%F4") ; ^o
12412 (?\371 . "%F9") ; `u
12413 (?\373 . "%FB") ; ^u
12414 (?\; . "%3B")
12415 (?? . "%3F")
12416 (?= . "%3D")
12417 (?+ . "%2B")
12419 "Association list of escapes for some characters problematic in links.
12420 This is the list that is used for internal purposes.")
12422 (defconst org-link-escape-chars-browser
12423 '((?\ . "%20")) ; 32 for the SPC char
12424 "Association list of escapes for some characters problematic in links.
12425 This is the list that is used before handing over to the browser.")
12427 (defun org-link-escape (text &optional table)
12428 "Escape charaters in TEXT that are problematic for links."
12429 (setq table (or table org-link-escape-chars))
12430 (when text
12431 (let ((re (mapconcat (lambda (x) (regexp-quote
12432 (char-to-string (car x))))
12433 table "\\|")))
12434 (while (string-match re text)
12435 (setq text
12436 (replace-match
12437 (cdr (assoc (string-to-char (match-string 0 text))
12438 table))
12439 t t text)))
12440 text)))
12442 (defun org-link-unescape (text &optional table)
12443 "Reverse the action of `org-link-escape'."
12444 (setq table (or table org-link-escape-chars))
12445 (when text
12446 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12447 table "\\|")))
12448 (while (string-match re text)
12449 (setq text
12450 (replace-match
12451 (char-to-string (car (rassoc (match-string 0 text) table)))
12452 t t text)))
12453 text)))
12455 (defun org-xor (a b)
12456 "Exclusive or."
12457 (if a (not b) b))
12459 (defun org-get-header (header)
12460 "Find a header field in the current buffer."
12461 (save-excursion
12462 (goto-char (point-min))
12463 (let ((case-fold-search t) s)
12464 (cond
12465 ((eq header 'from)
12466 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12467 (setq s (match-string 1)))
12468 (while (string-match "\"" s)
12469 (setq s (replace-match "" t t s)))
12470 (if (string-match "[<(].*" s)
12471 (setq s (replace-match "" t t s))))
12472 ((eq header 'message-id)
12473 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12474 (setq s (match-string 1))))
12475 ((eq header 'subject)
12476 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12477 (setq s (match-string 1)))))
12478 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12479 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12480 s)))
12483 (defun org-fixup-message-id-for-http (s)
12484 "Replace special characters in a message id, so it can be used in an http query."
12485 (while (string-match "<" s)
12486 (setq s (replace-match "%3C" t t s)))
12487 (while (string-match ">" s)
12488 (setq s (replace-match "%3E" t t s)))
12489 (while (string-match "@" s)
12490 (setq s (replace-match "%40" t t s)))
12493 ;;;###autoload
12494 (defun org-insert-link-global ()
12495 "Insert a link like Org-mode does.
12496 This command can be called in any mode to insert a link in Org-mode syntax."
12497 (interactive)
12498 (org-run-like-in-org-mode 'org-insert-link))
12500 (defun org-insert-link (&optional complete-file)
12501 "Insert a link. At the prompt, enter the link.
12503 Completion can be used to select a link previously stored with
12504 `org-store-link'. When the empty string is entered (i.e. if you just
12505 press RET at the prompt), the link defaults to the most recently
12506 stored link. As SPC triggers completion in the minibuffer, you need to
12507 use M-SPC or C-q SPC to force the insertion of a space character.
12509 You will also be prompted for a description, and if one is given, it will
12510 be displayed in the buffer instead of the link.
12512 If there is already a link at point, this command will allow you to edit link
12513 and description parts.
12515 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12516 selected using completion. The path to the file will be relative to
12517 the current directory if the file is in the current directory or a
12518 subdirectory. Otherwise, the link will be the absolute path as
12519 completed in the minibuffer (i.e. normally ~/path/to/file).
12521 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12522 is in the current directory or below.
12523 With three \\[universal-argument] prefixes, negate the meaning of
12524 `org-keep-stored-link-after-insertion'."
12525 (interactive "P")
12526 (let* ((wcf (current-window-configuration))
12527 (region (if (org-region-active-p)
12528 (buffer-substring (region-beginning) (region-end))))
12529 (remove (and region (list (region-beginning) (region-end))))
12530 (desc region)
12531 tmphist ; byte-compile incorrectly complains about this
12532 link entry file)
12533 (cond
12534 ((org-in-regexp org-bracket-link-regexp 1)
12535 ;; We do have a link at point, and we are going to edit it.
12536 (setq remove (list (match-beginning 0) (match-end 0)))
12537 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12538 (setq link (read-string "Link: "
12539 (org-link-unescape
12540 (org-match-string-no-properties 1)))))
12541 ((or (org-in-regexp org-angle-link-re)
12542 (org-in-regexp org-plain-link-re))
12543 ;; Convert to bracket link
12544 (setq remove (list (match-beginning 0) (match-end 0))
12545 link (read-string "Link: "
12546 (org-remove-angle-brackets (match-string 0)))))
12547 ((equal complete-file '(4))
12548 ;; Completing read for file names.
12549 (setq file (read-file-name "File: "))
12550 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12551 (pwd1 (file-name-as-directory (abbreviate-file-name
12552 (expand-file-name ".")))))
12553 (cond
12554 ((equal complete-file '(16))
12555 (setq link (org-make-link
12556 "file:"
12557 (abbreviate-file-name (expand-file-name file)))))
12558 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12559 (setq link (org-make-link "file:" (match-string 1 file))))
12560 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12561 (expand-file-name file))
12562 (setq link (org-make-link
12563 "file:" (match-string 1 (expand-file-name file)))))
12564 (t (setq link (org-make-link "file:" file))))))
12566 ;; Read link, with completion for stored links.
12567 (with-output-to-temp-buffer "*Org Links*"
12568 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12569 (when org-stored-links
12570 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12571 (princ (mapconcat
12572 (lambda (x)
12573 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12574 (reverse org-stored-links) "\n"))))
12575 (let ((cw (selected-window)))
12576 (select-window (get-buffer-window "*Org Links*"))
12577 (shrink-window-if-larger-than-buffer)
12578 (setq truncate-lines t)
12579 (select-window cw))
12580 ;; Fake a link history, containing the stored links.
12581 (setq tmphist (append (mapcar 'car org-stored-links)
12582 org-insert-link-history))
12583 (unwind-protect
12584 (setq link (org-completing-read
12585 "Link: "
12586 (append
12587 (mapcar (lambda (x) (list (concat (car x) ":")))
12588 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12589 (mapcar (lambda (x) (list (concat x ":")))
12590 org-link-types))
12591 nil nil nil
12592 'tmphist
12593 (or (car (car org-stored-links)))))
12594 (set-window-configuration wcf)
12595 (kill-buffer "*Org Links*"))
12596 (setq entry (assoc link org-stored-links))
12597 (or entry (push link org-insert-link-history))
12598 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12599 (not org-keep-stored-link-after-insertion))
12600 (setq org-stored-links (delq (assoc link org-stored-links)
12601 org-stored-links)))
12602 (setq desc (or desc (nth 1 entry)))))
12604 (if (string-match org-plain-link-re link)
12605 ;; URL-like link, normalize the use of angular brackets.
12606 (setq link (org-make-link (org-remove-angle-brackets link))))
12608 ;; Check if we are linking to the current file with a search option
12609 ;; If yes, simplify the link by using only the search option.
12610 (when (and buffer-file-name
12611 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12612 (let* ((path (match-string 1 link))
12613 (case-fold-search nil)
12614 (search (match-string 2 link)))
12615 (save-match-data
12616 (if (equal (file-truename buffer-file-name) (file-truename path))
12617 ;; We are linking to this same file, with a search option
12618 (setq link search)))))
12620 ;; Check if we can/should use a relative path. If yes, simplify the link
12621 (when (string-match "\\<file:\\(.*\\)" link)
12622 (let* ((path (match-string 1 link))
12623 (origpath path)
12624 (case-fold-search nil))
12625 (cond
12626 ((eq org-link-file-path-type 'absolute)
12627 (setq path (abbreviate-file-name (expand-file-name path))))
12628 ((eq org-link-file-path-type 'noabbrev)
12629 (setq path (expand-file-name path)))
12630 ((eq org-link-file-path-type 'relative)
12631 (setq path (file-relative-name path)))
12633 (save-match-data
12634 (if (string-match (concat "^" (regexp-quote
12635 (file-name-as-directory
12636 (expand-file-name "."))))
12637 (expand-file-name path))
12638 ;; We are linking a file with relative path name.
12639 (setq path (substring (expand-file-name path)
12640 (match-end 0)))))))
12641 (setq link (concat "file:" path))
12642 (if (equal desc origpath)
12643 (setq desc path))))
12645 (setq desc (read-string "Description: " desc))
12646 (unless (string-match "\\S-" desc) (setq desc nil))
12647 (if remove (apply 'delete-region remove))
12648 (insert (org-make-link-string link desc))))
12650 (defun org-completing-read (&rest args)
12651 (let ((minibuffer-local-completion-map
12652 (copy-keymap minibuffer-local-completion-map)))
12653 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12654 (apply 'completing-read args)))
12656 ;;; Opening/following a link
12657 (defvar org-link-search-failed nil)
12659 (defun org-next-link ()
12660 "Move forward to the next link.
12661 If the link is in hidden text, expose it."
12662 (interactive)
12663 (when (and org-link-search-failed (eq this-command last-command))
12664 (goto-char (point-min))
12665 (message "Link search wrapped back to beginning of buffer"))
12666 (setq org-link-search-failed nil)
12667 (let* ((pos (point))
12668 (ct (org-context))
12669 (a (assoc :link ct)))
12670 (if a (goto-char (nth 2 a)))
12671 (if (re-search-forward org-any-link-re nil t)
12672 (progn
12673 (goto-char (match-beginning 0))
12674 (if (org-invisible-p) (org-show-context)))
12675 (goto-char pos)
12676 (setq org-link-search-failed t)
12677 (error "No further link found"))))
12679 (defun org-previous-link ()
12680 "Move backward to the previous link.
12681 If the link is in hidden text, expose it."
12682 (interactive)
12683 (when (and org-link-search-failed (eq this-command last-command))
12684 (goto-char (point-max))
12685 (message "Link search wrapped back to end of buffer"))
12686 (setq org-link-search-failed nil)
12687 (let* ((pos (point))
12688 (ct (org-context))
12689 (a (assoc :link ct)))
12690 (if a (goto-char (nth 1 a)))
12691 (if (re-search-backward org-any-link-re nil t)
12692 (progn
12693 (goto-char (match-beginning 0))
12694 (if (org-invisible-p) (org-show-context)))
12695 (goto-char pos)
12696 (setq org-link-search-failed t)
12697 (error "No further link found"))))
12699 (defun org-find-file-at-mouse (ev)
12700 "Open file link or URL at mouse."
12701 (interactive "e")
12702 (mouse-set-point ev)
12703 (org-open-at-point 'in-emacs))
12705 (defun org-open-at-mouse (ev)
12706 "Open file link or URL at mouse."
12707 (interactive "e")
12708 (mouse-set-point ev)
12709 (org-open-at-point))
12711 (defvar org-window-config-before-follow-link nil
12712 "The window configuration before following a link.
12713 This is saved in case the need arises to restore it.")
12715 (defvar org-open-link-marker (make-marker)
12716 "Marker pointing to the location where `org-open-at-point; was called.")
12718 ;;;###autoload
12719 (defun org-open-at-point-global ()
12720 "Follow a link like Org-mode does.
12721 This command can be called in any mode to follow a link that has
12722 Org-mode syntax."
12723 (interactive)
12724 (org-run-like-in-org-mode 'org-open-at-point))
12726 (defun org-open-at-point (&optional in-emacs)
12727 "Open link at or after point.
12728 If there is no link at point, this function will search forward up to
12729 the end of the current subtree.
12730 Normally, files will be opened by an appropriate application. If the
12731 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12732 (interactive "P")
12733 (move-marker org-open-link-marker (point))
12734 (setq org-window-config-before-follow-link (current-window-configuration))
12735 (org-remove-occur-highlights nil nil t)
12736 (if (org-at-timestamp-p t)
12737 (org-follow-timestamp-link)
12738 (let (type path link line search (pos (point)))
12739 (catch 'match
12740 (save-excursion
12741 (skip-chars-forward "^]\n\r")
12742 (when (org-in-regexp org-bracket-link-regexp)
12743 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12744 (while (string-match " *\n *" link)
12745 (setq link (replace-match " " t t link)))
12746 (setq link (org-link-expand-abbrev link))
12747 (if (string-match org-link-re-with-space2 link)
12748 (setq type (match-string 1 link) path (match-string 2 link))
12749 (setq type "thisfile" path link))
12750 (throw 'match t)))
12752 (when (get-text-property (point) 'org-linked-text)
12753 (setq type "thisfile"
12754 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12755 (1+ (point)) (point))
12756 path (buffer-substring
12757 (previous-single-property-change pos 'org-linked-text)
12758 (next-single-property-change pos 'org-linked-text)))
12759 (throw 'match t))
12761 (save-excursion
12762 (when (or (org-in-regexp org-angle-link-re)
12763 (org-in-regexp org-plain-link-re))
12764 (setq type (match-string 1) path (match-string 2))
12765 (throw 'match t)))
12766 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12767 (setq type "tree-match"
12768 path (match-string 1))
12769 (throw 'match t))
12770 (save-excursion
12771 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12772 (setq type "tags"
12773 path (match-string 1))
12774 (while (string-match ":" path)
12775 (setq path (replace-match "+" t t path)))
12776 (throw 'match t))))
12777 (unless path
12778 (error "No link found"))
12779 ;; Remove any trailing spaces in path
12780 (if (string-match " +\\'" path)
12781 (setq path (replace-match "" t t path)))
12783 (cond
12785 ((assoc type org-link-protocols)
12786 (funcall (nth 1 (assoc type org-link-protocols)) path))
12788 ((equal type "mailto")
12789 (let ((cmd (car org-link-mailto-program))
12790 (args (cdr org-link-mailto-program)) args1
12791 (address path) (subject "") a)
12792 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12793 (setq address (match-string 1 path)
12794 subject (org-link-escape (match-string 2 path))))
12795 (while args
12796 (cond
12797 ((not (stringp (car args))) (push (pop args) args1))
12798 (t (setq a (pop args))
12799 (if (string-match "%a" a)
12800 (setq a (replace-match address t t a)))
12801 (if (string-match "%s" a)
12802 (setq a (replace-match subject t t a)))
12803 (push a args1))))
12804 (apply cmd (nreverse args1))))
12806 ((member type '("http" "https" "ftp" "news"))
12807 (browse-url (concat type ":" (org-link-escape
12808 path org-link-escape-chars-browser))))
12810 ((member type '("message"))
12811 (browse-url (concat type ":" path)))
12813 ((string= type "tags")
12814 (org-tags-view in-emacs path))
12815 ((string= type "thisfile")
12816 (if in-emacs
12817 (switch-to-buffer-other-window
12818 (org-get-buffer-for-internal-link (current-buffer)))
12819 (org-mark-ring-push))
12820 (let ((cmd `(org-link-search
12821 ,path
12822 ,(cond ((equal in-emacs '(4)) 'occur)
12823 ((equal in-emacs '(16)) 'org-occur)
12824 (t nil))
12825 ,pos)))
12826 (condition-case nil (eval cmd)
12827 (error (progn (widen) (eval cmd))))))
12829 ((string= type "tree-match")
12830 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12832 ((string= type "file")
12833 (if (string-match "::\\([0-9]+\\)\\'" path)
12834 (setq line (string-to-number (match-string 1 path))
12835 path (substring path 0 (match-beginning 0)))
12836 (if (string-match "::\\(.+\\)\\'" path)
12837 (setq search (match-string 1 path)
12838 path (substring path 0 (match-beginning 0)))))
12839 (if (string-match "[*?{]" (file-name-nondirectory path))
12840 (dired path)
12841 (org-open-file path in-emacs line search)))
12843 ((string= type "news")
12844 (org-follow-gnus-link path))
12846 ((string= type "bbdb")
12847 (org-follow-bbdb-link path))
12849 ((string= type "info")
12850 (org-follow-info-link path))
12852 ((string= type "gnus")
12853 (let (group article)
12854 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12855 (error "Error in Gnus link"))
12856 (setq group (match-string 1 path)
12857 article (match-string 3 path))
12858 (org-follow-gnus-link group article)))
12860 ((string= type "vm")
12861 (let (folder article)
12862 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12863 (error "Error in VM link"))
12864 (setq folder (match-string 1 path)
12865 article (match-string 3 path))
12866 ;; in-emacs is the prefix arg, will be interpreted as read-only
12867 (org-follow-vm-link folder article in-emacs)))
12869 ((string= type "wl")
12870 (let (folder article)
12871 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12872 (error "Error in Wanderlust link"))
12873 (setq folder (match-string 1 path)
12874 article (match-string 3 path))
12875 (org-follow-wl-link folder article)))
12877 ((string= type "mhe")
12878 (let (folder article)
12879 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12880 (error "Error in MHE link"))
12881 (setq folder (match-string 1 path)
12882 article (match-string 3 path))
12883 (org-follow-mhe-link folder article)))
12885 ((string= type "rmail")
12886 (let (folder article)
12887 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12888 (error "Error in RMAIL link"))
12889 (setq folder (match-string 1 path)
12890 article (match-string 3 path))
12891 (org-follow-rmail-link folder article)))
12893 ((string= type "shell")
12894 (let ((cmd path))
12895 (if (or (not org-confirm-shell-link-function)
12896 (funcall org-confirm-shell-link-function
12897 (format "Execute \"%s\" in shell? "
12898 (org-add-props cmd nil
12899 'face 'org-warning))))
12900 (progn
12901 (message "Executing %s" cmd)
12902 (shell-command cmd))
12903 (error "Abort"))))
12905 ((string= type "elisp")
12906 (let ((cmd path))
12907 (if (or (not org-confirm-elisp-link-function)
12908 (funcall org-confirm-elisp-link-function
12909 (format "Execute \"%s\" as elisp? "
12910 (org-add-props cmd nil
12911 'face 'org-warning))))
12912 (message "%s => %s" cmd (eval (read cmd)))
12913 (error "Abort"))))
12916 (browse-url-at-point)))))
12917 (move-marker org-open-link-marker nil))
12919 ;;; File search
12921 (defvar org-create-file-search-functions nil
12922 "List of functions to construct the right search string for a file link.
12923 These functions are called in turn with point at the location to
12924 which the link should point.
12926 A function in the hook should first test if it would like to
12927 handle this file type, for example by checking the major-mode or
12928 the file extension. If it decides not to handle this file, it
12929 should just return nil to give other functions a chance. If it
12930 does handle the file, it must return the search string to be used
12931 when following the link. The search string will be part of the
12932 file link, given after a double colon, and `org-open-at-point'
12933 will automatically search for it. If special measures must be
12934 taken to make the search successful, another function should be
12935 added to the companion hook `org-execute-file-search-functions',
12936 which see.
12938 A function in this hook may also use `setq' to set the variable
12939 `description' to provide a suggestion for the descriptive text to
12940 be used for this link when it gets inserted into an Org-mode
12941 buffer with \\[org-insert-link].")
12943 (defvar org-execute-file-search-functions nil
12944 "List of functions to execute a file search triggered by a link.
12946 Functions added to this hook must accept a single argument, the
12947 search string that was part of the file link, the part after the
12948 double colon. The function must first check if it would like to
12949 handle this search, for example by checking the major-mode or the
12950 file extension. If it decides not to handle this search, it
12951 should just return nil to give other functions a chance. If it
12952 does handle the search, it must return a non-nil value to keep
12953 other functions from trying.
12955 Each function can access the current prefix argument through the
12956 variable `current-prefix-argument'. Note that a single prefix is
12957 used to force opening a link in Emacs, so it may be good to only
12958 use a numeric or double prefix to guide the search function.
12960 In case this is needed, a function in this hook can also restore
12961 the window configuration before `org-open-at-point' was called using:
12963 (set-window-configuration org-window-config-before-follow-link)")
12965 (defun org-link-search (s &optional type avoid-pos)
12966 "Search for a link search option.
12967 If S is surrounded by forward slashes, it is interpreted as a
12968 regular expression. In org-mode files, this will create an `org-occur'
12969 sparse tree. In ordinary files, `occur' will be used to list matches.
12970 If the current buffer is in `dired-mode', grep will be used to search
12971 in all files. If AVOID-POS is given, ignore matches near that position."
12972 (let ((case-fold-search t)
12973 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12974 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12975 (append '(("") (" ") ("\t") ("\n"))
12976 org-emphasis-alist)
12977 "\\|") "\\)"))
12978 (pos (point))
12979 (pre "") (post "")
12980 words re0 re1 re2 re3 re4 re5 re2a reall)
12981 (cond
12982 ;; First check if there are any special
12983 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12984 ;; Now try the builtin stuff
12985 ((save-excursion
12986 (goto-char (point-min))
12987 (and
12988 (re-search-forward
12989 (concat "<<" (regexp-quote s0) ">>") nil t)
12990 (setq pos (match-beginning 0))))
12991 ;; There is an exact target for this
12992 (goto-char pos))
12993 ((string-match "^/\\(.*\\)/$" s)
12994 ;; A regular expression
12995 (cond
12996 ((org-mode-p)
12997 (org-occur (match-string 1 s)))
12998 ;;((eq major-mode 'dired-mode)
12999 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
13000 (t (org-do-occur (match-string 1 s)))))
13002 ;; A normal search strings
13003 (when (equal (string-to-char s) ?*)
13004 ;; Anchor on headlines, post may include tags.
13005 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
13006 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
13007 s (substring s 1)))
13008 (remove-text-properties
13009 0 (length s)
13010 '(face nil mouse-face nil keymap nil fontified nil) s)
13011 ;; Make a series of regular expressions to find a match
13012 (setq words (org-split-string s "[ \n\r\t]+")
13013 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
13014 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
13015 "\\)" markers)
13016 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
13017 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
13018 re1 (concat pre re2 post)
13019 re3 (concat pre re4 post)
13020 re5 (concat pre ".*" re4)
13021 re2 (concat pre re2)
13022 re2a (concat pre re2a)
13023 re4 (concat pre re4)
13024 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
13025 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
13026 re5 "\\)"
13028 (cond
13029 ((eq type 'org-occur) (org-occur reall))
13030 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
13031 (t (goto-char (point-min))
13032 (if (or (org-search-not-self 1 re0 nil t)
13033 (org-search-not-self 1 re1 nil t)
13034 (org-search-not-self 1 re2 nil t)
13035 (org-search-not-self 1 re2a nil t)
13036 (org-search-not-self 1 re3 nil t)
13037 (org-search-not-self 1 re4 nil t)
13038 (org-search-not-self 1 re5 nil t)
13040 (goto-char (match-beginning 1))
13041 (goto-char pos)
13042 (error "No match")))))
13044 ;; Normal string-search
13045 (goto-char (point-min))
13046 (if (search-forward s nil t)
13047 (goto-char (match-beginning 0))
13048 (error "No match"))))
13049 (and (org-mode-p) (org-show-context 'link-search))))
13051 (defun org-search-not-self (group &rest args)
13052 "Execute `re-search-forward', but only accept matches that do not
13053 enclose the position of `org-open-link-marker'."
13054 (let ((m org-open-link-marker))
13055 (catch 'exit
13056 (while (apply 're-search-forward args)
13057 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
13058 (goto-char (match-end group))
13059 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
13060 (> (match-beginning 0) (marker-position m))
13061 (< (match-end 0) (marker-position m)))
13062 (save-match-data
13063 (or (not (org-in-regexp
13064 org-bracket-link-analytic-regexp 1))
13065 (not (match-end 4)) ; no description
13066 (and (<= (match-beginning 4) (point))
13067 (>= (match-end 4) (point))))))
13068 (throw 'exit (point))))))))
13070 (defun org-get-buffer-for-internal-link (buffer)
13071 "Return a buffer to be used for displaying the link target of internal links."
13072 (cond
13073 ((not org-display-internal-link-with-indirect-buffer)
13074 buffer)
13075 ((string-match "(Clone)$" (buffer-name buffer))
13076 (message "Buffer is already a clone, not making another one")
13077 ;; we also do not modify visibility in this case
13078 buffer)
13079 (t ; make a new indirect buffer for displaying the link
13080 (let* ((bn (buffer-name buffer))
13081 (ibn (concat bn "(Clone)"))
13082 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13083 (with-current-buffer ib (org-overview))
13084 ib))))
13086 (defun org-do-occur (regexp &optional cleanup)
13087 "Call the Emacs command `occur'.
13088 If CLEANUP is non-nil, remove the printout of the regular expression
13089 in the *Occur* buffer. This is useful if the regex is long and not useful
13090 to read."
13091 (occur regexp)
13092 (when cleanup
13093 (let ((cwin (selected-window)) win beg end)
13094 (when (setq win (get-buffer-window "*Occur*"))
13095 (select-window win))
13096 (goto-char (point-min))
13097 (when (re-search-forward "match[a-z]+" nil t)
13098 (setq beg (match-end 0))
13099 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13100 (setq end (1- (match-beginning 0)))))
13101 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13102 (goto-char (point-min))
13103 (select-window cwin))))
13105 ;;; The mark ring for links jumps
13107 (defvar org-mark-ring nil
13108 "Mark ring for positions before jumps in Org-mode.")
13109 (defvar org-mark-ring-last-goto nil
13110 "Last position in the mark ring used to go back.")
13111 ;; Fill and close the ring
13112 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13113 (loop for i from 1 to org-mark-ring-length do
13114 (push (make-marker) org-mark-ring))
13115 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13116 org-mark-ring)
13118 (defun org-mark-ring-push (&optional pos buffer)
13119 "Put the current position or POS into the mark ring and rotate it."
13120 (interactive)
13121 (setq pos (or pos (point)))
13122 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13123 (move-marker (car org-mark-ring)
13124 (or pos (point))
13125 (or buffer (current-buffer)))
13126 (message "%s"
13127 (substitute-command-keys
13128 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13130 (defun org-mark-ring-goto (&optional n)
13131 "Jump to the previous position in the mark ring.
13132 With prefix arg N, jump back that many stored positions. When
13133 called several times in succession, walk through the entire ring.
13134 Org-mode commands jumping to a different position in the current file,
13135 or to another Org-mode file, automatically push the old position
13136 onto the ring."
13137 (interactive "p")
13138 (let (p m)
13139 (if (eq last-command this-command)
13140 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13141 (setq p org-mark-ring))
13142 (setq org-mark-ring-last-goto p)
13143 (setq m (car p))
13144 (switch-to-buffer (marker-buffer m))
13145 (goto-char m)
13146 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13148 (defun org-remove-angle-brackets (s)
13149 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13150 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13152 (defun org-add-angle-brackets (s)
13153 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13154 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13157 ;;; Following specific links
13159 (defun org-follow-timestamp-link ()
13160 (cond
13161 ((org-at-date-range-p t)
13162 (let ((org-agenda-start-on-weekday)
13163 (t1 (match-string 1))
13164 (t2 (match-string 2)))
13165 (setq t1 (time-to-days (org-time-string-to-time t1))
13166 t2 (time-to-days (org-time-string-to-time t2)))
13167 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13168 ((org-at-timestamp-p t)
13169 (org-agenda-list nil (time-to-days (org-time-string-to-time
13170 (substring (match-string 1) 0 10)))
13172 (t (error "This should not happen"))))
13175 (defun org-follow-bbdb-link (name)
13176 "Follow a BBDB link to NAME."
13177 (require 'bbdb)
13178 (let ((inhibit-redisplay (not debug-on-error))
13179 (bbdb-electric-p nil))
13180 (catch 'exit
13181 ;; Exact match on name
13182 (bbdb-name (concat "\\`" name "\\'") nil)
13183 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13184 ;; Exact match on name
13185 (bbdb-company (concat "\\`" name "\\'") nil)
13186 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13187 ;; Partial match on name
13188 (bbdb-name name nil)
13189 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13190 ;; Partial match on company
13191 (bbdb-company name nil)
13192 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13193 ;; General match including network address and notes
13194 (bbdb name nil)
13195 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13196 (delete-window (get-buffer-window "*BBDB*"))
13197 (error "No matching BBDB record")))))
13199 (defun org-follow-info-link (name)
13200 "Follow an info file & node link to NAME."
13201 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13202 (string-match "\\(.*\\)" name))
13203 (progn
13204 (require 'info)
13205 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13206 (Info-find-node (match-string 1 name) (match-string 2 name))
13207 (Info-find-node (match-string 1 name) "Top")))
13208 (message "Could not open: %s" name)))
13210 (defun org-follow-gnus-link (&optional group article)
13211 "Follow a Gnus link to GROUP and ARTICLE."
13212 (require 'gnus)
13213 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13214 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13215 (cond ((and group article)
13216 (gnus-group-read-group 1 nil group)
13217 (gnus-summary-goto-article (string-to-number article) nil t))
13218 (group (gnus-group-jump-to-group group))))
13220 (defun org-follow-vm-link (&optional folder article readonly)
13221 "Follow a VM link to FOLDER and ARTICLE."
13222 (require 'vm)
13223 (setq article (org-add-angle-brackets article))
13224 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13225 ;; ange-ftp or efs or tramp access
13226 (let ((user (or (match-string 1 folder) (user-login-name)))
13227 (host (match-string 2 folder))
13228 (file (match-string 3 folder)))
13229 (cond
13230 ((featurep 'tramp)
13231 ;; use tramp to access the file
13232 (if (featurep 'xemacs)
13233 (setq folder (format "[%s@%s]%s" user host file))
13234 (setq folder (format "/%s@%s:%s" user host file))))
13236 ;; use ange-ftp or efs
13237 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13238 (setq folder (format "/%s@%s:%s" user host file))))))
13239 (when folder
13240 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13241 (sit-for 0.1)
13242 (when article
13243 (vm-select-folder-buffer)
13244 (widen)
13245 (let ((case-fold-search t))
13246 (goto-char (point-min))
13247 (if (not (re-search-forward
13248 (concat "^" "message-id: *" (regexp-quote article))))
13249 (error "Could not find the specified message in this folder"))
13250 (vm-isearch-update)
13251 (vm-isearch-narrow)
13252 (vm-beginning-of-message)
13253 (vm-summarize)))))
13255 (defun org-follow-wl-link (folder article)
13256 "Follow a Wanderlust link to FOLDER and ARTICLE."
13257 (if (and (string= folder "%")
13258 article
13259 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13260 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13261 ;; Thus, we recompose folder and article ids.
13262 (setq folder (format "%s#%s" folder (match-string 1 article))
13263 article (match-string 3 article)))
13264 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13265 (error "No such folder: %s" folder))
13266 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13267 (and article
13268 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13269 (wl-summary-redisplay)))
13271 (defun org-follow-rmail-link (folder article)
13272 "Follow an RMAIL link to FOLDER and ARTICLE."
13273 (setq article (org-add-angle-brackets article))
13274 (let (message-number)
13275 (save-excursion
13276 (save-window-excursion
13277 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13278 (setq message-number
13279 (save-restriction
13280 (widen)
13281 (goto-char (point-max))
13282 (if (re-search-backward
13283 (concat "^Message-ID:\\s-+" (regexp-quote
13284 (or article "")))
13285 nil t)
13286 (rmail-what-message))))))
13287 (if message-number
13288 (progn
13289 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13290 (rmail-show-message message-number)
13291 message-number)
13292 (error "Message not found"))))
13294 ;;; mh-e integration based on planner-mode
13295 (defun org-mhe-get-message-real-folder ()
13296 "Return the name of the current message real folder, so if you use
13297 sequences, it will now work."
13298 (save-excursion
13299 (let* ((folder
13300 (if (equal major-mode 'mh-folder-mode)
13301 mh-current-folder
13302 ;; Refer to the show buffer
13303 mh-show-folder-buffer))
13304 (end-index
13305 (if (boundp 'mh-index-folder)
13306 (min (length mh-index-folder) (length folder))))
13308 ;; a simple test on mh-index-data does not work, because
13309 ;; mh-index-data is always nil in a show buffer.
13310 (if (and (boundp 'mh-index-folder)
13311 (string= mh-index-folder (substring folder 0 end-index)))
13312 (if (equal major-mode 'mh-show-mode)
13313 (save-window-excursion
13314 (let (pop-up-frames)
13315 (when (buffer-live-p (get-buffer folder))
13316 (progn
13317 (pop-to-buffer folder)
13318 (org-mhe-get-message-folder-from-index)
13321 (org-mhe-get-message-folder-from-index)
13323 folder
13327 (defun org-mhe-get-message-folder-from-index ()
13328 "Returns the name of the message folder in a index folder buffer."
13329 (save-excursion
13330 (mh-index-previous-folder)
13331 (re-search-forward "^\\(+.*\\)$" nil t)
13332 (message "%s" (match-string 1))))
13334 (defun org-mhe-get-message-folder ()
13335 "Return the name of the current message folder. Be careful if you
13336 use sequences."
13337 (save-excursion
13338 (if (equal major-mode 'mh-folder-mode)
13339 mh-current-folder
13340 ;; Refer to the show buffer
13341 mh-show-folder-buffer)))
13343 (defun org-mhe-get-message-num ()
13344 "Return the number of the current message. Be careful if you
13345 use sequences."
13346 (save-excursion
13347 (if (equal major-mode 'mh-folder-mode)
13348 (mh-get-msg-num nil)
13349 ;; Refer to the show buffer
13350 (mh-show-buffer-message-number))))
13352 (defun org-mhe-get-header (header)
13353 "Return a header of the message in folder mode. This will create a
13354 show buffer for the corresponding message. If you have a more clever
13355 idea..."
13356 (let* ((folder (org-mhe-get-message-folder))
13357 (num (org-mhe-get-message-num))
13358 (buffer (get-buffer-create (concat "show-" folder)))
13359 (header-field))
13360 (with-current-buffer buffer
13361 (mh-display-msg num folder)
13362 (if (equal major-mode 'mh-folder-mode)
13363 (mh-header-display)
13364 (mh-show-header-display))
13365 (set-buffer buffer)
13366 (setq header-field (mh-get-header-field header))
13367 (if (equal major-mode 'mh-folder-mode)
13368 (mh-show)
13369 (mh-show-show))
13370 header-field)))
13372 (defun org-follow-mhe-link (folder article)
13373 "Follow an MHE link to FOLDER and ARTICLE.
13374 If ARTICLE is nil FOLDER is shown. If the configuration variable
13375 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13376 ARTICLE is searched in all folders. Indexed searches (swish++,
13377 namazu, and others supported by MH-E) will always search in all
13378 folders."
13379 (require 'mh-e)
13380 (require 'mh-search)
13381 (require 'mh-utils)
13382 (mh-find-path)
13383 (if (not article)
13384 (mh-visit-folder (mh-normalize-folder-name folder))
13385 (setq article (org-add-angle-brackets article))
13386 (mh-search-choose)
13387 (if (equal mh-searcher 'pick)
13388 (progn
13389 (mh-search folder (list "--message-id" article))
13390 (when (and org-mhe-search-all-folders
13391 (not (org-mhe-get-message-real-folder)))
13392 (kill-this-buffer)
13393 (mh-search "+" (list "--message-id" article))))
13394 (mh-search "+" article))
13395 (if (org-mhe-get-message-real-folder)
13396 (mh-show-msg 1)
13397 (kill-this-buffer)
13398 (error "Message not found"))))
13400 ;;; BibTeX links
13402 ;; Use the custom search meachnism to construct and use search strings for
13403 ;; file links to BibTeX database entries.
13405 (defun org-create-file-search-in-bibtex ()
13406 "Create the search string and description for a BibTeX database entry."
13407 (when (eq major-mode 'bibtex-mode)
13408 ;; yes, we want to construct this search string.
13409 ;; Make a good description for this entry, using names, year and the title
13410 ;; Put it into the `description' variable which is dynamically scoped.
13411 (let ((bibtex-autokey-names 1)
13412 (bibtex-autokey-names-stretch 1)
13413 (bibtex-autokey-name-case-convert-function 'identity)
13414 (bibtex-autokey-name-separator " & ")
13415 (bibtex-autokey-additional-names " et al.")
13416 (bibtex-autokey-year-length 4)
13417 (bibtex-autokey-name-year-separator " ")
13418 (bibtex-autokey-titlewords 3)
13419 (bibtex-autokey-titleword-separator " ")
13420 (bibtex-autokey-titleword-case-convert-function 'identity)
13421 (bibtex-autokey-titleword-length 'infty)
13422 (bibtex-autokey-year-title-separator ": "))
13423 (setq description (bibtex-generate-autokey)))
13424 ;; Now parse the entry, get the key and return it.
13425 (save-excursion
13426 (bibtex-beginning-of-entry)
13427 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13429 (defun org-execute-file-search-in-bibtex (s)
13430 "Find the link search string S as a key for a database entry."
13431 (when (eq major-mode 'bibtex-mode)
13432 ;; Yes, we want to do the search in this file.
13433 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13434 (goto-char (point-min))
13435 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13436 (regexp-quote s) "[ \t\n]*,") nil t)
13437 (goto-char (match-beginning 0)))
13438 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13439 ;; Use double prefix to indicate that any web link should be browsed
13440 (let ((b (current-buffer)) (p (point)))
13441 ;; Restore the window configuration because we just use the web link
13442 (set-window-configuration org-window-config-before-follow-link)
13443 (save-excursion (set-buffer b) (goto-char p)
13444 (bibtex-url)))
13445 (recenter 0)) ; Move entry start to beginning of window
13446 ;; return t to indicate that the search is done.
13449 ;; Finally add the functions to the right hooks.
13450 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13451 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13453 ;; end of Bibtex link setup
13455 ;;; Following file links
13457 (defun org-open-file (path &optional in-emacs line search)
13458 "Open the file at PATH.
13459 First, this expands any special file name abbreviations. Then the
13460 configuration variable `org-file-apps' is checked if it contains an
13461 entry for this file type, and if yes, the corresponding command is launched.
13462 If no application is found, Emacs simply visits the file.
13463 With optional argument IN-EMACS, Emacs will visit the file.
13464 Optional LINE specifies a line to go to, optional SEARCH a string to
13465 search for. If LINE or SEARCH is given, the file will always be
13466 opened in Emacs.
13467 If the file does not exist, an error is thrown."
13468 (setq in-emacs (or in-emacs line search))
13469 (let* ((file (if (equal path "")
13470 buffer-file-name
13471 (substitute-in-file-name (expand-file-name path))))
13472 (apps (append org-file-apps (org-default-apps)))
13473 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13474 (dirp (if remp nil (file-directory-p file)))
13475 (dfile (downcase file))
13476 (old-buffer (current-buffer))
13477 (old-pos (point))
13478 (old-mode major-mode)
13479 ext cmd)
13480 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13481 (setq ext (match-string 1 dfile))
13482 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13483 (setq ext (match-string 1 dfile))))
13484 (if in-emacs
13485 (setq cmd 'emacs)
13486 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13487 (and dirp (cdr (assoc 'directory apps)))
13488 (cdr (assoc ext apps))
13489 (cdr (assoc t apps)))))
13490 (when (eq cmd 'mailcap)
13491 (require 'mailcap)
13492 (mailcap-parse-mailcaps)
13493 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13494 (command (mailcap-mime-info mime-type)))
13495 (if (stringp command)
13496 (setq cmd command)
13497 (setq cmd 'emacs))))
13498 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13499 (not (file-exists-p file))
13500 (not org-open-non-existing-files))
13501 (error "No such file: %s" file))
13502 (cond
13503 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13504 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13505 (while (string-match "['\"]%s['\"]" cmd)
13506 (setq cmd (replace-match "%s" t t cmd)))
13507 (while (string-match "%s" cmd)
13508 (setq cmd (replace-match
13509 (save-match-data (shell-quote-argument file))
13510 t t cmd)))
13511 (save-window-excursion
13512 (start-process-shell-command cmd nil cmd)))
13513 ((or (stringp cmd)
13514 (eq cmd 'emacs))
13515 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13516 (widen)
13517 (if line (goto-line line)
13518 (if search (org-link-search search))))
13519 ((consp cmd)
13520 (eval cmd))
13521 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13522 (and (org-mode-p) (eq old-mode 'org-mode)
13523 (or (not (equal old-buffer (current-buffer)))
13524 (not (equal old-pos (point))))
13525 (org-mark-ring-push old-pos old-buffer))))
13527 (defun org-default-apps ()
13528 "Return the default applications for this operating system."
13529 (cond
13530 ((eq system-type 'darwin)
13531 org-file-apps-defaults-macosx)
13532 ((eq system-type 'windows-nt)
13533 org-file-apps-defaults-windowsnt)
13534 (t org-file-apps-defaults-gnu)))
13536 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13537 (defun org-file-remote-p (file)
13538 "Test whether FILE specifies a location on a remote system.
13539 Return non-nil if the location is indeed remote.
13541 For example, the filename \"/user@host:/foo\" specifies a location
13542 on the system \"/user@host:\"."
13543 (cond ((fboundp 'file-remote-p)
13544 (file-remote-p file))
13545 ((fboundp 'tramp-handle-file-remote-p)
13546 (tramp-handle-file-remote-p file))
13547 ((and (boundp 'ange-ftp-name-format)
13548 (string-match (car ange-ftp-name-format) file))
13550 (t nil)))
13553 ;;;; Hooks for remember.el, and refiling
13555 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13556 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13558 ;;;###autoload
13559 (defun org-remember-insinuate ()
13560 "Setup remember.el for use wiht Org-mode."
13561 (require 'remember)
13562 (setq remember-annotation-functions '(org-remember-annotation))
13563 (setq remember-handler-functions '(org-remember-handler))
13564 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13566 ;;;###autoload
13567 (defun org-remember-annotation ()
13568 "Return a link to the current location as an annotation for remember.el.
13569 If you are using Org-mode files as target for data storage with
13570 remember.el, then the annotations should include a link compatible with the
13571 conventions in Org-mode. This function returns such a link."
13572 (org-store-link nil))
13574 (defconst org-remember-help
13575 "Select a destination location for the note.
13576 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13577 RET on headline -> Store as sublevel entry to current headline
13578 RET at beg-of-buf -> Append to file as level 2 headline
13579 <left>/<right> -> before/after current headline, same headings level")
13581 (defvar org-remember-previous-location nil)
13582 (defvar org-force-remember-template-char) ;; dynamically scoped
13584 (defun org-select-remember-template (&optional use-char)
13585 (when org-remember-templates
13586 (let* ((templates (mapcar (lambda (x)
13587 (if (stringp (car x))
13588 (append (list (nth 1 x) (car x)) (cddr x))
13589 (append (list (car x) "") (cdr x))))
13590 org-remember-templates))
13591 (char (or use-char
13592 (cond
13593 ((= (length templates) 1)
13594 (caar templates))
13595 ((and (boundp 'org-force-remember-template-char)
13596 org-force-remember-template-char)
13597 (if (stringp org-force-remember-template-char)
13598 (string-to-char org-force-remember-template-char)
13599 org-force-remember-template-char))
13601 (message "Select template: %s"
13602 (mapconcat
13603 (lambda (x)
13604 (cond
13605 ((not (string-match "\\S-" (nth 1 x)))
13606 (format "[%c]" (car x)))
13607 ((equal (downcase (car x))
13608 (downcase (aref (nth 1 x) 0)))
13609 (format "[%c]%s" (car x)
13610 (substring (nth 1 x) 1)))
13611 (t (format "[%c]%s" (car x) (nth 1 x)))))
13612 templates " "))
13613 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13614 (when (equal char0 ?\C-g)
13615 (jump-to-register remember-register)
13616 (kill-buffer remember-buffer))
13617 char0))))))
13618 (cddr (assoc char templates)))))
13620 (defvar x-last-selected-text)
13621 (defvar x-last-selected-text-primary)
13623 ;;;###autoload
13624 (defun org-remember-apply-template (&optional use-char skip-interactive)
13625 "Initialize *remember* buffer with template, invoke `org-mode'.
13626 This function should be placed into `remember-mode-hook' and in fact requires
13627 to be run from that hook to function properly."
13628 (if org-remember-templates
13629 (let* ((entry (org-select-remember-template use-char))
13630 (tpl (car entry))
13631 (plist-p (if org-store-link-plist t nil))
13632 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13633 (string-match "\\S-" (nth 1 entry)))
13634 (nth 1 entry)
13635 org-default-notes-file))
13636 (headline (nth 2 entry))
13637 (v-c (or (and (eq window-system 'x)
13638 (fboundp 'x-cut-buffer-or-selection-value)
13639 (x-cut-buffer-or-selection-value))
13640 (org-bound-and-true-p x-last-selected-text)
13641 (org-bound-and-true-p x-last-selected-text-primary)
13642 (and (> (length kill-ring) 0) (current-kill 0))))
13643 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13644 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13645 (v-u (concat "[" (substring v-t 1 -1) "]"))
13646 (v-U (concat "[" (substring v-T 1 -1) "]"))
13647 ;; `initial' and `annotation' are bound in `remember'
13648 (v-i (if (boundp 'initial) initial))
13649 (v-a (if (and (boundp 'annotation) annotation)
13650 (if (equal annotation "[[]]") "" annotation)
13651 ""))
13652 (v-A (if (and v-a
13653 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13654 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13655 v-a))
13656 (v-n user-full-name)
13657 (org-startup-folded nil)
13658 org-time-was-given org-end-time-was-given x
13659 prompt completions char time pos default histvar)
13660 (setq org-store-link-plist
13661 (append (list :annotation v-a :initial v-i)
13662 org-store-link-plist))
13663 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13664 (erase-buffer)
13665 (insert (substitute-command-keys
13666 (format
13667 "## Filing location: Select interactively, default, or last used:
13668 ## %s to select file and header location interactively.
13669 ## %s \"%s\" -> \"* %s\"
13670 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13671 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13672 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13673 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13674 (abbreviate-file-name (or file org-default-notes-file))
13675 (or headline "")
13676 (or (car org-remember-previous-location) "???")
13677 (or (cdr org-remember-previous-location) "???"))))
13678 (insert tpl) (goto-char (point-min))
13679 ;; Simple %-escapes
13680 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13681 (when (and initial (equal (match-string 0) "%i"))
13682 (save-match-data
13683 (let* ((lead (buffer-substring
13684 (point-at-bol) (match-beginning 0))))
13685 (setq v-i (mapconcat 'identity
13686 (org-split-string initial "\n")
13687 (concat "\n" lead))))))
13688 (replace-match
13689 (or (eval (intern (concat "v-" (match-string 1)))) "")
13690 t t))
13692 ;; %[] Insert contents of a file.
13693 (goto-char (point-min))
13694 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13695 (let ((start (match-beginning 0))
13696 (end (match-end 0))
13697 (filename (expand-file-name (match-string 1))))
13698 (goto-char start)
13699 (delete-region start end)
13700 (condition-case error
13701 (insert-file-contents filename)
13702 (error (insert (format "%%![Couldn't insert %s: %s]"
13703 filename error))))))
13704 ;; %() embedded elisp
13705 (goto-char (point-min))
13706 (while (re-search-forward "%\\((.+)\\)" nil t)
13707 (goto-char (match-beginning 0))
13708 (let ((template-start (point)))
13709 (forward-char 1)
13710 (let ((result
13711 (condition-case error
13712 (eval (read (current-buffer)))
13713 (error (format "%%![Error: %s]" error)))))
13714 (delete-region template-start (point))
13715 (insert result))))
13717 ;; From the property list
13718 (when plist-p
13719 (goto-char (point-min))
13720 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13721 (and (setq x (or (plist-get org-store-link-plist
13722 (intern (match-string 1))) ""))
13723 (replace-match x t t))))
13725 ;; Turn on org-mode in the remember buffer, set local variables
13726 (org-mode)
13727 (org-set-local 'org-finish-function 'org-remember-finalize)
13728 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13729 (org-set-local 'org-default-notes-file file))
13730 (if (and headline (stringp headline) (string-match "\\S-" headline))
13731 (org-set-local 'org-remember-default-headline headline))
13732 ;; Interactive template entries
13733 (goto-char (point-min))
13734 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13735 (setq char (if (match-end 3) (match-string 3))
13736 prompt (if (match-end 2) (match-string 2)))
13737 (goto-char (match-beginning 0))
13738 (replace-match "")
13739 (setq completions nil default nil)
13740 (when prompt
13741 (setq completions (org-split-string prompt "|")
13742 prompt (pop completions)
13743 default (car completions)
13744 histvar (intern (concat
13745 "org-remember-template-prompt-history::"
13746 (or prompt "")))
13747 completions (mapcar 'list completions)))
13748 (cond
13749 ((member char '("G" "g"))
13750 (let* ((org-last-tags-completion-table
13751 (org-global-tags-completion-table
13752 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13753 (org-add-colon-after-tag-completion t)
13754 (ins (completing-read
13755 (if prompt (concat prompt ": ") "Tags: ")
13756 'org-tags-completion-function nil nil nil
13757 'org-tags-history)))
13758 (setq ins (mapconcat 'identity
13759 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13760 ":"))
13761 (when (string-match "\\S-" ins)
13762 (or (equal (char-before) ?:) (insert ":"))
13763 (insert ins)
13764 (or (equal (char-after) ?:) (insert ":")))))
13765 (char
13766 (setq org-time-was-given (equal (upcase char) char))
13767 (setq time (org-read-date (equal (upcase char) "U") t nil
13768 prompt))
13769 (org-insert-time-stamp time org-time-was-given
13770 (member char '("u" "U"))
13771 nil nil (list org-end-time-was-given)))
13773 (insert (org-completing-read
13774 (concat (if prompt prompt "Enter string")
13775 (if default (concat " [" default "]"))
13776 ": ")
13777 completions nil nil nil histvar default)))))
13778 (goto-char (point-min))
13779 (if (re-search-forward "%\\?" nil t)
13780 (replace-match "")
13781 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13782 (org-mode)
13783 (org-set-local 'org-finish-function 'org-remember-finalize))
13784 (when (save-excursion
13785 (goto-char (point-min))
13786 (re-search-forward "%!" nil t))
13787 (replace-match "")
13788 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13790 (defun org-remember-finish-immediately ()
13791 "File remember note immediately.
13792 This should be run in `post-command-hook' and will remove itself
13793 from that hook."
13794 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13795 (when org-finish-function
13796 (funcall org-finish-function)))
13798 (defvar org-clock-marker) ; Defined below
13799 (defun org-remember-finalize ()
13800 "Finalize the remember process."
13801 (unless (fboundp 'remember-finalize)
13802 (defalias 'remember-finalize 'remember-buffer))
13803 (when (and org-clock-marker
13804 (equal (marker-buffer org-clock-marker) (current-buffer)))
13805 ;; FIXME: test this, this is w/o notetaking!
13806 (let (org-log-note-clock-out) (org-clock-out)))
13807 (when buffer-file-name
13808 (save-buffer)
13809 (setq buffer-file-name nil))
13810 (remember-finalize))
13812 ;;;###autoload
13813 (defun org-remember (&optional goto org-force-remember-template-char)
13814 "Call `remember'. If this is already a remember buffer, re-apply template.
13815 If there is an active region, make sure remember uses it as initial content
13816 of the remember buffer.
13818 When called interactively with a `C-u' prefix argument GOTO, don't remember
13819 anything, just go to the file/headline where the selected template usually
13820 stores its notes. With a double prefix arg `C-u C-u', go to the last
13821 note stored by remember.
13823 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13824 associated with a template in `org-remember-templates'."
13825 (interactive "P")
13826 (cond
13827 ((equal goto '(4)) (org-go-to-remember-target))
13828 ((equal goto '(16)) (org-remember-goto-last-stored))
13830 (if (memq org-finish-function '(remember-buffer remember-finalize))
13831 (progn
13832 (when (< (length org-remember-templates) 2)
13833 (error "No other template available"))
13834 (erase-buffer)
13835 (let ((annotation (plist-get org-store-link-plist :annotation))
13836 (initial (plist-get org-store-link-plist :initial)))
13837 (org-remember-apply-template))
13838 (message "Press C-c C-c to remember data"))
13839 (if (org-region-active-p)
13840 (remember (buffer-substring (point) (mark)))
13841 (call-interactively 'remember))))))
13843 (defun org-remember-goto-last-stored ()
13844 "Go to the location where the last remember note was stored."
13845 (interactive)
13846 (bookmark-jump "org-remember-last-stored")
13847 (message "This is the last note stored by remember"))
13849 (defun org-go-to-remember-target (&optional template-key)
13850 "Go to the target location of a remember template.
13851 The user is queried for the template."
13852 (interactive)
13853 (let* ((entry (org-select-remember-template template-key))
13854 (file (nth 1 entry))
13855 (heading (nth 2 entry))
13856 visiting)
13857 (unless (and file (stringp file) (string-match "\\S-" file))
13858 (setq file org-default-notes-file))
13859 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13860 (setq heading org-remember-default-headline))
13861 (setq visiting (org-find-base-buffer-visiting file))
13862 (if (not visiting) (find-file-noselect file))
13863 (switch-to-buffer (or visiting (get-file-buffer file)))
13864 (widen)
13865 (goto-char (point-min))
13866 (if (re-search-forward
13867 (concat "^\\*+[ \t]+" (regexp-quote heading)
13868 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13869 nil t)
13870 (goto-char (match-beginning 0))
13871 (error "Target headline not found: %s" heading))))
13873 (defvar org-note-abort nil) ; dynamically scoped
13875 ;;;###autoload
13876 (defun org-remember-handler ()
13877 "Store stuff from remember.el into an org file.
13878 First prompts for an org file. If the user just presses return, the value
13879 of `org-default-notes-file' is used.
13880 Then the command offers the headings tree of the selected file in order to
13881 file the text at a specific location.
13882 You can either immediately press RET to get the note appended to the
13883 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13884 find a better place. Then press RET or <left> or <right> in insert the note.
13886 Key Cursor position Note gets inserted
13887 -----------------------------------------------------------------------------
13888 RET buffer-start as level 1 heading at end of file
13889 RET on headline as sublevel of the heading at cursor
13890 RET no heading at cursor position, level taken from context.
13891 Or use prefix arg to specify level manually.
13892 <left> on headline as same level, before current heading
13893 <right> on headline as same level, after current heading
13895 So the fastest way to store the note is to press RET RET to append it to
13896 the default file. This way your current train of thought is not
13897 interrupted, in accordance with the principles of remember.el.
13898 You can also get the fast execution without prompting by using
13899 C-u C-c C-c to exit the remember buffer. See also the variable
13900 `org-remember-store-without-prompt'.
13902 Before being stored away, the function ensures that the text has a
13903 headline, i.e. a first line that starts with a \"*\". If not, a headline
13904 is constructed from the current date and some additional data.
13906 If the variable `org-adapt-indentation' is non-nil, the entire text is
13907 also indented so that it starts in the same column as the headline
13908 \(i.e. after the stars).
13910 See also the variable `org-reverse-note-order'."
13911 (goto-char (point-min))
13912 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13913 (replace-match ""))
13914 (goto-char (point-max))
13915 (beginning-of-line 1)
13916 (while (looking-at "[ \t]*$\\|##.*")
13917 (delete-region (1- (point)) (point-max))
13918 (beginning-of-line 1))
13919 (catch 'quit
13920 (if org-note-abort (throw 'quit nil))
13921 (let* ((txt (buffer-substring (point-min) (point-max)))
13922 (fastp (org-xor (equal current-prefix-arg '(4))
13923 org-remember-store-without-prompt))
13924 (file (cond
13925 (fastp org-default-notes-file)
13926 ((and (eq org-remember-interactive-interface 'refile)
13927 org-refile-targets)
13928 org-default-notes-file)
13929 ((not (and (equal current-prefix-arg '(16))
13930 org-remember-previous-location))
13931 (org-get-org-file))))
13932 (heading org-remember-default-headline)
13933 (visiting (and file (org-find-base-buffer-visiting file)))
13934 (org-startup-folded nil)
13935 (org-startup-align-all-tables nil)
13936 (org-goto-start-pos 1)
13937 spos exitcmd level indent reversed)
13938 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13939 (setq file (car org-remember-previous-location)
13940 heading (cdr org-remember-previous-location)
13941 fastp t))
13942 (setq current-prefix-arg nil)
13943 (if (string-match "[ \t\n]+\\'" txt)
13944 (setq txt (replace-match "" t t txt)))
13945 ;; Modify text so that it becomes a nice subtree which can be inserted
13946 ;; into an org tree.
13947 (let* ((lines (split-string txt "\n"))
13948 first)
13949 (setq first (car lines) lines (cdr lines))
13950 (if (string-match "^\\*+ " first)
13951 ;; Is already a headline
13952 (setq indent nil)
13953 ;; We need to add a headline: Use time and first buffer line
13954 (setq lines (cons first lines)
13955 first (concat "* " (current-time-string)
13956 " (" (remember-buffer-desc) ")")
13957 indent " "))
13958 (if (and org-adapt-indentation indent)
13959 (setq lines (mapcar
13960 (lambda (x)
13961 (if (string-match "\\S-" x)
13962 (concat indent x) x))
13963 lines)))
13964 (setq txt (concat first "\n"
13965 (mapconcat 'identity lines "\n"))))
13966 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13967 (setq txt (replace-match "\n\n" t t txt))
13968 (if (string-match "[ \t\n]*\\'" txt)
13969 (setq txt (replace-match "\n" t t txt))))
13970 ;; Put the modified text back into the remember buffer, for refile.
13971 (erase-buffer)
13972 (insert txt)
13973 (goto-char (point-min))
13974 (when (and (eq org-remember-interactive-interface 'refile)
13975 (not fastp))
13976 (org-refile nil (or visiting (find-file-noselect file)))
13977 (throw 'quit t))
13978 ;; Find the file
13979 (if (not visiting) (find-file-noselect file))
13980 (with-current-buffer (or visiting (get-file-buffer file))
13981 (unless (org-mode-p)
13982 (error "Target files for remember notes must be in Org-mode"))
13983 (save-excursion
13984 (save-restriction
13985 (widen)
13986 (and (goto-char (point-min))
13987 (not (re-search-forward "^\\* " nil t))
13988 (insert "\n* " (or heading "Notes") "\n"))
13989 (setq reversed (org-notes-order-reversed-p))
13991 ;; Find the default location
13992 (when (and heading (stringp heading) (string-match "\\S-" heading))
13993 (goto-char (point-min))
13994 (if (re-search-forward
13995 (concat "^\\*+[ \t]+" (regexp-quote heading)
13996 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13997 nil t)
13998 (setq org-goto-start-pos (match-beginning 0))
13999 (when fastp
14000 (goto-char (point-max))
14001 (unless (bolp) (newline))
14002 (insert "* " heading "\n")
14003 (setq org-goto-start-pos (point-at-bol 0)))))
14005 ;; Ask the User for a location, using the appropriate interface
14006 (cond
14007 (fastp (setq spos org-goto-start-pos
14008 exitcmd 'return))
14009 ((eq org-remember-interactive-interface 'outline)
14010 (setq spos (org-get-location (current-buffer)
14011 org-remember-help)
14012 exitcmd (cdr spos)
14013 spos (car spos)))
14014 ((eq org-remember-interactive-interface 'outline-path-completion)
14015 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
14016 (org-refile-use-outline-path t))
14017 (setq spos (org-refile-get-location "Heading: ")
14018 exitcmd 'return
14019 spos (nth 3 spos))))
14020 (t (error "this should not hapen")))
14021 (if (not spos) (throw 'quit nil)) ; return nil to show we did
14022 ; not handle this note
14023 (goto-char spos)
14024 (cond ((org-on-heading-p t)
14025 (org-back-to-heading t)
14026 (setq level (funcall outline-level))
14027 (cond
14028 ((eq exitcmd 'return)
14029 ;; sublevel of current
14030 (setq org-remember-previous-location
14031 (cons (abbreviate-file-name file)
14032 (org-get-heading 'notags)))
14033 (if reversed
14034 (outline-next-heading)
14035 (org-end-of-subtree t)
14036 (if (not (bolp))
14037 (if (looking-at "[ \t]*\n")
14038 (beginning-of-line 2)
14039 (end-of-line 1)
14040 (insert "\n"))))
14041 (bookmark-set "org-remember-last-stored")
14042 (org-paste-subtree (org-get-legal-level level 1) txt))
14043 ((eq exitcmd 'left)
14044 ;; before current
14045 (bookmark-set "org-remember-last-stored")
14046 (org-paste-subtree level txt))
14047 ((eq exitcmd 'right)
14048 ;; after current
14049 (org-end-of-subtree t)
14050 (bookmark-set "org-remember-last-stored")
14051 (org-paste-subtree level txt))
14052 (t (error "This should not happen"))))
14054 ((and (bobp) (not reversed))
14055 ;; Put it at the end, one level below level 1
14056 (save-restriction
14057 (widen)
14058 (goto-char (point-max))
14059 (if (not (bolp)) (newline))
14060 (bookmark-set "org-remember-last-stored")
14061 (org-paste-subtree (org-get-legal-level 1 1) txt)))
14063 ((and (bobp) reversed)
14064 ;; Put it at the start, as level 1
14065 (save-restriction
14066 (widen)
14067 (goto-char (point-min))
14068 (re-search-forward "^\\*+ " nil t)
14069 (beginning-of-line 1)
14070 (bookmark-set "org-remember-last-stored")
14071 (org-paste-subtree 1 txt)))
14073 ;; Put it right there, with automatic level determined by
14074 ;; org-paste-subtree or from prefix arg
14075 (bookmark-set "org-remember-last-stored")
14076 (org-paste-subtree
14077 (if (numberp current-prefix-arg) current-prefix-arg)
14078 txt)))
14079 (when remember-save-after-remembering
14080 (save-buffer)
14081 (if (not visiting) (kill-buffer (current-buffer)))))))))
14083 t) ;; return t to indicate that we took care of this note.
14085 (defun org-get-org-file ()
14086 "Read a filename, with default directory `org-directory'."
14087 (let ((default (or org-default-notes-file remember-data-file)))
14088 (read-file-name (format "File name [%s]: " default)
14089 (file-name-as-directory org-directory)
14090 default)))
14092 (defun org-notes-order-reversed-p ()
14093 "Check if the current file should receive notes in reversed order."
14094 (cond
14095 ((not org-reverse-note-order) nil)
14096 ((eq t org-reverse-note-order) t)
14097 ((not (listp org-reverse-note-order)) nil)
14098 (t (catch 'exit
14099 (let ((all org-reverse-note-order)
14100 entry)
14101 (while (setq entry (pop all))
14102 (if (string-match (car entry) buffer-file-name)
14103 (throw 'exit (cdr entry))))
14104 nil)))))
14106 ;;; Refiling
14108 (defvar org-refile-target-table nil
14109 "The list of refile targets, created by `org-refile'.")
14111 (defvar org-agenda-new-buffers nil
14112 "Buffers created to visit agenda files.")
14114 (defun org-get-refile-targets (&optional default-buffer)
14115 "Produce a table with refile targets."
14116 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
14117 targets txt re files f desc descre)
14118 (with-current-buffer (or default-buffer (current-buffer))
14119 (while (setq entry (pop entries))
14120 (setq files (car entry) desc (cdr entry))
14121 (cond
14122 ((null files) (setq files (list (current-buffer))))
14123 ((eq files 'org-agenda-files)
14124 (setq files (org-agenda-files 'unrestricted)))
14125 ((and (symbolp files) (fboundp files))
14126 (setq files (funcall files)))
14127 ((and (symbolp files) (boundp files))
14128 (setq files (symbol-value files))))
14129 (if (stringp files) (setq files (list files)))
14130 (cond
14131 ((eq (car desc) :tag)
14132 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
14133 ((eq (car desc) :todo)
14134 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
14135 ((eq (car desc) :regexp)
14136 (setq descre (cdr desc)))
14137 ((eq (car desc) :level)
14138 (setq descre (concat "^\\*\\{" (number-to-string
14139 (if org-odd-levels-only
14140 (1- (* 2 (cdr desc)))
14141 (cdr desc)))
14142 "\\}[ \t]")))
14143 ((eq (car desc) :maxlevel)
14144 (setq descre (concat "^\\*\\{1," (number-to-string
14145 (if org-odd-levels-only
14146 (1- (* 2 (cdr desc)))
14147 (cdr desc)))
14148 "\\}[ \t]")))
14149 (t (error "Bad refiling target description %s" desc)))
14150 (while (setq f (pop files))
14151 (save-excursion
14152 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
14153 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
14154 (save-excursion
14155 (save-restriction
14156 (widen)
14157 (goto-char (point-min))
14158 (while (re-search-forward descre nil t)
14159 (goto-char (point-at-bol))
14160 (when (looking-at org-complex-heading-regexp)
14161 (setq txt (match-string 4)
14162 re (concat "^" (regexp-quote
14163 (buffer-substring (match-beginning 1)
14164 (match-end 4)))))
14165 (if (match-end 5) (setq re (concat re "[ \t]+"
14166 (regexp-quote
14167 (match-string 5)))))
14168 (setq re (concat re "[ \t]*$"))
14169 (when org-refile-use-outline-path
14170 (setq txt (mapconcat 'identity
14171 (append
14172 (if (eq org-refile-use-outline-path 'file)
14173 (list (file-name-nondirectory
14174 (buffer-file-name (buffer-base-buffer))))
14175 (if (eq org-refile-use-outline-path 'full-file-path)
14176 (list (buffer-file-name (buffer-base-buffer)))))
14177 (org-get-outline-path)
14178 (list txt))
14179 "/")))
14180 (push (list txt f re (point)) targets))
14181 (goto-char (point-at-eol))))))))
14182 (nreverse targets))))
14184 (defun org-get-outline-path ()
14185 "Return the outline path to the current entry, as a list."
14186 (let (rtn)
14187 (save-excursion
14188 (while (org-up-heading-safe)
14189 (when (looking-at org-complex-heading-regexp)
14190 (push (org-match-string-no-properties 4) rtn)))
14191 rtn)))
14193 (defvar org-refile-history nil
14194 "History for refiling operations.")
14196 (defun org-refile (&optional goto default-buffer)
14197 "Move the entry at point to another heading.
14198 The list of target headings is compiled using the information in
14199 `org-refile-targets', which see. This list is created upon first use, and
14200 you can update it by calling this command with a double prefix (`C-u C-u').
14201 FIXME: Can we find a better way of updating?
14203 At the target location, the entry is filed as a subitem of the target heading.
14204 Depending on `org-reverse-note-order', the new subitem will either be the
14205 first of the last subitem.
14207 With prefix arg GOTO, the command will only visit the target location,
14208 not actually move anything.
14209 With a double prefix `C-c C-c', go to the location where the last refiling
14210 operation has put the subtree.
14212 With a double prefix argument, the command can be used to jump to any
14213 heading in the current buffer."
14214 (interactive "P")
14215 (let* ((cbuf (current-buffer))
14216 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14217 pos it nbuf file re level reversed)
14218 (if (equal goto '(16))
14219 (org-refile-goto-last-stored)
14220 (when (setq it (org-refile-get-location
14221 (if goto "Goto: " "Refile to: ") default-buffer))
14222 (setq file (nth 1 it)
14223 re (nth 2 it)
14224 pos (nth 3 it))
14225 (setq nbuf (or (find-buffer-visiting file)
14226 (find-file-noselect file)))
14227 (if goto
14228 (progn
14229 (switch-to-buffer nbuf)
14230 (goto-char pos)
14231 (org-show-context 'org-goto))
14232 (org-copy-special)
14233 (save-excursion
14234 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14235 (find-file-noselect file))))
14236 (setq reversed (org-notes-order-reversed-p))
14237 (save-excursion
14238 (save-restriction
14239 (widen)
14240 (goto-char pos)
14241 (looking-at outline-regexp)
14242 (setq level (org-get-legal-level (funcall outline-level) 1))
14243 (goto-char
14244 (if reversed
14245 (outline-next-heading)
14246 (or (save-excursion (outline-get-next-sibling))
14247 (org-end-of-subtree t t)
14248 (point-max))))
14249 (bookmark-set "org-refile-last-stored")
14250 (org-paste-subtree level))))
14251 (org-cut-special)
14252 (message "Entry refiled to \"%s\"" (car it)))))))
14254 (defun org-refile-goto-last-stored ()
14255 "Go to the location where the last refile was stored."
14256 (interactive)
14257 (bookmark-jump "org-refile-last-stored")
14258 (message "This is the location of the last refile"))
14260 (defun org-refile-get-location (&optional prompt default-buffer)
14261 "Prompt the user for a refile location, using PROMPT."
14262 (let ((org-refile-targets org-refile-targets)
14263 (org-refile-use-outline-path org-refile-use-outline-path))
14264 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14265 (unless org-refile-target-table
14266 (error "No refile targets"))
14267 (let* ((cbuf (current-buffer))
14268 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14269 (fname (and filename (file-truename filename)))
14270 (tbl (mapcar
14271 (lambda (x)
14272 (if (not (equal fname (file-truename (nth 1 x))))
14273 (cons (concat (car x) " (" (file-name-nondirectory
14274 (nth 1 x)) ")")
14275 (cdr x))
14277 org-refile-target-table))
14278 (completion-ignore-case t))
14279 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14280 tbl)))
14282 ;;;; Dynamic blocks
14284 (defun org-find-dblock (name)
14285 "Find the first dynamic block with name NAME in the buffer.
14286 If not found, stay at current position and return nil."
14287 (let (pos)
14288 (save-excursion
14289 (goto-char (point-min))
14290 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14291 nil t)
14292 (match-beginning 0))))
14293 (if pos (goto-char pos))
14294 pos))
14296 (defconst org-dblock-start-re
14297 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14298 "Matches the startline of a dynamic block, with parameters.")
14300 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14301 "Matches the end of a dyhamic block.")
14303 (defun org-create-dblock (plist)
14304 "Create a dynamic block section, with parameters taken from PLIST.
14305 PLIST must containe a :name entry which is used as name of the block."
14306 (unless (bolp) (newline))
14307 (let ((name (plist-get plist :name)))
14308 (insert "#+BEGIN: " name)
14309 (while plist
14310 (if (eq (car plist) :name)
14311 (setq plist (cddr plist))
14312 (insert " " (prin1-to-string (pop plist)))))
14313 (insert "\n\n#+END:\n")
14314 (beginning-of-line -2)))
14316 (defun org-prepare-dblock ()
14317 "Prepare dynamic block for refresh.
14318 This empties the block, puts the cursor at the insert position and returns
14319 the property list including an extra property :name with the block name."
14320 (unless (looking-at org-dblock-start-re)
14321 (error "Not at a dynamic block"))
14322 (let* ((begdel (1+ (match-end 0)))
14323 (name (org-no-properties (match-string 1)))
14324 (params (append (list :name name)
14325 (read (concat "(" (match-string 3) ")")))))
14326 (unless (re-search-forward org-dblock-end-re nil t)
14327 (error "Dynamic block not terminated"))
14328 (delete-region begdel (match-beginning 0))
14329 (goto-char begdel)
14330 (open-line 1)
14331 params))
14333 (defun org-map-dblocks (&optional command)
14334 "Apply COMMAND to all dynamic blocks in the current buffer.
14335 If COMMAND is not given, use `org-update-dblock'."
14336 (let ((cmd (or command 'org-update-dblock))
14337 pos)
14338 (save-excursion
14339 (goto-char (point-min))
14340 (while (re-search-forward org-dblock-start-re nil t)
14341 (goto-char (setq pos (match-beginning 0)))
14342 (condition-case nil
14343 (funcall cmd)
14344 (error (message "Error during update of dynamic block")))
14345 (goto-char pos)
14346 (unless (re-search-forward org-dblock-end-re nil t)
14347 (error "Dynamic block not terminated"))))))
14349 (defun org-dblock-update (&optional arg)
14350 "User command for updating dynamic blocks.
14351 Update the dynamic block at point. With prefix ARG, update all dynamic
14352 blocks in the buffer."
14353 (interactive "P")
14354 (if arg
14355 (org-update-all-dblocks)
14356 (or (looking-at org-dblock-start-re)
14357 (org-beginning-of-dblock))
14358 (org-update-dblock)))
14360 (defun org-update-dblock ()
14361 "Update the dynamic block at point
14362 This means to empty the block, parse for parameters and then call
14363 the correct writing function."
14364 (save-window-excursion
14365 (let* ((pos (point))
14366 (line (org-current-line))
14367 (params (org-prepare-dblock))
14368 (name (plist-get params :name))
14369 (cmd (intern (concat "org-dblock-write:" name))))
14370 (message "Updating dynamic block `%s' at line %d..." name line)
14371 (funcall cmd params)
14372 (message "Updating dynamic block `%s' at line %d...done" name line)
14373 (goto-char pos))))
14375 (defun org-beginning-of-dblock ()
14376 "Find the beginning of the dynamic block at point.
14377 Error if there is no scuh block at point."
14378 (let ((pos (point))
14379 beg)
14380 (end-of-line 1)
14381 (if (and (re-search-backward org-dblock-start-re nil t)
14382 (setq beg (match-beginning 0))
14383 (re-search-forward org-dblock-end-re nil t)
14384 (> (match-end 0) pos))
14385 (goto-char beg)
14386 (goto-char pos)
14387 (error "Not in a dynamic block"))))
14389 (defun org-update-all-dblocks ()
14390 "Update all dynamic blocks in the buffer.
14391 This function can be used in a hook."
14392 (when (org-mode-p)
14393 (org-map-dblocks 'org-update-dblock)))
14396 ;;;; Completion
14398 (defconst org-additional-option-like-keywords
14399 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14400 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14401 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14403 (defun org-complete (&optional arg)
14404 "Perform completion on word at point.
14405 At the beginning of a headline, this completes TODO keywords as given in
14406 `org-todo-keywords'.
14407 If the current word is preceded by a backslash, completes the TeX symbols
14408 that are supported for HTML support.
14409 If the current word is preceded by \"#+\", completes special words for
14410 setting file options.
14411 In the line after \"#+STARTUP:, complete valid keywords.\"
14412 At all other locations, this simply calls the value of
14413 `org-completion-fallback-command'."
14414 (interactive "P")
14415 (org-without-partial-completion
14416 (catch 'exit
14417 (let* ((end (point))
14418 (beg1 (save-excursion
14419 (skip-chars-backward (org-re "[:alnum:]_@"))
14420 (point)))
14421 (beg (save-excursion
14422 (skip-chars-backward "a-zA-Z0-9_:$")
14423 (point)))
14424 (confirm (lambda (x) (stringp (car x))))
14425 (searchhead (equal (char-before beg) ?*))
14426 (tag (and (equal (char-before beg1) ?:)
14427 (equal (char-after (point-at-bol)) ?*)))
14428 (prop (and (equal (char-before beg1) ?:)
14429 (not (equal (char-after (point-at-bol)) ?*))))
14430 (texp (equal (char-before beg) ?\\))
14431 (link (equal (char-before beg) ?\[))
14432 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14433 beg)
14434 "#+"))
14435 (startup (string-match "^#\\+STARTUP:.*"
14436 (buffer-substring (point-at-bol) (point))))
14437 (completion-ignore-case opt)
14438 (type nil)
14439 (tbl nil)
14440 (table (cond
14441 (opt
14442 (setq type :opt)
14443 (append
14444 (mapcar
14445 (lambda (x)
14446 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14447 (cons (match-string 2 x) (match-string 1 x)))
14448 (org-split-string (org-get-current-options) "\n"))
14449 (mapcar 'list org-additional-option-like-keywords)))
14450 (startup
14451 (setq type :startup)
14452 org-startup-options)
14453 (link (append org-link-abbrev-alist-local
14454 org-link-abbrev-alist))
14455 (texp
14456 (setq type :tex)
14457 org-html-entities)
14458 ((string-match "\\`\\*+[ \t]+\\'"
14459 (buffer-substring (point-at-bol) beg))
14460 (setq type :todo)
14461 (mapcar 'list org-todo-keywords-1))
14462 (searchhead
14463 (setq type :searchhead)
14464 (save-excursion
14465 (goto-char (point-min))
14466 (while (re-search-forward org-todo-line-regexp nil t)
14467 (push (list
14468 (org-make-org-heading-search-string
14469 (match-string 3) t))
14470 tbl)))
14471 tbl)
14472 (tag (setq type :tag beg beg1)
14473 (or org-tag-alist (org-get-buffer-tags)))
14474 (prop (setq type :prop beg beg1)
14475 (mapcar 'list (org-buffer-property-keys nil t t)))
14476 (t (progn
14477 (call-interactively org-completion-fallback-command)
14478 (throw 'exit nil)))))
14479 (pattern (buffer-substring-no-properties beg end))
14480 (completion (try-completion pattern table confirm)))
14481 (cond ((eq completion t)
14482 (if (not (assoc (upcase pattern) table))
14483 (message "Already complete")
14484 (if (equal type :opt)
14485 (insert (substring (cdr (assoc (upcase pattern) table))
14486 (length pattern)))
14487 (if (memq type '(:tag :prop)) (insert ":")))))
14488 ((null completion)
14489 (message "Can't find completion for \"%s\"" pattern)
14490 (ding))
14491 ((not (string= pattern completion))
14492 (delete-region beg end)
14493 (if (string-match " +$" completion)
14494 (setq completion (replace-match "" t t completion)))
14495 (insert completion)
14496 (if (get-buffer-window "*Completions*")
14497 (delete-window (get-buffer-window "*Completions*")))
14498 (if (assoc completion table)
14499 (if (eq type :todo) (insert " ")
14500 (if (memq type '(:tag :prop)) (insert ":"))))
14501 (if (and (equal type :opt) (assoc completion table))
14502 (message "%s" (substitute-command-keys
14503 "Press \\[org-complete] again to insert example settings"))))
14505 (message "Making completion list...")
14506 (let ((list (sort (all-completions pattern table confirm)
14507 'string<)))
14508 (with-output-to-temp-buffer "*Completions*"
14509 (condition-case nil
14510 ;; Protection needed for XEmacs and emacs 21
14511 (display-completion-list list pattern)
14512 (error (display-completion-list list)))))
14513 (message "Making completion list...%s" "done")))))))
14515 ;;;; TODO, DEADLINE, Comments
14517 (defun org-toggle-comment ()
14518 "Change the COMMENT state of an entry."
14519 (interactive)
14520 (save-excursion
14521 (org-back-to-heading)
14522 (let (case-fold-search)
14523 (if (looking-at (concat outline-regexp
14524 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14525 (replace-match "" t t nil 1)
14526 (if (looking-at outline-regexp)
14527 (progn
14528 (goto-char (match-end 0))
14529 (insert org-comment-string " ")))))))
14531 (defvar org-last-todo-state-is-todo nil
14532 "This is non-nil when the last TODO state change led to a TODO state.
14533 If the last change removed the TODO tag or switched to DONE, then
14534 this is nil.")
14536 (defvar org-setting-tags nil) ; dynamically skiped
14538 ;; FIXME: better place
14539 (defun org-property-or-variable-value (var &optional inherit)
14540 "Check if there is a property fixing the value of VAR.
14541 If yes, return this value. If not, return the current value of the variable."
14542 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14543 (if (and prop (stringp prop) (string-match "\\S-" prop))
14544 (read prop)
14545 (symbol-value var))))
14547 (defun org-parse-local-options (string var)
14548 "Parse STRING for startup setting relevant for variable VAR."
14549 (let ((rtn (symbol-value var))
14550 e opts)
14551 (save-match-data
14552 (if (or (not string) (not (string-match "\\S-" string)))
14554 (setq opts (delq nil (mapcar (lambda (x)
14555 (setq e (assoc x org-startup-options))
14556 (if (eq (nth 1 e) var) e nil))
14557 (org-split-string string "[ \t]+"))))
14558 (if (not opts)
14560 (setq rtn nil)
14561 (while (setq e (pop opts))
14562 (if (not (nth 3 e))
14563 (setq rtn (nth 2 e))
14564 (if (not (listp rtn)) (setq rtn nil))
14565 (push (nth 2 e) rtn)))
14566 rtn)))))
14568 (defvar org-blocker-hook nil
14569 "Hook for functions that are allowed to block a state change.
14571 Each function gets as its single argument a property list, see
14572 `org-trigger-hook' for more information about this list.
14574 If any of the functions in this hook returns nil, the state change
14575 is blocked.")
14577 (defvar org-trigger-hook nil
14578 "Hook for functions that are triggered by a state change.
14580 Each function gets as its single argument a property list with at least
14581 the following elements:
14583 (:type type-of-change :position pos-at-entry-start
14584 :from old-state :to new-state)
14586 Depending on the type, more properties may be present.
14588 This mechanism is currently implemented for:
14590 TODO state changes
14591 ------------------
14592 :type todo-state-change
14593 :from previous state (keyword as a string), or nil
14594 :to new state (keyword as a string), or nil")
14597 (defun org-todo (&optional arg)
14598 "Change the TODO state of an item.
14599 The state of an item is given by a keyword at the start of the heading,
14600 like
14601 *** TODO Write paper
14602 *** DONE Call mom
14604 The different keywords are specified in the variable `org-todo-keywords'.
14605 By default the available states are \"TODO\" and \"DONE\".
14606 So for this example: when the item starts with TODO, it is changed to DONE.
14607 When it starts with DONE, the DONE is removed. And when neither TODO nor
14608 DONE are present, add TODO at the beginning of the heading.
14610 With C-u prefix arg, use completion to determine the new state.
14611 With numeric prefix arg, switch to that state.
14613 For calling through lisp, arg is also interpreted in the following way:
14614 'none -> empty state
14615 \"\"(empty string) -> switch to empty state
14616 'done -> switch to DONE
14617 'nextset -> switch to the next set of keywords
14618 'previousset -> switch to the previous set of keywords
14619 \"WAITING\" -> switch to the specified keyword, but only if it
14620 really is a member of `org-todo-keywords'."
14621 (interactive "P")
14622 (save-excursion
14623 (catch 'exit
14624 (org-back-to-heading)
14625 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14626 (or (looking-at (concat " +" org-todo-regexp " *"))
14627 (looking-at " *"))
14628 (let* ((match-data (match-data))
14629 (startpos (point-at-bol))
14630 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14631 (org-log-done org-log-done)
14632 (org-log-repeat org-log-repeat)
14633 (org-todo-log-states org-todo-log-states)
14634 (this (match-string 1))
14635 (hl-pos (match-beginning 0))
14636 (head (org-get-todo-sequence-head this))
14637 (ass (assoc head org-todo-kwd-alist))
14638 (interpret (nth 1 ass))
14639 (done-word (nth 3 ass))
14640 (final-done-word (nth 4 ass))
14641 (last-state (or this ""))
14642 (completion-ignore-case t)
14643 (member (member this org-todo-keywords-1))
14644 (tail (cdr member))
14645 (state (cond
14646 ((and org-todo-key-trigger
14647 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14648 (and (not arg) org-use-fast-todo-selection
14649 (not (eq org-use-fast-todo-selection 'prefix)))))
14650 ;; Use fast selection
14651 (org-fast-todo-selection))
14652 ((and (equal arg '(4))
14653 (or (not org-use-fast-todo-selection)
14654 (not org-todo-key-trigger)))
14655 ;; Read a state with completion
14656 (completing-read "State: " (mapcar (lambda(x) (list x))
14657 org-todo-keywords-1)
14658 nil t))
14659 ((eq arg 'right)
14660 (if this
14661 (if tail (car tail) nil)
14662 (car org-todo-keywords-1)))
14663 ((eq arg 'left)
14664 (if (equal member org-todo-keywords-1)
14666 (if this
14667 (nth (- (length org-todo-keywords-1) (length tail) 2)
14668 org-todo-keywords-1)
14669 (org-last org-todo-keywords-1))))
14670 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14671 (setq arg nil))) ; hack to fall back to cycling
14672 (arg
14673 ;; user or caller requests a specific state
14674 (cond
14675 ((equal arg "") nil)
14676 ((eq arg 'none) nil)
14677 ((eq arg 'done) (or done-word (car org-done-keywords)))
14678 ((eq arg 'nextset)
14679 (or (car (cdr (member head org-todo-heads)))
14680 (car org-todo-heads)))
14681 ((eq arg 'previousset)
14682 (let ((org-todo-heads (reverse org-todo-heads)))
14683 (or (car (cdr (member head org-todo-heads)))
14684 (car org-todo-heads))))
14685 ((car (member arg org-todo-keywords-1)))
14686 ((nth (1- (prefix-numeric-value arg))
14687 org-todo-keywords-1))))
14688 ((null member) (or head (car org-todo-keywords-1)))
14689 ((equal this final-done-word) nil) ;; -> make empty
14690 ((null tail) nil) ;; -> first entry
14691 ((eq interpret 'sequence)
14692 (car tail))
14693 ((memq interpret '(type priority))
14694 (if (eq this-command last-command)
14695 (car tail)
14696 (if (> (length tail) 0)
14697 (or done-word (car org-done-keywords))
14698 nil)))
14699 (t nil)))
14700 (next (if state (concat " " state " ") " "))
14701 (change-plist (list :type 'todo-state-change :from this :to state
14702 :position startpos))
14703 dolog now-done-p)
14704 (when org-blocker-hook
14705 (unless (save-excursion
14706 (save-match-data
14707 (run-hook-with-args-until-failure
14708 'org-blocker-hook change-plist)))
14709 (if (interactive-p)
14710 (error "TODO state change from %s to %s blocked" this state)
14711 ;; fail silently
14712 (message "TODO state change from %s to %s blocked" this state)
14713 (throw 'exit nil))))
14714 (store-match-data match-data)
14715 (replace-match next t t)
14716 (unless (pos-visible-in-window-p hl-pos)
14717 (message "TODO state changed to %s" (org-trim next)))
14718 (unless head
14719 (setq head (org-get-todo-sequence-head state)
14720 ass (assoc head org-todo-kwd-alist)
14721 interpret (nth 1 ass)
14722 done-word (nth 3 ass)
14723 final-done-word (nth 4 ass)))
14724 (when (memq arg '(nextset previousset))
14725 (message "Keyword-Set %d/%d: %s"
14726 (- (length org-todo-sets) -1
14727 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14728 (length org-todo-sets)
14729 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14730 (setq org-last-todo-state-is-todo
14731 (not (member state org-done-keywords)))
14732 (setq now-done-p (and (member state org-done-keywords)
14733 (not (member this org-done-keywords))))
14734 (and logging (org-local-logging logging))
14735 (when (and (or org-todo-log-states org-log-done)
14736 (not (memq arg '(nextset previousset))))
14737 ;; we need to look at recording a time and note
14738 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14739 (nth 2 (assoc this org-todo-log-states))))
14740 (when (and state
14741 (member state org-not-done-keywords)
14742 (not (member this org-not-done-keywords)))
14743 ;; This is now a todo state and was not one before
14744 ;; If there was a CLOSED time stamp, get rid of it.
14745 (org-add-planning-info nil nil 'closed))
14746 (when (and now-done-p org-log-done)
14747 ;; It is now done, and it was not done before
14748 (org-add-planning-info 'closed (org-current-time))
14749 (if (and (not dolog) (eq 'note org-log-done))
14750 (org-add-log-maybe 'done state 'findpos 'note)))
14751 (when (and state dolog)
14752 ;; This is a non-nil state, and we need to log it
14753 (org-add-log-maybe 'state state 'findpos dolog)))
14754 ;; Fixup tag positioning
14755 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14756 (run-hooks 'org-after-todo-state-change-hook)
14757 (if (and arg (not (member state org-done-keywords)))
14758 (setq head (org-get-todo-sequence-head state)))
14759 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14760 ;; Do we need to trigger a repeat?
14761 (when now-done-p (org-auto-repeat-maybe state))
14762 ;; Fixup cursor location if close to the keyword
14763 (if (and (outline-on-heading-p)
14764 (not (bolp))
14765 (save-excursion (beginning-of-line 1)
14766 (looking-at org-todo-line-regexp))
14767 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14768 (progn
14769 (goto-char (or (match-end 2) (match-end 1)))
14770 (just-one-space)))
14771 (when org-trigger-hook
14772 (save-excursion
14773 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14775 (defun org-local-logging (value)
14776 "Get logging settings from a property VALUE."
14777 (let* (words w a)
14778 ;; directly set the variables, they are already local.
14779 (setq org-log-done nil
14780 org-log-repeat nil
14781 org-todo-log-states nil)
14782 (setq words (org-split-string value))
14783 (while (setq w (pop words))
14784 (cond
14785 ((setq a (assoc w org-startup-options))
14786 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14787 (set (nth 1 a) (nth 2 a))))
14788 ((setq a (org-extract-log-state-settings w))
14789 (and (member (car a) org-todo-keywords-1)
14790 (push a org-todo-log-states)))))))
14792 (defun org-get-todo-sequence-head (kwd)
14793 "Return the head of the TODO sequence to which KWD belongs.
14794 If KWD is not set, check if there is a text property remembering the
14795 right sequence."
14796 (let (p)
14797 (cond
14798 ((not kwd)
14799 (or (get-text-property (point-at-bol) 'org-todo-head)
14800 (progn
14801 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14802 nil (point-at-eol)))
14803 (get-text-property p 'org-todo-head))))
14804 ((not (member kwd org-todo-keywords-1))
14805 (car org-todo-keywords-1))
14806 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14808 (defun org-fast-todo-selection ()
14809 "Fast TODO keyword selection with single keys.
14810 Returns the new TODO keyword, or nil if no state change should occur."
14811 (let* ((fulltable org-todo-key-alist)
14812 (done-keywords org-done-keywords) ;; needed for the faces.
14813 (maxlen (apply 'max (mapcar
14814 (lambda (x)
14815 (if (stringp (car x)) (string-width (car x)) 0))
14816 fulltable)))
14817 (expert nil)
14818 (fwidth (+ maxlen 3 1 3))
14819 (ncol (/ (- (window-width) 4) fwidth))
14820 tg cnt e c tbl
14821 groups ingroup)
14822 (save-window-excursion
14823 (if expert
14824 (set-buffer (get-buffer-create " *Org todo*"))
14825 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14826 (erase-buffer)
14827 (org-set-local 'org-done-keywords done-keywords)
14828 (setq tbl fulltable cnt 0)
14829 (while (setq e (pop tbl))
14830 (cond
14831 ((equal e '(:startgroup))
14832 (push '() groups) (setq ingroup t)
14833 (when (not (= cnt 0))
14834 (setq cnt 0)
14835 (insert "\n"))
14836 (insert "{ "))
14837 ((equal e '(:endgroup))
14838 (setq ingroup nil cnt 0)
14839 (insert "}\n"))
14841 (setq tg (car e) c (cdr e))
14842 (if ingroup (push tg (car groups)))
14843 (setq tg (org-add-props tg nil 'face
14844 (org-get-todo-face tg)))
14845 (if (and (= cnt 0) (not ingroup)) (insert " "))
14846 (insert "[" c "] " tg (make-string
14847 (- fwidth 4 (length tg)) ?\ ))
14848 (when (= (setq cnt (1+ cnt)) ncol)
14849 (insert "\n")
14850 (if ingroup (insert " "))
14851 (setq cnt 0)))))
14852 (insert "\n")
14853 (goto-char (point-min))
14854 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14855 (fit-window-to-buffer))
14856 (message "[a-z..]:Set [SPC]:clear")
14857 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14858 (cond
14859 ((or (= c ?\C-g)
14860 (and (= c ?q) (not (rassoc c fulltable))))
14861 (setq quit-flag t))
14862 ((= c ?\ ) nil)
14863 ((setq e (rassoc c fulltable) tg (car e))
14865 (t (setq quit-flag t))))))
14867 (defun org-get-repeat ()
14868 "Check if tere is a deadline/schedule with repeater in this entry."
14869 (save-match-data
14870 (save-excursion
14871 (org-back-to-heading t)
14872 (if (re-search-forward
14873 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14874 (match-string 1)))))
14876 (defvar org-last-changed-timestamp)
14877 (defvar org-log-post-message)
14878 (defvar org-log-note-purpose)
14879 (defun org-auto-repeat-maybe (done-word)
14880 "Check if the current headline contains a repeated deadline/schedule.
14881 If yes, set TODO state back to what it was and change the base date
14882 of repeating deadline/scheduled time stamps to new date.
14883 This function is run automatically after each state change to a DONE state."
14884 ;; last-state is dynamically scoped into this function
14885 (let* ((repeat (org-get-repeat))
14886 (aa (assoc last-state org-todo-kwd-alist))
14887 (interpret (nth 1 aa))
14888 (head (nth 2 aa))
14889 (whata '(("d" . day) ("m" . month) ("y" . year)))
14890 (msg "Entry repeats: ")
14891 (org-log-done nil)
14892 (org-todo-log-states nil)
14893 re type n what ts)
14894 (when repeat
14895 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
14896 (org-todo (if (eq interpret 'type) last-state head))
14897 (when (and org-log-repeat
14898 (or (not (memq 'org-add-log-note
14899 (default-value 'post-command-hook)))
14900 (eq org-log-note-purpose 'done)))
14901 ;; Make sure a note is taken;
14902 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
14903 'findpos org-log-repeat))
14904 (org-back-to-heading t)
14905 (org-add-planning-info nil nil 'closed)
14906 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14907 org-deadline-time-regexp "\\)\\|\\("
14908 org-ts-regexp "\\)"))
14909 (while (re-search-forward
14910 re (save-excursion (outline-next-heading) (point)) t)
14911 (setq type (if (match-end 1) org-scheduled-string
14912 (if (match-end 3) org-deadline-string "Plain:"))
14913 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14914 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14915 (setq n (string-to-number (match-string 1 ts))
14916 what (match-string 2 ts))
14917 (if (equal what "w") (setq n (* n 7) what "d"))
14918 (org-timestamp-change n (cdr (assoc what whata)))
14919 (setq msg (concat msg type org-last-changed-timestamp " "))))
14920 (setq org-log-post-message msg)
14921 (message "%s" msg))))
14923 (defun org-show-todo-tree (arg)
14924 "Make a compact tree which shows all headlines marked with TODO.
14925 The tree will show the lines where the regexp matches, and all higher
14926 headlines above the match.
14927 With a \\[universal-argument] prefix, also show the DONE entries.
14928 With a numeric prefix N, construct a sparse tree for the Nth element
14929 of `org-todo-keywords-1'."
14930 (interactive "P")
14931 (let ((case-fold-search nil)
14932 (kwd-re
14933 (cond ((null arg) org-not-done-regexp)
14934 ((equal arg '(4))
14935 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14936 (mapcar 'list org-todo-keywords-1))))
14937 (concat "\\("
14938 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14939 "\\)\\>")))
14940 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14941 (regexp-quote (nth (1- (prefix-numeric-value arg))
14942 org-todo-keywords-1)))
14943 (t (error "Invalid prefix argument: %s" arg)))))
14944 (message "%d TODO entries found"
14945 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14947 (defun org-deadline (&optional remove)
14948 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14949 With argument REMOVE, remove any deadline from the item."
14950 (interactive "P")
14951 (if remove
14952 (progn
14953 (org-remove-timestamp-with-keyword org-deadline-string)
14954 (message "Item no longer has a deadline."))
14955 (org-add-planning-info 'deadline nil 'closed)))
14957 (defun org-schedule (&optional remove)
14958 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14959 With argument REMOVE, remove any scheduling date from the item."
14960 (interactive "P")
14961 (if remove
14962 (progn
14963 (org-remove-timestamp-with-keyword org-scheduled-string)
14964 (message "Item is no longer scheduled."))
14965 (org-add-planning-info 'scheduled nil 'closed)))
14967 (defun org-remove-timestamp-with-keyword (keyword)
14968 "Remove all time stamps with KEYWORD in the current entry."
14969 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14970 beg)
14971 (save-excursion
14972 (org-back-to-heading t)
14973 (setq beg (point))
14974 (org-end-of-subtree t t)
14975 (while (re-search-backward re beg t)
14976 (replace-match "")
14977 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14978 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14980 (defun org-add-planning-info (what &optional time &rest remove)
14981 "Insert new timestamp with keyword in the line directly after the headline.
14982 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14983 If non is given, the user is prompted for a date.
14984 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14985 be removed."
14986 (interactive)
14987 (let (org-time-was-given org-end-time-was-given)
14988 (when what (setq time (or time (org-read-date nil 'to-time))))
14989 (when (and org-insert-labeled-timestamps-at-point
14990 (member what '(scheduled deadline)))
14991 (insert
14992 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14993 (org-insert-time-stamp time org-time-was-given
14994 nil nil nil (list org-end-time-was-given))
14995 (setq what nil))
14996 (save-excursion
14997 (save-restriction
14998 (let (col list elt ts buffer-invisibility-spec)
14999 (org-back-to-heading t)
15000 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
15001 (goto-char (match-end 1))
15002 (setq col (current-column))
15003 (goto-char (match-end 0))
15004 (if (eobp) (insert "\n") (forward-char 1))
15005 (if (and (not (looking-at outline-regexp))
15006 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
15007 "[^\r\n]*"))
15008 (not (equal (match-string 1) org-clock-string)))
15009 (narrow-to-region (match-beginning 0) (match-end 0))
15010 (insert-before-markers "\n")
15011 (backward-char 1)
15012 (narrow-to-region (point) (point))
15013 (indent-to-column col))
15014 ;; Check if we have to remove something.
15015 (setq list (cons what remove))
15016 (while list
15017 (setq elt (pop list))
15018 (goto-char (point-min))
15019 (when (or (and (eq elt 'scheduled)
15020 (re-search-forward org-scheduled-time-regexp nil t))
15021 (and (eq elt 'deadline)
15022 (re-search-forward org-deadline-time-regexp nil t))
15023 (and (eq elt 'closed)
15024 (re-search-forward org-closed-time-regexp nil t)))
15025 (replace-match "")
15026 (if (looking-at "--+<[^>]+>") (replace-match ""))
15027 (if (looking-at " +") (replace-match ""))))
15028 (goto-char (point-max))
15029 (when what
15030 (insert
15031 (if (not (equal (char-before) ?\ )) " " "")
15032 (cond ((eq what 'scheduled) org-scheduled-string)
15033 ((eq what 'deadline) org-deadline-string)
15034 ((eq what 'closed) org-closed-string))
15035 " ")
15036 (setq ts (org-insert-time-stamp
15037 time
15038 (or org-time-was-given
15039 (and (eq what 'closed) org-log-done-with-time))
15040 (eq what 'closed)
15041 nil nil (list org-end-time-was-given)))
15042 (end-of-line 1))
15043 (goto-char (point-min))
15044 (widen)
15045 (if (looking-at "[ \t]+\r?\n")
15046 (replace-match ""))
15047 ts)))))
15049 (defvar org-log-note-marker (make-marker))
15050 (defvar org-log-note-purpose nil)
15051 (defvar org-log-note-state nil)
15052 (defvar org-log-note-how nil)
15053 (defvar org-log-note-window-configuration nil)
15054 (defvar org-log-note-return-to (make-marker))
15055 (defvar org-log-post-message nil
15056 "Message to be displayed after a log note has been stored.
15057 The auto-repeater uses this.")
15059 (defun org-add-log-maybe (&optional purpose state findpos how)
15060 "Set up the post command hook to take a note.
15061 If this is about to TODO state change, the new state is expected in STATE.
15062 When FINDPOS is non-nil, find the correct position for the note in
15063 the current entry. If not, assume that it can be inserted at point."
15064 (save-excursion
15065 (when findpos
15066 (org-back-to-heading t)
15067 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
15068 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
15069 "[^\r\n]*\\)?"))
15070 (goto-char (match-end 0))
15071 (unless org-log-states-order-reversed
15072 (and (= (char-after) ?\n) (forward-char 1))
15073 (org-skip-over-state-notes)
15074 (skip-chars-backward " \t\n\r")))
15075 (move-marker org-log-note-marker (point))
15076 (setq org-log-note-purpose purpose
15077 org-log-note-state state
15078 org-log-note-how how)
15079 (add-hook 'post-command-hook 'org-add-log-note 'append)))
15081 (defun org-skip-over-state-notes ()
15082 "Skip past the list of State notes in an entry."
15083 (if (looking-at "\n[ \t]*- State") (forward-char 1))
15084 (while (looking-at "[ \t]*- State")
15085 (condition-case nil
15086 (org-next-item)
15087 (error (org-end-of-item)))))
15089 (defun org-add-log-note (&optional purpose)
15090 "Pop up a window for taking a note, and add this note later at point."
15091 (remove-hook 'post-command-hook 'org-add-log-note)
15092 (setq org-log-note-window-configuration (current-window-configuration))
15093 (delete-other-windows)
15094 (move-marker org-log-note-return-to (point))
15095 (switch-to-buffer (marker-buffer org-log-note-marker))
15096 (goto-char org-log-note-marker)
15097 (org-switch-to-buffer-other-window "*Org Note*")
15098 (erase-buffer)
15099 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
15100 (org-store-log-note)
15101 (let ((org-inhibit-startup t)) (org-mode))
15102 (insert (format "# Insert note for %s.
15103 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
15104 (cond
15105 ((eq org-log-note-purpose 'clock-out) "stopped clock")
15106 ((eq org-log-note-purpose 'done) "closed todo item")
15107 ((eq org-log-note-purpose 'state)
15108 (format "state change to \"%s\"" org-log-note-state))
15109 (t (error "This should not happen")))))
15110 (org-set-local 'org-finish-function 'org-store-log-note)))
15112 (defun org-store-log-note ()
15113 "Finish taking a log note, and insert it to where it belongs."
15114 (let ((txt (buffer-string))
15115 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
15116 lines ind)
15117 (kill-buffer (current-buffer))
15118 (while (string-match "\\`#.*\n[ \t\n]*" txt)
15119 (setq txt (replace-match "" t t txt)))
15120 (if (string-match "\\s-+\\'" txt)
15121 (setq txt (replace-match "" t t txt)))
15122 (setq lines (org-split-string txt "\n"))
15123 (when (and note (string-match "\\S-" note))
15124 (setq note
15125 (org-replace-escapes
15126 note
15127 (list (cons "%u" (user-login-name))
15128 (cons "%U" user-full-name)
15129 (cons "%t" (format-time-string
15130 (org-time-stamp-format 'long 'inactive)
15131 (current-time)))
15132 (cons "%s" (if org-log-note-state
15133 (concat "\"" org-log-note-state "\"")
15134 "")))))
15135 (if lines (setq note (concat note " \\\\")))
15136 (push note lines))
15137 (when (or current-prefix-arg org-note-abort) (setq lines nil))
15138 (when lines
15139 (save-excursion
15140 (set-buffer (marker-buffer org-log-note-marker))
15141 (save-excursion
15142 (goto-char org-log-note-marker)
15143 (move-marker org-log-note-marker nil)
15144 (end-of-line 1)
15145 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
15146 (indent-relative nil)
15147 (insert "- " (pop lines))
15148 (org-indent-line-function)
15149 (beginning-of-line 1)
15150 (looking-at "[ \t]*")
15151 (setq ind (concat (match-string 0) " "))
15152 (end-of-line 1)
15153 (while lines (insert "\n" ind (pop lines)))))))
15154 (set-window-configuration org-log-note-window-configuration)
15155 (with-current-buffer (marker-buffer org-log-note-return-to)
15156 (goto-char org-log-note-return-to))
15157 (move-marker org-log-note-return-to nil)
15158 (and org-log-post-message (message "%s" org-log-post-message)))
15160 ;; FIXME: what else would be useful?
15161 ;; - priority
15162 ;; - date
15164 (defun org-sparse-tree (&optional arg)
15165 "Create a sparse tree, prompt for the details.
15166 This command can create sparse trees. You first need to select the type
15167 of match used to create the tree:
15169 t Show entries with a specific TODO keyword.
15170 T Show entries selected by a tags match.
15171 p Enter a property name and its value (both with completion on existing
15172 names/values) and show entries with that property.
15173 r Show entries matching a regular expression
15174 d Show deadlines due within `org-deadline-warning-days'."
15175 (interactive "P")
15176 (let (ans kwd value)
15177 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15178 (setq ans (read-char-exclusive))
15179 (cond
15180 ((equal ans ?d)
15181 (call-interactively 'org-check-deadlines))
15182 ((equal ans ?b)
15183 (call-interactively 'org-check-before-date))
15184 ((equal ans ?t)
15185 (org-show-todo-tree '(4)))
15186 ((equal ans ?T)
15187 (call-interactively 'org-tags-sparse-tree))
15188 ((member ans '(?p ?P))
15189 (setq kwd (completing-read "Property: "
15190 (mapcar 'list (org-buffer-property-keys))))
15191 (setq value (completing-read "Value: "
15192 (mapcar 'list (org-property-values kwd))))
15193 (unless (string-match "\\`{.*}\\'" value)
15194 (setq value (concat "\"" value "\"")))
15195 (org-tags-sparse-tree arg (concat kwd "=" value)))
15196 ((member ans '(?r ?R ?/))
15197 (call-interactively 'org-occur))
15198 (t (error "No such sparse tree command \"%c\"" ans)))))
15200 (defvar org-occur-highlights nil)
15201 (make-variable-buffer-local 'org-occur-highlights)
15203 (defun org-occur (regexp &optional keep-previous callback)
15204 "Make a compact tree which shows all matches of REGEXP.
15205 The tree will show the lines where the regexp matches, and all higher
15206 headlines above the match. It will also show the heading after the match,
15207 to make sure editing the matching entry is easy.
15208 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15209 call to `org-occur' will be kept, to allow stacking of calls to this
15210 command.
15211 If CALLBACK is non-nil, it is a function which is called to confirm
15212 that the match should indeed be shown."
15213 (interactive "sRegexp: \nP")
15214 (or keep-previous (org-remove-occur-highlights nil nil t))
15215 (let ((cnt 0))
15216 (save-excursion
15217 (goto-char (point-min))
15218 (if (or (not keep-previous) ; do not want to keep
15219 (not org-occur-highlights)) ; no previous matches
15220 ;; hide everything
15221 (org-overview))
15222 (while (re-search-forward regexp nil t)
15223 (when (or (not callback)
15224 (save-match-data (funcall callback)))
15225 (setq cnt (1+ cnt))
15226 (when org-highlight-sparse-tree-matches
15227 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15228 (org-show-context 'occur-tree))))
15229 (when org-remove-highlights-with-change
15230 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15231 nil 'local))
15232 (unless org-sparse-tree-open-archived-trees
15233 (org-hide-archived-subtrees (point-min) (point-max)))
15234 (run-hooks 'org-occur-hook)
15235 (if (interactive-p)
15236 (message "%d match(es) for regexp %s" cnt regexp))
15237 cnt))
15239 (defun org-show-context (&optional key)
15240 "Make sure point and context and visible.
15241 How much context is shown depends upon the variables
15242 `org-show-hierarchy-above', `org-show-following-heading'. and
15243 `org-show-siblings'."
15244 (let ((heading-p (org-on-heading-p t))
15245 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15246 (following-p (org-get-alist-option org-show-following-heading key))
15247 (entry-p (org-get-alist-option org-show-entry-below key))
15248 (siblings-p (org-get-alist-option org-show-siblings key)))
15249 (catch 'exit
15250 ;; Show heading or entry text
15251 (if (and heading-p (not entry-p))
15252 (org-flag-heading nil) ; only show the heading
15253 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15254 (org-show-hidden-entry))) ; show entire entry
15255 (when following-p
15256 ;; Show next sibling, or heading below text
15257 (save-excursion
15258 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15259 (org-flag-heading nil))))
15260 (when siblings-p (org-show-siblings))
15261 (when hierarchy-p
15262 ;; show all higher headings, possibly with siblings
15263 (save-excursion
15264 (while (and (condition-case nil
15265 (progn (org-up-heading-all 1) t)
15266 (error nil))
15267 (not (bobp)))
15268 (org-flag-heading nil)
15269 (when siblings-p (org-show-siblings))))))))
15271 (defun org-reveal (&optional siblings)
15272 "Show current entry, hierarchy above it, and the following headline.
15273 This can be used to show a consistent set of context around locations
15274 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15275 not t for the search context.
15277 With optional argument SIBLINGS, on each level of the hierarchy all
15278 siblings are shown. This repairs the tree structure to what it would
15279 look like when opened with hierarchical calls to `org-cycle'."
15280 (interactive "P")
15281 (let ((org-show-hierarchy-above t)
15282 (org-show-following-heading t)
15283 (org-show-siblings (if siblings t org-show-siblings)))
15284 (org-show-context nil)))
15286 (defun org-highlight-new-match (beg end)
15287 "Highlight from BEG to END and mark the highlight is an occur headline."
15288 (let ((ov (org-make-overlay beg end)))
15289 (org-overlay-put ov 'face 'secondary-selection)
15290 (push ov org-occur-highlights)))
15292 (defun org-remove-occur-highlights (&optional beg end noremove)
15293 "Remove the occur highlights from the buffer.
15294 BEG and END are ignored. If NOREMOVE is nil, remove this function
15295 from the `before-change-functions' in the current buffer."
15296 (interactive)
15297 (unless org-inhibit-highlight-removal
15298 (mapc 'org-delete-overlay org-occur-highlights)
15299 (setq org-occur-highlights nil)
15300 (unless noremove
15301 (remove-hook 'before-change-functions
15302 'org-remove-occur-highlights 'local))))
15304 ;;;; Priorities
15306 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15307 "Regular expression matching the priority indicator.")
15309 (defvar org-remove-priority-next-time nil)
15311 (defun org-priority-up ()
15312 "Increase the priority of the current item."
15313 (interactive)
15314 (org-priority 'up))
15316 (defun org-priority-down ()
15317 "Decrease the priority of the current item."
15318 (interactive)
15319 (org-priority 'down))
15321 (defun org-priority (&optional action)
15322 "Change the priority of an item by ARG.
15323 ACTION can be `set', `up', `down', or a character."
15324 (interactive)
15325 (setq action (or action 'set))
15326 (let (current new news have remove)
15327 (save-excursion
15328 (org-back-to-heading)
15329 (if (looking-at org-priority-regexp)
15330 (setq current (string-to-char (match-string 2))
15331 have t)
15332 (setq current org-default-priority))
15333 (cond
15334 ((or (eq action 'set) (integerp action))
15335 (if (integerp action)
15336 (setq new action)
15337 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15338 (setq new (read-char-exclusive)))
15339 (if (and (= (upcase org-highest-priority) org-highest-priority)
15340 (= (upcase org-lowest-priority) org-lowest-priority))
15341 (setq new (upcase new)))
15342 (cond ((equal new ?\ ) (setq remove t))
15343 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15344 (error "Priority must be between `%c' and `%c'"
15345 org-highest-priority org-lowest-priority))))
15346 ((eq action 'up)
15347 (if (and (not have) (eq last-command this-command))
15348 (setq new org-lowest-priority)
15349 (setq new (if (and org-priority-start-cycle-with-default (not have))
15350 org-default-priority (1- current)))))
15351 ((eq action 'down)
15352 (if (and (not have) (eq last-command this-command))
15353 (setq new org-highest-priority)
15354 (setq new (if (and org-priority-start-cycle-with-default (not have))
15355 org-default-priority (1+ current)))))
15356 (t (error "Invalid action")))
15357 (if (or (< (upcase new) org-highest-priority)
15358 (> (upcase new) org-lowest-priority))
15359 (setq remove t))
15360 (setq news (format "%c" new))
15361 (if have
15362 (if remove
15363 (replace-match "" t t nil 1)
15364 (replace-match news t t nil 2))
15365 (if remove
15366 (error "No priority cookie found in line")
15367 (looking-at org-todo-line-regexp)
15368 (if (match-end 2)
15369 (progn
15370 (goto-char (match-end 2))
15371 (insert " [#" news "]"))
15372 (goto-char (match-beginning 3))
15373 (insert "[#" news "] ")))))
15374 (org-preserve-lc (org-set-tags nil 'align))
15375 (if remove
15376 (message "Priority removed")
15377 (message "Priority of current item set to %s" news))))
15380 (defun org-get-priority (s)
15381 "Find priority cookie and return priority."
15382 (save-match-data
15383 (if (not (string-match org-priority-regexp s))
15384 (* 1000 (- org-lowest-priority org-default-priority))
15385 (* 1000 (- org-lowest-priority
15386 (string-to-char (match-string 2 s)))))))
15388 ;;;; Tags
15390 (defun org-scan-tags (action matcher &optional todo-only)
15391 "Scan headline tags with inheritance and produce output ACTION.
15392 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15393 evaluated, testing if a given set of tags qualifies a headline for
15394 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15395 are included in the output."
15396 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15397 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15398 (org-re
15399 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15400 (props (list 'face nil
15401 'done-face 'org-done
15402 'undone-face nil
15403 'mouse-face 'highlight
15404 'org-not-done-regexp org-not-done-regexp
15405 'org-todo-regexp org-todo-regexp
15406 'keymap org-agenda-keymap
15407 'help-echo
15408 (format "mouse-2 or RET jump to org file %s"
15409 (abbreviate-file-name
15410 (or (buffer-file-name (buffer-base-buffer))
15411 (buffer-name (buffer-base-buffer)))))))
15412 (case-fold-search nil)
15413 lspos
15414 tags tags-list tags-alist (llast 0) rtn level category i txt
15415 todo marker entry priority)
15416 (save-excursion
15417 (goto-char (point-min))
15418 (when (eq action 'sparse-tree)
15419 (org-overview)
15420 (org-remove-occur-highlights))
15421 (while (re-search-forward re nil t)
15422 (catch :skip
15423 (setq todo (if (match-end 1) (match-string 2))
15424 tags (if (match-end 4) (match-string 4)))
15425 (goto-char (setq lspos (1+ (match-beginning 0))))
15426 (setq level (org-reduced-level (funcall outline-level))
15427 category (org-get-category))
15428 (setq i llast llast level)
15429 ;; remove tag lists from same and sublevels
15430 (while (>= i level)
15431 (when (setq entry (assoc i tags-alist))
15432 (setq tags-alist (delete entry tags-alist)))
15433 (setq i (1- i)))
15434 ;; add the nex tags
15435 (when tags
15436 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15437 tags-alist
15438 (cons (cons level tags) tags-alist)))
15439 ;; compile tags for current headline
15440 (setq tags-list
15441 (if org-use-tag-inheritance
15442 (apply 'append (mapcar 'cdr tags-alist))
15443 tags))
15444 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15445 (eval matcher)
15446 (or (not org-agenda-skip-archived-trees)
15447 (not (member org-archive-tag tags-list))))
15448 (and (eq action 'agenda) (org-agenda-skip))
15449 ;; list this headline
15451 (if (eq action 'sparse-tree)
15452 (progn
15453 (and org-highlight-sparse-tree-matches
15454 (org-get-heading) (match-end 0)
15455 (org-highlight-new-match
15456 (match-beginning 0) (match-beginning 1)))
15457 (org-show-context 'tags-tree))
15458 (setq txt (org-format-agenda-item
15460 (concat
15461 (if org-tags-match-list-sublevels
15462 (make-string (1- level) ?.) "")
15463 (org-get-heading))
15464 category tags-list)
15465 priority (org-get-priority txt))
15466 (goto-char lspos)
15467 (setq marker (org-agenda-new-marker))
15468 (org-add-props txt props
15469 'org-marker marker 'org-hd-marker marker 'org-category category
15470 'priority priority 'type "tagsmatch")
15471 (push txt rtn))
15472 ;; if we are to skip sublevels, jump to end of subtree
15473 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15474 (when (and (eq action 'sparse-tree)
15475 (not org-sparse-tree-open-archived-trees))
15476 (org-hide-archived-subtrees (point-min) (point-max)))
15477 (nreverse rtn)))
15479 (defvar todo-only) ;; dynamically scoped
15481 (defun org-tags-sparse-tree (&optional todo-only match)
15482 "Create a sparse tree according to tags string MATCH.
15483 MATCH can contain positive and negative selection of tags, like
15484 \"+WORK+URGENT-WITHBOSS\".
15485 If optional argument TODO_ONLY is non-nil, only select lines that are
15486 also TODO lines."
15487 (interactive "P")
15488 (org-prepare-agenda-buffers (list (current-buffer)))
15489 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15491 (defvar org-cached-props nil)
15492 (defun org-cached-entry-get (pom property)
15493 (if (or (eq t org-use-property-inheritance)
15494 (member property org-use-property-inheritance))
15495 ;; Caching is not possible, check it directly
15496 (org-entry-get pom property 'inherit)
15497 ;; Get all properties, so that we can do complicated checks easily
15498 (cdr (assoc property (or org-cached-props
15499 (setq org-cached-props
15500 (org-entry-properties pom)))))))
15502 (defun org-global-tags-completion-table (&optional files)
15503 "Return the list of all tags in all agenda buffer/files."
15504 (save-excursion
15505 (org-uniquify
15506 (delq nil
15507 (apply 'append
15508 (mapcar
15509 (lambda (file)
15510 (set-buffer (find-file-noselect file))
15511 (append (org-get-buffer-tags)
15512 (mapcar (lambda (x) (if (stringp (car-safe x))
15513 (list (car-safe x)) nil))
15514 org-tag-alist)))
15515 (if (and files (car files))
15516 files
15517 (org-agenda-files))))))))
15519 (defun org-make-tags-matcher (match)
15520 "Create the TAGS//TODO matcher form for the selection string MATCH."
15521 ;; todo-only is scoped dynamically into this function, and the function
15522 ;; may change it it the matcher asksk for it.
15523 (unless match
15524 ;; Get a new match request, with completion
15525 (let ((org-last-tags-completion-table
15526 (org-global-tags-completion-table)))
15527 (setq match (completing-read
15528 "Match: " 'org-tags-completion-function nil nil nil
15529 'org-tags-history))))
15531 ;; Parse the string and create a lisp form
15532 (let ((match0 match)
15533 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15534 minus tag mm
15535 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15536 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15537 (if (string-match "/+" match)
15538 ;; match contains also a todo-matching request
15539 (progn
15540 (setq tagsmatch (substring match 0 (match-beginning 0))
15541 todomatch (substring match (match-end 0)))
15542 (if (string-match "^!" todomatch)
15543 (setq todo-only t todomatch (substring todomatch 1)))
15544 (if (string-match "^\\s-*$" todomatch)
15545 (setq todomatch nil)))
15546 ;; only matching tags
15547 (setq tagsmatch match todomatch nil))
15549 ;; Make the tags matcher
15550 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15551 (setq tagsmatcher t)
15552 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15553 (while (setq term (pop orterms))
15554 (while (and (equal (substring term -1) "\\") orterms)
15555 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15556 (while (string-match re term)
15557 (setq minus (and (match-end 1)
15558 (equal (match-string 1 term) "-"))
15559 tag (match-string 2 term)
15560 re-p (equal (string-to-char tag) ?{)
15561 level-p (match-end 3)
15562 prop-p (match-end 4)
15563 mm (cond
15564 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15565 (level-p `(= level ,(string-to-number
15566 (match-string 3 term))))
15567 (prop-p
15568 (setq pn (match-string 4 term)
15569 pv (match-string 5 term)
15570 cat-p (equal pn "CATEGORY")
15571 re-p (equal (string-to-char pv) ?{)
15572 pv (substring pv 1 -1))
15573 (if (equal pn "CATEGORY")
15574 (setq gv '(get-text-property (point) 'org-category))
15575 (setq gv `(org-cached-entry-get nil ,pn)))
15576 (if re-p
15577 `(string-match ,pv (or ,gv ""))
15578 `(equal ,pv (or ,gv ""))))
15579 (t `(member ,(downcase tag) tags-list)))
15580 mm (if minus (list 'not mm) mm)
15581 term (substring term (match-end 0)))
15582 (push mm tagsmatcher))
15583 (push (if (> (length tagsmatcher) 1)
15584 (cons 'and tagsmatcher)
15585 (car tagsmatcher))
15586 orlist)
15587 (setq tagsmatcher nil))
15588 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15589 (setq tagsmatcher
15590 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15592 ;; Make the todo matcher
15593 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15594 (setq todomatcher t)
15595 (setq orterms (org-split-string todomatch "|") orlist nil)
15596 (while (setq term (pop orterms))
15597 (while (string-match re term)
15598 (setq minus (and (match-end 1)
15599 (equal (match-string 1 term) "-"))
15600 kwd (match-string 2 term)
15601 re-p (equal (string-to-char kwd) ?{)
15602 term (substring term (match-end 0))
15603 mm (if re-p
15604 `(string-match ,(substring kwd 1 -1) todo)
15605 (list 'equal 'todo kwd))
15606 mm (if minus (list 'not mm) mm))
15607 (push mm todomatcher))
15608 (push (if (> (length todomatcher) 1)
15609 (cons 'and todomatcher)
15610 (car todomatcher))
15611 orlist)
15612 (setq todomatcher nil))
15613 (setq todomatcher (if (> (length orlist) 1)
15614 (cons 'or orlist) (car orlist))))
15616 ;; Return the string and lisp forms of the matcher
15617 (setq matcher (if todomatcher
15618 (list 'and tagsmatcher todomatcher)
15619 tagsmatcher))
15620 (cons match0 matcher)))
15622 (defun org-match-any-p (re list)
15623 "Does re match any element of list?"
15624 (setq list (mapcar (lambda (x) (string-match re x)) list))
15625 (delq nil list))
15627 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15628 (defvar org-tags-overlay (org-make-overlay 1 1))
15629 (org-detach-overlay org-tags-overlay)
15631 (defun org-align-tags-here (to-col)
15632 ;; Assumes that this is a headline
15633 (let ((pos (point)) (col (current-column)) tags)
15634 (beginning-of-line 1)
15635 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15636 (< pos (match-beginning 2)))
15637 (progn
15638 (setq tags (match-string 2))
15639 (goto-char (match-beginning 1))
15640 (insert " ")
15641 (delete-region (point) (1+ (match-end 0)))
15642 (backward-char 1)
15643 (move-to-column
15644 (max (1+ (current-column))
15645 (1+ col)
15646 (if (> to-col 0)
15647 to-col
15648 (- (abs to-col) (length tags))))
15650 (insert tags)
15651 (move-to-column (min (current-column) col) t))
15652 (goto-char pos))))
15654 (defun org-set-tags (&optional arg just-align)
15655 "Set the tags for the current headline.
15656 With prefix ARG, realign all tags in headings in the current buffer."
15657 (interactive "P")
15658 (let* ((re (concat "^" outline-regexp))
15659 (current (org-get-tags-string))
15660 (col (current-column))
15661 (org-setting-tags t)
15662 table current-tags inherited-tags ; computed below when needed
15663 tags p0 c0 c1 rpl)
15664 (if arg
15665 (save-excursion
15666 (goto-char (point-min))
15667 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15668 (while (re-search-forward re nil t)
15669 (org-set-tags nil t)
15670 (end-of-line 1)))
15671 (message "All tags realigned to column %d" org-tags-column))
15672 (if just-align
15673 (setq tags current)
15674 ;; Get a new set of tags from the user
15675 (save-excursion
15676 (setq table (or org-tag-alist (org-get-buffer-tags))
15677 org-last-tags-completion-table table
15678 current-tags (org-split-string current ":")
15679 inherited-tags (nreverse
15680 (nthcdr (length current-tags)
15681 (nreverse (org-get-tags-at))))
15682 tags
15683 (if (or (eq t org-use-fast-tag-selection)
15684 (and org-use-fast-tag-selection
15685 (delq nil (mapcar 'cdr table))))
15686 (org-fast-tag-selection
15687 current-tags inherited-tags table
15688 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15689 (let ((org-add-colon-after-tag-completion t))
15690 (org-trim
15691 (org-without-partial-completion
15692 (completing-read "Tags: " 'org-tags-completion-function
15693 nil nil current 'org-tags-history)))))))
15694 (while (string-match "[-+&]+" tags)
15695 ;; No boolean logic, just a list
15696 (setq tags (replace-match ":" t t tags))))
15698 (if (string-match "\\`[\t ]*\\'" tags)
15699 (setq tags "")
15700 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15701 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15703 ;; Insert new tags at the correct column
15704 (beginning-of-line 1)
15705 (cond
15706 ((and (equal current "") (equal tags "")))
15707 ((re-search-forward
15708 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15709 (point-at-eol) t)
15710 (if (equal tags "")
15711 (setq rpl "")
15712 (goto-char (match-beginning 0))
15713 (setq c0 (current-column) p0 (point)
15714 c1 (max (1+ c0) (if (> org-tags-column 0)
15715 org-tags-column
15716 (- (- org-tags-column) (length tags))))
15717 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15718 (replace-match rpl t t)
15719 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15720 tags)
15721 (t (error "Tags alignment failed")))
15722 (move-to-column col)
15723 (unless just-align
15724 (run-hooks 'org-after-tags-change-hook)))))
15726 (defun org-change-tag-in-region (beg end tag off)
15727 "Add or remove TAG for each entry in the region.
15728 This works in the agenda, and also in an org-mode buffer."
15729 (interactive
15730 (list (region-beginning) (region-end)
15731 (let ((org-last-tags-completion-table
15732 (if (org-mode-p)
15733 (org-get-buffer-tags)
15734 (org-global-tags-completion-table))))
15735 (completing-read
15736 "Tag: " 'org-tags-completion-function nil nil nil
15737 'org-tags-history))
15738 (progn
15739 (message "[s]et or [r]emove? ")
15740 (equal (read-char-exclusive) ?r))))
15741 (if (fboundp 'deactivate-mark) (deactivate-mark))
15742 (let ((agendap (equal major-mode 'org-agenda-mode))
15743 l1 l2 m buf pos newhead (cnt 0))
15744 (goto-char end)
15745 (setq l2 (1- (org-current-line)))
15746 (goto-char beg)
15747 (setq l1 (org-current-line))
15748 (loop for l from l1 to l2 do
15749 (goto-line l)
15750 (setq m (get-text-property (point) 'org-hd-marker))
15751 (when (or (and (org-mode-p) (org-on-heading-p))
15752 (and agendap m))
15753 (setq buf (if agendap (marker-buffer m) (current-buffer))
15754 pos (if agendap m (point)))
15755 (with-current-buffer buf
15756 (save-excursion
15757 (save-restriction
15758 (goto-char pos)
15759 (setq cnt (1+ cnt))
15760 (org-toggle-tag tag (if off 'off 'on))
15761 (setq newhead (org-get-heading)))))
15762 (and agendap (org-agenda-change-all-lines newhead m))))
15763 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15765 (defun org-tags-completion-function (string predicate &optional flag)
15766 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15767 (confirm (lambda (x) (stringp (car x)))))
15768 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15769 (setq s1 (match-string 1 string)
15770 s2 (match-string 2 string))
15771 (setq s1 "" s2 string))
15772 (cond
15773 ((eq flag nil)
15774 ;; try completion
15775 (setq rtn (try-completion s2 ctable confirm))
15776 (if (stringp rtn)
15777 (setq rtn
15778 (concat s1 s2 (substring rtn (length s2))
15779 (if (and org-add-colon-after-tag-completion
15780 (assoc rtn ctable))
15781 ":" ""))))
15782 rtn)
15783 ((eq flag t)
15784 ;; all-completions
15785 (all-completions s2 ctable confirm)
15787 ((eq flag 'lambda)
15788 ;; exact match?
15789 (assoc s2 ctable)))
15792 (defun org-fast-tag-insert (kwd tags face &optional end)
15793 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15794 (insert (format "%-12s" (concat kwd ":"))
15795 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15796 (or end "")))
15798 (defun org-fast-tag-show-exit (flag)
15799 (save-excursion
15800 (goto-line 3)
15801 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15802 (replace-match ""))
15803 (when flag
15804 (end-of-line 1)
15805 (move-to-column (- (window-width) 19) t)
15806 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15808 (defun org-set-current-tags-overlay (current prefix)
15809 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15810 (if (featurep 'xemacs)
15811 (org-overlay-display org-tags-overlay (concat prefix s)
15812 'secondary-selection)
15813 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15814 (org-overlay-display org-tags-overlay (concat prefix s)))))
15816 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15817 "Fast tag selection with single keys.
15818 CURRENT is the current list of tags in the headline, INHERITED is the
15819 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15820 possibly with grouping information. TODO-TABLE is a similar table with
15821 TODO keywords, should these have keys assigned to them.
15822 If the keys are nil, a-z are automatically assigned.
15823 Returns the new tags string, or nil to not change the current settings."
15824 (let* ((fulltable (append table todo-table))
15825 (maxlen (apply 'max (mapcar
15826 (lambda (x)
15827 (if (stringp (car x)) (string-width (car x)) 0))
15828 fulltable)))
15829 (buf (current-buffer))
15830 (expert (eq org-fast-tag-selection-single-key 'expert))
15831 (buffer-tags nil)
15832 (fwidth (+ maxlen 3 1 3))
15833 (ncol (/ (- (window-width) 4) fwidth))
15834 (i-face 'org-done)
15835 (c-face 'org-todo)
15836 tg cnt e c char c1 c2 ntable tbl rtn
15837 ov-start ov-end ov-prefix
15838 (exit-after-next org-fast-tag-selection-single-key)
15839 (done-keywords org-done-keywords)
15840 groups ingroup)
15841 (save-excursion
15842 (beginning-of-line 1)
15843 (if (looking-at
15844 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15845 (setq ov-start (match-beginning 1)
15846 ov-end (match-end 1)
15847 ov-prefix "")
15848 (setq ov-start (1- (point-at-eol))
15849 ov-end (1+ ov-start))
15850 (skip-chars-forward "^\n\r")
15851 (setq ov-prefix
15852 (concat
15853 (buffer-substring (1- (point)) (point))
15854 (if (> (current-column) org-tags-column)
15856 (make-string (- org-tags-column (current-column)) ?\ ))))))
15857 (org-move-overlay org-tags-overlay ov-start ov-end)
15858 (save-window-excursion
15859 (if expert
15860 (set-buffer (get-buffer-create " *Org tags*"))
15861 (delete-other-windows)
15862 (split-window-vertically)
15863 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15864 (erase-buffer)
15865 (org-set-local 'org-done-keywords done-keywords)
15866 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15867 (org-fast-tag-insert "Current" current c-face "\n\n")
15868 (org-fast-tag-show-exit exit-after-next)
15869 (org-set-current-tags-overlay current ov-prefix)
15870 (setq tbl fulltable char ?a cnt 0)
15871 (while (setq e (pop tbl))
15872 (cond
15873 ((equal e '(:startgroup))
15874 (push '() groups) (setq ingroup t)
15875 (when (not (= cnt 0))
15876 (setq cnt 0)
15877 (insert "\n"))
15878 (insert "{ "))
15879 ((equal e '(:endgroup))
15880 (setq ingroup nil cnt 0)
15881 (insert "}\n"))
15883 (setq tg (car e) c2 nil)
15884 (if (cdr e)
15885 (setq c (cdr e))
15886 ;; automatically assign a character.
15887 (setq c1 (string-to-char
15888 (downcase (substring
15889 tg (if (= (string-to-char tg) ?@) 1 0)))))
15890 (if (or (rassoc c1 ntable) (rassoc c1 table))
15891 (while (or (rassoc char ntable) (rassoc char table))
15892 (setq char (1+ char)))
15893 (setq c2 c1))
15894 (setq c (or c2 char)))
15895 (if ingroup (push tg (car groups)))
15896 (setq tg (org-add-props tg nil 'face
15897 (cond
15898 ((not (assoc tg table))
15899 (org-get-todo-face tg))
15900 ((member tg current) c-face)
15901 ((member tg inherited) i-face)
15902 (t nil))))
15903 (if (and (= cnt 0) (not ingroup)) (insert " "))
15904 (insert "[" c "] " tg (make-string
15905 (- fwidth 4 (length tg)) ?\ ))
15906 (push (cons tg c) ntable)
15907 (when (= (setq cnt (1+ cnt)) ncol)
15908 (insert "\n")
15909 (if ingroup (insert " "))
15910 (setq cnt 0)))))
15911 (setq ntable (nreverse ntable))
15912 (insert "\n")
15913 (goto-char (point-min))
15914 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15915 (fit-window-to-buffer))
15916 (setq rtn
15917 (catch 'exit
15918 (while t
15919 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15920 (if groups " [!] no groups" " [!]groups")
15921 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15922 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15923 (cond
15924 ((= c ?\r) (throw 'exit t))
15925 ((= c ?!)
15926 (setq groups (not groups))
15927 (goto-char (point-min))
15928 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15929 ((= c ?\C-c)
15930 (if (not expert)
15931 (org-fast-tag-show-exit
15932 (setq exit-after-next (not exit-after-next)))
15933 (setq expert nil)
15934 (delete-other-windows)
15935 (split-window-vertically)
15936 (org-switch-to-buffer-other-window " *Org tags*")
15937 (and (fboundp 'fit-window-to-buffer)
15938 (fit-window-to-buffer))))
15939 ((or (= c ?\C-g)
15940 (and (= c ?q) (not (rassoc c ntable))))
15941 (org-detach-overlay org-tags-overlay)
15942 (setq quit-flag t))
15943 ((= c ?\ )
15944 (setq current nil)
15945 (if exit-after-next (setq exit-after-next 'now)))
15946 ((= c ?\t)
15947 (condition-case nil
15948 (setq tg (completing-read
15949 "Tag: "
15950 (or buffer-tags
15951 (with-current-buffer buf
15952 (org-get-buffer-tags)))))
15953 (quit (setq tg "")))
15954 (when (string-match "\\S-" tg)
15955 (add-to-list 'buffer-tags (list tg))
15956 (if (member tg current)
15957 (setq current (delete tg current))
15958 (push tg current)))
15959 (if exit-after-next (setq exit-after-next 'now)))
15960 ((setq e (rassoc c todo-table) tg (car e))
15961 (with-current-buffer buf
15962 (save-excursion (org-todo tg)))
15963 (if exit-after-next (setq exit-after-next 'now)))
15964 ((setq e (rassoc c ntable) tg (car e))
15965 (if (member tg current)
15966 (setq current (delete tg current))
15967 (loop for g in groups do
15968 (if (member tg g)
15969 (mapc (lambda (x)
15970 (setq current (delete x current)))
15971 g)))
15972 (push tg current))
15973 (if exit-after-next (setq exit-after-next 'now))))
15975 ;; Create a sorted list
15976 (setq current
15977 (sort current
15978 (lambda (a b)
15979 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15980 (if (eq exit-after-next 'now) (throw 'exit t))
15981 (goto-char (point-min))
15982 (beginning-of-line 2)
15983 (delete-region (point) (point-at-eol))
15984 (org-fast-tag-insert "Current" current c-face)
15985 (org-set-current-tags-overlay current ov-prefix)
15986 (while (re-search-forward
15987 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15988 (setq tg (match-string 1))
15989 (add-text-properties
15990 (match-beginning 1) (match-end 1)
15991 (list 'face
15992 (cond
15993 ((member tg current) c-face)
15994 ((member tg inherited) i-face)
15995 (t (get-text-property (match-beginning 1) 'face))))))
15996 (goto-char (point-min)))))
15997 (org-detach-overlay org-tags-overlay)
15998 (if rtn
15999 (mapconcat 'identity current ":")
16000 nil))))
16002 (defun org-get-tags-string ()
16003 "Get the TAGS string in the current headline."
16004 (unless (org-on-heading-p t)
16005 (error "Not on a heading"))
16006 (save-excursion
16007 (beginning-of-line 1)
16008 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16009 (org-match-string-no-properties 1)
16010 "")))
16012 (defun org-get-tags ()
16013 "Get the list of tags specified in the current headline."
16014 (org-split-string (org-get-tags-string) ":"))
16016 (defun org-get-buffer-tags ()
16017 "Get a table of all tags used in the buffer, for completion."
16018 (let (tags)
16019 (save-excursion
16020 (goto-char (point-min))
16021 (while (re-search-forward
16022 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
16023 (when (equal (char-after (point-at-bol 0)) ?*)
16024 (mapc (lambda (x) (add-to-list 'tags x))
16025 (org-split-string (org-match-string-no-properties 1) ":")))))
16026 (mapcar 'list tags)))
16029 ;;;; Properties
16031 ;;; Setting and retrieving properties
16033 (defconst org-special-properties
16034 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
16035 "TIMESTAMP" "TIMESTAMP_IA")
16036 "The special properties valid in Org-mode.
16038 These are properties that are not defined in the property drawer,
16039 but in some other way.")
16041 (defconst org-default-properties
16042 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
16043 "LOCATION" "LOGGING" "COLUMNS")
16044 "Some properties that are used by Org-mode for various purposes.
16045 Being in this list makes sure that they are offered for completion.")
16047 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
16048 "Regular expression matching the first line of a property drawer.")
16050 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
16051 "Regular expression matching the first line of a property drawer.")
16053 (defun org-property-action ()
16054 "Do an action on properties."
16055 (interactive)
16056 (let (c)
16057 (org-at-property-p)
16058 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
16059 (setq c (read-char-exclusive))
16060 (cond
16061 ((equal c ?s)
16062 (call-interactively 'org-set-property))
16063 ((equal c ?d)
16064 (call-interactively 'org-delete-property))
16065 ((equal c ?D)
16066 (call-interactively 'org-delete-property-globally))
16067 ((equal c ?c)
16068 (call-interactively 'org-compute-property-at-point))
16069 (t (error "No such property action %c" c)))))
16071 (defun org-at-property-p ()
16072 "Is the cursor in a property line?"
16073 ;; FIXME: Does not check if we are actually in the drawer.
16074 ;; FIXME: also returns true on any drawers.....
16075 ;; This is used by C-c C-c for property action.
16076 (save-excursion
16077 (beginning-of-line 1)
16078 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
16080 (defmacro org-with-point-at (pom &rest body)
16081 "Move to buffer and point of point-or-marker POM for the duration of BODY."
16082 (declare (indent 1) (debug t))
16083 `(save-excursion
16084 (if (markerp pom) (set-buffer (marker-buffer pom)))
16085 (save-excursion
16086 (goto-char (or pom (point)))
16087 ,@body)))
16089 (defun org-get-property-block (&optional beg end force)
16090 "Return the (beg . end) range of the body of the property drawer.
16091 BEG and END can be beginning and end of subtree, if not given
16092 they will be found.
16093 If the drawer does not exist and FORCE is non-nil, create the drawer."
16094 (catch 'exit
16095 (save-excursion
16096 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
16097 (end (or end (progn (outline-next-heading) (point)))))
16098 (goto-char beg)
16099 (if (re-search-forward org-property-start-re end t)
16100 (setq beg (1+ (match-end 0)))
16101 (if force
16102 (save-excursion
16103 (org-insert-property-drawer)
16104 (setq end (progn (outline-next-heading) (point))))
16105 (throw 'exit nil))
16106 (goto-char beg)
16107 (if (re-search-forward org-property-start-re end t)
16108 (setq beg (1+ (match-end 0)))))
16109 (if (re-search-forward org-property-end-re end t)
16110 (setq end (match-beginning 0))
16111 (or force (throw 'exit nil))
16112 (goto-char beg)
16113 (setq end beg)
16114 (org-indent-line-function)
16115 (insert ":END:\n"))
16116 (cons beg end)))))
16118 (defun org-entry-properties (&optional pom which)
16119 "Get all properties of the entry at point-or-marker POM.
16120 This includes the TODO keyword, the tags, time strings for deadline,
16121 scheduled, and clocking, and any additional properties defined in the
16122 entry. The return value is an alist, keys may occur multiple times
16123 if the property key was used several times.
16124 POM may also be nil, in which case the current entry is used.
16125 If WHICH is nil or `all', get all properties. If WHICH is
16126 `special' or `standard', only get that subclass."
16127 (setq which (or which 'all))
16128 (org-with-point-at pom
16129 (let ((clockstr (substring org-clock-string 0 -1))
16130 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
16131 beg end range props sum-props key value string clocksum)
16132 (save-excursion
16133 (when (condition-case nil (org-back-to-heading t) (error nil))
16134 (setq beg (point))
16135 (setq sum-props (get-text-property (point) 'org-summaries))
16136 (setq clocksum (get-text-property (point) :org-clock-minutes))
16137 (outline-next-heading)
16138 (setq end (point))
16139 (when (memq which '(all special))
16140 ;; Get the special properties, like TODO and tags
16141 (goto-char beg)
16142 (when (and (looking-at org-todo-line-regexp) (match-end 2))
16143 (push (cons "TODO" (org-match-string-no-properties 2)) props))
16144 (when (looking-at org-priority-regexp)
16145 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16146 (when (and (setq value (org-get-tags-string))
16147 (string-match "\\S-" value))
16148 (push (cons "TAGS" value) props))
16149 (when (setq value (org-get-tags-at))
16150 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16151 props))
16152 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16153 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16154 string (if (equal key clockstr)
16155 (org-no-properties
16156 (org-trim
16157 (buffer-substring
16158 (match-beginning 3) (goto-char (point-at-eol)))))
16159 (substring (org-match-string-no-properties 3) 1 -1)))
16160 (unless key
16161 (if (= (char-after (match-beginning 3)) ?\[)
16162 (setq key "TIMESTAMP_IA")
16163 (setq key "TIMESTAMP")))
16164 (when (or (equal key clockstr) (not (assoc key props)))
16165 (push (cons key string) props)))
16169 (when (memq which '(all standard))
16170 ;; Get the standard properties, like :PORP: ...
16171 (setq range (org-get-property-block beg end))
16172 (when range
16173 (goto-char (car range))
16174 (while (re-search-forward
16175 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16176 (cdr range) t)
16177 (setq key (org-match-string-no-properties 1)
16178 value (org-trim (or (org-match-string-no-properties 2) "")))
16179 (unless (member key excluded)
16180 (push (cons key (or value "")) props)))))
16181 (if clocksum
16182 (push (cons "CLOCKSUM"
16183 (org-column-number-to-string (/ (float clocksum) 60.)
16184 'add_times))
16185 props))
16186 (append sum-props (nreverse props)))))))
16188 (defun org-entry-get (pom property &optional inherit)
16189 "Get value of PROPERTY for entry at point-or-marker POM.
16190 If INHERIT is non-nil and the entry does not have the property,
16191 then also check higher levels of the hierarchy.
16192 If the property is present but empty, the return value is the empty string.
16193 If the property is not present at all, nil is returned."
16194 (org-with-point-at pom
16195 (if inherit
16196 (org-entry-get-with-inheritance property)
16197 (if (member property org-special-properties)
16198 ;; We need a special property. Use brute force, get all properties.
16199 (cdr (assoc property (org-entry-properties nil 'special)))
16200 (let ((range (org-get-property-block)))
16201 (if (and range
16202 (goto-char (car range))
16203 (re-search-forward
16204 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16205 (cdr range) t))
16206 ;; Found the property, return it.
16207 (if (match-end 1)
16208 (org-match-string-no-properties 1)
16209 "")))))))
16211 (defun org-entry-delete (pom property)
16212 "Delete the property PROPERTY from entry at point-or-marker POM."
16213 (org-with-point-at pom
16214 (if (member property org-special-properties)
16215 nil ; cannot delete these properties.
16216 (let ((range (org-get-property-block)))
16217 (if (and range
16218 (goto-char (car range))
16219 (re-search-forward
16220 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16221 (cdr range) t))
16222 (progn
16223 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16225 nil)))))
16227 ;; Multi-values properties are properties that contain multiple values
16228 ;; These values are assumed to be single words, separated by whitespace.
16229 (defun org-entry-add-to-multivalued-property (pom property value)
16230 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16231 (let* ((old (org-entry-get pom property))
16232 (values (and old (org-split-string old "[ \t]"))))
16233 (unless (member value values)
16234 (setq values (cons value values))
16235 (org-entry-put pom property
16236 (mapconcat 'identity values " ")))))
16238 (defun org-entry-remove-from-multivalued-property (pom property value)
16239 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16240 (let* ((old (org-entry-get pom property))
16241 (values (and old (org-split-string old "[ \t]"))))
16242 (when (member value values)
16243 (setq values (delete value values))
16244 (org-entry-put pom property
16245 (mapconcat 'identity values " ")))))
16247 (defun org-entry-member-in-multivalued-property (pom property value)
16248 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16249 (let* ((old (org-entry-get pom property))
16250 (values (and old (org-split-string old "[ \t]"))))
16251 (member value values)))
16253 (defvar org-entry-property-inherited-from (make-marker))
16255 (defun org-entry-get-with-inheritance (property)
16256 "Get entry property, and search higher levels if not present."
16257 (let (tmp)
16258 (save-excursion
16259 (save-restriction
16260 (widen)
16261 (catch 'ex
16262 (while t
16263 (when (setq tmp (org-entry-get nil property))
16264 (org-back-to-heading t)
16265 (move-marker org-entry-property-inherited-from (point))
16266 (throw 'ex tmp))
16267 (or (org-up-heading-safe) (throw 'ex nil)))))
16268 (or tmp (cdr (assoc property org-local-properties))
16269 (cdr (assoc property org-global-properties))))))
16271 (defun org-entry-put (pom property value)
16272 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16273 (org-with-point-at pom
16274 (org-back-to-heading t)
16275 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16276 range)
16277 (cond
16278 ((equal property "TODO")
16279 (when (and (stringp value) (string-match "\\S-" value)
16280 (not (member value org-todo-keywords-1)))
16281 (error "\"%s\" is not a valid TODO state" value))
16282 (if (or (not value)
16283 (not (string-match "\\S-" value)))
16284 (setq value 'none))
16285 (org-todo value)
16286 (org-set-tags nil 'align))
16287 ((equal property "PRIORITY")
16288 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16289 (string-to-char value) ?\ ))
16290 (org-set-tags nil 'align))
16291 ((equal property "SCHEDULED")
16292 (if (re-search-forward org-scheduled-time-regexp end t)
16293 (cond
16294 ((eq value 'earlier) (org-timestamp-change -1 'day))
16295 ((eq value 'later) (org-timestamp-change 1 'day))
16296 (t (call-interactively 'org-schedule)))
16297 (call-interactively 'org-schedule)))
16298 ((equal property "DEADLINE")
16299 (if (re-search-forward org-deadline-time-regexp end t)
16300 (cond
16301 ((eq value 'earlier) (org-timestamp-change -1 'day))
16302 ((eq value 'later) (org-timestamp-change 1 'day))
16303 (t (call-interactively 'org-deadline)))
16304 (call-interactively 'org-deadline)))
16305 ((member property org-special-properties)
16306 (error "The %s property can not yet be set with `org-entry-put'"
16307 property))
16308 (t ; a non-special property
16309 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16310 (setq range (org-get-property-block beg end 'force))
16311 (goto-char (car range))
16312 (if (re-search-forward
16313 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16314 (progn
16315 (delete-region (match-beginning 1) (match-end 1))
16316 (goto-char (match-beginning 1)))
16317 (goto-char (cdr range))
16318 (insert "\n")
16319 (backward-char 1)
16320 (org-indent-line-function)
16321 (insert ":" property ":"))
16322 (and value (insert " " value))
16323 (org-indent-line-function)))))))
16325 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16326 "Get all property keys in the current buffer.
16327 With INCLUDE-SPECIALS, also list the special properties that relect things
16328 like tags and TODO state.
16329 With INCLUDE-DEFAULTS, also include properties that has special meaning
16330 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16331 With INCLUDE-COLUMNS, also include property names given in COLUMN
16332 formats in the current buffer."
16333 (let (rtn range cfmt cols s p)
16334 (save-excursion
16335 (save-restriction
16336 (widen)
16337 (goto-char (point-min))
16338 (while (re-search-forward org-property-start-re nil t)
16339 (setq range (org-get-property-block))
16340 (goto-char (car range))
16341 (while (re-search-forward
16342 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16343 (cdr range) t)
16344 (add-to-list 'rtn (org-match-string-no-properties 1)))
16345 (outline-next-heading))))
16347 (when include-specials
16348 (setq rtn (append org-special-properties rtn)))
16350 (when include-defaults
16351 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16353 (when include-columns
16354 (save-excursion
16355 (save-restriction
16356 (widen)
16357 (goto-char (point-min))
16358 (while (re-search-forward
16359 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16360 nil t)
16361 (setq cfmt (match-string 2) s 0)
16362 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16363 cfmt s)
16364 (setq s (match-end 0)
16365 p (match-string 1 cfmt))
16366 (unless (or (equal p "ITEM")
16367 (member p org-special-properties))
16368 (add-to-list 'rtn (match-string 1 cfmt))))))))
16370 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16372 (defun org-property-values (key)
16373 "Return a list of all values of property KEY."
16374 (save-excursion
16375 (save-restriction
16376 (widen)
16377 (goto-char (point-min))
16378 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16379 values)
16380 (while (re-search-forward re nil t)
16381 (add-to-list 'values (org-trim (match-string 1))))
16382 (delete "" values)))))
16384 (defun org-insert-property-drawer ()
16385 "Insert a property drawer into the current entry."
16386 (interactive)
16387 (org-back-to-heading t)
16388 (looking-at outline-regexp)
16389 (let ((indent (- (match-end 0)(match-beginning 0)))
16390 (beg (point))
16391 (re (concat "^[ \t]*" org-keyword-time-regexp))
16392 end hiddenp)
16393 (outline-next-heading)
16394 (setq end (point))
16395 (goto-char beg)
16396 (while (re-search-forward re end t))
16397 (setq hiddenp (org-invisible-p))
16398 (end-of-line 1)
16399 (and (equal (char-after) ?\n) (forward-char 1))
16400 (org-skip-over-state-notes)
16401 (skip-chars-backward " \t\n\r")
16402 (if (eq (char-before) ?*) (forward-char 1))
16403 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16404 (beginning-of-line 0)
16405 (indent-to-column indent)
16406 (beginning-of-line 2)
16407 (indent-to-column indent)
16408 (beginning-of-line 0)
16409 (if hiddenp
16410 (save-excursion
16411 (org-back-to-heading t)
16412 (hide-entry))
16413 (org-flag-drawer t))))
16415 (defun org-set-property (property value)
16416 "In the current entry, set PROPERTY to VALUE.
16417 When called interactively, this will prompt for a property name, offering
16418 completion on existing and default properties. And then it will prompt
16419 for a value, offering competion either on allowed values (via an inherited
16420 xxx_ALL property) or on existing values in other instances of this property
16421 in the current file."
16422 (interactive
16423 (let* ((prop (completing-read
16424 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16425 (cur (org-entry-get nil prop))
16426 (allowed (org-property-get-allowed-values nil prop 'table))
16427 (existing (mapcar 'list (org-property-values prop)))
16428 (val (if allowed
16429 (completing-read "Value: " allowed nil 'req-match)
16430 (completing-read
16431 (concat "Value" (if (and cur (string-match "\\S-" cur))
16432 (concat "[" cur "]") "")
16433 ": ")
16434 existing nil nil "" nil cur))))
16435 (list prop (if (equal val "") cur val))))
16436 (unless (equal (org-entry-get nil property) value)
16437 (org-entry-put nil property value)))
16439 (defun org-delete-property (property)
16440 "In the current entry, delete PROPERTY."
16441 (interactive
16442 (let* ((prop (completing-read
16443 "Property: " (org-entry-properties nil 'standard))))
16444 (list prop)))
16445 (message "Property %s %s" property
16446 (if (org-entry-delete nil property)
16447 "deleted"
16448 "was not present in the entry")))
16450 (defun org-delete-property-globally (property)
16451 "Remove PROPERTY globally, from all entries."
16452 (interactive
16453 (let* ((prop (completing-read
16454 "Globally remove property: "
16455 (mapcar 'list (org-buffer-property-keys)))))
16456 (list prop)))
16457 (save-excursion
16458 (save-restriction
16459 (widen)
16460 (goto-char (point-min))
16461 (let ((cnt 0))
16462 (while (re-search-forward
16463 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16464 nil t)
16465 (setq cnt (1+ cnt))
16466 (replace-match ""))
16467 (message "Property \"%s\" removed from %d entries" property cnt)))))
16469 (defvar org-columns-current-fmt-compiled) ; defined below
16471 (defun org-compute-property-at-point ()
16472 "Compute the property at point.
16473 This looks for an enclosing column format, extracts the operator and
16474 then applies it to the proerty in the column format's scope."
16475 (interactive)
16476 (unless (org-at-property-p)
16477 (error "Not at a property"))
16478 (let ((prop (org-match-string-no-properties 2)))
16479 (org-columns-get-format-and-top-level)
16480 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16481 (error "No operator defined for property %s" prop))
16482 (org-columns-compute prop)))
16484 (defun org-property-get-allowed-values (pom property &optional table)
16485 "Get allowed values for the property PROPERTY.
16486 When TABLE is non-nil, return an alist that can directly be used for
16487 completion."
16488 (let (vals)
16489 (cond
16490 ((equal property "TODO")
16491 (setq vals (org-with-point-at pom
16492 (append org-todo-keywords-1 '("")))))
16493 ((equal property "PRIORITY")
16494 (let ((n org-lowest-priority))
16495 (while (>= n org-highest-priority)
16496 (push (char-to-string n) vals)
16497 (setq n (1- n)))))
16498 ((member property org-special-properties))
16500 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16502 (when (and vals (string-match "\\S-" vals))
16503 (setq vals (car (read-from-string (concat "(" vals ")"))))
16504 (setq vals (mapcar (lambda (x)
16505 (cond ((stringp x) x)
16506 ((numberp x) (number-to-string x))
16507 ((symbolp x) (symbol-name x))
16508 (t "???")))
16509 vals)))))
16510 (if table (mapcar 'list vals) vals)))
16512 (defun org-property-previous-allowed-value (&optional previous)
16513 "Switch to the next allowed value for this property."
16514 (interactive)
16515 (org-property-next-allowed-value t))
16517 (defun org-property-next-allowed-value (&optional previous)
16518 "Switch to the next allowed value for this property."
16519 (interactive)
16520 (unless (org-at-property-p)
16521 (error "Not at a property"))
16522 (let* ((key (match-string 2))
16523 (value (match-string 3))
16524 (allowed (or (org-property-get-allowed-values (point) key)
16525 (and (member value '("[ ]" "[-]" "[X]"))
16526 '("[ ]" "[X]"))))
16527 nval)
16528 (unless allowed
16529 (error "Allowed values for this property have not been defined"))
16530 (if previous (setq allowed (reverse allowed)))
16531 (if (member value allowed)
16532 (setq nval (car (cdr (member value allowed)))))
16533 (setq nval (or nval (car allowed)))
16534 (if (equal nval value)
16535 (error "Only one allowed value for this property"))
16536 (org-at-property-p)
16537 (replace-match (concat " :" key ": " nval) t t)
16538 (org-indent-line-function)
16539 (beginning-of-line 1)
16540 (skip-chars-forward " \t")))
16542 (defun org-find-entry-with-id (ident)
16543 "Locate the entry that contains the ID property with exact value IDENT.
16544 IDENT can be a string, a symbol or a number, this function will search for
16545 the string representation of it.
16546 Return the position where this entry starts, or nil if there is no such entry."
16547 (let ((id (cond
16548 ((stringp ident) ident)
16549 ((symbol-name ident) (symbol-name ident))
16550 ((numberp ident) (number-to-string ident))
16551 (t (error "IDENT %s must be a string, symbol or number" ident))))
16552 (case-fold-search nil))
16553 (save-excursion
16554 (save-restriction
16555 (widen)
16556 (goto-char (point-min))
16557 (when (re-search-forward
16558 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16559 nil t)
16560 (org-back-to-heading)
16561 (point))))))
16563 ;;; Column View
16565 (defvar org-columns-overlays nil
16566 "Holds the list of current column overlays.")
16568 (defvar org-columns-current-fmt nil
16569 "Local variable, holds the currently active column format.")
16570 (defvar org-columns-current-fmt-compiled nil
16571 "Local variable, holds the currently active column format.
16572 This is the compiled version of the format.")
16573 (defvar org-columns-current-widths nil
16574 "Loval variable, holds the currently widths of fields.")
16575 (defvar org-columns-current-maxwidths nil
16576 "Loval variable, holds the currently active maximum column widths.")
16577 (defvar org-columns-begin-marker (make-marker)
16578 "Points to the position where last a column creation command was called.")
16579 (defvar org-columns-top-level-marker (make-marker)
16580 "Points to the position where current columns region starts.")
16582 (defvar org-columns-map (make-sparse-keymap)
16583 "The keymap valid in column display.")
16585 (defun org-columns-content ()
16586 "Switch to contents view while in columns view."
16587 (interactive)
16588 (org-overview)
16589 (org-content))
16591 (org-defkey org-columns-map "c" 'org-columns-content)
16592 (org-defkey org-columns-map "o" 'org-overview)
16593 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16594 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16595 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16596 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16597 (org-defkey org-columns-map "v" 'org-columns-show-value)
16598 (org-defkey org-columns-map "q" 'org-columns-quit)
16599 (org-defkey org-columns-map "r" 'org-columns-redo)
16600 (org-defkey org-columns-map "g" 'org-columns-redo)
16601 (org-defkey org-columns-map [left] 'backward-char)
16602 (org-defkey org-columns-map "\M-b" 'backward-char)
16603 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16604 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16605 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16606 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16607 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16608 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16609 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16610 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16611 (org-defkey org-columns-map "<" 'org-columns-narrow)
16612 (org-defkey org-columns-map ">" 'org-columns-widen)
16613 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16614 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16615 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16616 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16618 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16619 '("Column"
16620 ["Edit property" org-columns-edit-value t]
16621 ["Next allowed value" org-columns-next-allowed-value t]
16622 ["Previous allowed value" org-columns-previous-allowed-value t]
16623 ["Show full value" org-columns-show-value t]
16624 ["Edit allowed values" org-columns-edit-allowed t]
16625 "--"
16626 ["Edit column attributes" org-columns-edit-attributes t]
16627 ["Increase column width" org-columns-widen t]
16628 ["Decrease column width" org-columns-narrow t]
16629 "--"
16630 ["Move column right" org-columns-move-right t]
16631 ["Move column left" org-columns-move-left t]
16632 ["Add column" org-columns-new t]
16633 ["Delete column" org-columns-delete t]
16634 "--"
16635 ["CONTENTS" org-columns-content t]
16636 ["OVERVIEW" org-overview t]
16637 ["Refresh columns display" org-columns-redo t]
16638 "--"
16639 ["Open link" org-columns-open-link t]
16640 "--"
16641 ["Quit" org-columns-quit t]))
16643 (defun org-columns-new-overlay (beg end &optional string face)
16644 "Create a new column overlay and add it to the list."
16645 (let ((ov (org-make-overlay beg end)))
16646 (org-overlay-put ov 'face (or face 'secondary-selection))
16647 (org-overlay-display ov string face)
16648 (push ov org-columns-overlays)
16649 ov))
16651 (defun org-columns-display-here (&optional props)
16652 "Overlay the current line with column display."
16653 (interactive)
16654 (let* ((fmt org-columns-current-fmt-compiled)
16655 (beg (point-at-bol))
16656 (level-face (save-excursion
16657 (beginning-of-line 1)
16658 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16659 (org-get-level-face 2))))
16660 (color (list :foreground
16661 (face-attribute (or level-face 'default) :foreground)))
16662 props pom property ass width f string ov column val modval)
16663 ;; Check if the entry is in another buffer.
16664 (unless props
16665 (if (eq major-mode 'org-agenda-mode)
16666 (setq pom (or (get-text-property (point) 'org-hd-marker)
16667 (get-text-property (point) 'org-marker))
16668 props (if pom (org-entry-properties pom) nil))
16669 (setq props (org-entry-properties nil))))
16670 ;; Walk the format
16671 (while (setq column (pop fmt))
16672 (setq property (car column)
16673 ass (if (equal property "ITEM")
16674 (cons "ITEM"
16675 (save-match-data
16676 (org-no-properties
16677 (org-remove-tabs
16678 (buffer-substring-no-properties
16679 (point-at-bol) (point-at-eol))))))
16680 (assoc property props))
16681 width (or (cdr (assoc property org-columns-current-maxwidths))
16682 (nth 2 column)
16683 (length property))
16684 f (format "%%-%d.%ds | " width width)
16685 val (or (cdr ass) "")
16686 modval (if (equal property "ITEM")
16687 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16688 string (format f (or modval val)))
16689 ;; Create the overlay
16690 (org-unmodified
16691 (setq ov (org-columns-new-overlay
16692 beg (setq beg (1+ beg)) string
16693 (list color 'org-column)))
16694 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16695 (org-overlay-put ov 'keymap org-columns-map)
16696 (org-overlay-put ov 'org-columns-key property)
16697 (org-overlay-put ov 'org-columns-value (cdr ass))
16698 (org-overlay-put ov 'org-columns-value-modified modval)
16699 (org-overlay-put ov 'org-columns-pom pom)
16700 (org-overlay-put ov 'org-columns-format f))
16701 (if (or (not (char-after beg))
16702 (equal (char-after beg) ?\n))
16703 (let ((inhibit-read-only t))
16704 (save-excursion
16705 (goto-char beg)
16706 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16707 ;; Make the rest of the line disappear.
16708 (org-unmodified
16709 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16710 (org-overlay-put ov 'invisible t)
16711 (org-overlay-put ov 'keymap org-columns-map)
16712 (org-overlay-put ov 'intangible t)
16713 (push ov org-columns-overlays)
16714 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16715 (org-overlay-put ov 'keymap org-columns-map)
16716 (push ov org-columns-overlays)
16717 (let ((inhibit-read-only t))
16718 (put-text-property (max (point-min) (1- (point-at-bol)))
16719 (min (point-max) (1+ (point-at-eol)))
16720 'read-only "Type `e' to edit property")))))
16722 (defvar org-previous-header-line-format nil
16723 "The header line format before column view was turned on.")
16724 (defvar org-columns-inhibit-recalculation nil
16725 "Inhibit recomputing of columns on column view startup.")
16728 (defvar header-line-format)
16729 (defun org-columns-display-here-title ()
16730 "Overlay the newline before the current line with the table title."
16731 (interactive)
16732 (let ((fmt org-columns-current-fmt-compiled)
16733 string (title "")
16734 property width f column str widths)
16735 (while (setq column (pop fmt))
16736 (setq property (car column)
16737 str (or (nth 1 column) property)
16738 width (or (cdr (assoc property org-columns-current-maxwidths))
16739 (nth 2 column)
16740 (length str))
16741 widths (push width widths)
16742 f (format "%%-%d.%ds | " width width)
16743 string (format f str)
16744 title (concat title string)))
16745 (setq title (concat
16746 (org-add-props " " nil 'display '(space :align-to 0))
16747 (org-add-props title nil 'face '(:weight bold :underline t))))
16748 (org-set-local 'org-previous-header-line-format header-line-format)
16749 (org-set-local 'org-columns-current-widths (nreverse widths))
16750 (setq header-line-format title)))
16752 (defun org-columns-remove-overlays ()
16753 "Remove all currently active column overlays."
16754 (interactive)
16755 (when (marker-buffer org-columns-begin-marker)
16756 (with-current-buffer (marker-buffer org-columns-begin-marker)
16757 (when (local-variable-p 'org-previous-header-line-format)
16758 (setq header-line-format org-previous-header-line-format)
16759 (kill-local-variable 'org-previous-header-line-format))
16760 (move-marker org-columns-begin-marker nil)
16761 (move-marker org-columns-top-level-marker nil)
16762 (org-unmodified
16763 (mapc 'org-delete-overlay org-columns-overlays)
16764 (setq org-columns-overlays nil)
16765 (let ((inhibit-read-only t))
16766 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16768 (defun org-columns-cleanup-item (item fmt)
16769 "Remove from ITEM what is a column in the format FMT."
16770 (if (not org-complex-heading-regexp)
16771 item
16772 (when (string-match org-complex-heading-regexp item)
16773 (concat
16774 (org-add-props (concat (match-string 1 item) " ") nil
16775 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16776 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16777 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16778 " " (match-string 4 item)
16779 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16781 (defun org-columns-show-value ()
16782 "Show the full value of the property."
16783 (interactive)
16784 (let ((value (get-char-property (point) 'org-columns-value)))
16785 (message "Value is: %s" (or value ""))))
16787 (defun org-columns-quit ()
16788 "Remove the column overlays and in this way exit column editing."
16789 (interactive)
16790 (org-unmodified
16791 (org-columns-remove-overlays)
16792 (let ((inhibit-read-only t))
16793 (remove-text-properties (point-min) (point-max) '(read-only t))))
16794 (when (eq major-mode 'org-agenda-mode)
16795 (message
16796 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16798 (defun org-columns-check-computed ()
16799 "Check if this column value is computed.
16800 If yes, throw an error indicating that changing it does not make sense."
16801 (let ((val (get-char-property (point) 'org-columns-value)))
16802 (when (and (stringp val)
16803 (get-char-property 0 'org-computed val))
16804 (error "This value is computed from the entry's children"))))
16806 (defun org-columns-todo (&optional arg)
16807 "Change the TODO state during column view."
16808 (interactive "P")
16809 (org-columns-edit-value "TODO"))
16811 (defun org-columns-set-tags-or-toggle (&optional arg)
16812 "Toggle checkbox at point, or set tags for current headline."
16813 (interactive "P")
16814 (if (string-match "\\`\\[[ xX-]\\]\\'"
16815 (get-char-property (point) 'org-columns-value))
16816 (org-columns-next-allowed-value)
16817 (org-columns-edit-value "TAGS")))
16819 (defun org-columns-edit-value (&optional key)
16820 "Edit the value of the property at point in column view.
16821 Where possible, use the standard interface for changing this line."
16822 (interactive)
16823 (org-columns-check-computed)
16824 (let* ((external-key key)
16825 (col (current-column))
16826 (key (or key (get-char-property (point) 'org-columns-key)))
16827 (value (get-char-property (point) 'org-columns-value))
16828 (bol (point-at-bol)) (eol (point-at-eol))
16829 (pom (or (get-text-property bol 'org-hd-marker)
16830 (point))) ; keep despite of compiler waring
16831 (line-overlays
16832 (delq nil (mapcar (lambda (x)
16833 (and (eq (overlay-buffer x) (current-buffer))
16834 (>= (overlay-start x) bol)
16835 (<= (overlay-start x) eol)
16837 org-columns-overlays)))
16838 nval eval allowed)
16839 (cond
16840 ((equal key "CLOCKSUM")
16841 (error "This special column cannot be edited"))
16842 ((equal key "ITEM")
16843 (setq eval '(org-with-point-at pom
16844 (org-edit-headline))))
16845 ((equal key "TODO")
16846 (setq eval '(org-with-point-at pom
16847 (let ((current-prefix-arg
16848 (if external-key current-prefix-arg '(4))))
16849 (call-interactively 'org-todo)))))
16850 ((equal key "PRIORITY")
16851 (setq eval '(org-with-point-at pom
16852 (call-interactively 'org-priority))))
16853 ((equal key "TAGS")
16854 (setq eval '(org-with-point-at pom
16855 (let ((org-fast-tag-selection-single-key
16856 (if (eq org-fast-tag-selection-single-key 'expert)
16857 t org-fast-tag-selection-single-key)))
16858 (call-interactively 'org-set-tags)))))
16859 ((equal key "DEADLINE")
16860 (setq eval '(org-with-point-at pom
16861 (call-interactively 'org-deadline))))
16862 ((equal key "SCHEDULED")
16863 (setq eval '(org-with-point-at pom
16864 (call-interactively 'org-schedule))))
16866 (setq allowed (org-property-get-allowed-values pom key 'table))
16867 (if allowed
16868 (setq nval (completing-read "Value: " allowed nil t))
16869 (setq nval (read-string "Edit: " value)))
16870 (setq nval (org-trim nval))
16871 (when (not (equal nval value))
16872 (setq eval '(org-entry-put pom key nval)))))
16873 (when eval
16874 (let ((inhibit-read-only t))
16875 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16876 (unwind-protect
16877 (progn
16878 (setq org-columns-overlays
16879 (org-delete-all line-overlays org-columns-overlays))
16880 (mapc 'org-delete-overlay line-overlays)
16881 (org-columns-eval eval))
16882 (org-columns-display-here))))
16883 (move-to-column col)
16884 (if (and (org-mode-p)
16885 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16886 (org-columns-update key))))
16888 (defun org-edit-headline () ; FIXME: this is not columns specific
16889 "Edit the current headline, the part without TODO keyword, TAGS."
16890 (org-back-to-heading)
16891 (when (looking-at org-todo-line-regexp)
16892 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16893 (txt (match-string 3))
16894 (post "")
16895 txt2)
16896 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16897 (setq post (match-string 0 txt)
16898 txt (substring txt 0 (match-beginning 0))))
16899 (setq txt2 (read-string "Edit: " txt))
16900 (when (not (equal txt txt2))
16901 (beginning-of-line 1)
16902 (insert pre txt2 post)
16903 (delete-region (point) (point-at-eol))
16904 (org-set-tags nil t)))))
16906 (defun org-columns-edit-allowed ()
16907 "Edit the list of allowed values for the current property."
16908 (interactive)
16909 (let* ((key (get-char-property (point) 'org-columns-key))
16910 (key1 (concat key "_ALL"))
16911 (allowed (org-entry-get (point) key1 t))
16912 nval)
16913 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16914 (setq nval (read-string "Allowed: " allowed))
16915 (org-entry-put
16916 (cond ((marker-position org-entry-property-inherited-from)
16917 org-entry-property-inherited-from)
16918 ((marker-position org-columns-top-level-marker)
16919 org-columns-top-level-marker))
16920 key1 nval)))
16922 (defmacro org-no-warnings (&rest body)
16923 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16925 (defun org-columns-eval (form)
16926 (let (hidep)
16927 (save-excursion
16928 (beginning-of-line 1)
16929 ;; `next-line' is needed here, because it skips invisible line.
16930 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16931 (setq hidep (org-on-heading-p 1)))
16932 (eval form)
16933 (and hidep (hide-entry))))
16935 (defun org-columns-previous-allowed-value ()
16936 "Switch to the previous allowed value for this column."
16937 (interactive)
16938 (org-columns-next-allowed-value t))
16940 (defun org-columns-next-allowed-value (&optional previous)
16941 "Switch to the next allowed value for this column."
16942 (interactive)
16943 (org-columns-check-computed)
16944 (let* ((col (current-column))
16945 (key (get-char-property (point) 'org-columns-key))
16946 (value (get-char-property (point) 'org-columns-value))
16947 (bol (point-at-bol)) (eol (point-at-eol))
16948 (pom (or (get-text-property bol 'org-hd-marker)
16949 (point))) ; keep despite of compiler waring
16950 (line-overlays
16951 (delq nil (mapcar (lambda (x)
16952 (and (eq (overlay-buffer x) (current-buffer))
16953 (>= (overlay-start x) bol)
16954 (<= (overlay-start x) eol)
16956 org-columns-overlays)))
16957 (allowed (or (org-property-get-allowed-values pom key)
16958 (and (memq
16959 (nth 4 (assoc key org-columns-current-fmt-compiled))
16960 '(checkbox checkbox-n-of-m checkbox-percent))
16961 '("[ ]" "[X]"))))
16962 nval)
16963 (when (equal key "ITEM")
16964 (error "Cannot edit item headline from here"))
16965 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16966 (error "Allowed values for this property have not been defined"))
16967 (if (member key '("SCHEDULED" "DEADLINE"))
16968 (setq nval (if previous 'earlier 'later))
16969 (if previous (setq allowed (reverse allowed)))
16970 (if (member value allowed)
16971 (setq nval (car (cdr (member value allowed)))))
16972 (setq nval (or nval (car allowed)))
16973 (if (equal nval value)
16974 (error "Only one allowed value for this property")))
16975 (let ((inhibit-read-only t))
16976 (remove-text-properties (1- bol) eol '(read-only t))
16977 (unwind-protect
16978 (progn
16979 (setq org-columns-overlays
16980 (org-delete-all line-overlays org-columns-overlays))
16981 (mapc 'org-delete-overlay line-overlays)
16982 (org-columns-eval '(org-entry-put pom key nval)))
16983 (org-columns-display-here)))
16984 (move-to-column col)
16985 (if (and (org-mode-p)
16986 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16987 (org-columns-update key))))
16989 (defun org-verify-version (task)
16990 (cond
16991 ((eq task 'columns)
16992 (if (or (featurep 'xemacs)
16993 (< emacs-major-version 22))
16994 (error "Emacs 22 is required for the columns feature")))))
16996 (defun org-columns-open-link (&optional arg)
16997 (interactive "P")
16998 (let ((value (get-char-property (point) 'org-columns-value)))
16999 (org-open-link-from-string value arg)))
17001 (defun org-open-link-from-string (s &optional arg)
17002 "Open a link in the string S, as if it was in Org-mode."
17003 (interactive)
17004 (with-temp-buffer
17005 (let ((org-inhibit-startup t))
17006 (org-mode)
17007 (insert s)
17008 (goto-char (point-min))
17009 (org-open-at-point arg))))
17011 (defun org-columns-get-format-and-top-level ()
17012 (let (fmt)
17013 (when (condition-case nil (org-back-to-heading) (error nil))
17014 (move-marker org-entry-property-inherited-from nil)
17015 (setq fmt (org-entry-get nil "COLUMNS" t)))
17016 (setq fmt (or fmt org-columns-default-format))
17017 (org-set-local 'org-columns-current-fmt fmt)
17018 (org-columns-compile-format fmt)
17019 (if (marker-position org-entry-property-inherited-from)
17020 (move-marker org-columns-top-level-marker
17021 org-entry-property-inherited-from)
17022 (move-marker org-columns-top-level-marker (point)))
17023 fmt))
17025 (defun org-columns ()
17026 "Turn on column view on an org-mode file."
17027 (interactive)
17028 (org-verify-version 'columns)
17029 (org-columns-remove-overlays)
17030 (move-marker org-columns-begin-marker (point))
17031 (let (beg end fmt cache maxwidths)
17032 (setq fmt (org-columns-get-format-and-top-level))
17033 (save-excursion
17034 (goto-char org-columns-top-level-marker)
17035 (setq beg (point))
17036 (unless org-columns-inhibit-recalculation
17037 (org-columns-compute-all))
17038 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
17039 (point-max)))
17040 ;; Get and cache the properties
17041 (goto-char beg)
17042 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
17043 (save-excursion
17044 (save-restriction
17045 (narrow-to-region beg end)
17046 (org-clock-sum))))
17047 (while (re-search-forward (concat "^" outline-regexp) end t)
17048 (push (cons (org-current-line) (org-entry-properties)) cache))
17049 (when cache
17050 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17051 (org-set-local 'org-columns-current-maxwidths maxwidths)
17052 (org-columns-display-here-title)
17053 (mapc (lambda (x)
17054 (goto-line (car x))
17055 (org-columns-display-here (cdr x)))
17056 cache)))))
17058 (defun org-columns-new (&optional prop title width op fmt &rest rest)
17059 "Insert a new column, to the leeft o the current column."
17060 (interactive)
17061 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
17062 cell)
17063 (setq prop (completing-read
17064 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
17065 nil nil prop))
17066 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
17067 (setq width (read-string "Column width: " (if width (number-to-string width))))
17068 (if (string-match "\\S-" width)
17069 (setq width (string-to-number width))
17070 (setq width nil))
17071 (setq fmt (completing-read "Summary [none]: "
17072 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
17073 nil t))
17074 (if (string-match "\\S-" fmt)
17075 (setq fmt (intern fmt))
17076 (setq fmt nil))
17077 (if (eq fmt 'none) (setq fmt nil))
17078 (if editp
17079 (progn
17080 (setcar editp prop)
17081 (setcdr editp (list title width nil fmt)))
17082 (setq cell (nthcdr (1- (current-column))
17083 org-columns-current-fmt-compiled))
17084 (setcdr cell (cons (list prop title width nil fmt)
17085 (cdr cell))))
17086 (org-columns-store-format)
17087 (org-columns-redo)))
17089 (defun org-columns-delete ()
17090 "Delete the column at point from columns view."
17091 (interactive)
17092 (let* ((n (current-column))
17093 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
17094 (when (y-or-n-p
17095 (format "Are you sure you want to remove column \"%s\"? " title))
17096 (setq org-columns-current-fmt-compiled
17097 (delq (nth n org-columns-current-fmt-compiled)
17098 org-columns-current-fmt-compiled))
17099 (org-columns-store-format)
17100 (org-columns-redo)
17101 (if (>= (current-column) (length org-columns-current-fmt-compiled))
17102 (backward-char 1)))))
17104 (defun org-columns-edit-attributes ()
17105 "Edit the attributes of the current column."
17106 (interactive)
17107 (let* ((n (current-column))
17108 (info (nth n org-columns-current-fmt-compiled)))
17109 (apply 'org-columns-new info)))
17111 (defun org-columns-widen (arg)
17112 "Make the column wider by ARG characters."
17113 (interactive "p")
17114 (let* ((n (current-column))
17115 (entry (nth n org-columns-current-fmt-compiled))
17116 (width (or (nth 2 entry)
17117 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
17118 (setq width (max 1 (+ width arg)))
17119 (setcar (nthcdr 2 entry) width)
17120 (org-columns-store-format)
17121 (org-columns-redo)))
17123 (defun org-columns-narrow (arg)
17124 "Make the column nrrower by ARG characters."
17125 (interactive "p")
17126 (org-columns-widen (- arg)))
17128 (defun org-columns-move-right ()
17129 "Swap this column with the one to the right."
17130 (interactive)
17131 (let* ((n (current-column))
17132 (cell (nthcdr n org-columns-current-fmt-compiled))
17134 (when (>= n (1- (length org-columns-current-fmt-compiled)))
17135 (error "Cannot shift this column further to the right"))
17136 (setq e (car cell))
17137 (setcar cell (car (cdr cell)))
17138 (setcdr cell (cons e (cdr (cdr cell))))
17139 (org-columns-store-format)
17140 (org-columns-redo)
17141 (forward-char 1)))
17143 (defun org-columns-move-left ()
17144 "Swap this column with the one to the left."
17145 (interactive)
17146 (let* ((n (current-column)))
17147 (when (= n 0)
17148 (error "Cannot shift this column further to the left"))
17149 (backward-char 1)
17150 (org-columns-move-right)
17151 (backward-char 1)))
17153 (defun org-columns-store-format ()
17154 "Store the text version of the current columns format in appropriate place.
17155 This is either in the COLUMNS property of the node starting the current column
17156 display, or in the #+COLUMNS line of the current buffer."
17157 (let (fmt (cnt 0))
17158 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17159 (org-set-local 'org-columns-current-fmt fmt)
17160 (if (marker-position org-columns-top-level-marker)
17161 (save-excursion
17162 (goto-char org-columns-top-level-marker)
17163 (if (and (org-at-heading-p)
17164 (org-entry-get nil "COLUMNS"))
17165 (org-entry-put nil "COLUMNS" fmt)
17166 (goto-char (point-min))
17167 ;; Overwrite all #+COLUMNS lines....
17168 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17169 (setq cnt (1+ cnt))
17170 (replace-match (concat "#+COLUMNS: " fmt) t t))
17171 (unless (> cnt 0)
17172 (goto-char (point-min))
17173 (or (org-on-heading-p t) (outline-next-heading))
17174 (let ((inhibit-read-only t))
17175 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17176 (org-set-local 'org-columns-default-format fmt))))))
17178 (defvar org-overriding-columns-format nil
17179 "When set, overrides any other definition.")
17180 (defvar org-agenda-view-columns-initially nil
17181 "When set, switch to columns view immediately after creating the agenda.")
17183 (defun org-agenda-columns ()
17184 "Turn on column view in the agenda."
17185 (interactive)
17186 (org-verify-version 'columns)
17187 (org-columns-remove-overlays)
17188 (move-marker org-columns-begin-marker (point))
17189 (let (fmt cache maxwidths m)
17190 (cond
17191 ((and (local-variable-p 'org-overriding-columns-format)
17192 org-overriding-columns-format)
17193 (setq fmt org-overriding-columns-format))
17194 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17195 (setq fmt (org-entry-get m "COLUMNS" t)))
17196 ((and (boundp 'org-columns-current-fmt)
17197 (local-variable-p 'org-columns-current-fmt)
17198 org-columns-current-fmt)
17199 (setq fmt org-columns-current-fmt))
17200 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17201 (setq m (get-text-property m 'org-hd-marker))
17202 (setq fmt (org-entry-get m "COLUMNS" t))))
17203 (setq fmt (or fmt org-columns-default-format))
17204 (org-set-local 'org-columns-current-fmt fmt)
17205 (org-columns-compile-format fmt)
17206 (save-excursion
17207 ;; Get and cache the properties
17208 (goto-char (point-min))
17209 (while (not (eobp))
17210 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17211 (get-text-property (point) 'org-marker)))
17212 (push (cons (org-current-line) (org-entry-properties m)) cache))
17213 (beginning-of-line 2))
17214 (when cache
17215 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17216 (org-set-local 'org-columns-current-maxwidths maxwidths)
17217 (org-columns-display-here-title)
17218 (mapc (lambda (x)
17219 (goto-line (car x))
17220 (org-columns-display-here (cdr x)))
17221 cache)))))
17223 (defun org-columns-get-autowidth-alist (s cache)
17224 "Derive the maximum column widths from the format and the cache."
17225 (let ((start 0) rtn)
17226 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17227 (push (cons (match-string 1 s) 1) rtn)
17228 (setq start (match-end 0)))
17229 (mapc (lambda (x)
17230 (setcdr x (apply 'max
17231 (mapcar
17232 (lambda (y)
17233 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17234 cache))))
17235 rtn)
17236 rtn))
17238 (defun org-columns-compute-all ()
17239 "Compute all columns that have operators defined."
17240 (org-unmodified
17241 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17242 (let ((columns org-columns-current-fmt-compiled) col)
17243 (while (setq col (pop columns))
17244 (when (nth 3 col)
17245 (save-excursion
17246 (org-columns-compute (car col)))))))
17248 (defun org-columns-update (property)
17249 "Recompute PROPERTY, and update the columns display for it."
17250 (org-columns-compute property)
17251 (let (fmt val pos)
17252 (save-excursion
17253 (mapc (lambda (ov)
17254 (when (equal (org-overlay-get ov 'org-columns-key) property)
17255 (setq pos (org-overlay-start ov))
17256 (goto-char pos)
17257 (when (setq val (cdr (assoc property
17258 (get-text-property
17259 (point-at-bol) 'org-summaries))))
17260 (setq fmt (org-overlay-get ov 'org-columns-format))
17261 (org-overlay-put ov 'org-columns-value val)
17262 (org-overlay-put ov 'display (format fmt val)))))
17263 org-columns-overlays))))
17265 (defun org-columns-compute (property)
17266 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17267 (interactive)
17268 (let* ((re (concat "^" outline-regexp))
17269 (lmax 30) ; Does anyone use deeper levels???
17270 (lsum (make-vector lmax 0))
17271 (lflag (make-vector lmax nil))
17272 (level 0)
17273 (ass (assoc property org-columns-current-fmt-compiled))
17274 (format (nth 4 ass))
17275 (printf (nth 5 ass))
17276 (beg org-columns-top-level-marker)
17277 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17278 (save-excursion
17279 ;; Find the region to compute
17280 (goto-char beg)
17281 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17282 (goto-char end)
17283 ;; Walk the tree from the back and do the computations
17284 (while (re-search-backward re beg t)
17285 (setq sumpos (match-beginning 0)
17286 last-level level
17287 level (org-outline-level)
17288 val (org-entry-get nil property)
17289 valflag (and val (string-match "\\S-" val)))
17290 (cond
17291 ((< level last-level)
17292 ;; put the sum of lower levels here as a property
17293 (setq sum (aref lsum last-level) ; current sum
17294 flag (aref lflag last-level) ; any valid entries from children?
17295 str (org-column-number-to-string sum format printf)
17296 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17297 useval (if flag str1 (if valflag val ""))
17298 sum-alist (get-text-property sumpos 'org-summaries))
17299 (if (assoc property sum-alist)
17300 (setcdr (assoc property sum-alist) useval)
17301 (push (cons property useval) sum-alist)
17302 (org-unmodified
17303 (add-text-properties sumpos (1+ sumpos)
17304 (list 'org-summaries sum-alist))))
17305 (when val
17306 (org-entry-put nil property (if flag str val)))
17307 ;; add current to current level accumulator
17308 (when (or flag valflag)
17309 (aset lsum level (+ (aref lsum level)
17310 (if flag sum (org-column-string-to-number
17311 (if flag str val) format))))
17312 (aset lflag level t))
17313 ;; clear accumulators for deeper levels
17314 (loop for l from (1+ level) to (1- lmax) do
17315 (aset lsum l 0)
17316 (aset lflag l nil)))
17317 ((>= level last-level)
17318 ;; add what we have here to the accumulator for this level
17319 (aset lsum level (+ (aref lsum level)
17320 (org-column-string-to-number (or val "0") format)))
17321 (and valflag (aset lflag level t)))
17322 (t (error "This should not happen")))))))
17324 (defun org-columns-redo ()
17325 "Construct the column display again."
17326 (interactive)
17327 (message "Recomputing columns...")
17328 (save-excursion
17329 (if (marker-position org-columns-begin-marker)
17330 (goto-char org-columns-begin-marker))
17331 (org-columns-remove-overlays)
17332 (if (org-mode-p)
17333 (call-interactively 'org-columns)
17334 (call-interactively 'org-agenda-columns)))
17335 (message "Recomputing columns...done"))
17337 (defun org-columns-not-in-agenda ()
17338 (if (eq major-mode 'org-agenda-mode)
17339 (error "This command is only allowed in Org-mode buffers")))
17342 (defun org-string-to-number (s)
17343 "Convert string to number, and interpret hh:mm:ss."
17344 (if (not (string-match ":" s))
17345 (string-to-number s)
17346 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17347 (while l
17348 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17349 sum)))
17351 (defun org-column-number-to-string (n fmt &optional printf)
17352 "Convert a computed column number to a string value, according to FMT."
17353 (cond
17354 ((eq fmt 'add_times)
17355 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17356 (format "%d:%02d" h m)))
17357 ((eq fmt 'checkbox)
17358 (cond ((= n (floor n)) "[X]")
17359 ((> n 1.) "[-]")
17360 (t "[ ]")))
17361 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17362 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17363 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17364 (printf (format printf n))
17365 ((eq fmt 'currency)
17366 (format "%.2f" n))
17367 (t (number-to-string n))))
17369 (defun org-nofm-to-completion (n m &optional percent)
17370 (if (not percent)
17371 (format "[%d/%d]" n m)
17372 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17374 (defun org-column-string-to-number (s fmt)
17375 "Convert a column value to a number that can be used for column computing."
17376 (cond
17377 ((string-match ":" s)
17378 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17379 (while l
17380 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17381 sum))
17382 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17383 (if (equal s "[X]") 1. 0.000001))
17384 (t (string-to-number s))))
17386 (defun org-columns-uncompile-format (cfmt)
17387 "Turn the compiled columns format back into a string representation."
17388 (let ((rtn "") e s prop title op width fmt printf)
17389 (while (setq e (pop cfmt))
17390 (setq prop (car e)
17391 title (nth 1 e)
17392 width (nth 2 e)
17393 op (nth 3 e)
17394 fmt (nth 4 e)
17395 printf (nth 5 e))
17396 (cond
17397 ((eq fmt 'add_times) (setq op ":"))
17398 ((eq fmt 'checkbox) (setq op "X"))
17399 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17400 ((eq fmt 'checkbox-percent) (setq op "X%"))
17401 ((eq fmt 'add_numbers) (setq op "+"))
17402 ((eq fmt 'currency) (setq op "$")))
17403 (if (and op printf) (setq op (concat op ";" printf)))
17404 (if (equal title prop) (setq title nil))
17405 (setq s (concat "%" (if width (number-to-string width))
17406 prop
17407 (if title (concat "(" title ")"))
17408 (if op (concat "{" op "}"))))
17409 (setq rtn (concat rtn " " s)))
17410 (org-trim rtn)))
17412 (defun org-columns-compile-format (fmt)
17413 "Turn a column format string into an alist of specifications.
17414 The alist has one entry for each column in the format. The elements of
17415 that list are:
17416 property the property
17417 title the title field for the columns
17418 width the column width in characters, can be nil for automatic
17419 operator the operator if any
17420 format the output format for computed results, derived from operator
17421 printf a printf format for computed values"
17422 (let ((start 0) width prop title op f printf)
17423 (setq org-columns-current-fmt-compiled nil)
17424 (while (string-match
17425 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17426 fmt start)
17427 (setq start (match-end 0)
17428 width (match-string 1 fmt)
17429 prop (match-string 2 fmt)
17430 title (or (match-string 3 fmt) prop)
17431 op (match-string 4 fmt)
17432 f nil
17433 printf nil)
17434 (if width (setq width (string-to-number width)))
17435 (when (and op (string-match ";" op))
17436 (setq printf (substring op (match-end 0))
17437 op (substring op 0 (match-beginning 0))))
17438 (cond
17439 ((equal op "+") (setq f 'add_numbers))
17440 ((equal op "$") (setq f 'currency))
17441 ((equal op ":") (setq f 'add_times))
17442 ((equal op "X") (setq f 'checkbox))
17443 ((equal op "X/") (setq f 'checkbox-n-of-m))
17444 ((equal op "X%") (setq f 'checkbox-percent))
17446 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17447 (setq org-columns-current-fmt-compiled
17448 (nreverse org-columns-current-fmt-compiled))))
17451 ;;; Dynamic block for Column view
17453 (defun org-columns-capture-view (&optional maxlevel skip-empty-rows)
17454 "Get the column view of the current buffer or subtree.
17455 The first optional argument MAXLEVEL sets the level limit. A
17456 second optional argument SKIP-EMPTY-ROWS tells whether to skip
17457 empty rows, an empty row being one where all the column view
17458 specifiers except ITEM are empty. This function returns a list
17459 containing the title row and all other rows. Each row is a list
17460 of fields."
17461 (save-excursion
17462 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17463 (n (length title)) row tbl)
17464 (goto-char (point-min))
17465 (while (and (re-search-forward "^\\(\\*+\\) " nil t)
17466 (or (null maxlevel)
17467 (>= maxlevel
17468 (if org-odd-levels-only
17469 (/ (1+ (length (match-string 1))) 2)
17470 (length (match-string 1))))))
17471 (when (get-char-property (match-beginning 0) 'org-columns-key)
17472 (setq row nil)
17473 (loop for i from 0 to (1- n) do
17474 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17475 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17477 row))
17478 (setq row (nreverse row))
17479 (unless (and skip-empty-rows
17480 (eq 1 (length (delete "" (delete-dups row)))))
17481 (push row tbl))))
17482 (append (list title 'hline) (nreverse tbl)))))
17484 (defun org-dblock-write:columnview (params)
17485 "Write the column view table.
17486 PARAMS is a property list of parameters:
17488 :width enforce same column widths with <N> specifiers.
17489 :id the :ID: property of the entry where the columns view
17490 should be built, as a string. When `local', call locally.
17491 When `global' call column view with the cursor at the beginning
17492 of the buffer (usually this means that the whole buffer switches
17493 to column view).
17494 :hlines When t, insert a hline before each item. When a number, insert
17495 a hline before each level <= that number.
17496 :vlines When t, make each column a colgroup to enforce vertical lines.
17497 :maxlevel When set to a number, don't capture headlines below this level.
17498 :skip-empty-rows
17499 When t, skip rows where all specifiers other than ITEM are empty."
17500 (let ((pos (move-marker (make-marker) (point)))
17501 (hlines (plist-get params :hlines))
17502 (vlines (plist-get params :vlines))
17503 (maxlevel (plist-get params :maxlevel))
17504 (skip-empty-rows (plist-get params :skip-empty-rows))
17505 tbl id idpos nfields tmp)
17506 (save-excursion
17507 (save-restriction
17508 (when (setq id (plist-get params :id))
17509 (cond ((not id) nil)
17510 ((eq id 'global) (goto-char (point-min)))
17511 ((eq id 'local) nil)
17512 ((setq idpos (org-find-entry-with-id id))
17513 (goto-char idpos))
17514 (t (error "Cannot find entry with :ID: %s" id))))
17515 (org-columns)
17516 (setq tbl (org-columns-capture-view maxlevel skip-empty-rows))
17517 (setq nfields (length (car tbl)))
17518 (org-columns-quit)))
17519 (goto-char pos)
17520 (move-marker pos nil)
17521 (when tbl
17522 (when (plist-get params :hlines)
17523 (setq tmp nil)
17524 (while tbl
17525 (if (eq (car tbl) 'hline)
17526 (push (pop tbl) tmp)
17527 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17528 (if (and (not (eq (car tmp) 'hline))
17529 (or (eq hlines t)
17530 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17531 (push 'hline tmp)))
17532 (push (pop tbl) tmp)))
17533 (setq tbl (nreverse tmp)))
17534 (when vlines
17535 (setq tbl (mapcar (lambda (x)
17536 (if (eq 'hline x) x (cons "" x)))
17537 tbl))
17538 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17539 (setq pos (point))
17540 (insert (org-listtable-to-string tbl))
17541 (when (plist-get params :width)
17542 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17543 org-columns-current-widths "|")))
17544 (goto-char pos)
17545 (org-table-align))))
17547 (defun org-listtable-to-string (tbl)
17548 "Convert a listtable TBL to a string that contains the Org-mode table.
17549 The table still need to be alligned. The resulting string has no leading
17550 and tailing newline characters."
17551 (mapconcat
17552 (lambda (x)
17553 (cond
17554 ((listp x)
17555 (concat "|" (mapconcat 'identity x "|") "|"))
17556 ((eq x 'hline) "|-|")
17557 (t (error "Garbage in listtable: %s" x))))
17558 tbl "\n"))
17560 (defun org-insert-columns-dblock ()
17561 "Create a dynamic block capturing a column view table."
17562 (interactive)
17563 (let ((defaults '(:name "columnview" :hlines 1))
17564 (id (completing-read
17565 "Capture columns (local, global, entry with :ID: property) [local]: "
17566 (append '(("global") ("local"))
17567 (mapcar 'list (org-property-values "ID"))))))
17568 (if (equal id "") (setq id 'local))
17569 (if (equal id "global") (setq id 'global))
17570 (setq defaults (append defaults (list :id id)))
17571 (org-create-dblock defaults)
17572 (org-update-dblock)))
17574 ;;;; Timestamps
17576 (defvar org-last-changed-timestamp nil)
17577 (defvar org-time-was-given) ; dynamically scoped parameter
17578 (defvar org-end-time-was-given) ; dynamically scoped parameter
17579 (defvar org-ts-what) ; dynamically scoped parameter
17581 (defun org-time-stamp (arg)
17582 "Prompt for a date/time and insert a time stamp.
17583 If the user specifies a time like HH:MM, or if this command is called
17584 with a prefix argument, the time stamp will contain date and time.
17585 Otherwise, only the date will be included. All parts of a date not
17586 specified by the user will be filled in from the current date/time.
17587 So if you press just return without typing anything, the time stamp
17588 will represent the current date/time. If there is already a timestamp
17589 at the cursor, it will be modified."
17590 (interactive "P")
17591 (let* ((ts nil)
17592 (default-time
17593 ;; Default time is either today, or, when entering a range,
17594 ;; the range start.
17595 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17596 (save-excursion
17597 (re-search-backward
17598 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17599 (- (point) 20) t)))
17600 (apply 'encode-time (org-parse-time-string (match-string 1)))
17601 (current-time)))
17602 (default-input (and ts (org-get-compact-tod ts)))
17603 org-time-was-given org-end-time-was-given time)
17604 (cond
17605 ((and (org-at-timestamp-p)
17606 (eq last-command 'org-time-stamp)
17607 (eq this-command 'org-time-stamp))
17608 (insert "--")
17609 (setq time (let ((this-command this-command))
17610 (org-read-date arg 'totime nil nil default-time default-input)))
17611 (org-insert-time-stamp time (or org-time-was-given arg)))
17612 ((org-at-timestamp-p)
17613 (setq time (let ((this-command this-command))
17614 (org-read-date arg 'totime nil nil default-time default-input)))
17615 (when (org-at-timestamp-p) ; just to get the match data
17616 (replace-match "")
17617 (setq org-last-changed-timestamp
17618 (org-insert-time-stamp
17619 time (or org-time-was-given arg)
17620 nil nil nil (list org-end-time-was-given))))
17621 (message "Timestamp updated"))
17623 (setq time (let ((this-command this-command))
17624 (org-read-date arg 'totime nil nil default-time default-input)))
17625 (org-insert-time-stamp time (or org-time-was-given arg)
17626 nil nil nil (list org-end-time-was-given))))))
17628 ;; FIXME: can we use this for something else????
17629 ;; like computing time differences?????
17630 (defun org-get-compact-tod (s)
17631 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17632 (let* ((t1 (match-string 1 s))
17633 (h1 (string-to-number (match-string 2 s)))
17634 (m1 (string-to-number (match-string 3 s)))
17635 (t2 (and (match-end 4) (match-string 5 s)))
17636 (h2 (and t2 (string-to-number (match-string 6 s))))
17637 (m2 (and t2 (string-to-number (match-string 7 s))))
17638 dh dm)
17639 (if (not t2)
17641 (setq dh (- h2 h1) dm (- m2 m1))
17642 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17643 (concat t1 "+" (number-to-string dh)
17644 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17646 (defun org-time-stamp-inactive (&optional arg)
17647 "Insert an inactive time stamp.
17648 An inactive time stamp is enclosed in square brackets instead of angle
17649 brackets. It is inactive in the sense that it does not trigger agenda entries,
17650 does not link to the calendar and cannot be changed with the S-cursor keys.
17651 So these are more for recording a certain time/date."
17652 (interactive "P")
17653 (let (org-time-was-given org-end-time-was-given time)
17654 (setq time (org-read-date arg 'totime))
17655 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17656 nil nil (list org-end-time-was-given))))
17658 (defvar org-date-ovl (org-make-overlay 1 1))
17659 (org-overlay-put org-date-ovl 'face 'org-warning)
17660 (org-detach-overlay org-date-ovl)
17662 (defvar org-ans1) ; dynamically scoped parameter
17663 (defvar org-ans2) ; dynamically scoped parameter
17665 (defvar org-plain-time-of-day-regexp) ; defined below
17667 (defvar org-read-date-overlay nil)
17668 (defvar org-dcst nil) ; dynamically scoped
17670 (defun org-read-date (&optional with-time to-time from-string prompt
17671 default-time default-input)
17672 "Read a date, possibly a time, and make things smooth for the user.
17673 The prompt will suggest to enter an ISO date, but you can also enter anything
17674 which will at least partially be understood by `parse-time-string'.
17675 Unrecognized parts of the date will default to the current day, month, year,
17676 hour and minute. If this command is called to replace a timestamp at point,
17677 of to enter the second timestamp of a range, the default time is taken from the
17678 existing stamp. For example,
17679 3-2-5 --> 2003-02-05
17680 feb 15 --> currentyear-02-15
17681 sep 12 9 --> 2009-09-12
17682 12:45 --> today 12:45
17683 22 sept 0:34 --> currentyear-09-22 0:34
17684 12 --> currentyear-currentmonth-12
17685 Fri --> nearest Friday (today or later)
17686 etc.
17688 Furthermore you can specify a relative date by giving, as the *first* thing
17689 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17690 change in days weeks, months, years.
17691 With a single plus or minus, the date is relative to today. With a double
17692 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17693 +4d --> four days from today
17694 +4 --> same as above
17695 +2w --> two weeks from today
17696 ++5 --> five days from default date
17698 The function understands only English month and weekday abbreviations,
17699 but this can be configured with the variables `parse-time-months' and
17700 `parse-time-weekdays'.
17702 While prompting, a calendar is popped up - you can also select the
17703 date with the mouse (button 1). The calendar shows a period of three
17704 months. To scroll it to other months, use the keys `>' and `<'.
17705 If you don't like the calendar, turn it off with
17706 \(setq org-read-date-popup-calendar nil)
17708 With optional argument TO-TIME, the date will immediately be converted
17709 to an internal time.
17710 With an optional argument WITH-TIME, the prompt will suggest to also
17711 insert a time. Note that when WITH-TIME is not set, you can still
17712 enter a time, and this function will inform the calling routine about
17713 this change. The calling routine may then choose to change the format
17714 used to insert the time stamp into the buffer to include the time.
17715 With optional argument FROM-STRING, read from this string instead from
17716 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17717 the time/date that is used for everything that is not specified by the
17718 user."
17719 (require 'parse-time)
17720 (let* ((org-time-stamp-rounding-minutes
17721 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
17722 (org-dcst org-display-custom-times)
17723 (ct (org-current-time))
17724 (def (or default-time ct))
17725 (defdecode (decode-time def))
17726 (dummy (progn
17727 (when (< (nth 2 defdecode) org-extend-today-until)
17728 (setcar (nthcdr 2 defdecode) -1)
17729 (setcar (nthcdr 1 defdecode) 59)
17730 (setq def (apply 'encode-time defdecode)
17731 defdecode (decode-time def)))))
17732 (calendar-move-hook nil)
17733 (view-diary-entries-initially nil)
17734 (view-calendar-holidays-initially nil)
17735 (timestr (format-time-string
17736 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17737 (prompt (concat (if prompt (concat prompt " ") "")
17738 (format "Date+time [%s]: " timestr)))
17739 ans (org-ans0 "") org-ans1 org-ans2 final)
17741 (cond
17742 (from-string (setq ans from-string))
17743 (org-read-date-popup-calendar
17744 (save-excursion
17745 (save-window-excursion
17746 (calendar)
17747 (calendar-forward-day (- (time-to-days def)
17748 (calendar-absolute-from-gregorian
17749 (calendar-current-date))))
17750 (org-eval-in-calendar nil t)
17751 (let* ((old-map (current-local-map))
17752 (map (copy-keymap calendar-mode-map))
17753 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17754 (org-defkey map (kbd "RET") 'org-calendar-select)
17755 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17756 'org-calendar-select-mouse)
17757 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17758 'org-calendar-select-mouse)
17759 (org-defkey minibuffer-local-map [(meta shift left)]
17760 (lambda () (interactive)
17761 (org-eval-in-calendar '(calendar-backward-month 1))))
17762 (org-defkey minibuffer-local-map [(meta shift right)]
17763 (lambda () (interactive)
17764 (org-eval-in-calendar '(calendar-forward-month 1))))
17765 (org-defkey minibuffer-local-map [(meta shift up)]
17766 (lambda () (interactive)
17767 (org-eval-in-calendar '(calendar-backward-year 1))))
17768 (org-defkey minibuffer-local-map [(meta shift down)]
17769 (lambda () (interactive)
17770 (org-eval-in-calendar '(calendar-forward-year 1))))
17771 (org-defkey minibuffer-local-map [(shift up)]
17772 (lambda () (interactive)
17773 (org-eval-in-calendar '(calendar-backward-week 1))))
17774 (org-defkey minibuffer-local-map [(shift down)]
17775 (lambda () (interactive)
17776 (org-eval-in-calendar '(calendar-forward-week 1))))
17777 (org-defkey minibuffer-local-map [(shift left)]
17778 (lambda () (interactive)
17779 (org-eval-in-calendar '(calendar-backward-day 1))))
17780 (org-defkey minibuffer-local-map [(shift right)]
17781 (lambda () (interactive)
17782 (org-eval-in-calendar '(calendar-forward-day 1))))
17783 (org-defkey minibuffer-local-map ">"
17784 (lambda () (interactive)
17785 (org-eval-in-calendar '(scroll-calendar-left 1))))
17786 (org-defkey minibuffer-local-map "<"
17787 (lambda () (interactive)
17788 (org-eval-in-calendar '(scroll-calendar-right 1))))
17789 (unwind-protect
17790 (progn
17791 (use-local-map map)
17792 (add-hook 'post-command-hook 'org-read-date-display)
17793 (setq org-ans0 (read-string prompt default-input nil nil))
17794 ;; org-ans0: from prompt
17795 ;; org-ans1: from mouse click
17796 ;; org-ans2: from calendar motion
17797 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17798 (remove-hook 'post-command-hook 'org-read-date-display)
17799 (use-local-map old-map)
17800 (when org-read-date-overlay
17801 (org-delete-overlay org-read-date-overlay)
17802 (setq org-read-date-overlay nil)))))))
17804 (t ; Naked prompt only
17805 (unwind-protect
17806 (setq ans (read-string prompt default-input nil timestr))
17807 (when org-read-date-overlay
17808 (org-delete-overlay org-read-date-overlay)
17809 (setq org-read-date-overlay nil)))))
17811 (setq final (org-read-date-analyze ans def defdecode))
17813 (if to-time
17814 (apply 'encode-time final)
17815 (if (and (boundp 'org-time-was-given) org-time-was-given)
17816 (format "%04d-%02d-%02d %02d:%02d"
17817 (nth 5 final) (nth 4 final) (nth 3 final)
17818 (nth 2 final) (nth 1 final))
17819 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17820 (defvar def)
17821 (defvar defdecode)
17822 (defvar with-time)
17823 (defun org-read-date-display ()
17824 "Display the currrent date prompt interpretation in the minibuffer."
17825 (when org-read-date-display-live
17826 (when org-read-date-overlay
17827 (org-delete-overlay org-read-date-overlay))
17828 (let ((p (point)))
17829 (end-of-line 1)
17830 (while (not (equal (buffer-substring
17831 (max (point-min) (- (point) 4)) (point))
17832 " "))
17833 (insert " "))
17834 (goto-char p))
17835 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17836 " " (or org-ans1 org-ans2)))
17837 (org-end-time-was-given nil)
17838 (f (org-read-date-analyze ans def defdecode))
17839 (fmts (if org-dcst
17840 org-time-stamp-custom-formats
17841 org-time-stamp-formats))
17842 (fmt (if (or with-time
17843 (and (boundp 'org-time-was-given) org-time-was-given))
17844 (cdr fmts)
17845 (car fmts)))
17846 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17847 (when (and org-end-time-was-given
17848 (string-match org-plain-time-of-day-regexp txt))
17849 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17850 org-end-time-was-given
17851 (substring txt (match-end 0)))))
17852 (setq org-read-date-overlay
17853 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17854 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17856 (defun org-read-date-analyze (ans def defdecode)
17857 "Analyze the combined answer of the date prompt."
17858 ;; FIXME: cleanup and comment
17859 (let (delta deltan deltaw deltadef year month day
17860 hour minute second wday pm h2 m2 tl wday1)
17862 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17863 (setq ans (replace-match "" t t ans)
17864 deltan (car delta)
17865 deltaw (nth 1 delta)
17866 deltadef (nth 2 delta)))
17868 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17869 (when (string-match
17870 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17871 (setq year (if (match-end 2)
17872 (string-to-number (match-string 2 ans))
17873 (string-to-number (format-time-string "%Y")))
17874 month (string-to-number (match-string 3 ans))
17875 day (string-to-number (match-string 4 ans)))
17876 (if (< year 100) (setq year (+ 2000 year)))
17877 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17878 t nil ans)))
17879 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17880 ;; If there is a time with am/pm, and *no* time without it, we convert
17881 ;; so that matching will be successful.
17882 (loop for i from 1 to 2 do ; twice, for end time as well
17883 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17884 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17885 (setq hour (string-to-number (match-string 1 ans))
17886 minute (if (match-end 3)
17887 (string-to-number (match-string 3 ans))
17889 pm (equal ?p
17890 (string-to-char (downcase (match-string 4 ans)))))
17891 (if (and (= hour 12) (not pm))
17892 (setq hour 0)
17893 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17894 (setq ans (replace-match (format "%02d:%02d" hour minute)
17895 t t ans))))
17897 ;; Check if a time range is given as a duration
17898 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17899 (setq hour (string-to-number (match-string 1 ans))
17900 h2 (+ hour (string-to-number (match-string 3 ans)))
17901 minute (string-to-number (match-string 2 ans))
17902 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17903 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17904 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17906 ;; Check if there is a time range
17907 (when (boundp 'org-end-time-was-given)
17908 (setq org-time-was-given nil)
17909 (when (and (string-match org-plain-time-of-day-regexp ans)
17910 (match-end 8))
17911 (setq org-end-time-was-given (match-string 8 ans))
17912 (setq ans (concat (substring ans 0 (match-beginning 7))
17913 (substring ans (match-end 7))))))
17915 (setq tl (parse-time-string ans)
17916 day (or (nth 3 tl) (nth 3 defdecode))
17917 month (or (nth 4 tl)
17918 (if (and org-read-date-prefer-future
17919 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17920 (1+ (nth 4 defdecode))
17921 (nth 4 defdecode)))
17922 year (or (nth 5 tl)
17923 (if (and org-read-date-prefer-future
17924 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17925 (1+ (nth 5 defdecode))
17926 (nth 5 defdecode)))
17927 hour (or (nth 2 tl) (nth 2 defdecode))
17928 minute (or (nth 1 tl) (nth 1 defdecode))
17929 second (or (nth 0 tl) 0)
17930 wday (nth 6 tl))
17931 (when deltan
17932 (unless deltadef
17933 (let ((now (decode-time (current-time))))
17934 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17935 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17936 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17937 ((equal deltaw "m") (setq month (+ month deltan)))
17938 ((equal deltaw "y") (setq year (+ year deltan)))))
17939 (when (and wday (not (nth 3 tl)))
17940 ;; Weekday was given, but no day, so pick that day in the week
17941 ;; on or after the derived date.
17942 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17943 (unless (equal wday wday1)
17944 (setq day (+ day (% (- wday wday1 -7) 7)))))
17945 (if (and (boundp 'org-time-was-given)
17946 (nth 2 tl))
17947 (setq org-time-was-given t))
17948 (if (< year 100) (setq year (+ 2000 year)))
17949 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17950 (list second minute hour day month year)))
17952 (defvar parse-time-weekdays)
17954 (defun org-read-date-get-relative (s today default)
17955 "Check string S for special relative date string.
17956 TODAY and DEFAULT are internal times, for today and for a default.
17957 Return shift list (N what def-flag)
17958 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17959 N is the number of WHATs to shift.
17960 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17961 the DEFAULT date rather than TODAY."
17962 (when (string-match
17963 (concat
17964 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17965 "\\([0-9]+\\)?"
17966 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17967 "\\([ \t]\\|$\\)") s)
17968 (let* ((dir (if (match-end 1)
17969 (string-to-char (substring (match-string 1 s) -1))
17970 ?+))
17971 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17972 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17973 (what (if (match-end 3) (match-string 3 s) "d"))
17974 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17975 (date (if rel default today))
17976 (wday (nth 6 (decode-time date)))
17977 delta)
17978 (if wday1
17979 (progn
17980 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17981 (if (= dir ?-) (setq delta (- delta 7)))
17982 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17983 (list delta "d" rel))
17984 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17986 (defun org-eval-in-calendar (form &optional keepdate)
17987 "Eval FORM in the calendar window and return to current window.
17988 Also, store the cursor date in variable org-ans2."
17989 (let ((sw (selected-window)))
17990 (select-window (get-buffer-window "*Calendar*"))
17991 (eval form)
17992 (when (and (not keepdate) (calendar-cursor-to-date))
17993 (let* ((date (calendar-cursor-to-date))
17994 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17995 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17996 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17997 (select-window sw)))
17999 ; ;; Update the prompt to show new default date
18000 ; (save-excursion
18001 ; (goto-char (point-min))
18002 ; (when (and org-ans2
18003 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
18004 ; (get-text-property (match-end 0) 'field))
18005 ; (let ((inhibit-read-only t))
18006 ; (replace-match (concat "[" org-ans2 "]") t t)
18007 ; (add-text-properties (point-min) (1+ (match-end 0))
18008 ; (text-properties-at (1+ (point-min)))))))))
18010 (defun org-calendar-select ()
18011 "Return to `org-read-date' with the date currently selected.
18012 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18013 (interactive)
18014 (when (calendar-cursor-to-date)
18015 (let* ((date (calendar-cursor-to-date))
18016 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18017 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18018 (if (active-minibuffer-window) (exit-minibuffer))))
18020 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
18021 "Insert a date stamp for the date given by the internal TIME.
18022 WITH-HM means, use the stamp format that includes the time of the day.
18023 INACTIVE means use square brackets instead of angular ones, so that the
18024 stamp will not contribute to the agenda.
18025 PRE and POST are optional strings to be inserted before and after the
18026 stamp.
18027 The command returns the inserted time stamp."
18028 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
18029 stamp)
18030 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
18031 (insert-before-markers (or pre ""))
18032 (insert-before-markers (setq stamp (format-time-string fmt time)))
18033 (when (listp extra)
18034 (setq extra (car extra))
18035 (if (and (stringp extra)
18036 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
18037 (setq extra (format "-%02d:%02d"
18038 (string-to-number (match-string 1 extra))
18039 (string-to-number (match-string 2 extra))))
18040 (setq extra nil)))
18041 (when extra
18042 (backward-char 1)
18043 (insert-before-markers extra)
18044 (forward-char 1))
18045 (insert-before-markers (or post ""))
18046 stamp))
18048 (defun org-toggle-time-stamp-overlays ()
18049 "Toggle the use of custom time stamp formats."
18050 (interactive)
18051 (setq org-display-custom-times (not org-display-custom-times))
18052 (unless org-display-custom-times
18053 (let ((p (point-min)) (bmp (buffer-modified-p)))
18054 (while (setq p (next-single-property-change p 'display))
18055 (if (and (get-text-property p 'display)
18056 (eq (get-text-property p 'face) 'org-date))
18057 (remove-text-properties
18058 p (setq p (next-single-property-change p 'display))
18059 '(display t))))
18060 (set-buffer-modified-p bmp)))
18061 (if (featurep 'xemacs)
18062 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
18063 (org-restart-font-lock)
18064 (setq org-table-may-need-update t)
18065 (if org-display-custom-times
18066 (message "Time stamps are overlayed with custom format")
18067 (message "Time stamp overlays removed")))
18069 (defun org-display-custom-time (beg end)
18070 "Overlay modified time stamp format over timestamp between BED and END."
18071 (let* ((ts (buffer-substring beg end))
18072 t1 w1 with-hm tf time str w2 (off 0))
18073 (save-match-data
18074 (setq t1 (org-parse-time-string ts t))
18075 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
18076 (setq off (- (match-end 0) (match-beginning 0)))))
18077 (setq end (- end off))
18078 (setq w1 (- end beg)
18079 with-hm (and (nth 1 t1) (nth 2 t1))
18080 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
18081 time (org-fix-decoded-time t1)
18082 str (org-add-props
18083 (format-time-string
18084 (substring tf 1 -1) (apply 'encode-time time))
18085 nil 'mouse-face 'highlight)
18086 w2 (length str))
18087 (if (not (= w2 w1))
18088 (add-text-properties (1+ beg) (+ 2 beg)
18089 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
18090 (if (featurep 'xemacs)
18091 (progn
18092 (put-text-property beg end 'invisible t)
18093 (put-text-property beg end 'end-glyph (make-glyph str)))
18094 (put-text-property beg end 'display str))))
18096 (defun org-translate-time (string)
18097 "Translate all timestamps in STRING to custom format.
18098 But do this only if the variable `org-display-custom-times' is set."
18099 (when org-display-custom-times
18100 (save-match-data
18101 (let* ((start 0)
18102 (re org-ts-regexp-both)
18103 t1 with-hm inactive tf time str beg end)
18104 (while (setq start (string-match re string start))
18105 (setq beg (match-beginning 0)
18106 end (match-end 0)
18107 t1 (save-match-data
18108 (org-parse-time-string (substring string beg end) t))
18109 with-hm (and (nth 1 t1) (nth 2 t1))
18110 inactive (equal (substring string beg (1+ beg)) "[")
18111 tf (funcall (if with-hm 'cdr 'car)
18112 org-time-stamp-custom-formats)
18113 time (org-fix-decoded-time t1)
18114 str (format-time-string
18115 (concat
18116 (if inactive "[" "<") (substring tf 1 -1)
18117 (if inactive "]" ">"))
18118 (apply 'encode-time time))
18119 string (replace-match str t t string)
18120 start (+ start (length str)))))))
18121 string)
18123 (defun org-fix-decoded-time (time)
18124 "Set 0 instead of nil for the first 6 elements of time.
18125 Don't touch the rest."
18126 (let ((n 0))
18127 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
18129 (defun org-days-to-time (timestamp-string)
18130 "Difference between TIMESTAMP-STRING and now in days."
18131 (- (time-to-days (org-time-string-to-time timestamp-string))
18132 (time-to-days (current-time))))
18134 (defun org-deadline-close (timestamp-string &optional ndays)
18135 "Is the time in TIMESTAMP-STRING close to the current date?"
18136 (setq ndays (or ndays (org-get-wdays timestamp-string)))
18137 (and (< (org-days-to-time timestamp-string) ndays)
18138 (not (org-entry-is-done-p))))
18140 (defun org-get-wdays (ts)
18141 "Get the deadline lead time appropriate for timestring TS."
18142 (cond
18143 ((<= org-deadline-warning-days 0)
18144 ;; 0 or negative, enforce this value no matter what
18145 (- org-deadline-warning-days))
18146 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
18147 ;; lead time is specified.
18148 (floor (* (string-to-number (match-string 1 ts))
18149 (cdr (assoc (match-string 2 ts)
18150 '(("d" . 1) ("w" . 7)
18151 ("m" . 30.4) ("y" . 365.25)))))))
18152 ;; go for the default.
18153 (t org-deadline-warning-days)))
18155 (defun org-calendar-select-mouse (ev)
18156 "Return to `org-read-date' with the date currently selected.
18157 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18158 (interactive "e")
18159 (mouse-set-point ev)
18160 (when (calendar-cursor-to-date)
18161 (let* ((date (calendar-cursor-to-date))
18162 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18163 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18164 (if (active-minibuffer-window) (exit-minibuffer))))
18166 (defun org-check-deadlines (ndays)
18167 "Check if there are any deadlines due or past due.
18168 A deadline is considered due if it happens within `org-deadline-warning-days'
18169 days from today's date. If the deadline appears in an entry marked DONE,
18170 it is not shown. The prefix arg NDAYS can be used to test that many
18171 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18172 (interactive "P")
18173 (let* ((org-warn-days
18174 (cond
18175 ((equal ndays '(4)) 100000)
18176 (ndays (prefix-numeric-value ndays))
18177 (t (abs org-deadline-warning-days))))
18178 (case-fold-search nil)
18179 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18180 (callback
18181 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18183 (message "%d deadlines past-due or due within %d days"
18184 (org-occur regexp nil callback)
18185 org-warn-days)))
18187 (defun org-check-before-date (date)
18188 "Check if there are deadlines or scheduled entries before DATE."
18189 (interactive (list (org-read-date)))
18190 (let ((case-fold-search nil)
18191 (regexp (concat "\\<\\(" org-deadline-string
18192 "\\|" org-scheduled-string
18193 "\\) *<\\([^>]+\\)>"))
18194 (callback
18195 (lambda () (time-less-p
18196 (org-time-string-to-time (match-string 2))
18197 (org-time-string-to-time date)))))
18198 (message "%d entries before %s"
18199 (org-occur regexp nil callback) date)))
18201 (defun org-evaluate-time-range (&optional to-buffer)
18202 "Evaluate a time range by computing the difference between start and end.
18203 Normally the result is just printed in the echo area, but with prefix arg
18204 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18205 If the time range is actually in a table, the result is inserted into the
18206 next column.
18207 For time difference computation, a year is assumed to be exactly 365
18208 days in order to avoid rounding problems."
18209 (interactive "P")
18211 (org-clock-update-time-maybe)
18212 (save-excursion
18213 (unless (org-at-date-range-p t)
18214 (goto-char (point-at-bol))
18215 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18216 (if (not (org-at-date-range-p t))
18217 (error "Not at a time-stamp range, and none found in current line")))
18218 (let* ((ts1 (match-string 1))
18219 (ts2 (match-string 2))
18220 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18221 (match-end (match-end 0))
18222 (time1 (org-time-string-to-time ts1))
18223 (time2 (org-time-string-to-time ts2))
18224 (t1 (time-to-seconds time1))
18225 (t2 (time-to-seconds time2))
18226 (diff (abs (- t2 t1)))
18227 (negative (< (- t2 t1) 0))
18228 ;; (ys (floor (* 365 24 60 60)))
18229 (ds (* 24 60 60))
18230 (hs (* 60 60))
18231 (fy "%dy %dd %02d:%02d")
18232 (fy1 "%dy %dd")
18233 (fd "%dd %02d:%02d")
18234 (fd1 "%dd")
18235 (fh "%02d:%02d")
18236 y d h m align)
18237 (if havetime
18238 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18240 d (floor (/ diff ds)) diff (mod diff ds)
18241 h (floor (/ diff hs)) diff (mod diff hs)
18242 m (floor (/ diff 60)))
18243 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18245 d (floor (+ (/ diff ds) 0.5))
18246 h 0 m 0))
18247 (if (not to-buffer)
18248 (message "%s" (org-make-tdiff-string y d h m))
18249 (if (org-at-table-p)
18250 (progn
18251 (goto-char match-end)
18252 (setq align t)
18253 (and (looking-at " *|") (goto-char (match-end 0))))
18254 (goto-char match-end))
18255 (if (looking-at
18256 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18257 (replace-match ""))
18258 (if negative (insert " -"))
18259 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18260 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18261 (insert " " (format fh h m))))
18262 (if align (org-table-align))
18263 (message "Time difference inserted")))))
18265 (defun org-make-tdiff-string (y d h m)
18266 (let ((fmt "")
18267 (l nil))
18268 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18269 l (push y l)))
18270 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18271 l (push d l)))
18272 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18273 l (push h l)))
18274 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18275 l (push m l)))
18276 (apply 'format fmt (nreverse l))))
18278 (defun org-time-string-to-time (s)
18279 (apply 'encode-time (org-parse-time-string s)))
18281 (defun org-time-string-to-absolute (s &optional daynr prefer)
18282 "Convert a time stamp to an absolute day number.
18283 If there is a specifyer for a cyclic time stamp, get the closest date to
18284 DAYNR."
18285 (cond
18286 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18287 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18288 daynr
18289 (+ daynr 1000)))
18290 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18291 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18292 (time-to-days (current-time))) (match-string 0 s)
18293 prefer))
18294 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18296 (defun org-time-from-absolute (d)
18297 "Return the time corresponding to date D.
18298 D may be an absolute day number, or a calendar-type list (month day year)."
18299 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18300 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18302 (defun org-calendar-holiday ()
18303 "List of holidays, for Diary display in Org-mode."
18304 (require 'holidays)
18305 (let ((hl (funcall
18306 (if (fboundp 'calendar-check-holidays)
18307 'calendar-check-holidays 'check-calendar-holidays) date)))
18308 (if hl (mapconcat 'identity hl "; "))))
18310 (defun org-diary-sexp-entry (sexp entry date)
18311 "Process a SEXP diary ENTRY for DATE."
18312 (require 'diary-lib)
18313 (let ((result (if calendar-debug-sexp
18314 (let ((stack-trace-on-error t))
18315 (eval (car (read-from-string sexp))))
18316 (condition-case nil
18317 (eval (car (read-from-string sexp)))
18318 (error
18319 (beep)
18320 (message "Bad sexp at line %d in %s: %s"
18321 (org-current-line)
18322 (buffer-file-name) sexp)
18323 (sleep-for 2))))))
18324 (cond ((stringp result) result)
18325 ((and (consp result)
18326 (stringp (cdr result))) (cdr result))
18327 (result entry)
18328 (t nil))))
18330 (defun org-diary-to-ical-string (frombuf)
18331 "Get iCalendar entries from diary entries in buffer FROMBUF.
18332 This uses the icalendar.el library."
18333 (let* ((tmpdir (if (featurep 'xemacs)
18334 (temp-directory)
18335 temporary-file-directory))
18336 (tmpfile (make-temp-name
18337 (expand-file-name "orgics" tmpdir)))
18338 buf rtn b e)
18339 (save-excursion
18340 (set-buffer frombuf)
18341 (icalendar-export-region (point-min) (point-max) tmpfile)
18342 (setq buf (find-buffer-visiting tmpfile))
18343 (set-buffer buf)
18344 (goto-char (point-min))
18345 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18346 (setq b (match-beginning 0)))
18347 (goto-char (point-max))
18348 (if (re-search-backward "^END:VEVENT" nil t)
18349 (setq e (match-end 0)))
18350 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18351 (kill-buffer buf)
18352 (kill-buffer frombuf)
18353 (delete-file tmpfile)
18354 rtn))
18356 (defun org-closest-date (start current change prefer)
18357 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18358 When PREFER is `past' return a date that is either CURRENT or past.
18359 When PREFER is `future', return a date that is either CURRENT or future."
18360 ;; Make the proper lists from the dates
18361 (catch 'exit
18362 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18363 dn dw sday cday n1 n2
18364 d m y y1 y2 date1 date2 nmonths nm ny m2)
18366 (setq start (org-date-to-gregorian start)
18367 current (org-date-to-gregorian
18368 (if org-agenda-repeating-timestamp-show-all
18369 current
18370 (time-to-days (current-time))))
18371 sday (calendar-absolute-from-gregorian start)
18372 cday (calendar-absolute-from-gregorian current))
18374 (if (<= cday sday) (throw 'exit sday))
18376 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18377 (setq dn (string-to-number (match-string 1 change))
18378 dw (cdr (assoc (match-string 2 change) a1)))
18379 (error "Invalid change specifyer: %s" change))
18380 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18381 (cond
18382 ((eq dw 'day)
18383 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18384 n2 (+ n1 dn)))
18385 ((eq dw 'year)
18386 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18387 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18388 (setq date1 (list m d y1)
18389 n1 (calendar-absolute-from-gregorian date1)
18390 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18391 n2 (calendar-absolute-from-gregorian date2)))
18392 ((eq dw 'month)
18393 ;; approx number of month between the tow dates
18394 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18395 ;; How often does dn fit in there?
18396 (setq d (nth 1 start) m (car start) y (nth 2 start)
18397 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18398 m (+ m nm)
18399 ny (floor (/ m 12))
18400 y (+ y ny)
18401 m (- m (* ny 12)))
18402 (while (> m 12) (setq m (- m 12) y (1+ y)))
18403 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18404 (setq m2 (+ m dn) y2 y)
18405 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18406 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18407 (while (< n2 cday)
18408 (setq n1 n2 m m2 y y2)
18409 (setq m2 (+ m dn) y2 y)
18410 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18411 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18413 (if org-agenda-repeating-timestamp-show-all
18414 (cond
18415 ((eq prefer 'past) n1)
18416 ((eq prefer 'future) (if (= cday n1) n1 n2))
18417 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18418 (cond
18419 ((eq prefer 'past) n1)
18420 ((eq prefer 'future) (if (= cday n1) n1 n2))
18421 (t (if (= cday n1) n1 n2)))))))
18423 (defun org-date-to-gregorian (date)
18424 "Turn any specification of DATE into a gregorian date for the calendar."
18425 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18426 ((and (listp date) (= (length date) 3)) date)
18427 ((stringp date)
18428 (setq date (org-parse-time-string date))
18429 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18430 ((listp date)
18431 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18433 (defun org-parse-time-string (s &optional nodefault)
18434 "Parse the standard Org-mode time string.
18435 This should be a lot faster than the normal `parse-time-string'.
18436 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18437 hour and minute fields will be nil if not given."
18438 (if (string-match org-ts-regexp0 s)
18439 (list 0
18440 (if (or (match-beginning 8) (not nodefault))
18441 (string-to-number (or (match-string 8 s) "0")))
18442 (if (or (match-beginning 7) (not nodefault))
18443 (string-to-number (or (match-string 7 s) "0")))
18444 (string-to-number (match-string 4 s))
18445 (string-to-number (match-string 3 s))
18446 (string-to-number (match-string 2 s))
18447 nil nil nil)
18448 (make-list 9 0)))
18450 (defun org-timestamp-up (&optional arg)
18451 "Increase the date item at the cursor by one.
18452 If the cursor is on the year, change the year. If it is on the month or
18453 the day, change that.
18454 With prefix ARG, change by that many units."
18455 (interactive "p")
18456 (org-timestamp-change (prefix-numeric-value arg)))
18458 (defun org-timestamp-down (&optional arg)
18459 "Decrease the date item at the cursor by one.
18460 If the cursor is on the year, change the year. If it is on the month or
18461 the day, change that.
18462 With prefix ARG, change by that many units."
18463 (interactive "p")
18464 (org-timestamp-change (- (prefix-numeric-value arg))))
18466 (defun org-timestamp-up-day (&optional arg)
18467 "Increase the date in the time stamp by one day.
18468 With prefix ARG, change that many days."
18469 (interactive "p")
18470 (if (and (not (org-at-timestamp-p t))
18471 (org-on-heading-p))
18472 (org-todo 'up)
18473 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18475 (defun org-timestamp-down-day (&optional arg)
18476 "Decrease the date in the time stamp by one day.
18477 With prefix ARG, change that many days."
18478 (interactive "p")
18479 (if (and (not (org-at-timestamp-p t))
18480 (org-on-heading-p))
18481 (org-todo 'down)
18482 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18484 (defsubst org-pos-in-match-range (pos n)
18485 (and (match-beginning n)
18486 (<= (match-beginning n) pos)
18487 (>= (match-end n) pos)))
18489 (defun org-at-timestamp-p (&optional inactive-ok)
18490 "Determine if the cursor is in or at a timestamp."
18491 (interactive)
18492 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18493 (pos (point))
18494 (ans (or (looking-at tsr)
18495 (save-excursion
18496 (skip-chars-backward "^[<\n\r\t")
18497 (if (> (point) (point-min)) (backward-char 1))
18498 (and (looking-at tsr)
18499 (> (- (match-end 0) pos) -1))))))
18500 (and ans
18501 (boundp 'org-ts-what)
18502 (setq org-ts-what
18503 (cond
18504 ((= pos (match-beginning 0)) 'bracket)
18505 ((= pos (1- (match-end 0))) 'bracket)
18506 ((org-pos-in-match-range pos 2) 'year)
18507 ((org-pos-in-match-range pos 3) 'month)
18508 ((org-pos-in-match-range pos 7) 'hour)
18509 ((org-pos-in-match-range pos 8) 'minute)
18510 ((or (org-pos-in-match-range pos 4)
18511 (org-pos-in-match-range pos 5)) 'day)
18512 ((and (> pos (or (match-end 8) (match-end 5)))
18513 (< pos (match-end 0)))
18514 (- pos (or (match-end 8) (match-end 5))))
18515 (t 'day))))
18516 ans))
18518 (defun org-toggle-timestamp-type ()
18519 "Toggle the type (<active> or [inactive]) of a time stamp."
18520 (interactive)
18521 (when (org-at-timestamp-p t)
18522 (save-excursion
18523 (goto-char (match-beginning 0))
18524 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18525 (goto-char (1- (match-end 0)))
18526 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18527 (message "Timestamp is now %sactive"
18528 (if (equal (char-before) ?>) "in" ""))))
18530 (defun org-timestamp-change (n &optional what)
18531 "Change the date in the time stamp at point.
18532 The date will be changed by N times WHAT. WHAT can be `day', `month',
18533 `year', `minute', `second'. If WHAT is not given, the cursor position
18534 in the timestamp determines what will be changed."
18535 (let ((pos (point))
18536 with-hm inactive
18537 (dm (max (nth 1 org-time-stamp-rounding-minutes-when-changing) 1))
18538 org-ts-what
18539 extra rem
18540 ts time time0)
18541 (if (not (org-at-timestamp-p t))
18542 (error "Not at a timestamp"))
18543 (if (and (not what) (eq org-ts-what 'bracket))
18544 (org-toggle-timestamp-type)
18545 (if (and (not what) (not (eq org-ts-what 'day))
18546 org-display-custom-times
18547 (get-text-property (point) 'display)
18548 (not (get-text-property (1- (point)) 'display)))
18549 (setq org-ts-what 'day))
18550 (setq org-ts-what (or what org-ts-what)
18551 inactive (= (char-after (match-beginning 0)) ?\[)
18552 ts (match-string 0))
18553 (replace-match "")
18554 (if (string-match
18555 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18557 (setq extra (match-string 1 ts)))
18558 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18559 (setq with-hm t))
18560 (setq time0 (org-parse-time-string ts))
18561 (when (and (eq org-ts-what 'minute)
18562 (eq current-prefix-arg nil))
18563 (setq n (* dm (signum n)))
18564 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
18565 (setcar (cdr time0) (+ (nth 1 time0)
18566 (if (> n 0) (- rem) (- dm rem))))))
18567 (setq time
18568 (encode-time (or (car time0) 0)
18569 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18570 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18571 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18572 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18573 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18574 (nthcdr 6 time0)))
18575 (when (integerp org-ts-what)
18576 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18577 (if (eq what 'calendar)
18578 (let ((cal-date (org-get-date-from-calendar)))
18579 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18580 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18581 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18582 (setcar time0 (or (car time0) 0))
18583 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18584 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18585 (setq time (apply 'encode-time time0))))
18586 (setq org-last-changed-timestamp
18587 (org-insert-time-stamp time with-hm inactive nil nil extra))
18588 (org-clock-update-time-maybe)
18589 (goto-char pos)
18590 ;; Try to recenter the calendar window, if any
18591 (if (and org-calendar-follow-timestamp-change
18592 (get-buffer-window "*Calendar*" t)
18593 (memq org-ts-what '(day month year)))
18594 (org-recenter-calendar (time-to-days time))))))
18596 ;; FIXME: does not yet work for lead times
18597 (defun org-modify-ts-extra (s pos n)
18598 "Change the different parts of the lead-time and repeat fields in timestamp."
18599 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18600 ng h m new)
18601 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18602 (cond
18603 ((or (org-pos-in-match-range pos 2)
18604 (org-pos-in-match-range pos 3))
18605 (setq m (string-to-number (match-string 3 s))
18606 h (string-to-number (match-string 2 s)))
18607 (if (org-pos-in-match-range pos 2)
18608 (setq h (+ h n))
18609 (setq m (+ m n)))
18610 (if (< m 0) (setq m (+ m 60) h (1- h)))
18611 (if (> m 59) (setq m (- m 60) h (1+ h)))
18612 (setq h (min 24 (max 0 h)))
18613 (setq ng 1 new (format "-%02d:%02d" h m)))
18614 ((org-pos-in-match-range pos 6)
18615 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18616 ((org-pos-in-match-range pos 5)
18617 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18619 (when ng
18620 (setq s (concat
18621 (substring s 0 (match-beginning ng))
18623 (substring s (match-end ng))))))
18626 (defun org-recenter-calendar (date)
18627 "If the calendar is visible, recenter it to DATE."
18628 (let* ((win (selected-window))
18629 (cwin (get-buffer-window "*Calendar*" t))
18630 (calendar-move-hook nil))
18631 (when cwin
18632 (select-window cwin)
18633 (calendar-goto-date (if (listp date) date
18634 (calendar-gregorian-from-absolute date)))
18635 (select-window win))))
18637 (defun org-goto-calendar (&optional arg)
18638 "Go to the Emacs calendar at the current date.
18639 If there is a time stamp in the current line, go to that date.
18640 A prefix ARG can be used to force the current date."
18641 (interactive "P")
18642 (let ((tsr org-ts-regexp) diff
18643 (calendar-move-hook nil)
18644 (view-calendar-holidays-initially nil)
18645 (view-diary-entries-initially nil))
18646 (if (or (org-at-timestamp-p)
18647 (save-excursion
18648 (beginning-of-line 1)
18649 (looking-at (concat ".*" tsr))))
18650 (let ((d1 (time-to-days (current-time)))
18651 (d2 (time-to-days
18652 (org-time-string-to-time (match-string 1)))))
18653 (setq diff (- d2 d1))))
18654 (calendar)
18655 (calendar-goto-today)
18656 (if (and diff (not arg)) (calendar-forward-day diff))))
18658 (defun org-get-date-from-calendar ()
18659 "Return a list (month day year) of date at point in calendar."
18660 (with-current-buffer "*Calendar*"
18661 (save-match-data
18662 (calendar-cursor-to-date))))
18664 (defun org-date-from-calendar ()
18665 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18666 If there is already a time stamp at the cursor position, update it."
18667 (interactive)
18668 (if (org-at-timestamp-p t)
18669 (org-timestamp-change 0 'calendar)
18670 (let ((cal-date (org-get-date-from-calendar)))
18671 (org-insert-time-stamp
18672 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18674 (defvar appt-time-msg-list)
18676 ;;;###autoload
18677 (defun org-agenda-to-appt (&optional refresh filter)
18678 "Activate appointments found in `org-agenda-files'.
18679 With a \\[universal-argument] prefix, refresh the list of
18680 appointements.
18682 If FILTER is t, interactively prompt the user for a regular
18683 expression, and filter out entries that don't match it.
18685 If FILTER is a string, use this string as a regular expression
18686 for filtering entries out.
18688 FILTER can also be an alist with the car of each cell being
18689 either 'headline or 'category. For example:
18691 '((headline \"IMPORTANT\")
18692 (category \"Work\"))
18694 will only add headlines containing IMPORTANT or headlines
18695 belonging to the \"Work\" category."
18696 (interactive "P")
18697 (require 'calendar)
18698 (if refresh (setq appt-time-msg-list nil))
18699 (if (eq filter t)
18700 (setq filter (read-from-minibuffer "Regexp filter: ")))
18701 (let* ((cnt 0) ; count added events
18702 (org-agenda-new-buffers nil)
18703 (org-deadline-warning-days 0)
18704 (today (org-date-to-gregorian
18705 (time-to-days (current-time))))
18706 (files (org-agenda-files)) entries file)
18707 ;; Get all entries which may contain an appt
18708 (while (setq file (pop files))
18709 (setq entries
18710 (append entries
18711 (org-agenda-get-day-entries
18712 file today :timestamp :scheduled :deadline))))
18713 (setq entries (delq nil entries))
18714 ;; Map thru entries and find if we should filter them out
18715 (mapc
18716 (lambda(x)
18717 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18718 (cat (get-text-property 1 'org-category x))
18719 (tod (get-text-property 1 'time-of-day x))
18720 (ok (or (null filter)
18721 (and (stringp filter) (string-match filter evt))
18722 (and (listp filter)
18723 (or (string-match
18724 (cadr (assoc 'category filter)) cat)
18725 (string-match
18726 (cadr (assoc 'headline filter)) evt))))))
18727 ;; FIXME: Shall we remove text-properties for the appt text?
18728 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18729 (when (and ok tod)
18730 (setq tod (number-to-string tod)
18731 tod (when (string-match
18732 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18733 (concat (match-string 1 tod) ":"
18734 (match-string 2 tod))))
18735 (appt-add tod evt)
18736 (setq cnt (1+ cnt))))) entries)
18737 (org-release-buffers org-agenda-new-buffers)
18738 (if (eq cnt 0)
18739 (message "No event to add")
18740 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18742 ;;; The clock for measuring work time.
18744 (defvar org-mode-line-string "")
18745 (put 'org-mode-line-string 'risky-local-variable t)
18747 (defvar org-mode-line-timer nil)
18748 (defvar org-clock-heading "")
18749 (defvar org-clock-start-time "")
18751 (defun org-update-mode-line ()
18752 (let* ((delta (- (time-to-seconds (current-time))
18753 (time-to-seconds org-clock-start-time)))
18754 (h (floor delta 3600))
18755 (m (floor (- delta (* 3600 h)) 60)))
18756 (setq org-mode-line-string
18757 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18758 'help-echo "Org-mode clock is running"))
18759 (force-mode-line-update)))
18761 (defvar org-clock-marker (make-marker)
18762 "Marker recording the last clock-in.")
18763 (defvar org-clock-mode-line-entry nil
18764 "Information for the modeline about the running clock.")
18766 (defun org-clock-in ()
18767 "Start the clock on the current item.
18768 If necessary, clock-out of the currently active clock."
18769 (interactive)
18770 (org-clock-out t)
18771 (let (ts)
18772 (save-excursion
18773 (org-back-to-heading t)
18774 (when (and org-clock-in-switch-to-state
18775 (not (looking-at (concat outline-regexp "[ \t]*"
18776 org-clock-in-switch-to-state
18777 "\\>"))))
18778 (org-todo org-clock-in-switch-to-state))
18779 (if (and org-clock-heading-function
18780 (functionp org-clock-heading-function))
18781 (setq org-clock-heading (funcall org-clock-heading-function))
18782 (if (looking-at org-complex-heading-regexp)
18783 (setq org-clock-heading (match-string 4))
18784 (setq org-clock-heading "???")))
18785 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18786 (org-clock-find-position)
18788 (insert "\n") (backward-char 1)
18789 (indent-relative)
18790 (insert org-clock-string " ")
18791 (setq org-clock-start-time (current-time))
18792 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18793 (move-marker org-clock-marker (point) (buffer-base-buffer))
18794 (or global-mode-string (setq global-mode-string '("")))
18795 (or (memq 'org-mode-line-string global-mode-string)
18796 (setq global-mode-string
18797 (append global-mode-string '(org-mode-line-string))))
18798 (org-update-mode-line)
18799 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18800 (message "Clock started at %s" ts))))
18802 (defun org-clock-find-position ()
18803 "Find the location where the next clock line should be inserted."
18804 (org-back-to-heading t)
18805 (catch 'exit
18806 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18807 (re (concat "^[ \t]*" org-clock-string))
18808 (cnt 0)
18809 first last)
18810 (goto-char beg)
18811 (when (eobp) (newline) (setq end (max (point) end)))
18812 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18813 ;; we seem to have a CLOCK drawer, so go there.
18814 (beginning-of-line 2)
18815 (throw 'exit t))
18816 ;; Lets count the CLOCK lines
18817 (goto-char beg)
18818 (while (re-search-forward re end t)
18819 (setq first (or first (match-beginning 0))
18820 last (match-beginning 0)
18821 cnt (1+ cnt)))
18822 (when (and (integerp org-clock-into-drawer)
18823 (>= (1+ cnt) org-clock-into-drawer))
18824 ;; Wrap current entries into a new drawer
18825 (goto-char last)
18826 (beginning-of-line 2)
18827 (if (org-at-item-p) (org-end-of-item))
18828 (insert ":END:\n")
18829 (beginning-of-line 0)
18830 (org-indent-line-function)
18831 (goto-char first)
18832 (insert ":CLOCK:\n")
18833 (beginning-of-line 0)
18834 (org-indent-line-function)
18835 (org-flag-drawer t)
18836 (beginning-of-line 2)
18837 (throw 'exit nil))
18839 (goto-char beg)
18840 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18841 (not (equal (match-string 1) org-clock-string)))
18842 ;; Planning info, skip to after it
18843 (beginning-of-line 2)
18844 (or (bolp) (newline)))
18845 (when (eq t org-clock-into-drawer)
18846 (insert ":CLOCK:\n:END:\n")
18847 (beginning-of-line -1)
18848 (org-indent-line-function)
18849 (org-flag-drawer t)
18850 (beginning-of-line 2)
18851 (org-indent-line-function)))))
18853 (defun org-clock-out (&optional fail-quietly)
18854 "Stop the currently running clock.
18855 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18856 (interactive)
18857 (catch 'exit
18858 (if (not (marker-buffer org-clock-marker))
18859 (if fail-quietly (throw 'exit t) (error "No active clock")))
18860 (let (ts te s h m)
18861 (save-excursion
18862 (set-buffer (marker-buffer org-clock-marker))
18863 (goto-char org-clock-marker)
18864 (beginning-of-line 1)
18865 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18866 (equal (match-string 1) org-clock-string))
18867 (setq ts (match-string 2))
18868 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18869 (goto-char (match-end 0))
18870 (delete-region (point) (point-at-eol))
18871 (insert "--")
18872 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18873 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18874 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18875 h (floor (/ s 3600))
18876 s (- s (* 3600 h))
18877 m (floor (/ s 60))
18878 s (- s (* 60 s)))
18879 (insert " => " (format "%2d:%02d" h m))
18880 (move-marker org-clock-marker nil)
18881 (when org-log-note-clock-out
18882 (org-add-log-maybe 'clock-out))
18883 (when org-mode-line-timer
18884 (cancel-timer org-mode-line-timer)
18885 (setq org-mode-line-timer nil))
18886 (setq global-mode-string
18887 (delq 'org-mode-line-string global-mode-string))
18888 (force-mode-line-update)
18889 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18891 (defun org-clock-cancel ()
18892 "Cancel the running clock be removing the start timestamp."
18893 (interactive)
18894 (if (not (marker-buffer org-clock-marker))
18895 (error "No active clock"))
18896 (save-excursion
18897 (set-buffer (marker-buffer org-clock-marker))
18898 (goto-char org-clock-marker)
18899 (delete-region (1- (point-at-bol)) (point-at-eol)))
18900 (setq global-mode-string
18901 (delq 'org-mode-line-string global-mode-string))
18902 (force-mode-line-update)
18903 (message "Clock canceled"))
18905 (defun org-clock-goto (&optional delete-windows)
18906 "Go to the currently clocked-in entry."
18907 (interactive "P")
18908 (if (not (marker-buffer org-clock-marker))
18909 (error "No active clock"))
18910 (switch-to-buffer-other-window
18911 (marker-buffer org-clock-marker))
18912 (if delete-windows (delete-other-windows))
18913 (goto-char org-clock-marker)
18914 (org-show-entry)
18915 (org-back-to-heading)
18916 (recenter))
18918 (defvar org-clock-file-total-minutes nil
18919 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18920 (make-variable-buffer-local 'org-clock-file-total-minutes)
18922 (defun org-clock-sum (&optional tstart tend)
18923 "Sum the times for each subtree.
18924 Puts the resulting times in minutes as a text property on each headline."
18925 (interactive)
18926 (let* ((bmp (buffer-modified-p))
18927 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18928 org-clock-string
18929 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18930 (lmax 30)
18931 (ltimes (make-vector lmax 0))
18932 (t1 0)
18933 (level 0)
18934 ts te dt
18935 time)
18936 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18937 (save-excursion
18938 (goto-char (point-max))
18939 (while (re-search-backward re nil t)
18940 (cond
18941 ((match-end 2)
18942 ;; Two time stamps
18943 (setq ts (match-string 2)
18944 te (match-string 3)
18945 ts (time-to-seconds
18946 (apply 'encode-time (org-parse-time-string ts)))
18947 te (time-to-seconds
18948 (apply 'encode-time (org-parse-time-string te)))
18949 ts (if tstart (max ts tstart) ts)
18950 te (if tend (min te tend) te)
18951 dt (- te ts)
18952 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18953 ((match-end 4)
18954 ;; A naket time
18955 (setq t1 (+ t1 (string-to-number (match-string 5))
18956 (* 60 (string-to-number (match-string 4))))))
18957 (t ;; A headline
18958 (setq level (- (match-end 1) (match-beginning 1)))
18959 (when (or (> t1 0) (> (aref ltimes level) 0))
18960 (loop for l from 0 to level do
18961 (aset ltimes l (+ (aref ltimes l) t1)))
18962 (setq t1 0 time (aref ltimes level))
18963 (loop for l from level to (1- lmax) do
18964 (aset ltimes l 0))
18965 (goto-char (match-beginning 0))
18966 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18967 (setq org-clock-file-total-minutes (aref ltimes 0)))
18968 (set-buffer-modified-p bmp)))
18970 (defun org-clock-display (&optional total-only)
18971 "Show subtree times in the entire buffer.
18972 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18973 in the echo area."
18974 (interactive)
18975 (org-remove-clock-overlays)
18976 (let (time h m p)
18977 (org-clock-sum)
18978 (unless total-only
18979 (save-excursion
18980 (goto-char (point-min))
18981 (while (or (and (equal (setq p (point)) (point-min))
18982 (get-text-property p :org-clock-minutes))
18983 (setq p (next-single-property-change
18984 (point) :org-clock-minutes)))
18985 (goto-char p)
18986 (when (setq time (get-text-property p :org-clock-minutes))
18987 (org-put-clock-overlay time (funcall outline-level))))
18988 (setq h (/ org-clock-file-total-minutes 60)
18989 m (- org-clock-file-total-minutes (* 60 h)))
18990 ;; Arrange to remove the overlays upon next change.
18991 (when org-remove-highlights-with-change
18992 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18993 nil 'local))))
18994 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18996 (defvar org-clock-overlays nil)
18997 (make-variable-buffer-local 'org-clock-overlays)
18999 (defun org-put-clock-overlay (time &optional level)
19000 "Put an overlays on the current line, displaying TIME.
19001 If LEVEL is given, prefix time with a corresponding number of stars.
19002 This creates a new overlay and stores it in `org-clock-overlays', so that it
19003 will be easy to remove."
19004 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
19005 (l (if level (org-get-legal-level level 0) 0))
19006 (off 0)
19007 ov tx)
19008 (move-to-column c)
19009 (unless (eolp) (skip-chars-backward "^ \t"))
19010 (skip-chars-backward " \t")
19011 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
19012 tx (concat (buffer-substring (1- (point)) (point))
19013 (make-string (+ off (max 0 (- c (current-column)))) ?.)
19014 (org-add-props (format "%s %2d:%02d%s"
19015 (make-string l ?*) h m
19016 (make-string (- 16 l) ?\ ))
19017 '(face secondary-selection))
19018 ""))
19019 (if (not (featurep 'xemacs))
19020 (org-overlay-put ov 'display tx)
19021 (org-overlay-put ov 'invisible t)
19022 (org-overlay-put ov 'end-glyph (make-glyph tx)))
19023 (push ov org-clock-overlays)))
19025 (defun org-remove-clock-overlays (&optional beg end noremove)
19026 "Remove the occur highlights from the buffer.
19027 BEG and END are ignored. If NOREMOVE is nil, remove this function
19028 from the `before-change-functions' in the current buffer."
19029 (interactive)
19030 (unless org-inhibit-highlight-removal
19031 (mapc 'org-delete-overlay org-clock-overlays)
19032 (setq org-clock-overlays nil)
19033 (unless noremove
19034 (remove-hook 'before-change-functions
19035 'org-remove-clock-overlays 'local))))
19037 (defun org-clock-out-if-current ()
19038 "Clock out if the current entry contains the running clock.
19039 This is used to stop the clock after a TODO entry is marked DONE,
19040 and is only done if the variable `org-clock-out-when-done' is not nil."
19041 (when (and org-clock-out-when-done
19042 (member state org-done-keywords)
19043 (equal (marker-buffer org-clock-marker) (current-buffer))
19044 (< (point) org-clock-marker)
19045 (> (save-excursion (outline-next-heading) (point))
19046 org-clock-marker))
19047 ;; Clock out, but don't accept a logging message for this.
19048 (let ((org-log-note-clock-out nil))
19049 (org-clock-out))))
19051 (add-hook 'org-after-todo-state-change-hook
19052 'org-clock-out-if-current)
19054 (defun org-check-running-clock ()
19055 "Check if the current buffer contains the running clock.
19056 If yes, offer to stop it and to save the buffer with the changes."
19057 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
19058 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
19059 (buffer-name))))
19060 (org-clock-out)
19061 (when (y-or-n-p "Save changed buffer?")
19062 (save-buffer))))
19064 (defun org-clock-report (&optional arg)
19065 "Create a table containing a report about clocked time.
19066 If the cursor is inside an existing clocktable block, then the table
19067 will be updated. If not, a new clocktable will be inserted.
19068 When called with a prefix argument, move to the first clock table in the
19069 buffer and update it."
19070 (interactive "P")
19071 (org-remove-clock-overlays)
19072 (when arg
19073 (org-find-dblock "clocktable")
19074 (org-show-entry))
19075 (if (org-in-clocktable-p)
19076 (goto-char (org-in-clocktable-p))
19077 (org-create-dblock (list :name "clocktable"
19078 :maxlevel 2 :scope 'file)))
19079 (org-update-dblock))
19081 (defun org-in-clocktable-p ()
19082 "Check if the cursor is in a clocktable."
19083 (let ((pos (point)) start)
19084 (save-excursion
19085 (end-of-line 1)
19086 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
19087 (setq start (match-beginning 0))
19088 (re-search-forward "^#\\+END:.*" nil t)
19089 (>= (match-end 0) pos)
19090 start))))
19092 (defun org-clock-update-time-maybe ()
19093 "If this is a CLOCK line, update it and return t.
19094 Otherwise, return nil."
19095 (interactive)
19096 (save-excursion
19097 (beginning-of-line 1)
19098 (skip-chars-forward " \t")
19099 (when (looking-at org-clock-string)
19100 (let ((re (concat "[ \t]*" org-clock-string
19101 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
19102 "\\([ \t]*=>.*\\)?"))
19103 ts te h m s)
19104 (if (not (looking-at re))
19106 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
19107 (end-of-line 1)
19108 (setq ts (match-string 1)
19109 te (match-string 2))
19110 (setq s (- (time-to-seconds
19111 (apply 'encode-time (org-parse-time-string te)))
19112 (time-to-seconds
19113 (apply 'encode-time (org-parse-time-string ts))))
19114 h (floor (/ s 3600))
19115 s (- s (* 3600 h))
19116 m (floor (/ s 60))
19117 s (- s (* 60 s)))
19118 (insert " => " (format "%2d:%02d" h m))
19119 t)))))
19121 (defun org-clock-special-range (key &optional time as-strings)
19122 "Return two times bordering a special time range.
19123 Key is a symbol specifying the range and can be one of `today', `yesterday',
19124 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
19125 A week starts Monday 0:00 and ends Sunday 24:00.
19126 The range is determined relative to TIME. TIME defaults to the current time.
19127 The return value is a cons cell with two internal times like the ones
19128 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
19129 the returned times will be formatted strings."
19130 (let* ((tm (decode-time (or time (current-time))))
19131 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
19132 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
19133 (dow (nth 6 tm))
19134 s1 m1 h1 d1 month1 y1 diff ts te fm)
19135 (cond
19136 ((eq key 'today)
19137 (setq h 0 m 0 h1 24 m1 0))
19138 ((eq key 'yesterday)
19139 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19140 ((eq key 'thisweek)
19141 (setq diff (if (= dow 0) 6 (1- dow))
19142 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19143 ((eq key 'lastweek)
19144 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19145 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19146 ((eq key 'thismonth)
19147 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19148 ((eq key 'lastmonth)
19149 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19150 ((eq key 'thisyear)
19151 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19152 ((eq key 'lastyear)
19153 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19154 (t (error "No such time block %s" key)))
19155 (setq ts (encode-time s m h d month y)
19156 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19157 (or d1 d) (or month1 month) (or y1 y)))
19158 (setq fm (cdr org-time-stamp-formats))
19159 (if as-strings
19160 (cons (format-time-string fm ts) (format-time-string fm te))
19161 (cons ts te))))
19163 (defun org-dblock-write:clocktable (params)
19164 "Write the standard clocktable."
19165 (catch 'exit
19166 (let* ((hlchars '((1 . "*") (2 . "/")))
19167 (ins (make-marker))
19168 (total-time nil)
19169 (scope (plist-get params :scope))
19170 (tostring (plist-get params :tostring))
19171 (multifile (plist-get params :multifile))
19172 (header (plist-get params :header))
19173 (maxlevel (or (plist-get params :maxlevel) 3))
19174 (step (plist-get params :step))
19175 (emph (plist-get params :emphasize))
19176 (ts (plist-get params :tstart))
19177 (te (plist-get params :tend))
19178 (block (plist-get params :block))
19179 ipos time h m p level hlc hdl
19180 cc beg end pos tbl)
19181 (when step
19182 (org-clocktable-steps params)
19183 (throw 'exit nil))
19184 (when block
19185 (setq cc (org-clock-special-range block nil t)
19186 ts (car cc) te (cdr cc)))
19187 (if ts (setq ts (time-to-seconds
19188 (apply 'encode-time (org-parse-time-string ts)))))
19189 (if te (setq te (time-to-seconds
19190 (apply 'encode-time (org-parse-time-string te)))))
19191 (move-marker ins (point))
19192 (setq ipos (point))
19194 ;; Get the right scope
19195 (setq pos (point))
19196 (save-restriction
19197 (cond
19198 ((not scope))
19199 ((eq scope 'file) (widen))
19200 ((eq scope 'subtree) (org-narrow-to-subtree))
19201 ((eq scope 'tree)
19202 (while (org-up-heading-safe))
19203 (org-narrow-to-subtree))
19204 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19205 (symbol-name scope)))
19206 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19207 (catch 'exit
19208 (while (org-up-heading-safe)
19209 (looking-at outline-regexp)
19210 (if (<= (org-reduced-level (funcall outline-level)) level)
19211 (throw 'exit nil))))
19212 (org-narrow-to-subtree))
19213 ((or (listp scope) (eq scope 'agenda))
19214 (let* ((files (if (listp scope) scope (org-agenda-files)))
19215 (scope 'agenda)
19216 (p1 (copy-sequence params))
19217 file)
19218 (plist-put p1 :tostring t)
19219 (plist-put p1 :multifile t)
19220 (plist-put p1 :scope 'file)
19221 (org-prepare-agenda-buffers files)
19222 (while (setq file (pop files))
19223 (with-current-buffer (find-buffer-visiting file)
19224 (push (org-clocktable-add-file
19225 file (org-dblock-write:clocktable p1)) tbl)
19226 (setq total-time (+ (or total-time 0)
19227 org-clock-file-total-minutes)))))))
19228 (goto-char pos)
19230 (unless (eq scope 'agenda)
19231 (org-clock-sum ts te)
19232 (goto-char (point-min))
19233 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19234 (goto-char p)
19235 (when (setq time (get-text-property p :org-clock-minutes))
19236 (save-excursion
19237 (beginning-of-line 1)
19238 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19239 (setq level (org-reduced-level
19240 (- (match-end 1) (match-beginning 1))))
19241 (<= level maxlevel))
19242 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19243 hdl (match-string 2)
19244 h (/ time 60)
19245 m (- time (* 60 h)))
19246 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19247 (push (concat
19248 "| " (int-to-string level) "|" hlc hdl hlc " |"
19249 (make-string (1- level) ?|)
19250 hlc (format "%d:%02d" h m) hlc
19251 " |") tbl))))))
19252 (setq tbl (nreverse tbl))
19253 (if tostring
19254 (if tbl (mapconcat 'identity tbl "\n") nil)
19255 (goto-char ins)
19256 (insert-before-markers
19257 (or header
19258 (concat
19259 "Clock summary at ["
19260 (substring
19261 (format-time-string (cdr org-time-stamp-formats))
19262 1 -1)
19263 "]."
19264 (if block
19265 (format " Considered range is /%s/." block)
19267 "\n\n"))
19268 (if (eq scope 'agenda) "|File" "")
19269 "|L|Headline|Time|\n")
19270 (setq total-time (or total-time org-clock-file-total-minutes)
19271 h (/ total-time 60)
19272 m (- total-time (* 60 h)))
19273 (insert-before-markers
19274 "|-\n|"
19275 (if (eq scope 'agenda) "|" "")
19277 "*Total time*| "
19278 (format "*%d:%02d*" h m)
19279 "|\n|-\n")
19280 (setq tbl (delq nil tbl))
19281 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19282 (equal (substring (car tbl) 0 2) "|-"))
19283 (pop tbl))
19284 (insert-before-markers (mapconcat
19285 'identity (delq nil tbl)
19286 (if (eq scope 'agenda) "\n|-\n" "\n")))
19287 (backward-delete-char 1)
19288 (goto-char ipos)
19289 (skip-chars-forward "^|")
19290 (org-table-align))))))
19292 (defun org-clocktable-steps (params)
19293 (let* ((p1 (copy-sequence params))
19294 (ts (plist-get p1 :tstart))
19295 (te (plist-get p1 :tend))
19296 (step0 (plist-get p1 :step))
19297 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19298 (block (plist-get p1 :block))
19300 (when block
19301 (setq cc (org-clock-special-range block nil t)
19302 ts (car cc) te (cdr cc)))
19303 (if ts (setq ts (time-to-seconds
19304 (apply 'encode-time (org-parse-time-string ts)))))
19305 (if te (setq te (time-to-seconds
19306 (apply 'encode-time (org-parse-time-string te)))))
19307 (plist-put p1 :header "")
19308 (plist-put p1 :step nil)
19309 (plist-put p1 :block nil)
19310 (while (< ts te)
19311 (or (bolp) (insert "\n"))
19312 (plist-put p1 :tstart (format-time-string
19313 (car org-time-stamp-formats)
19314 (seconds-to-time ts)))
19315 (plist-put p1 :tend (format-time-string
19316 (car org-time-stamp-formats)
19317 (seconds-to-time (setq ts (+ ts step)))))
19318 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19319 (plist-get p1 :tstart) "\n")
19320 (org-dblock-write:clocktable p1)
19321 (re-search-forward "#\\+END:")
19322 (end-of-line 0))))
19325 (defun org-clocktable-add-file (file table)
19326 (if table
19327 (let ((lines (org-split-string table "\n"))
19328 (ff (file-name-nondirectory file)))
19329 (mapconcat 'identity
19330 (mapcar (lambda (x)
19331 (if (string-match org-table-dataline-regexp x)
19332 (concat "|" ff x)
19334 lines)
19335 "\n"))))
19337 ;; FIXME: I don't think anybody uses this, ask David
19338 (defun org-collect-clock-time-entries ()
19339 "Return an internal list with clocking information.
19340 This list has one entry for each CLOCK interval.
19341 FIXME: describe the elements."
19342 (interactive)
19343 (let ((re (concat "^[ \t]*" org-clock-string
19344 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19345 rtn beg end next cont level title total closedp leafp
19346 clockpos titlepos h m donep)
19347 (save-excursion
19348 (org-clock-sum)
19349 (goto-char (point-min))
19350 (while (re-search-forward re nil t)
19351 (setq clockpos (match-beginning 0)
19352 beg (match-string 1) end (match-string 2)
19353 cont (match-end 0))
19354 (setq beg (apply 'encode-time (org-parse-time-string beg))
19355 end (apply 'encode-time (org-parse-time-string end)))
19356 (org-back-to-heading t)
19357 (setq donep (org-entry-is-done-p))
19358 (setq titlepos (point)
19359 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19360 h (/ total 60) m (- total (* 60 h))
19361 total (cons h m))
19362 (looking-at "\\(\\*+\\) +\\(.*\\)")
19363 (setq level (- (match-end 1) (match-beginning 1))
19364 title (org-match-string-no-properties 2))
19365 (save-excursion (outline-next-heading) (setq next (point)))
19366 (setq closedp (re-search-forward org-closed-time-regexp next t))
19367 (goto-char next)
19368 (setq leafp (and (looking-at "^\\*+ ")
19369 (<= (- (match-end 0) (point)) level)))
19370 (push (list beg end clockpos closedp donep
19371 total title titlepos level leafp)
19372 rtn)
19373 (goto-char cont)))
19374 (nreverse rtn)))
19376 ;;;; Agenda, and Diary Integration
19378 ;;; Define the Org-agenda-mode
19380 (defvar org-agenda-mode-map (make-sparse-keymap)
19381 "Keymap for `org-agenda-mode'.")
19383 (defvar org-agenda-menu) ; defined later in this file.
19384 (defvar org-agenda-follow-mode nil)
19385 (defvar org-agenda-show-log nil)
19386 (defvar org-agenda-redo-command nil)
19387 (defvar org-agenda-query-string nil)
19388 (defvar org-agenda-mode-hook nil)
19389 (defvar org-agenda-type nil)
19390 (defvar org-agenda-force-single-file nil)
19392 (defun org-agenda-mode ()
19393 "Mode for time-sorted view on action items in Org-mode files.
19395 The following commands are available:
19397 \\{org-agenda-mode-map}"
19398 (interactive)
19399 (kill-all-local-variables)
19400 (setq org-agenda-undo-list nil
19401 org-agenda-pending-undo-list nil)
19402 (setq major-mode 'org-agenda-mode)
19403 ;; Keep global-font-lock-mode from turning on font-lock-mode
19404 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19405 (setq mode-name "Org-Agenda")
19406 (use-local-map org-agenda-mode-map)
19407 (easy-menu-add org-agenda-menu)
19408 (if org-startup-truncated (setq truncate-lines t))
19409 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19410 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19411 ;; Make sure properties are removed when copying text
19412 (when (boundp 'buffer-substring-filters)
19413 (org-set-local 'buffer-substring-filters
19414 (cons (lambda (x)
19415 (set-text-properties 0 (length x) nil x) x)
19416 buffer-substring-filters)))
19417 (unless org-agenda-keep-modes
19418 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19419 org-agenda-show-log nil))
19420 (easy-menu-change
19421 '("Agenda") "Agenda Files"
19422 (append
19423 (list
19424 (vector
19425 (if (get 'org-agenda-files 'org-restrict)
19426 "Restricted to single file"
19427 "Edit File List")
19428 '(org-edit-agenda-file-list)
19429 (not (get 'org-agenda-files 'org-restrict)))
19430 "--")
19431 (mapcar 'org-file-menu-entry (org-agenda-files))))
19432 (org-agenda-set-mode-name)
19433 (apply
19434 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19435 (list 'org-agenda-mode-hook)))
19437 (substitute-key-definition 'undo 'org-agenda-undo
19438 org-agenda-mode-map global-map)
19439 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19440 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19441 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19442 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19443 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19444 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19445 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19446 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19447 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19448 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19449 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19450 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19451 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19452 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19453 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19454 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19455 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19456 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19457 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19458 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19459 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19460 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19461 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19462 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19463 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19464 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19465 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19466 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19467 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19469 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19470 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19471 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19472 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19473 (while l (org-defkey org-agenda-mode-map
19474 (int-to-string (pop l)) 'digit-argument)))
19476 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19477 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19478 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19479 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19480 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19481 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19482 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19483 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19484 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19485 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19486 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19487 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19488 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19489 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19490 (org-defkey org-agenda-mode-map "n" 'next-line)
19491 (org-defkey org-agenda-mode-map "p" 'previous-line)
19492 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19493 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19494 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19495 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19496 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19497 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19498 (eval-after-load "calendar"
19499 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19500 'org-calendar-goto-agenda))
19501 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19502 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19503 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19504 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19505 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19506 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19507 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19508 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19509 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19510 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19511 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19512 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19513 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19514 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19515 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19516 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19517 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19518 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19519 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19520 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19521 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19522 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19524 (org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add)
19525 (org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract)
19526 (org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re)
19527 (org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re)
19529 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19530 "Local keymap for agenda entries from Org-mode.")
19532 (org-defkey org-agenda-keymap
19533 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19534 (org-defkey org-agenda-keymap
19535 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19536 (when org-agenda-mouse-1-follows-link
19537 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19538 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19539 '("Agenda"
19540 ("Agenda Files")
19541 "--"
19542 ["Show" org-agenda-show t]
19543 ["Go To (other window)" org-agenda-goto t]
19544 ["Go To (this window)" org-agenda-switch-to t]
19545 ["Follow Mode" org-agenda-follow-mode
19546 :style toggle :selected org-agenda-follow-mode :active t]
19547 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19548 "--"
19549 ["Cycle TODO" org-agenda-todo t]
19550 ["Archive subtree" org-agenda-archive t]
19551 ["Delete subtree" org-agenda-kill t]
19552 "--"
19553 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19554 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19555 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19556 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19557 "--"
19558 ("Tags and Properties"
19559 ["Show all Tags" org-agenda-show-tags t]
19560 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19561 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19562 "--"
19563 ["Column View" org-columns t])
19564 ("Date/Schedule"
19565 ["Schedule" org-agenda-schedule t]
19566 ["Set Deadline" org-agenda-deadline t]
19567 "--"
19568 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19569 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19570 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19571 ("Clock"
19572 ["Clock in" org-agenda-clock-in t]
19573 ["Clock out" org-agenda-clock-out t]
19574 ["Clock cancel" org-agenda-clock-cancel t]
19575 ["Goto running clock" org-clock-goto t])
19576 ("Priority"
19577 ["Set Priority" org-agenda-priority t]
19578 ["Increase Priority" org-agenda-priority-up t]
19579 ["Decrease Priority" org-agenda-priority-down t]
19580 ["Show Priority" org-agenda-show-priority t])
19581 ("Calendar/Diary"
19582 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19583 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19584 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19585 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19586 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19587 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19588 "--"
19589 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19590 "--"
19591 ("View"
19592 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19593 :style radio :selected (equal org-agenda-ndays 1)]
19594 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19595 :style radio :selected (equal org-agenda-ndays 7)]
19596 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19597 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19598 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19599 :style radio :selected (member org-agenda-ndays '(365 366))]
19600 "--"
19601 ["Show Logbook entries" org-agenda-log-mode
19602 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19603 ["Include Diary" org-agenda-toggle-diary
19604 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19605 ["Use Time Grid" org-agenda-toggle-time-grid
19606 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19607 ["Write view to file" org-write-agenda t]
19608 ["Rebuild buffer" org-agenda-redo t]
19609 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19610 "--"
19611 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19612 "--"
19613 ["Quit" org-agenda-quit t]
19614 ["Exit and Release Buffers" org-agenda-exit t]
19617 ;;; Agenda undo
19619 (defvar org-agenda-allow-remote-undo t
19620 "Non-nil means, allow remote undo from the agenda buffer.")
19621 (defvar org-agenda-undo-list nil
19622 "List of undoable operations in the agenda since last refresh.")
19623 (defvar org-agenda-undo-has-started-in nil
19624 "Buffers that have already seen `undo-start' in the current undo sequence.")
19625 (defvar org-agenda-pending-undo-list nil
19626 "In a series of undo commands, this is the list of remaning undo items.")
19628 (defmacro org-if-unprotected (&rest body)
19629 "Execute BODY if there is no `org-protected' text property at point."
19630 (declare (debug t))
19631 `(unless (get-text-property (point) 'org-protected)
19632 ,@body))
19634 (defmacro org-with-remote-undo (_buffer &rest _body)
19635 "Execute BODY while recording undo information in two buffers."
19636 (declare (indent 1) (debug t))
19637 `(let ((_cline (org-current-line))
19638 (_cmd this-command)
19639 (_buf1 (current-buffer))
19640 (_buf2 ,_buffer)
19641 (_undo1 buffer-undo-list)
19642 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19643 _c1 _c2)
19644 ,@_body
19645 (when org-agenda-allow-remote-undo
19646 (setq _c1 (org-verify-change-for-undo
19647 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19648 _c2 (org-verify-change-for-undo
19649 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19650 (when (or _c1 _c2)
19651 ;; make sure there are undo boundaries
19652 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19653 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19654 ;; remember which buffer to undo
19655 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19656 org-agenda-undo-list)))))
19658 (defun org-agenda-undo ()
19659 "Undo a remote editing step in the agenda.
19660 This undoes changes both in the agenda buffer and in the remote buffer
19661 that have been changed along."
19662 (interactive)
19663 (or org-agenda-allow-remote-undo
19664 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19665 (if (not (eq this-command last-command))
19666 (setq org-agenda-undo-has-started-in nil
19667 org-agenda-pending-undo-list org-agenda-undo-list))
19668 (if (not org-agenda-pending-undo-list)
19669 (error "No further undo information"))
19670 (let* ((entry (pop org-agenda-pending-undo-list))
19671 buf line cmd rembuf)
19672 (setq cmd (pop entry) line (pop entry))
19673 (setq rembuf (nth 2 entry))
19674 (org-with-remote-undo rembuf
19675 (while (bufferp (setq buf (pop entry)))
19676 (if (pop entry)
19677 (with-current-buffer buf
19678 (let ((last-undo-buffer buf)
19679 (inhibit-read-only t))
19680 (unless (memq buf org-agenda-undo-has-started-in)
19681 (push buf org-agenda-undo-has-started-in)
19682 (make-local-variable 'pending-undo-list)
19683 (undo-start))
19684 (while (and pending-undo-list
19685 (listp pending-undo-list)
19686 (not (car pending-undo-list)))
19687 (pop pending-undo-list))
19688 (undo-more 1))))))
19689 (goto-line line)
19690 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19692 (defun org-verify-change-for-undo (l1 l2)
19693 "Verify that a real change occurred between the undo lists L1 and L2."
19694 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19695 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19696 (not (eq l1 l2)))
19698 ;;; Agenda dispatch
19700 (defvar org-agenda-restrict nil)
19701 (defvar org-agenda-restrict-begin (make-marker))
19702 (defvar org-agenda-restrict-end (make-marker))
19703 (defvar org-agenda-last-dispatch-buffer nil)
19704 (defvar org-agenda-overriding-restriction nil)
19706 ;;;###autoload
19707 (defun org-agenda (arg &optional keys restriction)
19708 "Dispatch agenda commands to collect entries to the agenda buffer.
19709 Prompts for a command to execute. Any prefix arg will be passed
19710 on to the selected command. The default selections are:
19712 a Call `org-agenda-list' to display the agenda for current day or week.
19713 t Call `org-todo-list' to display the global todo list.
19714 T Call `org-todo-list' to display the global todo list, select only
19715 entries with a specific TODO keyword (the user gets a prompt).
19716 m Call `org-tags-view' to display headlines with tags matching
19717 a condition (the user is prompted for the condition).
19718 M Like `m', but select only TODO entries, no ordinary headlines.
19719 L Create a timeline for the current buffer.
19720 e Export views to associated files.
19722 More commands can be added by configuring the variable
19723 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19724 searches can be pre-defined in this way.
19726 If the current buffer is in Org-mode and visiting a file, you can also
19727 first press `<' once to indicate that the agenda should be temporarily
19728 \(until the next use of \\[org-agenda]) restricted to the current file.
19729 Pressing `<' twice means to restrict to the current subtree or region
19730 \(if active)."
19731 (interactive "P")
19732 (catch 'exit
19733 (let* ((prefix-descriptions nil)
19734 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19735 (org-agenda-custom-commands
19736 ;; normalize different versions
19737 (delq nil
19738 (mapcar
19739 (lambda (x)
19740 (cond ((stringp (cdr x))
19741 (push x prefix-descriptions)
19742 nil)
19743 ((stringp (nth 1 x)) x)
19744 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19745 (t (cons (car x) (cons "" (cdr x))))))
19746 org-agenda-custom-commands)))
19747 (buf (current-buffer))
19748 (bfn (buffer-file-name (buffer-base-buffer)))
19749 entry key type match lprops ans)
19750 ;; Turn off restriction unless there is an overriding one
19751 (unless org-agenda-overriding-restriction
19752 (put 'org-agenda-files 'org-restrict nil)
19753 (setq org-agenda-restrict nil)
19754 (move-marker org-agenda-restrict-begin nil)
19755 (move-marker org-agenda-restrict-end nil))
19756 ;; Delete old local properties
19757 (put 'org-agenda-redo-command 'org-lprops nil)
19758 ;; Remember where this call originated
19759 (setq org-agenda-last-dispatch-buffer (current-buffer))
19760 (unless keys
19761 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19762 keys (car ans)
19763 restriction (cdr ans)))
19764 ;; Estabish the restriction, if any
19765 (when (and (not org-agenda-overriding-restriction) restriction)
19766 (put 'org-agenda-files 'org-restrict (list bfn))
19767 (cond
19768 ((eq restriction 'region)
19769 (setq org-agenda-restrict t)
19770 (move-marker org-agenda-restrict-begin (region-beginning))
19771 (move-marker org-agenda-restrict-end (region-end)))
19772 ((eq restriction 'subtree)
19773 (save-excursion
19774 (setq org-agenda-restrict t)
19775 (org-back-to-heading t)
19776 (move-marker org-agenda-restrict-begin (point))
19777 (move-marker org-agenda-restrict-end
19778 (progn (org-end-of-subtree t)))))))
19780 (require 'calendar) ; FIXME: can we avoid this for some commands?
19781 ;; For example the todo list should not need it (but does...)
19782 (cond
19783 ((setq entry (assoc keys org-agenda-custom-commands))
19784 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19785 (progn
19786 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19787 (put 'org-agenda-redo-command 'org-lprops lprops)
19788 (cond
19789 ((eq type 'agenda)
19790 (org-let lprops '(org-agenda-list current-prefix-arg)))
19791 ((eq type 'alltodo)
19792 (org-let lprops '(org-todo-list current-prefix-arg)))
19793 ((eq type 'search)
19794 (org-let lprops '(org-search-view current-prefix-arg match)))
19795 ((eq type 'stuck)
19796 (org-let lprops '(org-agenda-list-stuck-projects
19797 current-prefix-arg)))
19798 ((eq type 'tags)
19799 (org-let lprops '(org-tags-view current-prefix-arg match)))
19800 ((eq type 'tags-todo)
19801 (org-let lprops '(org-tags-view '(4) match)))
19802 ((eq type 'todo)
19803 (org-let lprops '(org-todo-list match)))
19804 ((eq type 'tags-tree)
19805 (org-check-for-org-mode)
19806 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19807 ((eq type 'todo-tree)
19808 (org-check-for-org-mode)
19809 (org-let lprops
19810 '(org-occur (concat "^" outline-regexp "[ \t]*"
19811 (regexp-quote match) "\\>"))))
19812 ((eq type 'occur-tree)
19813 (org-check-for-org-mode)
19814 (org-let lprops '(org-occur match)))
19815 ((functionp type)
19816 (org-let lprops '(funcall type match)))
19817 ((fboundp type)
19818 (org-let lprops '(funcall type match)))
19819 (t (error "Invalid custom agenda command type %s" type))))
19820 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19821 ((equal keys "C")
19822 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19823 (customize-variable 'org-agenda-custom-commands))
19824 ((equal keys "a") (call-interactively 'org-agenda-list))
19825 ((equal keys "s") (call-interactively 'org-search-view))
19826 ((equal keys "t") (call-interactively 'org-todo-list))
19827 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19828 ((equal keys "m") (call-interactively 'org-tags-view))
19829 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19830 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19831 ((equal keys "L")
19832 (unless (org-mode-p)
19833 (error "This is not an Org-mode file"))
19834 (unless restriction
19835 (put 'org-agenda-files 'org-restrict (list bfn))
19836 (org-call-with-arg 'org-timeline arg)))
19837 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19838 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19839 ((equal keys "!") (customize-variable 'org-stuck-projects))
19840 (t (error "Invalid agenda key"))))))
19842 (defun org-agenda-normalize-custom-commands (cmds)
19843 (delq nil
19844 (mapcar
19845 (lambda (x)
19846 (cond ((stringp (cdr x)) nil)
19847 ((stringp (nth 1 x)) x)
19848 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19849 (t (cons (car x) (cons "" (cdr x))))))
19850 cmds)))
19852 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19853 "The user interface for selecting an agenda command."
19854 (catch 'exit
19855 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19856 (restrict-ok (and bfn (org-mode-p)))
19857 (region-p (org-region-active-p))
19858 (custom org-agenda-custom-commands)
19859 (selstring "")
19860 restriction second-time
19861 c entry key type match prefixes rmheader header-end custom1 desc)
19862 (save-window-excursion
19863 (delete-other-windows)
19864 (org-switch-to-buffer-other-window " *Agenda Commands*")
19865 (erase-buffer)
19866 (insert (eval-when-compile
19867 (let ((header
19869 Press key for an agenda command: < Buffer,subtree/region restriction
19870 -------------------------------- > Remove restriction
19871 a Agenda for current week or day e Export agenda views
19872 t List of all TODO entries T Entries with special TODO kwd
19873 m Match a TAGS query M Like m, but only TODO entries
19874 L Timeline for current buffer # List stuck projects (!=configure)
19875 s Search for keywords C Configure custom agenda commands
19876 / Multi-occur
19878 (start 0))
19879 (while (string-match
19880 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19881 header start)
19882 (setq start (match-end 0))
19883 (add-text-properties (match-beginning 2) (match-end 2)
19884 '(face bold) header))
19885 header)))
19886 (setq header-end (move-marker (make-marker) (point)))
19887 (while t
19888 (setq custom1 custom)
19889 (when (eq rmheader t)
19890 (goto-line 1)
19891 (re-search-forward ":" nil t)
19892 (delete-region (match-end 0) (point-at-eol))
19893 (forward-char 1)
19894 (looking-at "-+")
19895 (delete-region (match-end 0) (point-at-eol))
19896 (move-marker header-end (match-end 0)))
19897 (goto-char header-end)
19898 (delete-region (point) (point-max))
19899 (while (setq entry (pop custom1))
19900 (setq key (car entry) desc (nth 1 entry)
19901 type (nth 2 entry) match (nth 3 entry))
19902 (if (> (length key) 1)
19903 (add-to-list 'prefixes (string-to-char key))
19904 (insert
19905 (format
19906 "\n%-4s%-14s: %s"
19907 (org-add-props (copy-sequence key)
19908 '(face bold))
19909 (cond
19910 ((string-match "\\S-" desc) desc)
19911 ((eq type 'agenda) "Agenda for current week or day")
19912 ((eq type 'alltodo) "List of all TODO entries")
19913 ((eq type 'search) "Word search")
19914 ((eq type 'stuck) "List of stuck projects")
19915 ((eq type 'todo) "TODO keyword")
19916 ((eq type 'tags) "Tags query")
19917 ((eq type 'tags-todo) "Tags (TODO)")
19918 ((eq type 'tags-tree) "Tags tree")
19919 ((eq type 'todo-tree) "TODO kwd tree")
19920 ((eq type 'occur-tree) "Occur tree")
19921 ((functionp type) (if (symbolp type)
19922 (symbol-name type)
19923 "Lambda expression"))
19924 (t "???"))
19925 (cond
19926 ((stringp match)
19927 (org-add-props match nil 'face 'org-warning))
19928 (match
19929 (format "set of %d commands" (length match)))
19930 (t ""))))))
19931 (when prefixes
19932 (mapc (lambda (x)
19933 (insert
19934 (format "\n%s %s"
19935 (org-add-props (char-to-string x)
19936 nil 'face 'bold)
19937 (or (cdr (assoc (concat selstring (char-to-string x))
19938 prefix-descriptions))
19939 "Prefix key"))))
19940 prefixes))
19941 (goto-char (point-min))
19942 (when (fboundp 'fit-window-to-buffer)
19943 (if second-time
19944 (if (not (pos-visible-in-window-p (point-max)))
19945 (fit-window-to-buffer))
19946 (setq second-time t)
19947 (fit-window-to-buffer)))
19948 (message "Press key for agenda command%s:"
19949 (if (or restrict-ok org-agenda-overriding-restriction)
19950 (if org-agenda-overriding-restriction
19951 " (restriction lock active)"
19952 (if restriction
19953 (format " (restricted to %s)" restriction)
19954 " (unrestricted)"))
19955 ""))
19956 (setq c (read-char-exclusive))
19957 (message "")
19958 (cond
19959 ((assoc (char-to-string c) custom)
19960 (setq selstring (concat selstring (char-to-string c)))
19961 (throw 'exit (cons selstring restriction)))
19962 ((memq c prefixes)
19963 (setq selstring (concat selstring (char-to-string c))
19964 prefixes nil
19965 rmheader (or rmheader t)
19966 custom (delq nil (mapcar
19967 (lambda (x)
19968 (if (or (= (length (car x)) 1)
19969 (/= (string-to-char (car x)) c))
19971 (cons (substring (car x) 1) (cdr x))))
19972 custom))))
19973 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19974 (message "Restriction is only possible in Org-mode buffers")
19975 (ding) (sit-for 1))
19976 ((eq c ?1)
19977 (org-agenda-remove-restriction-lock 'noupdate)
19978 (setq restriction 'buffer))
19979 ((eq c ?0)
19980 (org-agenda-remove-restriction-lock 'noupdate)
19981 (setq restriction (if region-p 'region 'subtree)))
19982 ((eq c ?<)
19983 (org-agenda-remove-restriction-lock 'noupdate)
19984 (setq restriction
19985 (cond
19986 ((eq restriction 'buffer)
19987 (if region-p 'region 'subtree))
19988 ((memq restriction '(subtree region))
19989 nil)
19990 (t 'buffer))))
19991 ((eq c ?>)
19992 (org-agenda-remove-restriction-lock 'noupdate)
19993 (setq restriction nil))
19994 ((and (equal selstring "") (memq c '(?s ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19995 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19996 ((and (> (length selstring) 0) (eq c ?\d))
19997 (delete-window)
19998 (org-agenda-get-restriction-and-command prefix-descriptions))
20000 ((equal c ?q) (error "Abort"))
20001 (t (error "Invalid key %c" c))))))))
20003 (defun org-run-agenda-series (name series)
20004 (org-prepare-agenda name)
20005 (let* ((org-agenda-multi t)
20006 (redo (list 'org-run-agenda-series name (list 'quote series)))
20007 (cmds (car series))
20008 (gprops (nth 1 series))
20009 match ;; The byte compiler incorrectly complains about this. Keep it!
20010 cmd type lprops)
20011 (while (setq cmd (pop cmds))
20012 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
20013 (cond
20014 ((eq type 'agenda)
20015 (org-let2 gprops lprops
20016 '(call-interactively 'org-agenda-list)))
20017 ((eq type 'alltodo)
20018 (org-let2 gprops lprops
20019 '(call-interactively 'org-todo-list)))
20020 ((eq type 'search)
20021 (org-let2 gprops lprops
20022 '(org-search-view current-prefix-arg match)))
20023 ((eq type 'stuck)
20024 (org-let2 gprops lprops
20025 '(call-interactively 'org-agenda-list-stuck-projects)))
20026 ((eq type 'tags)
20027 (org-let2 gprops lprops
20028 '(org-tags-view current-prefix-arg match)))
20029 ((eq type 'tags-todo)
20030 (org-let2 gprops lprops
20031 '(org-tags-view '(4) match)))
20032 ((eq type 'todo)
20033 (org-let2 gprops lprops
20034 '(org-todo-list match)))
20035 ((fboundp type)
20036 (org-let2 gprops lprops
20037 '(funcall type match)))
20038 (t (error "Invalid type in command series"))))
20039 (widen)
20040 (setq org-agenda-redo-command redo)
20041 (goto-char (point-min)))
20042 (org-finalize-agenda))
20044 ;;;###autoload
20045 (defmacro org-batch-agenda (cmd-key &rest parameters)
20046 "Run an agenda command in batch mode and send the result to STDOUT.
20047 If CMD-KEY is a string of length 1, it is used as a key in
20048 `org-agenda-custom-commands' and triggers this command. If it is a
20049 longer string it is used as a tags/todo match string.
20050 Paramters are alternating variable names and values that will be bound
20051 before running the agenda command."
20052 (let (pars)
20053 (while parameters
20054 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20055 (if (> (length cmd-key) 2)
20056 (eval (list 'let (nreverse pars)
20057 (list 'org-tags-view nil cmd-key)))
20058 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20059 (set-buffer org-agenda-buffer-name)
20060 (princ (org-encode-for-stdout (buffer-string)))))
20062 (defun org-encode-for-stdout (string)
20063 (if (fboundp 'encode-coding-string)
20064 (encode-coding-string string buffer-file-coding-system)
20065 string))
20067 (defvar org-agenda-info nil)
20069 ;;;###autoload
20070 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
20071 "Run an agenda command in batch mode and send the result to STDOUT.
20072 If CMD-KEY is a string of length 1, it is used as a key in
20073 `org-agenda-custom-commands' and triggers this command. If it is a
20074 longer string it is used as a tags/todo match string.
20075 Paramters are alternating variable names and values that will be bound
20076 before running the agenda command.
20078 The output gives a line for each selected agenda item. Each
20079 item is a list of comma-separated values, like this:
20081 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
20083 category The category of the item
20084 head The headline, without TODO kwd, TAGS and PRIORITY
20085 type The type of the agenda entry, can be
20086 todo selected in TODO match
20087 tagsmatch selected in tags match
20088 diary imported from diary
20089 deadline a deadline on given date
20090 scheduled scheduled on given date
20091 timestamp entry has timestamp on given date
20092 closed entry was closed on given date
20093 upcoming-deadline warning about deadline
20094 past-scheduled forwarded scheduled item
20095 block entry has date block including g. date
20096 todo The todo keyword, if any
20097 tags All tags including inherited ones, separated by colons
20098 date The relevant date, like 2007-2-14
20099 time The time, like 15:00-16:50
20100 extra Sting with extra planning info
20101 priority-l The priority letter if any was given
20102 priority-n The computed numerical priority
20103 agenda-day The day in the agenda where this is listed"
20105 (let (pars)
20106 (while parameters
20107 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20108 (push (list 'org-agenda-remove-tags t) pars)
20109 (if (> (length cmd-key) 2)
20110 (eval (list 'let (nreverse pars)
20111 (list 'org-tags-view nil cmd-key)))
20112 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20113 (set-buffer org-agenda-buffer-name)
20114 (let* ((lines (org-split-string (buffer-string) "\n"))
20115 line)
20116 (while (setq line (pop lines))
20117 (catch 'next
20118 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
20119 (setq org-agenda-info
20120 (org-fix-agenda-info (text-properties-at 0 line)))
20121 (princ
20122 (org-encode-for-stdout
20123 (mapconcat 'org-agenda-export-csv-mapper
20124 '(org-category txt type todo tags date time-of-day extra
20125 priority-letter priority agenda-day)
20126 ",")))
20127 (princ "\n"))))))
20129 (defun org-fix-agenda-info (props)
20130 "Make sure all properties on an agenda item have a canonical form,
20131 so the export commands can easily use it."
20132 (let (tmp re)
20133 (when (setq tmp (plist-get props 'tags))
20134 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20135 (when (setq tmp (plist-get props 'date))
20136 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20137 (let ((calendar-date-display-form '(year "-" month "-" day)))
20138 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20140 (setq tmp (calendar-date-string tmp)))
20141 (setq props (plist-put props 'date tmp)))
20142 (when (setq tmp (plist-get props 'day))
20143 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20144 (let ((calendar-date-display-form '(year "-" month "-" day)))
20145 (setq tmp (calendar-date-string tmp)))
20146 (setq props (plist-put props 'day tmp))
20147 (setq props (plist-put props 'agenda-day tmp)))
20148 (when (setq tmp (plist-get props 'txt))
20149 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20150 (plist-put props 'priority-letter (match-string 1 tmp))
20151 (setq tmp (replace-match "" t t tmp)))
20152 (when (and (setq re (plist-get props 'org-todo-regexp))
20153 (setq re (concat "\\`\\.*" re " ?"))
20154 (string-match re tmp))
20155 (plist-put props 'todo (match-string 1 tmp))
20156 (setq tmp (replace-match "" t t tmp)))
20157 (plist-put props 'txt tmp)))
20158 props)
20160 (defun org-agenda-export-csv-mapper (prop)
20161 (let ((res (plist-get org-agenda-info prop)))
20162 (setq res
20163 (cond
20164 ((not res) "")
20165 ((stringp res) res)
20166 (t (prin1-to-string res))))
20167 (while (string-match "," res)
20168 (setq res (replace-match ";" t t res)))
20169 (org-trim res)))
20172 ;;;###autoload
20173 (defun org-store-agenda-views (&rest parameters)
20174 (interactive)
20175 (eval (list 'org-batch-store-agenda-views)))
20177 ;; FIXME, why is this a macro?????
20178 ;;;###autoload
20179 (defmacro org-batch-store-agenda-views (&rest parameters)
20180 "Run all custom agenda commands that have a file argument."
20181 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20182 (pop-up-frames nil)
20183 (dir default-directory)
20184 pars cmd thiscmdkey files opts)
20185 (while parameters
20186 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20187 (setq pars (reverse pars))
20188 (save-window-excursion
20189 (while cmds
20190 (setq cmd (pop cmds)
20191 thiscmdkey (car cmd)
20192 opts (nth 4 cmd)
20193 files (nth 5 cmd))
20194 (if (stringp files) (setq files (list files)))
20195 (when files
20196 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20197 (list 'org-agenda nil thiscmdkey)))
20198 (set-buffer org-agenda-buffer-name)
20199 (while files
20200 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20201 (list 'org-write-agenda
20202 (expand-file-name (pop files) dir) t))))
20203 (and (get-buffer org-agenda-buffer-name)
20204 (kill-buffer org-agenda-buffer-name)))))))
20206 (defun org-write-agenda (file &optional nosettings)
20207 "Write the current buffer (an agenda view) as a file.
20208 Depending on the extension of the file name, plain text (.txt),
20209 HTML (.html or .htm) or Postscript (.ps) is produced.
20210 If NOSETTINGS is given, do not scope the settings of
20211 `org-agenda-exporter-settings' into the export commands. This is used when
20212 the settings have already been scoped and we do not wish to overrule other,
20213 higher priority settings."
20214 (interactive "FWrite agenda to file: ")
20215 (if (not (file-writable-p file))
20216 (error "Cannot write agenda to file %s" file))
20217 (cond
20218 ((string-match "\\.html?\\'" file) (require 'htmlize))
20219 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20220 (org-let (if nosettings nil org-agenda-exporter-settings)
20221 '(save-excursion
20222 (save-window-excursion
20223 (cond
20224 ((string-match "\\.html?\\'" file)
20225 (set-buffer (htmlize-buffer (current-buffer)))
20227 (when (and org-agenda-export-html-style
20228 (string-match "<style>" org-agenda-export-html-style))
20229 ;; replace <style> section with org-agenda-export-html-style
20230 (goto-char (point-min))
20231 (kill-region (- (search-forward "<style") 6)
20232 (search-forward "</style>"))
20233 (insert org-agenda-export-html-style))
20234 (write-file file)
20235 (kill-buffer (current-buffer))
20236 (message "HTML written to %s" file))
20237 ((string-match "\\.ps\\'" file)
20238 (ps-print-buffer-with-faces file)
20239 (message "Postscript written to %s" file))
20241 (let ((bs (buffer-string)))
20242 (find-file file)
20243 (insert bs)
20244 (save-buffer 0)
20245 (kill-buffer (current-buffer))
20246 (message "Plain text written to %s" file))))))
20247 (set-buffer org-agenda-buffer-name)))
20249 (defmacro org-no-read-only (&rest body)
20250 "Inhibit read-only for BODY."
20251 `(let ((inhibit-read-only t)) ,@body))
20253 (defun org-check-for-org-mode ()
20254 "Make sure current buffer is in org-mode. Error if not."
20255 (or (org-mode-p)
20256 (error "Cannot execute org-mode agenda command on buffer in %s."
20257 major-mode)))
20259 (defun org-fit-agenda-window ()
20260 "Fit the window to the buffer size."
20261 (and (memq org-agenda-window-setup '(reorganize-frame))
20262 (fboundp 'fit-window-to-buffer)
20263 (fit-window-to-buffer
20265 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20266 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20268 ;;; Agenda file list
20270 (defun org-agenda-files (&optional unrestricted)
20271 "Get the list of agenda files.
20272 Optional UNRESTRICTED means return the full list even if a restriction
20273 is currently in place."
20274 (let ((files
20275 (cond
20276 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20277 ((stringp org-agenda-files) (org-read-agenda-file-list))
20278 ((listp org-agenda-files) org-agenda-files)
20279 (t (error "Invalid value of `org-agenda-files'")))))
20280 (setq files (apply 'append
20281 (mapcar (lambda (f)
20282 (if (file-directory-p f)
20283 (directory-files f t
20284 org-agenda-file-regexp)
20285 (list f)))
20286 files)))
20287 (if org-agenda-skip-unavailable-files
20288 (delq nil
20289 (mapcar (function
20290 (lambda (file)
20291 (and (file-readable-p file) file)))
20292 files))
20293 files))) ; `org-check-agenda-file' will remove them from the list
20295 (defun org-edit-agenda-file-list ()
20296 "Edit the list of agenda files.
20297 Depending on setup, this either uses customize to edit the variable
20298 `org-agenda-files', or it visits the file that is holding the list. In the
20299 latter case, the buffer is set up in a way that saving it automatically kills
20300 the buffer and restores the previous window configuration."
20301 (interactive)
20302 (if (stringp org-agenda-files)
20303 (let ((cw (current-window-configuration)))
20304 (find-file org-agenda-files)
20305 (org-set-local 'org-window-configuration cw)
20306 (org-add-hook 'after-save-hook
20307 (lambda ()
20308 (set-window-configuration
20309 (prog1 org-window-configuration
20310 (kill-buffer (current-buffer))))
20311 (org-install-agenda-files-menu)
20312 (message "New agenda file list installed"))
20313 nil 'local)
20314 (message "%s" (substitute-command-keys
20315 "Edit list and finish with \\[save-buffer]")))
20316 (customize-variable 'org-agenda-files)))
20318 (defun org-store-new-agenda-file-list (list)
20319 "Set new value for the agenda file list and save it correcly."
20320 (if (stringp org-agenda-files)
20321 (let ((f org-agenda-files) b)
20322 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20323 (with-temp-file f
20324 (insert (mapconcat 'identity list "\n") "\n")))
20325 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20326 (setq org-agenda-files list)
20327 (customize-save-variable 'org-agenda-files org-agenda-files))))
20329 (defun org-read-agenda-file-list ()
20330 "Read the list of agenda files from a file."
20331 (when (stringp org-agenda-files)
20332 (with-temp-buffer
20333 (insert-file-contents org-agenda-files)
20334 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20337 ;;;###autoload
20338 (defun org-cycle-agenda-files ()
20339 "Cycle through the files in `org-agenda-files'.
20340 If the current buffer visits an agenda file, find the next one in the list.
20341 If the current buffer does not, find the first agenda file."
20342 (interactive)
20343 (let* ((fs (org-agenda-files t))
20344 (files (append fs (list (car fs))))
20345 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20346 file)
20347 (unless files (error "No agenda files"))
20348 (catch 'exit
20349 (while (setq file (pop files))
20350 (if (equal (file-truename file) tcf)
20351 (when (car files)
20352 (find-file (car files))
20353 (throw 'exit t))))
20354 (find-file (car fs)))
20355 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20357 (defun org-agenda-file-to-front (&optional to-end)
20358 "Move/add the current file to the top of the agenda file list.
20359 If the file is not present in the list, it is added to the front. If it is
20360 present, it is moved there. With optional argument TO-END, add/move to the
20361 end of the list."
20362 (interactive "P")
20363 (let ((org-agenda-skip-unavailable-files nil)
20364 (file-alist (mapcar (lambda (x)
20365 (cons (file-truename x) x))
20366 (org-agenda-files t)))
20367 (ctf (file-truename buffer-file-name))
20368 x had)
20369 (setq x (assoc ctf file-alist) had x)
20371 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20372 (if to-end
20373 (setq file-alist (append (delq x file-alist) (list x)))
20374 (setq file-alist (cons x (delq x file-alist))))
20375 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20376 (org-install-agenda-files-menu)
20377 (message "File %s to %s of agenda file list"
20378 (if had "moved" "added") (if to-end "end" "front"))))
20380 (defun org-remove-file (&optional file)
20381 "Remove current file from the list of files in variable `org-agenda-files'.
20382 These are the files which are being checked for agenda entries.
20383 Optional argument FILE means, use this file instead of the current."
20384 (interactive)
20385 (let* ((org-agenda-skip-unavailable-files nil)
20386 (file (or file buffer-file-name))
20387 (true-file (file-truename file))
20388 (afile (abbreviate-file-name file))
20389 (files (delq nil (mapcar
20390 (lambda (x)
20391 (if (equal true-file
20392 (file-truename x))
20393 nil x))
20394 (org-agenda-files t)))))
20395 (if (not (= (length files) (length (org-agenda-files t))))
20396 (progn
20397 (org-store-new-agenda-file-list files)
20398 (org-install-agenda-files-menu)
20399 (message "Removed file: %s" afile))
20400 (message "File was not in list: %s (not removed)" afile))))
20402 (defun org-file-menu-entry (file)
20403 (vector file (list 'find-file file) t))
20405 (defun org-check-agenda-file (file)
20406 "Make sure FILE exists. If not, ask user what to do."
20407 (when (not (file-exists-p file))
20408 (message "non-existent file %s. [R]emove from list or [A]bort?"
20409 (abbreviate-file-name file))
20410 (let ((r (downcase (read-char-exclusive))))
20411 (cond
20412 ((equal r ?r)
20413 (org-remove-file file)
20414 (throw 'nextfile t))
20415 (t (error "Abort"))))))
20417 ;;; Agenda prepare and finalize
20419 (defvar org-agenda-multi nil) ; dynammically scoped
20420 (defvar org-agenda-buffer-name "*Org Agenda*")
20421 (defvar org-pre-agenda-window-conf nil)
20422 (defvar org-agenda-name nil)
20423 (defun org-prepare-agenda (&optional name)
20424 (setq org-todo-keywords-for-agenda nil)
20425 (setq org-done-keywords-for-agenda nil)
20426 (if org-agenda-multi
20427 (progn
20428 (setq buffer-read-only nil)
20429 (goto-char (point-max))
20430 (unless (or (bobp) org-agenda-compact-blocks)
20431 (insert "\n" (make-string (window-width) ?=) "\n"))
20432 (narrow-to-region (point) (point-max)))
20433 (org-agenda-reset-markers)
20434 (org-prepare-agenda-buffers (org-agenda-files))
20435 (setq org-todo-keywords-for-agenda
20436 (org-uniquify org-todo-keywords-for-agenda))
20437 (setq org-done-keywords-for-agenda
20438 (org-uniquify org-done-keywords-for-agenda))
20439 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20440 (awin (get-buffer-window abuf)))
20441 (cond
20442 ((equal (current-buffer) abuf) nil)
20443 (awin (select-window awin))
20444 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20445 ((equal org-agenda-window-setup 'current-window)
20446 (switch-to-buffer abuf))
20447 ((equal org-agenda-window-setup 'other-window)
20448 (org-switch-to-buffer-other-window abuf))
20449 ((equal org-agenda-window-setup 'other-frame)
20450 (switch-to-buffer-other-frame abuf))
20451 ((equal org-agenda-window-setup 'reorganize-frame)
20452 (delete-other-windows)
20453 (org-switch-to-buffer-other-window abuf))))
20454 (setq buffer-read-only nil)
20455 (erase-buffer)
20456 (org-agenda-mode)
20457 (and name (not org-agenda-name)
20458 (org-set-local 'org-agenda-name name)))
20459 (setq buffer-read-only nil))
20461 (defun org-finalize-agenda ()
20462 "Finishing touch for the agenda buffer, called just before displaying it."
20463 (unless org-agenda-multi
20464 (save-excursion
20465 (let ((inhibit-read-only t))
20466 (goto-char (point-min))
20467 (while (org-activate-bracket-links (point-max))
20468 (add-text-properties (match-beginning 0) (match-end 0)
20469 '(face org-link)))
20470 (org-agenda-align-tags)
20471 (unless org-agenda-with-colors
20472 (remove-text-properties (point-min) (point-max) '(face nil))))
20473 (if (and (boundp 'org-overriding-columns-format)
20474 org-overriding-columns-format)
20475 (org-set-local 'org-overriding-columns-format
20476 org-overriding-columns-format))
20477 (if (and (boundp 'org-agenda-view-columns-initially)
20478 org-agenda-view-columns-initially)
20479 (org-agenda-columns))
20480 (when org-agenda-fontify-priorities
20481 (org-fontify-priorities))
20482 (run-hooks 'org-finalize-agenda-hook)
20483 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20486 (defun org-fontify-priorities ()
20487 "Make highest priority lines bold, and lowest italic."
20488 (interactive)
20489 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20490 (org-delete-overlay o)))
20491 (org-overlays-in (point-min) (point-max)))
20492 (save-excursion
20493 (let ((inhibit-read-only t)
20494 b e p ov h l)
20495 (goto-char (point-min))
20496 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20497 (setq h (or (get-char-property (point) 'org-highest-priority)
20498 org-highest-priority)
20499 l (or (get-char-property (point) 'org-lowest-priority)
20500 org-lowest-priority)
20501 p (string-to-char (match-string 1))
20502 b (match-beginning 0) e (point-at-eol)
20503 ov (org-make-overlay b e))
20504 (org-overlay-put
20505 ov 'face
20506 (cond ((listp org-agenda-fontify-priorities)
20507 (cdr (assoc p org-agenda-fontify-priorities)))
20508 ((equal p l) 'italic)
20509 ((equal p h) 'bold)))
20510 (org-overlay-put ov 'org-type 'org-priority)))))
20512 (defun org-prepare-agenda-buffers (files)
20513 "Create buffers for all agenda files, protect archived trees and comments."
20514 (interactive)
20515 (let ((pa '(:org-archived t))
20516 (pc '(:org-comment t))
20517 (pall '(:org-archived t :org-comment t))
20518 (inhibit-read-only t)
20519 (rea (concat ":" org-archive-tag ":"))
20520 bmp file re)
20521 (save-excursion
20522 (save-restriction
20523 (while (setq file (pop files))
20524 (if (bufferp file)
20525 (set-buffer file)
20526 (org-check-agenda-file file)
20527 (set-buffer (org-get-agenda-file-buffer file)))
20528 (widen)
20529 (setq bmp (buffer-modified-p))
20530 (org-refresh-category-properties)
20531 (setq org-todo-keywords-for-agenda
20532 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20533 (setq org-done-keywords-for-agenda
20534 (append org-done-keywords-for-agenda org-done-keywords))
20535 (save-excursion
20536 (remove-text-properties (point-min) (point-max) pall)
20537 (when org-agenda-skip-archived-trees
20538 (goto-char (point-min))
20539 (while (re-search-forward rea nil t)
20540 (if (org-on-heading-p t)
20541 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20542 (goto-char (point-min))
20543 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20544 (while (re-search-forward re nil t)
20545 (add-text-properties
20546 (match-beginning 0) (org-end-of-subtree t) pc)))
20547 (set-buffer-modified-p bmp))))))
20549 (defvar org-agenda-skip-function nil
20550 "Function to be called at each match during agenda construction.
20551 If this function returns nil, the current match should not be skipped.
20552 Otherwise, the function must return a position from where the search
20553 should be continued.
20554 This may also be a Lisp form, it will be evaluated.
20555 Never set this variable using `setq' or so, because then it will apply
20556 to all future agenda commands. Instead, bind it with `let' to scope
20557 it dynamically into the agenda-constructing command. A good way to set
20558 it is through options in org-agenda-custom-commands.")
20560 (defun org-agenda-skip ()
20561 "Throw to `:skip' in places that should be skipped.
20562 Also moves point to the end of the skipped region, so that search can
20563 continue from there."
20564 (let ((p (point-at-bol)) to fp)
20565 (and org-agenda-skip-archived-trees
20566 (get-text-property p :org-archived)
20567 (org-end-of-subtree t)
20568 (throw :skip t))
20569 (and (get-text-property p :org-comment)
20570 (org-end-of-subtree t)
20571 (throw :skip t))
20572 (if (equal (char-after p) ?#) (throw :skip t))
20573 (when (and (or (setq fp (functionp org-agenda-skip-function))
20574 (consp org-agenda-skip-function))
20575 (setq to (save-excursion
20576 (save-match-data
20577 (if fp
20578 (funcall org-agenda-skip-function)
20579 (eval org-agenda-skip-function))))))
20580 (goto-char to)
20581 (throw :skip t))))
20583 (defvar org-agenda-markers nil
20584 "List of all currently active markers created by `org-agenda'.")
20585 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20586 "Creation time of the last agenda marker.")
20588 (defun org-agenda-new-marker (&optional pos)
20589 "Return a new agenda marker.
20590 Org-mode keeps a list of these markers and resets them when they are
20591 no longer in use."
20592 (let ((m (copy-marker (or pos (point)))))
20593 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20594 (push m org-agenda-markers)
20597 (defun org-agenda-reset-markers ()
20598 "Reset markers created by `org-agenda'."
20599 (while org-agenda-markers
20600 (move-marker (pop org-agenda-markers) nil)))
20602 (defun org-get-agenda-file-buffer (file)
20603 "Get a buffer visiting FILE. If the buffer needs to be created, add
20604 it to the list of buffers which might be released later."
20605 (let ((buf (org-find-base-buffer-visiting file)))
20606 (if buf
20607 buf ; just return it
20608 ;; Make a new buffer and remember it
20609 (setq buf (find-file-noselect file))
20610 (if buf (push buf org-agenda-new-buffers))
20611 buf)))
20613 (defun org-release-buffers (blist)
20614 "Release all buffers in list, asking the user for confirmation when needed.
20615 When a buffer is unmodified, it is just killed. When modified, it is saved
20616 \(if the user agrees) and then killed."
20617 (let (buf file)
20618 (while (setq buf (pop blist))
20619 (setq file (buffer-file-name buf))
20620 (when (and (buffer-modified-p buf)
20621 file
20622 (y-or-n-p (format "Save file %s? " file)))
20623 (with-current-buffer buf (save-buffer)))
20624 (kill-buffer buf))))
20626 (defun org-get-category (&optional pos)
20627 "Get the category applying to position POS."
20628 (get-text-property (or pos (point)) 'org-category))
20630 ;;; Agenda timeline
20632 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20634 (defun org-timeline (&optional include-all)
20635 "Show a time-sorted view of the entries in the current org file.
20636 Only entries with a time stamp of today or later will be listed. With
20637 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20638 under the current date.
20639 If the buffer contains an active region, only check the region for
20640 dates."
20641 (interactive "P")
20642 (require 'calendar)
20643 (org-compile-prefix-format 'timeline)
20644 (org-set-sorting-strategy 'timeline)
20645 (let* ((dopast t)
20646 (dotodo include-all)
20647 (doclosed org-agenda-show-log)
20648 (entry buffer-file-name)
20649 (date (calendar-current-date))
20650 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20651 (end (if (org-region-active-p) (region-end) (point-max)))
20652 (day-numbers (org-get-all-dates beg end 'no-ranges
20653 t doclosed ; always include today
20654 org-timeline-show-empty-dates))
20655 (org-deadline-warning-days 0)
20656 (org-agenda-only-exact-dates t)
20657 (today (time-to-days (current-time)))
20658 (past t)
20659 args
20660 s e rtn d emptyp)
20661 (setq org-agenda-redo-command
20662 (list 'progn
20663 (list 'org-switch-to-buffer-other-window (current-buffer))
20664 (list 'org-timeline (list 'quote include-all))))
20665 (if (not dopast)
20666 ;; Remove past dates from the list of dates.
20667 (setq day-numbers (delq nil (mapcar (lambda(x)
20668 (if (>= x today) x nil))
20669 day-numbers))))
20670 (org-prepare-agenda (concat "Timeline "
20671 (file-name-nondirectory buffer-file-name)))
20672 (if doclosed (push :closed args))
20673 (push :timestamp args)
20674 (push :deadline args)
20675 (push :scheduled args)
20676 (push :sexp args)
20677 (if dotodo (push :todo args))
20678 (while (setq d (pop day-numbers))
20679 (if (and (listp d) (eq (car d) :omitted))
20680 (progn
20681 (setq s (point))
20682 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20683 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20684 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20685 (if (and (>= d today)
20686 dopast
20687 past)
20688 (progn
20689 (setq past nil)
20690 (insert (make-string 79 ?-) "\n")))
20691 (setq date (calendar-gregorian-from-absolute d))
20692 (setq s (point))
20693 (setq rtn (and (not emptyp)
20694 (apply 'org-agenda-get-day-entries entry
20695 date args)))
20696 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20697 (progn
20698 (insert
20699 (if (stringp org-agenda-format-date)
20700 (format-time-string org-agenda-format-date
20701 (org-time-from-absolute date))
20702 (funcall org-agenda-format-date date))
20703 "\n")
20704 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20705 (put-text-property s (1- (point)) 'org-date-line t)
20706 (if (equal d today)
20707 (put-text-property s (1- (point)) 'org-today t))
20708 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20709 (put-text-property s (1- (point)) 'day d)))))
20710 (goto-char (point-min))
20711 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20712 (point-min)))
20713 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20714 (org-finalize-agenda)
20715 (setq buffer-read-only t)))
20717 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20718 "Return a list of all relevant day numbers from BEG to END buffer positions.
20719 If NO-RANGES is non-nil, include only the start and end dates of a range,
20720 not every single day in the range. If FORCE-TODAY is non-nil, make
20721 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20722 inactive time stamps (those in square brackets) are included.
20723 When EMPTY is non-nil, also include days without any entries."
20724 (let ((re (concat
20725 (if pre-re pre-re "")
20726 (if inactive org-ts-regexp-both org-ts-regexp)))
20727 dates dates1 date day day1 day2 ts1 ts2)
20728 (if force-today
20729 (setq dates (list (time-to-days (current-time)))))
20730 (save-excursion
20731 (goto-char beg)
20732 (while (re-search-forward re end t)
20733 (setq day (time-to-days (org-time-string-to-time
20734 (substring (match-string 1) 0 10))))
20735 (or (memq day dates) (push day dates)))
20736 (unless no-ranges
20737 (goto-char beg)
20738 (while (re-search-forward org-tr-regexp end t)
20739 (setq ts1 (substring (match-string 1) 0 10)
20740 ts2 (substring (match-string 2) 0 10)
20741 day1 (time-to-days (org-time-string-to-time ts1))
20742 day2 (time-to-days (org-time-string-to-time ts2)))
20743 (while (< (setq day1 (1+ day1)) day2)
20744 (or (memq day1 dates) (push day1 dates)))))
20745 (setq dates (sort dates '<))
20746 (when empty
20747 (while (setq day (pop dates))
20748 (setq day2 (car dates))
20749 (push day dates1)
20750 (when (and day2 empty)
20751 (if (or (eq empty t)
20752 (and (numberp empty) (<= (- day2 day) empty)))
20753 (while (< (setq day (1+ day)) day2)
20754 (push (list day) dates1))
20755 (push (cons :omitted (- day2 day)) dates1))))
20756 (setq dates (nreverse dates1)))
20757 dates)))
20759 ;;; Agenda Daily/Weekly
20761 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20762 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20763 (defvar org-agenda-last-arguments nil
20764 "The arguments of the previous call to org-agenda")
20765 (defvar org-starting-day nil) ; local variable in the agenda buffer
20766 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20767 (defvar org-include-all-loc nil) ; local variable
20768 (defvar org-agenda-remove-date nil) ; dynamically scoped
20770 ;;;###autoload
20771 (defun org-agenda-list (&optional include-all start-day ndays)
20772 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20773 The view will be for the current day or week, but from the overview buffer
20774 you will be able to go to other days/weeks.
20776 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20777 all unfinished TODO items will also be shown, before the agenda.
20778 This feature is considered obsolete, please use the TODO list or a block
20779 agenda instead.
20781 With a numeric prefix argument in an interactive call, the agenda will
20782 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20783 the number of days. NDAYS defaults to `org-agenda-ndays'.
20785 START-DAY defaults to TODAY, or to the most recent match for the weekday
20786 given in `org-agenda-start-on-weekday'."
20787 (interactive "P")
20788 (if (and (integerp include-all) (> include-all 0))
20789 (setq ndays include-all include-all nil))
20790 (setq ndays (or ndays org-agenda-ndays)
20791 start-day (or start-day org-agenda-start-day))
20792 (if org-agenda-overriding-arguments
20793 (setq include-all (car org-agenda-overriding-arguments)
20794 start-day (nth 1 org-agenda-overriding-arguments)
20795 ndays (nth 2 org-agenda-overriding-arguments)))
20796 (if (stringp start-day)
20797 ;; Convert to an absolute day number
20798 (setq start-day (time-to-days (org-read-date nil t start-day))))
20799 (setq org-agenda-last-arguments (list include-all start-day ndays))
20800 (org-compile-prefix-format 'agenda)
20801 (org-set-sorting-strategy 'agenda)
20802 (require 'calendar)
20803 (let* ((org-agenda-start-on-weekday
20804 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20805 org-agenda-start-on-weekday nil))
20806 (thefiles (org-agenda-files))
20807 (files thefiles)
20808 (today (time-to-days
20809 (time-subtract (current-time)
20810 (list 0 (* 3600 org-extend-today-until) 0))))
20811 (sd (or start-day today))
20812 (start (if (or (null org-agenda-start-on-weekday)
20813 (< org-agenda-ndays 7))
20815 (let* ((nt (calendar-day-of-week
20816 (calendar-gregorian-from-absolute sd)))
20817 (n1 org-agenda-start-on-weekday)
20818 (d (- nt n1)))
20819 (- sd (+ (if (< d 0) 7 0) d)))))
20820 (day-numbers (list start))
20821 (day-cnt 0)
20822 (inhibit-redisplay (not debug-on-error))
20823 s e rtn rtnall file date d start-pos end-pos todayp nd)
20824 (setq org-agenda-redo-command
20825 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20826 ;; Make the list of days
20827 (setq ndays (or ndays org-agenda-ndays)
20828 nd ndays)
20829 (while (> ndays 1)
20830 (push (1+ (car day-numbers)) day-numbers)
20831 (setq ndays (1- ndays)))
20832 (setq day-numbers (nreverse day-numbers))
20833 (org-prepare-agenda "Day/Week")
20834 (org-set-local 'org-starting-day (car day-numbers))
20835 (org-set-local 'org-include-all-loc include-all)
20836 (org-set-local 'org-agenda-span
20837 (org-agenda-ndays-to-span nd))
20838 (when (and (or include-all org-agenda-include-all-todo)
20839 (member today day-numbers))
20840 (setq files thefiles
20841 rtnall nil)
20842 (while (setq file (pop files))
20843 (catch 'nextfile
20844 (org-check-agenda-file file)
20845 (setq date (calendar-gregorian-from-absolute today)
20846 rtn (org-agenda-get-day-entries
20847 file date :todo))
20848 (setq rtnall (append rtnall rtn))))
20849 (when rtnall
20850 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20851 (add-text-properties (point-min) (1- (point))
20852 (list 'face 'org-agenda-structure))
20853 (insert (org-finalize-agenda-entries rtnall) "\n")))
20854 (unless org-agenda-compact-blocks
20855 (setq s (point))
20856 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20857 "-agenda:\n")
20858 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20859 'org-date-line t)))
20860 (while (setq d (pop day-numbers))
20861 (setq date (calendar-gregorian-from-absolute d)
20862 s (point))
20863 (if (or (setq todayp (= d today))
20864 (and (not start-pos) (= d sd)))
20865 (setq start-pos (point))
20866 (if (and start-pos (not end-pos))
20867 (setq end-pos (point))))
20868 (setq files thefiles
20869 rtnall nil)
20870 (while (setq file (pop files))
20871 (catch 'nextfile
20872 (org-check-agenda-file file)
20873 (if org-agenda-show-log
20874 (setq rtn (org-agenda-get-day-entries
20875 file date
20876 :deadline :scheduled :timestamp :sexp :closed))
20877 (setq rtn (org-agenda-get-day-entries
20878 file date
20879 :deadline :scheduled :sexp :timestamp)))
20880 (setq rtnall (append rtnall rtn))))
20881 (if org-agenda-include-diary
20882 (progn
20883 (require 'diary-lib)
20884 (setq rtn (org-get-entries-from-diary date))
20885 (setq rtnall (append rtnall rtn))))
20886 (if (or rtnall org-agenda-show-all-dates)
20887 (progn
20888 (setq day-cnt (1+ day-cnt))
20889 (insert
20890 (if (stringp org-agenda-format-date)
20891 (format-time-string org-agenda-format-date
20892 (org-time-from-absolute date))
20893 (funcall org-agenda-format-date date))
20894 "\n")
20895 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20896 (put-text-property s (1- (point)) 'org-date-line t)
20897 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20898 (if todayp (put-text-property s (1- (point)) 'org-today t))
20899 (if rtnall (insert
20900 (org-finalize-agenda-entries
20901 (org-agenda-add-time-grid-maybe
20902 rtnall nd todayp))
20903 "\n"))
20904 (put-text-property s (1- (point)) 'day d)
20905 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20906 (goto-char (point-min))
20907 (org-fit-agenda-window)
20908 (unless (and (pos-visible-in-window-p (point-min))
20909 (pos-visible-in-window-p (point-max)))
20910 (goto-char (1- (point-max)))
20911 (recenter -1)
20912 (if (not (pos-visible-in-window-p (or start-pos 1)))
20913 (progn
20914 (goto-char (or start-pos 1))
20915 (recenter 1))))
20916 (goto-char (or start-pos 1))
20917 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20918 (org-finalize-agenda)
20919 (setq buffer-read-only t)
20920 (message "")))
20922 (defun org-agenda-ndays-to-span (n)
20923 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20925 ;;; Agenda word search
20927 (defvar org-agenda-search-history nil)
20929 ;;;###autoload
20930 (defun org-search-view (&optional arg string)
20931 "Show all entries that contain words or regular expressions.
20932 If the first character of the search string is an asterisks,
20933 search only the headlines.
20935 The search string is broken into \"words\" by splitting at whitespace.
20936 The individual words are then interpreted as a boolean expression with
20937 logical AND. Words prefixed with a minus must not occur in the entry.
20938 Words without a prefix or prefixed with a plus must occur in the entry.
20939 Matching is case-insensitive and the words are enclosed by word delimiters.
20941 Words enclosed by curly braces are interpreted as regular expressions
20942 that must or must not match in the entry.
20944 This command searches the agenda files, and in addition the files listed
20945 in `org-agenda-text-search-extra-files'."
20946 (interactive "P")
20947 (org-compile-prefix-format 'search)
20948 (org-set-sorting-strategy 'search)
20949 (org-prepare-agenda "SEARCH")
20950 (let* ((props (list 'face nil
20951 'done-face 'org-done
20952 'org-not-done-regexp org-not-done-regexp
20953 'org-todo-regexp org-todo-regexp
20954 'mouse-face 'highlight
20955 'keymap org-agenda-keymap
20956 'help-echo (format "mouse-2 or RET jump to location")))
20957 regexp rtn rtnall files file pos
20958 marker priority category tags c neg re
20959 ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
20960 (unless (and (not arg)
20961 (stringp string)
20962 (string-match "\\S-" string))
20963 (setq string (read-string "[+-]Word/{Regexp} ...: "
20964 (cond
20965 ((integerp arg) (cons string arg))
20966 (arg string))
20967 'org-agenda-search-history)))
20968 (setq org-agenda-redo-command
20969 (list 'org-search-view 'current-prefix-arg string))
20970 (setq org-agenda-query-string string)
20972 (if (equal (string-to-char string) ?*)
20973 (setq hdl-only t
20974 words (substring string 1))
20975 (setq words string))
20976 (setq words (org-split-string words))
20977 (mapc (lambda (w)
20978 (setq c (string-to-char w))
20979 (if (equal c ?-)
20980 (setq neg t w (substring w 1))
20981 (if (equal c ?+)
20982 (setq neg nil w (substring w 1))
20983 (setq neg nil)))
20984 (if (string-match "\\`{.*}\\'" w)
20985 (setq re (substring w 1 -1))
20986 (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>")))
20987 (if neg (push re regexps-) (push re regexps+)))
20988 words)
20989 (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b)))))
20990 (if (not regexps+)
20991 (setq regexp (concat "^" org-outline-regexp))
20992 (setq regexp (pop regexps+))
20993 (if hdl-only (setq regexp (concat "^" org-outline-regexp ".*?"
20994 regexp))))
20995 (setq files (append (org-agenda-files) org-agenda-text-search-extra-files)
20996 rtnall nil)
20997 (while (setq file (pop files))
20998 (setq ee nil)
20999 (catch 'nextfile
21000 (org-check-agenda-file file)
21001 (setq buffer (if (file-exists-p file)
21002 (org-get-agenda-file-buffer file)
21003 (error "No such file %s" file)))
21004 (if (not buffer)
21005 ;; If file does not exist, make sure an error message is sent
21006 (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s"
21007 file))))
21008 (with-current-buffer buffer
21009 (unless (org-mode-p)
21010 (error "Agenda file %s is not in `org-mode'" file))
21011 (let ((case-fold-search t))
21012 (save-excursion
21013 (save-restriction
21014 (if org-agenda-restrict
21015 (narrow-to-region org-agenda-restrict-begin
21016 org-agenda-restrict-end)
21017 (widen))
21018 (goto-char (point-min))
21019 (unless (or (org-on-heading-p)
21020 (outline-next-heading))
21021 (throw 'nextfile t))
21022 (goto-char (max (point-min) (1- (point))))
21023 (while (re-search-forward regexp nil t)
21024 (org-back-to-heading t)
21025 (skip-chars-forward "* ")
21026 (setq beg (point-at-bol)
21027 beg1 (point)
21028 end (progn (outline-next-heading) (point)))
21029 (catch :skip
21030 (goto-char beg)
21031 (org-agenda-skip)
21032 (setq str (buffer-substring-no-properties
21033 (point-at-bol)
21034 (if hdl-only (point-at-eol) end)))
21035 (mapc (lambda (wr) (when (string-match wr str)
21036 (goto-char (1- end))
21037 (throw :skip t)))
21038 regexps-)
21039 (mapc (lambda (wr) (unless (string-match wr str)
21040 (goto-char (1- end))
21041 (throw :skip t)))
21042 regexps+)
21043 (goto-char beg)
21044 (setq marker (org-agenda-new-marker (point))
21045 category (org-get-category)
21046 tags (org-get-tags-at (point))
21047 txt (org-format-agenda-item
21049 (buffer-substring-no-properties
21050 beg1 (point-at-eol))
21051 category tags))
21052 (org-add-props txt props
21053 'org-marker marker 'org-hd-marker marker
21054 'priority 1000 'org-category category
21055 'type "search")
21056 (push txt ee)
21057 (goto-char (1- end)))))))))
21058 (setq rtn (nreverse ee))
21059 (setq rtnall (append rtnall rtn)))
21060 (if org-agenda-overriding-header
21061 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21062 nil 'face 'org-agenda-structure) "\n")
21063 (insert "Search words: ")
21064 (add-text-properties (point-min) (1- (point))
21065 (list 'face 'org-agenda-structure))
21066 (setq pos (point))
21067 (insert string "\n")
21068 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21069 (setq pos (point))
21070 (unless org-agenda-multi
21071 (insert "Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit\n")
21072 (add-text-properties pos (1- (point))
21073 (list 'face 'org-agenda-structure))))
21074 (when rtnall
21075 (insert (org-finalize-agenda-entries rtnall) "\n"))
21076 (goto-char (point-min))
21077 (org-fit-agenda-window)
21078 (add-text-properties (point-min) (point-max) '(org-agenda-type search))
21079 (org-finalize-agenda)
21080 (setq buffer-read-only t)))
21082 ;;; Agenda TODO list
21084 (defvar org-select-this-todo-keyword nil)
21085 (defvar org-last-arg nil)
21087 ;;;###autoload
21088 (defun org-todo-list (arg)
21089 "Show all TODO entries from all agenda file in a single list.
21090 The prefix arg can be used to select a specific TODO keyword and limit
21091 the list to these. When using \\[universal-argument], you will be prompted
21092 for a keyword. A numeric prefix directly selects the Nth keyword in
21093 `org-todo-keywords-1'."
21094 (interactive "P")
21095 (require 'calendar)
21096 (org-compile-prefix-format 'todo)
21097 (org-set-sorting-strategy 'todo)
21098 (org-prepare-agenda "TODO")
21099 (let* ((today (time-to-days (current-time)))
21100 (date (calendar-gregorian-from-absolute today))
21101 (kwds org-todo-keywords-for-agenda)
21102 (completion-ignore-case t)
21103 (org-select-this-todo-keyword
21104 (if (stringp arg) arg
21105 (and arg (integerp arg) (> arg 0)
21106 (nth (1- arg) kwds))))
21107 rtn rtnall files file pos)
21108 (when (equal arg '(4))
21109 (setq org-select-this-todo-keyword
21110 (completing-read "Keyword (or KWD1|K2D2|...): "
21111 (mapcar 'list kwds) nil nil)))
21112 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
21113 (org-set-local 'org-last-arg arg)
21114 (setq org-agenda-redo-command
21115 '(org-todo-list (or current-prefix-arg org-last-arg)))
21116 (setq files (org-agenda-files)
21117 rtnall nil)
21118 (while (setq file (pop files))
21119 (catch 'nextfile
21120 (org-check-agenda-file file)
21121 (setq rtn (org-agenda-get-day-entries file date :todo))
21122 (setq rtnall (append rtnall rtn))))
21123 (if org-agenda-overriding-header
21124 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21125 nil 'face 'org-agenda-structure) "\n")
21126 (insert "Global list of TODO items of type: ")
21127 (add-text-properties (point-min) (1- (point))
21128 (list 'face 'org-agenda-structure))
21129 (setq pos (point))
21130 (insert (or org-select-this-todo-keyword "ALL") "\n")
21131 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21132 (setq pos (point))
21133 (unless org-agenda-multi
21134 (insert "Available with `N r': (0)ALL")
21135 (let ((n 0) s)
21136 (mapc (lambda (x)
21137 (setq s (format "(%d)%s" (setq n (1+ n)) x))
21138 (if (> (+ (current-column) (string-width s) 1) (frame-width))
21139 (insert "\n "))
21140 (insert " " s))
21141 kwds))
21142 (insert "\n"))
21143 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21144 (when rtnall
21145 (insert (org-finalize-agenda-entries rtnall) "\n"))
21146 (goto-char (point-min))
21147 (org-fit-agenda-window)
21148 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
21149 (org-finalize-agenda)
21150 (setq buffer-read-only t)))
21152 ;;; Agenda tags match
21154 ;;;###autoload
21155 (defun org-tags-view (&optional todo-only match)
21156 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
21157 The prefix arg TODO-ONLY limits the search to TODO entries."
21158 (interactive "P")
21159 (org-compile-prefix-format 'tags)
21160 (org-set-sorting-strategy 'tags)
21161 (let* ((org-tags-match-list-sublevels
21162 (if todo-only t org-tags-match-list-sublevels))
21163 (completion-ignore-case t)
21164 rtn rtnall files file pos matcher
21165 buffer)
21166 (setq matcher (org-make-tags-matcher match)
21167 match (car matcher) matcher (cdr matcher))
21168 (org-prepare-agenda (concat "TAGS " match))
21169 (setq org-agenda-redo-command
21170 (list 'org-tags-view (list 'quote todo-only)
21171 (list 'if 'current-prefix-arg nil match)))
21172 (setq files (org-agenda-files)
21173 rtnall nil)
21174 (while (setq file (pop files))
21175 (catch 'nextfile
21176 (org-check-agenda-file file)
21177 (setq buffer (if (file-exists-p file)
21178 (org-get-agenda-file-buffer file)
21179 (error "No such file %s" file)))
21180 (if (not buffer)
21181 ;; If file does not exist, merror message to agenda
21182 (setq rtn (list
21183 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21184 rtnall (append rtnall rtn))
21185 (with-current-buffer buffer
21186 (unless (org-mode-p)
21187 (error "Agenda file %s is not in `org-mode'" file))
21188 (save-excursion
21189 (save-restriction
21190 (if org-agenda-restrict
21191 (narrow-to-region org-agenda-restrict-begin
21192 org-agenda-restrict-end)
21193 (widen))
21194 (setq rtn (org-scan-tags 'agenda matcher todo-only))
21195 (setq rtnall (append rtnall rtn))))))))
21196 (if org-agenda-overriding-header
21197 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21198 nil 'face 'org-agenda-structure) "\n")
21199 (insert "Headlines with TAGS match: ")
21200 (add-text-properties (point-min) (1- (point))
21201 (list 'face 'org-agenda-structure))
21202 (setq pos (point))
21203 (insert match "\n")
21204 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21205 (setq pos (point))
21206 (unless org-agenda-multi
21207 (insert "Press `C-u r' to search again with new search string\n"))
21208 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21209 (when rtnall
21210 (insert (org-finalize-agenda-entries rtnall) "\n"))
21211 (goto-char (point-min))
21212 (org-fit-agenda-window)
21213 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
21214 (org-finalize-agenda)
21215 (setq buffer-read-only t)))
21217 ;;; Agenda Finding stuck projects
21219 (defvar org-agenda-skip-regexp nil
21220 "Regular expression used in skipping subtrees for the agenda.
21221 This is basically a temporary global variable that can be set and then
21222 used by user-defined selections using `org-agenda-skip-function'.")
21224 (defvar org-agenda-overriding-header nil
21225 "When this is set during todo and tags searches, will replace header.")
21227 (defun org-agenda-skip-subtree-when-regexp-matches ()
21228 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
21229 If yes, it returns the end position of this tree, causing agenda commands
21230 to skip this subtree. This is a function that can be put into
21231 `org-agenda-skip-function' for the duration of a command."
21232 (let ((end (save-excursion (org-end-of-subtree t)))
21233 skip)
21234 (save-excursion
21235 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
21236 (and skip end)))
21238 (defun org-agenda-skip-entry-if (&rest conditions)
21239 "Skip entry if any of CONDITIONS is true.
21240 See `org-agenda-skip-if' for details."
21241 (org-agenda-skip-if nil conditions))
21243 (defun org-agenda-skip-subtree-if (&rest conditions)
21244 "Skip entry if any of CONDITIONS is true.
21245 See `org-agenda-skip-if' for details."
21246 (org-agenda-skip-if t conditions))
21248 (defun org-agenda-skip-if (subtree conditions)
21249 "Checks current entity for CONDITIONS.
21250 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21251 the entry, i.e. the text before the next heading is checked.
21253 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21254 from different tests. Valid conditions are:
21256 scheduled Check if there is a scheduled cookie
21257 notscheduled Check if there is no scheduled cookie
21258 deadline Check if there is a deadline
21259 notdeadline Check if there is no deadline
21260 regexp Check if regexp matches
21261 notregexp Check if regexp does not match.
21263 The regexp is taken from the conditions list, it must come right after
21264 the `regexp' or `notregexp' element.
21266 If any of these conditions is met, this function returns the end point of
21267 the entity, causing the search to continue from there. This is a function
21268 that can be put into `org-agenda-skip-function' for the duration of a command."
21269 (let (beg end m)
21270 (org-back-to-heading t)
21271 (setq beg (point)
21272 end (if subtree
21273 (progn (org-end-of-subtree t) (point))
21274 (progn (outline-next-heading) (1- (point)))))
21275 (goto-char beg)
21276 (and
21278 (and (memq 'scheduled conditions)
21279 (re-search-forward org-scheduled-time-regexp end t))
21280 (and (memq 'notscheduled conditions)
21281 (not (re-search-forward org-scheduled-time-regexp end t)))
21282 (and (memq 'deadline conditions)
21283 (re-search-forward org-deadline-time-regexp end t))
21284 (and (memq 'notdeadline conditions)
21285 (not (re-search-forward org-deadline-time-regexp end t)))
21286 (and (setq m (memq 'regexp conditions))
21287 (stringp (nth 1 m))
21288 (re-search-forward (nth 1 m) end t))
21289 (and (setq m (memq 'notregexp conditions))
21290 (stringp (nth 1 m))
21291 (not (re-search-forward (nth 1 m) end t))))
21292 end)))
21294 ;;;###autoload
21295 (defun org-agenda-list-stuck-projects (&rest ignore)
21296 "Create agenda view for projects that are stuck.
21297 Stuck projects are project that have no next actions. For the definitions
21298 of what a project is and how to check if it stuck, customize the variable
21299 `org-stuck-projects'.
21300 MATCH is being ignored."
21301 (interactive)
21302 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21303 ;; FIXME: we could have used org-agenda-skip-if here.
21304 (org-agenda-overriding-header "List of stuck projects: ")
21305 (matcher (nth 0 org-stuck-projects))
21306 (todo (nth 1 org-stuck-projects))
21307 (todo-wds (if (member "*" todo)
21308 (progn
21309 (org-prepare-agenda-buffers (org-agenda-files))
21310 (org-delete-all
21311 org-done-keywords-for-agenda
21312 (copy-sequence org-todo-keywords-for-agenda)))
21313 todo))
21314 (todo-re (concat "^\\*+[ \t]+\\("
21315 (mapconcat 'identity todo-wds "\\|")
21316 "\\)\\>"))
21317 (tags (nth 2 org-stuck-projects))
21318 (tags-re (if (member "*" tags)
21319 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21320 (concat "^\\*+ .*:\\("
21321 (mapconcat 'identity tags "\\|")
21322 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21323 (gen-re (nth 3 org-stuck-projects))
21324 (re-list
21325 (delq nil
21326 (list
21327 (if todo todo-re)
21328 (if tags tags-re)
21329 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21330 gen-re)))))
21331 (setq org-agenda-skip-regexp
21332 (if re-list
21333 (mapconcat 'identity re-list "\\|")
21334 (error "No information how to identify unstuck projects")))
21335 (org-tags-view nil matcher)
21336 (with-current-buffer org-agenda-buffer-name
21337 (setq org-agenda-redo-command
21338 '(org-agenda-list-stuck-projects
21339 (or current-prefix-arg org-last-arg))))))
21341 ;;; Diary integration
21343 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21345 (defun org-get-entries-from-diary (date)
21346 "Get the (Emacs Calendar) diary entries for DATE."
21347 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21348 (diary-display-hook '(fancy-diary-display))
21349 (pop-up-frames nil)
21350 (list-diary-entries-hook
21351 (cons 'org-diary-default-entry list-diary-entries-hook))
21352 (diary-file-name-prefix-function nil) ; turn this feature off
21353 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21354 entries
21355 (org-disable-agenda-to-diary t))
21356 (save-excursion
21357 (save-window-excursion
21358 (funcall (if (fboundp 'diary-list-entries)
21359 'diary-list-entries 'list-diary-entries)
21360 date 1)))
21361 (if (not (get-buffer fancy-diary-buffer))
21362 (setq entries nil)
21363 (with-current-buffer fancy-diary-buffer
21364 (setq buffer-read-only nil)
21365 (if (zerop (buffer-size))
21366 ;; No entries
21367 (setq entries nil)
21368 ;; Omit the date and other unnecessary stuff
21369 (org-agenda-cleanup-fancy-diary)
21370 ;; Add prefix to each line and extend the text properties
21371 (if (zerop (buffer-size))
21372 (setq entries nil)
21373 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21374 (set-buffer-modified-p nil)
21375 (kill-buffer fancy-diary-buffer)))
21376 (when entries
21377 (setq entries (org-split-string entries "\n"))
21378 (setq entries
21379 (mapcar
21380 (lambda (x)
21381 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21382 ;; Extend the text properties to the beginning of the line
21383 (org-add-props x (text-properties-at (1- (length x)) x)
21384 'type "diary" 'date date))
21385 entries)))))
21387 (defun org-agenda-cleanup-fancy-diary ()
21388 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21389 This gets rid of the date, the underline under the date, and
21390 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21391 date. It also removes lines that contain only whitespace."
21392 (goto-char (point-min))
21393 (if (looking-at ".*?:[ \t]*")
21394 (progn
21395 (replace-match "")
21396 (re-search-forward "\n=+$" nil t)
21397 (replace-match "")
21398 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21399 (re-search-forward "\n=+$" nil t)
21400 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21401 (goto-char (point-min))
21402 (while (re-search-forward "^ +\n" nil t)
21403 (replace-match ""))
21404 (goto-char (point-min))
21405 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21406 (replace-match "")))
21408 ;; Make sure entries from the diary have the right text properties.
21409 (eval-after-load "diary-lib"
21410 '(if (boundp 'diary-modify-entry-list-string-function)
21411 ;; We can rely on the hook, nothing to do
21413 ;; Hook not avaiable, must use advice to make this work
21414 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21415 "Make the position visible."
21416 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21417 (stringp string)
21418 buffer-file-name)
21419 (setq string (org-modify-diary-entry-string string))))))
21421 (defun org-modify-diary-entry-string (string)
21422 "Add text properties to string, allowing org-mode to act on it."
21423 (org-add-props string nil
21424 'mouse-face 'highlight
21425 'keymap org-agenda-keymap
21426 'help-echo (if buffer-file-name
21427 (format "mouse-2 or RET jump to diary file %s"
21428 (abbreviate-file-name buffer-file-name))
21430 'org-agenda-diary-link t
21431 'org-marker (org-agenda-new-marker (point-at-bol))))
21433 (defun org-diary-default-entry ()
21434 "Add a dummy entry to the diary.
21435 Needed to avoid empty dates which mess up holiday display."
21436 ;; Catch the error if dealing with the new add-to-diary-alist
21437 (when org-disable-agenda-to-diary
21438 (condition-case nil
21439 (add-to-diary-list original-date "Org-mode dummy" "")
21440 (error
21441 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21443 ;;;###autoload
21444 (defun org-diary (&rest args)
21445 "Return diary information from org-files.
21446 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21447 It accesses org files and extracts information from those files to be
21448 listed in the diary. The function accepts arguments specifying what
21449 items should be listed. The following arguments are allowed:
21451 :timestamp List the headlines of items containing a date stamp or
21452 date range matching the selected date. Deadlines will
21453 also be listed, on the expiration day.
21455 :sexp List entries resulting from diary-like sexps.
21457 :deadline List any deadlines past due, or due within
21458 `org-deadline-warning-days'. The listing occurs only
21459 in the diary for *today*, not at any other date. If
21460 an entry is marked DONE, it is no longer listed.
21462 :scheduled List all items which are scheduled for the given date.
21463 The diary for *today* also contains items which were
21464 scheduled earlier and are not yet marked DONE.
21466 :todo List all TODO items from the org-file. This may be a
21467 long list - so this is not turned on by default.
21468 Like deadlines, these entries only show up in the
21469 diary for *today*, not at any other date.
21471 The call in the diary file should look like this:
21473 &%%(org-diary) ~/path/to/some/orgfile.org
21475 Use a separate line for each org file to check. Or, if you omit the file name,
21476 all files listed in `org-agenda-files' will be checked automatically:
21478 &%%(org-diary)
21480 If you don't give any arguments (as in the example above), the default
21481 arguments (:deadline :scheduled :timestamp :sexp) are used.
21482 So the example above may also be written as
21484 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21486 The function expects the lisp variables `entry' and `date' to be provided
21487 by the caller, because this is how the calendar works. Don't use this
21488 function from a program - use `org-agenda-get-day-entries' instead."
21489 (when (> (- (time-to-seconds (current-time))
21490 org-agenda-last-marker-time)
21492 (org-agenda-reset-markers))
21493 (org-compile-prefix-format 'agenda)
21494 (org-set-sorting-strategy 'agenda)
21495 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21496 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21497 (list entry)
21498 (org-agenda-files t)))
21499 file rtn results)
21500 (org-prepare-agenda-buffers files)
21501 ;; If this is called during org-agenda, don't return any entries to
21502 ;; the calendar. Org Agenda will list these entries itself.
21503 (if org-disable-agenda-to-diary (setq files nil))
21504 (while (setq file (pop files))
21505 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21506 (setq results (append results rtn)))
21507 (if results
21508 (concat (org-finalize-agenda-entries results) "\n"))))
21510 ;;; Agenda entry finders
21512 (defun org-agenda-get-day-entries (file date &rest args)
21513 "Does the work for `org-diary' and `org-agenda'.
21514 FILE is the path to a file to be checked for entries. DATE is date like
21515 the one returned by `calendar-current-date'. ARGS are symbols indicating
21516 which kind of entries should be extracted. For details about these, see
21517 the documentation of `org-diary'."
21518 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21519 (let* ((org-startup-folded nil)
21520 (org-startup-align-all-tables nil)
21521 (buffer (if (file-exists-p file)
21522 (org-get-agenda-file-buffer file)
21523 (error "No such file %s" file)))
21524 arg results rtn)
21525 (if (not buffer)
21526 ;; If file does not exist, make sure an error message ends up in diary
21527 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21528 (with-current-buffer buffer
21529 (unless (org-mode-p)
21530 (error "Agenda file %s is not in `org-mode'" file))
21531 (let ((case-fold-search nil))
21532 (save-excursion
21533 (save-restriction
21534 (if org-agenda-restrict
21535 (narrow-to-region org-agenda-restrict-begin
21536 org-agenda-restrict-end)
21537 (widen))
21538 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21539 (while (setq arg (pop args))
21540 (cond
21541 ((and (eq arg :todo)
21542 (equal date (calendar-current-date)))
21543 (setq rtn (org-agenda-get-todos))
21544 (setq results (append results rtn)))
21545 ((eq arg :timestamp)
21546 (setq rtn (org-agenda-get-blocks))
21547 (setq results (append results rtn))
21548 (setq rtn (org-agenda-get-timestamps))
21549 (setq results (append results rtn)))
21550 ((eq arg :sexp)
21551 (setq rtn (org-agenda-get-sexps))
21552 (setq results (append results rtn)))
21553 ((eq arg :scheduled)
21554 (setq rtn (org-agenda-get-scheduled))
21555 (setq results (append results rtn)))
21556 ((eq arg :closed)
21557 (setq rtn (org-agenda-get-closed))
21558 (setq results (append results rtn)))
21559 ((eq arg :deadline)
21560 (setq rtn (org-agenda-get-deadlines))
21561 (setq results (append results rtn))))))))
21562 results))))
21564 (defun org-entry-is-todo-p ()
21565 (member (org-get-todo-state) org-not-done-keywords))
21567 (defun org-entry-is-done-p ()
21568 (member (org-get-todo-state) org-done-keywords))
21570 (defun org-get-todo-state ()
21571 (save-excursion
21572 (org-back-to-heading t)
21573 (and (looking-at org-todo-line-regexp)
21574 (match-end 2)
21575 (match-string 2))))
21577 (defun org-at-date-range-p (&optional inactive-ok)
21578 "Is the cursor inside a date range?"
21579 (interactive)
21580 (save-excursion
21581 (catch 'exit
21582 (let ((pos (point)))
21583 (skip-chars-backward "^[<\r\n")
21584 (skip-chars-backward "<[")
21585 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21586 (>= (match-end 0) pos)
21587 (throw 'exit t))
21588 (skip-chars-backward "^<[\r\n")
21589 (skip-chars-backward "<[")
21590 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21591 (>= (match-end 0) pos)
21592 (throw 'exit t)))
21593 nil)))
21595 (defun org-agenda-get-todos ()
21596 "Return the TODO information for agenda display."
21597 (let* ((props (list 'face nil
21598 'done-face 'org-done
21599 'org-not-done-regexp org-not-done-regexp
21600 'org-todo-regexp org-todo-regexp
21601 'mouse-face 'highlight
21602 'keymap org-agenda-keymap
21603 'help-echo
21604 (format "mouse-2 or RET jump to org file %s"
21605 (abbreviate-file-name buffer-file-name))))
21606 ;; FIXME: get rid of the \n at some point but watch out
21607 (regexp (concat "^\\*+[ \t]+\\("
21608 (if org-select-this-todo-keyword
21609 (if (equal org-select-this-todo-keyword "*")
21610 org-todo-regexp
21611 (concat "\\<\\("
21612 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21613 "\\)\\>"))
21614 org-not-done-regexp)
21615 "[^\n\r]*\\)"))
21616 marker priority category tags
21617 ee txt beg end)
21618 (goto-char (point-min))
21619 (while (re-search-forward regexp nil t)
21620 (catch :skip
21621 (save-match-data
21622 (beginning-of-line)
21623 (setq beg (point) end (progn (outline-next-heading) (point)))
21624 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21625 (re-search-forward org-ts-regexp end t))
21626 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21627 (re-search-forward org-scheduled-time-regexp end t))
21628 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21629 (re-search-forward org-deadline-time-regexp end t)
21630 (org-deadline-close (match-string 1))))
21631 (goto-char (1+ beg))
21632 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21633 (throw :skip nil)))
21634 (goto-char beg)
21635 (org-agenda-skip)
21636 (goto-char (match-beginning 1))
21637 (setq marker (org-agenda-new-marker (match-beginning 0))
21638 category (org-get-category)
21639 tags (org-get-tags-at (point))
21640 txt (org-format-agenda-item "" (match-string 1) category tags)
21641 priority (1+ (org-get-priority txt)))
21642 (org-add-props txt props
21643 'org-marker marker 'org-hd-marker marker
21644 'priority priority 'org-category category
21645 'type "todo")
21646 (push txt ee)
21647 (if org-agenda-todo-list-sublevels
21648 (goto-char (match-end 1))
21649 (org-end-of-subtree 'invisible))))
21650 (nreverse ee)))
21652 (defconst org-agenda-no-heading-message
21653 "No heading for this item in buffer or region.")
21655 (defun org-agenda-get-timestamps ()
21656 "Return the date stamp information for agenda display."
21657 (let* ((props (list 'face nil
21658 'org-not-done-regexp org-not-done-regexp
21659 'org-todo-regexp org-todo-regexp
21660 'mouse-face 'highlight
21661 'keymap org-agenda-keymap
21662 'help-echo
21663 (format "mouse-2 or RET jump to org file %s"
21664 (abbreviate-file-name buffer-file-name))))
21665 (d1 (calendar-absolute-from-gregorian date))
21666 (remove-re
21667 (concat
21668 (regexp-quote
21669 (format-time-string
21670 "<%Y-%m-%d"
21671 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21672 ".*?>"))
21673 (regexp
21674 (concat
21675 (regexp-quote
21676 (substring
21677 (format-time-string
21678 (car org-time-stamp-formats)
21679 (apply 'encode-time ; DATE bound by calendar
21680 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21681 0 11))
21682 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21683 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21684 marker hdmarker deadlinep scheduledp donep tmp priority category
21685 ee txt timestr tags b0 b3 e3 head)
21686 (goto-char (point-min))
21687 (while (re-search-forward regexp nil t)
21688 (setq b0 (match-beginning 0)
21689 b3 (match-beginning 3) e3 (match-end 3))
21690 (catch :skip
21691 (and (org-at-date-range-p) (throw :skip nil))
21692 (org-agenda-skip)
21693 (if (and (match-end 1)
21694 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21695 (throw :skip nil))
21696 (if (and e3
21697 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21698 (throw :skip nil))
21699 (setq marker (org-agenda-new-marker b0)
21700 category (org-get-category b0)
21701 tmp (buffer-substring (max (point-min)
21702 (- b0 org-ds-keyword-length))
21704 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21705 deadlinep (string-match org-deadline-regexp tmp)
21706 scheduledp (string-match org-scheduled-regexp tmp)
21707 donep (org-entry-is-done-p))
21708 (if (or scheduledp deadlinep) (throw :skip t))
21709 (if (string-match ">" timestr)
21710 ;; substring should only run to end of time stamp
21711 (setq timestr (substring timestr 0 (match-end 0))))
21712 (save-excursion
21713 (if (re-search-backward "^\\*+ " nil t)
21714 (progn
21715 (goto-char (match-beginning 0))
21716 (setq hdmarker (org-agenda-new-marker)
21717 tags (org-get-tags-at))
21718 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21719 (setq head (match-string 1))
21720 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21721 (setq txt (org-format-agenda-item
21722 nil head category tags timestr nil
21723 remove-re)))
21724 (setq txt org-agenda-no-heading-message))
21725 (setq priority (org-get-priority txt))
21726 (org-add-props txt props
21727 'org-marker marker 'org-hd-marker hdmarker)
21728 (org-add-props txt nil 'priority priority
21729 'org-category category 'date date
21730 'type "timestamp")
21731 (push txt ee))
21732 (outline-next-heading)))
21733 (nreverse ee)))
21735 (defun org-agenda-get-sexps ()
21736 "Return the sexp information for agenda display."
21737 (require 'diary-lib)
21738 (let* ((props (list 'face nil
21739 'mouse-face 'highlight
21740 'keymap org-agenda-keymap
21741 'help-echo
21742 (format "mouse-2 or RET jump to org file %s"
21743 (abbreviate-file-name buffer-file-name))))
21744 (regexp "^&?%%(")
21745 marker category ee txt tags entry result beg b sexp sexp-entry)
21746 (goto-char (point-min))
21747 (while (re-search-forward regexp nil t)
21748 (catch :skip
21749 (org-agenda-skip)
21750 (setq beg (match-beginning 0))
21751 (goto-char (1- (match-end 0)))
21752 (setq b (point))
21753 (forward-sexp 1)
21754 (setq sexp (buffer-substring b (point)))
21755 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21756 (org-trim (match-string 1))
21757 ""))
21758 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21759 (when result
21760 (setq marker (org-agenda-new-marker beg)
21761 category (org-get-category beg))
21763 (if (string-match "\\S-" result)
21764 (setq txt result)
21765 (setq txt "SEXP entry returned empty string"))
21767 (setq txt (org-format-agenda-item
21768 "" txt category tags 'time))
21769 (org-add-props txt props 'org-marker marker)
21770 (org-add-props txt nil
21771 'org-category category 'date date
21772 'type "sexp")
21773 (push txt ee))))
21774 (nreverse ee)))
21776 (defun org-agenda-get-closed ()
21777 "Return the logged TODO entries for agenda display."
21778 (let* ((props (list 'mouse-face 'highlight
21779 'org-not-done-regexp org-not-done-regexp
21780 'org-todo-regexp org-todo-regexp
21781 'keymap org-agenda-keymap
21782 'help-echo
21783 (format "mouse-2 or RET jump to org file %s"
21784 (abbreviate-file-name buffer-file-name))))
21785 (regexp (concat
21786 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21787 (regexp-quote
21788 (substring
21789 (format-time-string
21790 (car org-time-stamp-formats)
21791 (apply 'encode-time ; DATE bound by calendar
21792 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21793 1 11))))
21794 marker hdmarker priority category tags closedp
21795 ee txt timestr)
21796 (goto-char (point-min))
21797 (while (re-search-forward regexp nil t)
21798 (catch :skip
21799 (org-agenda-skip)
21800 (setq marker (org-agenda-new-marker (match-beginning 0))
21801 closedp (equal (match-string 1) org-closed-string)
21802 category (org-get-category (match-beginning 0))
21803 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21804 ;; donep (org-entry-is-done-p)
21806 (if (string-match "\\]" timestr)
21807 ;; substring should only run to end of time stamp
21808 (setq timestr (substring timestr 0 (match-end 0))))
21809 (save-excursion
21810 (if (re-search-backward "^\\*+ " nil t)
21811 (progn
21812 (goto-char (match-beginning 0))
21813 (setq hdmarker (org-agenda-new-marker)
21814 tags (org-get-tags-at))
21815 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21816 (setq txt (org-format-agenda-item
21817 (if closedp "Closed: " "Clocked: ")
21818 (match-string 1) category tags timestr)))
21819 (setq txt org-agenda-no-heading-message))
21820 (setq priority 100000)
21821 (org-add-props txt props
21822 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21823 'priority priority 'org-category category
21824 'type "closed" 'date date
21825 'undone-face 'org-warning 'done-face 'org-done)
21826 (push txt ee))
21827 (goto-char (point-at-eol))))
21828 (nreverse ee)))
21830 (defun org-agenda-get-deadlines ()
21831 "Return the deadline information for agenda display."
21832 (let* ((props (list 'mouse-face 'highlight
21833 'org-not-done-regexp org-not-done-regexp
21834 'org-todo-regexp org-todo-regexp
21835 'keymap org-agenda-keymap
21836 'help-echo
21837 (format "mouse-2 or RET jump to org file %s"
21838 (abbreviate-file-name buffer-file-name))))
21839 (regexp org-deadline-time-regexp)
21840 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21841 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21842 d2 diff dfrac wdays pos pos1 category tags
21843 ee txt head face s upcomingp donep timestr)
21844 (goto-char (point-min))
21845 (while (re-search-forward regexp nil t)
21846 (catch :skip
21847 (org-agenda-skip)
21848 (setq s (match-string 1)
21849 pos (1- (match-beginning 1))
21850 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21851 diff (- d2 d1)
21852 wdays (org-get-wdays s)
21853 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21854 upcomingp (and todayp (> diff 0)))
21855 ;; When to show a deadline in the calendar:
21856 ;; If the expiration is within wdays warning time.
21857 ;; Past-due deadlines are only shown on the current date
21858 (if (or (and (<= diff wdays)
21859 (and todayp (not org-agenda-only-exact-dates)))
21860 (= diff 0))
21861 (save-excursion
21862 (setq category (org-get-category))
21863 (if (re-search-backward "^\\*+[ \t]+" nil t)
21864 (progn
21865 (goto-char (match-end 0))
21866 (setq pos1 (match-beginning 0))
21867 (setq tags (org-get-tags-at pos1))
21868 (setq head (buffer-substring-no-properties
21869 (point)
21870 (progn (skip-chars-forward "^\r\n")
21871 (point))))
21872 (setq donep (string-match org-looking-at-done-regexp head))
21873 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21874 (setq timestr
21875 (concat (substring s (match-beginning 1)) " "))
21876 (setq timestr 'time))
21877 (if (and donep
21878 (or org-agenda-skip-deadline-if-done
21879 (not (= diff 0))))
21880 (setq txt nil)
21881 (setq txt (org-format-agenda-item
21882 (if (= diff 0)
21883 (car org-agenda-deadline-leaders)
21884 (format (nth 1 org-agenda-deadline-leaders)
21885 diff))
21886 head category tags timestr))))
21887 (setq txt org-agenda-no-heading-message))
21888 (when txt
21889 (setq face (org-agenda-deadline-face dfrac wdays))
21890 (org-add-props txt props
21891 'org-marker (org-agenda-new-marker pos)
21892 'org-hd-marker (org-agenda-new-marker pos1)
21893 'priority (+ (- diff)
21894 (org-get-priority txt))
21895 'org-category category
21896 'type (if upcomingp "upcoming-deadline" "deadline")
21897 'date (if upcomingp date d2)
21898 'face (if donep 'org-done face)
21899 'undone-face face 'done-face 'org-done)
21900 (push txt ee))))))
21901 (nreverse ee)))
21903 (defun org-agenda-deadline-face (fraction &optional wdays)
21904 "Return the face to displaying a deadline item.
21905 FRACTION is what fraction of the head-warning time has passed."
21906 (if (equal wdays 0) (setq fraction 1.))
21907 (let ((faces org-agenda-deadline-faces) f)
21908 (catch 'exit
21909 (while (setq f (pop faces))
21910 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21912 (defun org-agenda-get-scheduled ()
21913 "Return the scheduled information for agenda display."
21914 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21915 'org-todo-regexp org-todo-regexp
21916 'done-face 'org-done
21917 'mouse-face 'highlight
21918 'keymap org-agenda-keymap
21919 'help-echo
21920 (format "mouse-2 or RET jump to org file %s"
21921 (abbreviate-file-name buffer-file-name))))
21922 (regexp org-scheduled-time-regexp)
21923 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21924 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21925 d2 diff pos pos1 category tags
21926 ee txt head pastschedp donep face timestr s)
21927 (goto-char (point-min))
21928 (while (re-search-forward regexp nil t)
21929 (catch :skip
21930 (org-agenda-skip)
21931 (setq s (match-string 1)
21932 pos (1- (match-beginning 1))
21933 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21934 ;;; is this right?
21935 ;;; do we need to do this for deadleine too????
21936 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21937 diff (- d2 d1))
21938 (setq pastschedp (and todayp (< diff 0)))
21939 ;; When to show a scheduled item in the calendar:
21940 ;; If it is on or past the date.
21941 (if (or (and (< diff 0)
21942 (and todayp (not org-agenda-only-exact-dates)))
21943 (= diff 0))
21944 (save-excursion
21945 (setq category (org-get-category))
21946 (if (re-search-backward "^\\*+[ \t]+" nil t)
21947 (progn
21948 (goto-char (match-end 0))
21949 (setq pos1 (match-beginning 0))
21950 (setq tags (org-get-tags-at))
21951 (setq head (buffer-substring-no-properties
21952 (point)
21953 (progn (skip-chars-forward "^\r\n") (point))))
21954 (setq donep (string-match org-looking-at-done-regexp head))
21955 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21956 (setq timestr
21957 (concat (substring s (match-beginning 1)) " "))
21958 (setq timestr 'time))
21959 (if (and donep
21960 (or org-agenda-skip-scheduled-if-done
21961 (not (= diff 0))))
21962 (setq txt nil)
21963 (setq txt (org-format-agenda-item
21964 (if (= diff 0)
21965 (car org-agenda-scheduled-leaders)
21966 (format (nth 1 org-agenda-scheduled-leaders)
21967 (- 1 diff)))
21968 head category tags timestr))))
21969 (setq txt org-agenda-no-heading-message))
21970 (when txt
21971 (setq face (if pastschedp
21972 'org-scheduled-previously
21973 'org-scheduled-today))
21974 (org-add-props txt props
21975 'undone-face face
21976 'face (if donep 'org-done face)
21977 'org-marker (org-agenda-new-marker pos)
21978 'org-hd-marker (org-agenda-new-marker pos1)
21979 'type (if pastschedp "past-scheduled" "scheduled")
21980 'date (if pastschedp d2 date)
21981 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21982 'org-category category)
21983 (push txt ee))))))
21984 (nreverse ee)))
21986 (defun org-agenda-get-blocks ()
21987 "Return the date-range information for agenda display."
21988 (let* ((props (list 'face nil
21989 'org-not-done-regexp org-not-done-regexp
21990 'org-todo-regexp org-todo-regexp
21991 'mouse-face 'highlight
21992 'keymap org-agenda-keymap
21993 'help-echo
21994 (format "mouse-2 or RET jump to org file %s"
21995 (abbreviate-file-name buffer-file-name))))
21996 (regexp org-tr-regexp)
21997 (d0 (calendar-absolute-from-gregorian date))
21998 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21999 donep head)
22000 (goto-char (point-min))
22001 (while (re-search-forward regexp nil t)
22002 (catch :skip
22003 (org-agenda-skip)
22004 (setq pos (point))
22005 (setq timestr (match-string 0)
22006 s1 (match-string 1)
22007 s2 (match-string 2)
22008 d1 (time-to-days (org-time-string-to-time s1))
22009 d2 (time-to-days (org-time-string-to-time s2)))
22010 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
22011 ;; Only allow days between the limits, because the normal
22012 ;; date stamps will catch the limits.
22013 (save-excursion
22014 (setq marker (org-agenda-new-marker (point)))
22015 (setq category (org-get-category))
22016 (if (re-search-backward "^\\*+ " nil t)
22017 (progn
22018 (goto-char (match-beginning 0))
22019 (setq hdmarker (org-agenda-new-marker (point)))
22020 (setq tags (org-get-tags-at))
22021 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
22022 (setq head (match-string 1))
22023 (and org-agenda-skip-timestamp-if-done
22024 (org-entry-is-done-p)
22025 (throw :skip t))
22026 (setq txt (org-format-agenda-item
22027 (format (if (= d1 d2) "" "(%d/%d): ")
22028 (1+ (- d0 d1)) (1+ (- d2 d1)))
22029 head category tags
22030 (if (= d0 d1) timestr))))
22031 (setq txt org-agenda-no-heading-message))
22032 (org-add-props txt props
22033 'org-marker marker 'org-hd-marker hdmarker
22034 'type "block" 'date date
22035 'priority (org-get-priority txt) 'org-category category)
22036 (push txt ee)))
22037 (goto-char pos)))
22038 ;; Sort the entries by expiration date.
22039 (nreverse ee)))
22041 ;;; Agenda presentation and sorting
22043 (defconst org-plain-time-of-day-regexp
22044 (concat
22045 "\\(\\<[012]?[0-9]"
22046 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22047 "\\(--?"
22048 "\\(\\<[012]?[0-9]"
22049 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22050 "\\)?")
22051 "Regular expression to match a plain time or time range.
22052 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22053 groups carry important information:
22054 0 the full match
22055 1 the first time, range or not
22056 8 the second time, if it is a range.")
22058 (defconst org-plain-time-extension-regexp
22059 (concat
22060 "\\(\\<[012]?[0-9]"
22061 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22062 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
22063 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
22064 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22065 groups carry important information:
22066 0 the full match
22067 7 hours of duration
22068 9 minutes of duration")
22070 (defconst org-stamp-time-of-day-regexp
22071 (concat
22072 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
22073 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
22074 "\\(--?"
22075 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
22076 "Regular expression to match a timestamp time or time range.
22077 After a match, the following groups carry important information:
22078 0 the full match
22079 1 date plus weekday, for backreferencing to make sure both times on same day
22080 2 the first time, range or not
22081 4 the second time, if it is a range.")
22083 (defvar org-prefix-has-time nil
22084 "A flag, set by `org-compile-prefix-format'.
22085 The flag is set if the currently compiled format contains a `%t'.")
22086 (defvar org-prefix-has-tag nil
22087 "A flag, set by `org-compile-prefix-format'.
22088 The flag is set if the currently compiled format contains a `%T'.")
22090 (defun org-format-agenda-item (extra txt &optional category tags dotime
22091 noprefix remove-re)
22092 "Format TXT to be inserted into the agenda buffer.
22093 In particular, it adds the prefix and corresponding text properties. EXTRA
22094 must be a string and replaces the `%s' specifier in the prefix format.
22095 CATEGORY (string, symbol or nil) may be used to overrule the default
22096 category taken from local variable or file name. It will replace the `%c'
22097 specifier in the format. DOTIME, when non-nil, indicates that a
22098 time-of-day should be extracted from TXT for sorting of this entry, and for
22099 the `%t' specifier in the format. When DOTIME is a string, this string is
22100 searched for a time before TXT is. NOPREFIX is a flag and indicates that
22101 only the correctly processes TXT should be returned - this is used by
22102 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
22103 Any match of REMOVE-RE will be removed from TXT."
22104 (save-match-data
22105 ;; Diary entries sometimes have extra whitespace at the beginning
22106 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
22107 (let* ((category (or category
22108 org-category
22109 (if buffer-file-name
22110 (file-name-sans-extension
22111 (file-name-nondirectory buffer-file-name))
22112 "")))
22113 (tag (if tags (nth (1- (length tags)) tags) ""))
22114 time ; time and tag are needed for the eval of the prefix format
22115 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
22116 (time-of-day (and dotime (org-get-time-of-day ts)))
22117 stamp plain s0 s1 s2 rtn srp)
22118 (when (and dotime time-of-day org-prefix-has-time)
22119 ;; Extract starting and ending time and move them to prefix
22120 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
22121 (setq plain (string-match org-plain-time-of-day-regexp ts)))
22122 (setq s0 (match-string 0 ts)
22123 srp (and stamp (match-end 3))
22124 s1 (match-string (if plain 1 2) ts)
22125 s2 (match-string (if plain 8 (if srp 4 6)) ts))
22127 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
22128 ;; them, we might want to remove them there to avoid duplication.
22129 ;; The user can turn this off with a variable.
22130 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
22131 (string-match (concat (regexp-quote s0) " *") txt)
22132 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
22133 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
22134 (= (match-beginning 0) 0)
22136 (setq txt (replace-match "" nil nil txt))))
22137 ;; Normalize the time(s) to 24 hour
22138 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
22139 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
22141 (when (and s1 (not s2) org-agenda-default-appointment-duration
22142 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
22143 (let ((m (+ (string-to-number (match-string 2 s1))
22144 (* 60 (string-to-number (match-string 1 s1)))
22145 org-agenda-default-appointment-duration))
22147 (setq h (/ m 60) m (- m (* h 60)))
22148 (setq s2 (format "%02d:%02d" h m))))
22150 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22151 txt)
22152 ;; Tags are in the string
22153 (if (or (eq org-agenda-remove-tags t)
22154 (and org-agenda-remove-tags
22155 org-prefix-has-tag))
22156 (setq txt (replace-match "" t t txt))
22157 (setq txt (replace-match
22158 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
22159 (match-string 2 txt))
22160 t t txt))))
22162 (when remove-re
22163 (while (string-match remove-re txt)
22164 (setq txt (replace-match "" t t txt))))
22166 ;; Create the final string
22167 (if noprefix
22168 (setq rtn txt)
22169 ;; Prepare the variables needed in the eval of the compiled format
22170 (setq time (cond (s2 (concat s1 "-" s2))
22171 (s1 (concat s1 "......"))
22172 (t ""))
22173 extra (or extra "")
22174 category (if (symbolp category) (symbol-name category) category))
22175 ;; Evaluate the compiled format
22176 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
22178 ;; And finally add the text properties
22179 (org-add-props rtn nil
22180 'org-category (downcase category) 'tags tags
22181 'org-highest-priority org-highest-priority
22182 'org-lowest-priority org-lowest-priority
22183 'prefix-length (- (length rtn) (length txt))
22184 'time-of-day time-of-day
22185 'txt txt
22186 'time time
22187 'extra extra
22188 'dotime dotime))))
22190 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
22191 (defvar org-agenda-sorting-strategy-selected nil)
22193 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
22194 (catch 'exit
22195 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
22196 ((and todayp (member 'today (car org-agenda-time-grid))))
22197 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
22198 ((member 'weekly (car org-agenda-time-grid)))
22199 (t (throw 'exit list)))
22200 (let* ((have (delq nil (mapcar
22201 (lambda (x) (get-text-property 1 'time-of-day x))
22202 list)))
22203 (string (nth 1 org-agenda-time-grid))
22204 (gridtimes (nth 2 org-agenda-time-grid))
22205 (req (car org-agenda-time-grid))
22206 (remove (member 'remove-match req))
22207 new time)
22208 (if (and (member 'require-timed req) (not have))
22209 ;; don't show empty grid
22210 (throw 'exit list))
22211 (while (setq time (pop gridtimes))
22212 (unless (and remove (member time have))
22213 (setq time (int-to-string time))
22214 (push (org-format-agenda-item
22215 nil string "" nil
22216 (concat (substring time 0 -2) ":" (substring time -2)))
22217 new)
22218 (put-text-property
22219 1 (length (car new)) 'face 'org-time-grid (car new))))
22220 (if (member 'time-up org-agenda-sorting-strategy-selected)
22221 (append new list)
22222 (append list new)))))
22224 (defun org-compile-prefix-format (key)
22225 "Compile the prefix format into a Lisp form that can be evaluated.
22226 The resulting form is returned and stored in the variable
22227 `org-prefix-format-compiled'."
22228 (setq org-prefix-has-time nil org-prefix-has-tag nil)
22229 (let ((s (cond
22230 ((stringp org-agenda-prefix-format)
22231 org-agenda-prefix-format)
22232 ((assq key org-agenda-prefix-format)
22233 (cdr (assq key org-agenda-prefix-format)))
22234 (t " %-12:c%?-12t% s")))
22235 (start 0)
22236 varform vars var e c f opt)
22237 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
22238 s start)
22239 (setq var (cdr (assoc (match-string 4 s)
22240 '(("c" . category) ("t" . time) ("s" . extra)
22241 ("T" . tag))))
22242 c (or (match-string 3 s) "")
22243 opt (match-beginning 1)
22244 start (1+ (match-beginning 0)))
22245 (if (equal var 'time) (setq org-prefix-has-time t))
22246 (if (equal var 'tag) (setq org-prefix-has-tag t))
22247 (setq f (concat "%" (match-string 2 s) "s"))
22248 (if opt
22249 (setq varform
22250 `(if (equal "" ,var)
22252 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22253 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22254 (setq s (replace-match "%s" t nil s))
22255 (push varform vars))
22256 (setq vars (nreverse vars))
22257 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22259 (defun org-set-sorting-strategy (key)
22260 (if (symbolp (car org-agenda-sorting-strategy))
22261 ;; the old format
22262 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22263 (setq org-agenda-sorting-strategy-selected
22264 (or (cdr (assq key org-agenda-sorting-strategy))
22265 (cdr (assq 'agenda org-agenda-sorting-strategy))
22266 '(time-up category-keep priority-down)))))
22268 (defun org-get-time-of-day (s &optional string mod24)
22269 "Check string S for a time of day.
22270 If found, return it as a military time number between 0 and 2400.
22271 If not found, return nil.
22272 The optional STRING argument forces conversion into a 5 character wide string
22273 HH:MM."
22274 (save-match-data
22275 (when
22276 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22277 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22278 (let* ((h (string-to-number (match-string 1 s)))
22279 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22280 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22281 (am-p (equal ampm "am"))
22282 (h1 (cond ((not ampm) h)
22283 ((= h 12) (if am-p 0 12))
22284 (t (+ h (if am-p 0 12)))))
22285 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22286 (mod h1 24) h1))
22287 (t0 (+ (* 100 h2) m))
22288 (t1 (concat (if (>= h1 24) "+" " ")
22289 (if (< t0 100) "0" "")
22290 (if (< t0 10) "0" "")
22291 (int-to-string t0))))
22292 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22294 (defun org-finalize-agenda-entries (list &optional nosort)
22295 "Sort and concatenate the agenda items."
22296 (setq list (mapcar 'org-agenda-highlight-todo list))
22297 (if nosort
22298 list
22299 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22301 (defun org-agenda-highlight-todo (x)
22302 (let (re pl)
22303 (if (eq x 'line)
22304 (save-excursion
22305 (beginning-of-line 1)
22306 (setq re (get-text-property (point) 'org-todo-regexp))
22307 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22308 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22309 (add-text-properties (match-beginning 0) (match-end 0)
22310 (list 'face (org-get-todo-face 0)))
22311 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22312 (delete-region (match-beginning 1) (1- (match-end 0)))
22313 (goto-char (match-beginning 1))
22314 (insert (format org-agenda-todo-keyword-format s)))))
22315 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22316 pl (get-text-property 0 'prefix-length x))
22317 (when (and re
22318 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22319 x (or pl 0)) pl))
22320 (add-text-properties
22321 (or (match-end 1) (match-end 0)) (match-end 0)
22322 (list 'face (org-get-todo-face (match-string 2 x)))
22324 (setq x (concat (substring x 0 (match-end 1))
22325 (format org-agenda-todo-keyword-format
22326 (match-string 2 x))
22328 (substring x (match-end 3)))))
22329 x)))
22331 (defsubst org-cmp-priority (a b)
22332 "Compare the priorities of string A and B."
22333 (let ((pa (or (get-text-property 1 'priority a) 0))
22334 (pb (or (get-text-property 1 'priority b) 0)))
22335 (cond ((> pa pb) +1)
22336 ((< pa pb) -1)
22337 (t nil))))
22339 (defsubst org-cmp-category (a b)
22340 "Compare the string values of categories of strings A and B."
22341 (let ((ca (or (get-text-property 1 'org-category a) ""))
22342 (cb (or (get-text-property 1 'org-category b) "")))
22343 (cond ((string-lessp ca cb) -1)
22344 ((string-lessp cb ca) +1)
22345 (t nil))))
22347 (defsubst org-cmp-tag (a b)
22348 "Compare the string values of categories of strings A and B."
22349 (let ((ta (car (last (get-text-property 1 'tags a))))
22350 (tb (car (last (get-text-property 1 'tags b)))))
22351 (cond ((not ta) +1)
22352 ((not tb) -1)
22353 ((string-lessp ta tb) -1)
22354 ((string-lessp tb ta) +1)
22355 (t nil))))
22357 (defsubst org-cmp-time (a b)
22358 "Compare the time-of-day values of strings A and B."
22359 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22360 (ta (or (get-text-property 1 'time-of-day a) def))
22361 (tb (or (get-text-property 1 'time-of-day b) def)))
22362 (cond ((< ta tb) -1)
22363 ((< tb ta) +1)
22364 (t nil))))
22366 (defun org-entries-lessp (a b)
22367 "Predicate for sorting agenda entries."
22368 ;; The following variables will be used when the form is evaluated.
22369 ;; So even though the compiler complains, keep them.
22370 (let* ((time-up (org-cmp-time a b))
22371 (time-down (if time-up (- time-up) nil))
22372 (priority-up (org-cmp-priority a b))
22373 (priority-down (if priority-up (- priority-up) nil))
22374 (category-up (org-cmp-category a b))
22375 (category-down (if category-up (- category-up) nil))
22376 (category-keep (if category-up +1 nil))
22377 (tag-up (org-cmp-tag a b))
22378 (tag-down (if tag-up (- tag-up) nil)))
22379 (cdr (assoc
22380 (eval (cons 'or org-agenda-sorting-strategy-selected))
22381 '((-1 . t) (1 . nil) (nil . nil))))))
22383 ;;; Agenda restriction lock
22385 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22386 "Overlay to mark the headline to which arenda commands are restricted.")
22387 (org-overlay-put org-agenda-restriction-lock-overlay
22388 'face 'org-agenda-restriction-lock)
22389 (org-overlay-put org-agenda-restriction-lock-overlay
22390 'help-echo "Agendas are currently limited to this subtree.")
22391 (org-detach-overlay org-agenda-restriction-lock-overlay)
22392 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22393 "Overlay marking the agenda restriction line in speedbar.")
22394 (org-overlay-put org-speedbar-restriction-lock-overlay
22395 'face 'org-agenda-restriction-lock)
22396 (org-overlay-put org-speedbar-restriction-lock-overlay
22397 'help-echo "Agendas are currently limited to this item.")
22398 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22400 (defun org-agenda-set-restriction-lock (&optional type)
22401 "Set restriction lock for agenda, to current subtree or file.
22402 Restriction will be the file if TYPE is `file', or if type is the
22403 universal prefix '(4), or if the cursor is before the first headline
22404 in the file. Otherwise, restriction will be to the current subtree."
22405 (interactive "P")
22406 (and (equal type '(4)) (setq type 'file))
22407 (setq type (cond
22408 (type type)
22409 ((org-at-heading-p) 'subtree)
22410 ((condition-case nil (org-back-to-heading t) (error nil))
22411 'subtree)
22412 (t 'file)))
22413 (if (eq type 'subtree)
22414 (progn
22415 (setq org-agenda-restrict t)
22416 (setq org-agenda-overriding-restriction 'subtree)
22417 (put 'org-agenda-files 'org-restrict
22418 (list (buffer-file-name (buffer-base-buffer))))
22419 (org-back-to-heading t)
22420 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22421 (move-marker org-agenda-restrict-begin (point))
22422 (move-marker org-agenda-restrict-end
22423 (save-excursion (org-end-of-subtree t)))
22424 (message "Locking agenda restriction to subtree"))
22425 (put 'org-agenda-files 'org-restrict
22426 (list (buffer-file-name (buffer-base-buffer))))
22427 (setq org-agenda-restrict nil)
22428 (setq org-agenda-overriding-restriction 'file)
22429 (move-marker org-agenda-restrict-begin nil)
22430 (move-marker org-agenda-restrict-end nil)
22431 (message "Locking agenda restriction to file"))
22432 (setq current-prefix-arg nil)
22433 (org-agenda-maybe-redo))
22435 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22436 "Remove the agenda restriction lock."
22437 (interactive "P")
22438 (org-detach-overlay org-agenda-restriction-lock-overlay)
22439 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22440 (setq org-agenda-overriding-restriction nil)
22441 (setq org-agenda-restrict nil)
22442 (put 'org-agenda-files 'org-restrict nil)
22443 (move-marker org-agenda-restrict-begin nil)
22444 (move-marker org-agenda-restrict-end nil)
22445 (setq current-prefix-arg nil)
22446 (message "Agenda restriction lock removed")
22447 (or noupdate (org-agenda-maybe-redo)))
22449 (defun org-agenda-maybe-redo ()
22450 "If there is any window showing the agenda view, update it."
22451 (let ((w (get-buffer-window org-agenda-buffer-name t))
22452 (w0 (selected-window)))
22453 (when w
22454 (select-window w)
22455 (org-agenda-redo)
22456 (select-window w0)
22457 (if org-agenda-overriding-restriction
22458 (message "Agenda view shifted to new %s restriction"
22459 org-agenda-overriding-restriction)
22460 (message "Agenda restriction lock removed")))))
22462 ;;; Agenda commands
22464 (defun org-agenda-check-type (error &rest types)
22465 "Check if agenda buffer is of allowed type.
22466 If ERROR is non-nil, throw an error, otherwise just return nil."
22467 (if (memq org-agenda-type types)
22469 (if error
22470 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22471 nil)))
22473 (defun org-agenda-quit ()
22474 "Exit agenda by removing the window or the buffer."
22475 (interactive)
22476 (let ((buf (current-buffer)))
22477 (if (not (one-window-p)) (delete-window))
22478 (kill-buffer buf)
22479 (org-agenda-reset-markers)
22480 (org-columns-remove-overlays))
22481 ;; Maybe restore the pre-agenda window configuration.
22482 (and org-agenda-restore-windows-after-quit
22483 (not (eq org-agenda-window-setup 'other-frame))
22484 org-pre-agenda-window-conf
22485 (set-window-configuration org-pre-agenda-window-conf)))
22487 (defun org-agenda-exit ()
22488 "Exit agenda by removing the window or the buffer.
22489 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22490 Org-mode buffers visited directly by the user will not be touched."
22491 (interactive)
22492 (org-release-buffers org-agenda-new-buffers)
22493 (setq org-agenda-new-buffers nil)
22494 (org-agenda-quit))
22496 (defun org-agenda-execute (arg)
22497 "Execute another agenda command, keeping same window.\\<global-map>
22498 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22499 (interactive "P")
22500 (let ((org-agenda-window-setup 'current-window))
22501 (org-agenda arg)))
22503 (defun org-save-all-org-buffers ()
22504 "Save all Org-mode buffers without user confirmation."
22505 (interactive)
22506 (message "Saving all Org-mode buffers...")
22507 (save-some-buffers t 'org-mode-p)
22508 (message "Saving all Org-mode buffers... done"))
22510 (defun org-agenda-redo ()
22511 "Rebuild Agenda.
22512 When this is the global TODO list, a prefix argument will be interpreted."
22513 (interactive)
22514 (let* ((org-agenda-keep-modes t)
22515 (line (org-current-line))
22516 (window-line (- line (org-current-line (window-start))))
22517 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22518 (message "Rebuilding agenda buffer...")
22519 (org-let lprops '(eval org-agenda-redo-command))
22520 (setq org-agenda-undo-list nil
22521 org-agenda-pending-undo-list nil)
22522 (message "Rebuilding agenda buffer...done")
22523 (goto-line line)
22524 (recenter window-line)))
22526 (defun org-agenda-manipulate-query-add ()
22527 "Manipulate the query by adding a search term with positive selection.
22528 Positive selection means, the term must be matched for selection of an entry."
22529 (interactive)
22530 (org-agenda-manipulate-query ?\[))
22531 (defun org-agenda-manipulate-query-subtract ()
22532 "Manipulate the query by adding a search term with negative selection.
22533 Negative selection means, term must not be matched for selection of an entry."
22534 (interactive)
22535 (org-agenda-manipulate-query ?\]))
22536 (defun org-agenda-manipulate-query-add-re ()
22537 "Manipulate the query by adding a search regexp with positive selection.
22538 Positive selection means, the regexp must match for selection of an entry."
22539 (interactive)
22540 (org-agenda-manipulate-query ?\{))
22541 (defun org-agenda-manipulate-query-subtract-re ()
22542 "Manipulate the query by adding a search regexp with negative selection.
22543 Negative selection means, regexp must not match for selection of an entry."
22544 (interactive)
22545 (org-agenda-manipulate-query ?\}))
22546 (defun org-agenda-manipulate-query (char)
22547 (cond
22548 ((eq org-agenda-type 'search)
22549 (org-add-to-string
22550 'org-agenda-query-string
22551 (cdr (assoc char '((?\[ . " +") (?\] . " -")
22552 (?\{ . " +{}") (?\} . " -{}")))))
22553 (setq org-agenda-redo-command
22554 (list 'org-search-view
22555 (+ (length org-agenda-query-string)
22556 (if (member char '(?\{ ?\})) 0 1))
22557 org-agenda-query-string))
22558 (set-register org-agenda-query-register org-agenda-query-string)
22559 (org-agenda-redo))
22560 (t (error "Canot manipulate query for %s-type agenda buffers"
22561 org-agenda-type))))
22563 (defun org-add-to-string (var string)
22564 (set var (concat (symbol-value var) string)))
22566 (defun org-agenda-goto-date (date)
22567 "Jump to DATE in agenda."
22568 (interactive (list (org-read-date)))
22569 (org-agenda-list nil date))
22571 (defun org-agenda-goto-today ()
22572 "Go to today."
22573 (interactive)
22574 (org-agenda-check-type t 'timeline 'agenda)
22575 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22576 (cond
22577 (tdpos (goto-char tdpos))
22578 ((eq org-agenda-type 'agenda)
22579 (let* ((sd (time-to-days
22580 (time-subtract (current-time)
22581 (list 0 (* 3600 org-extend-today-until) 0))))
22582 (comp (org-agenda-compute-time-span sd org-agenda-span))
22583 (org-agenda-overriding-arguments org-agenda-last-arguments))
22584 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22585 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22586 (org-agenda-redo)
22587 (org-agenda-find-same-or-today-or-agenda)))
22588 (t (error "Cannot find today")))))
22590 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22591 (goto-char
22592 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22593 (text-property-any (point-min) (point-max) 'org-today t)
22594 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22595 (point-min))))
22597 (defun org-agenda-later (arg)
22598 "Go forward in time by thee current span.
22599 With prefix ARG, go forward that many times the current span."
22600 (interactive "p")
22601 (org-agenda-check-type t 'agenda)
22602 (let* ((span org-agenda-span)
22603 (sd org-starting-day)
22604 (greg (calendar-gregorian-from-absolute sd))
22605 (cnt (get-text-property (point) 'org-day-cnt))
22606 greg2 nd)
22607 (cond
22608 ((eq span 'day)
22609 (setq sd (+ arg sd) nd 1))
22610 ((eq span 'week)
22611 (setq sd (+ (* 7 arg) sd) nd 7))
22612 ((eq span 'month)
22613 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22614 sd (calendar-absolute-from-gregorian greg2))
22615 (setcar greg2 (1+ (car greg2)))
22616 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22617 ((eq span 'year)
22618 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22619 sd (calendar-absolute-from-gregorian greg2))
22620 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22621 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22622 (let ((org-agenda-overriding-arguments
22623 (list (car org-agenda-last-arguments) sd nd t)))
22624 (org-agenda-redo)
22625 (org-agenda-find-same-or-today-or-agenda cnt))))
22627 (defun org-agenda-earlier (arg)
22628 "Go backward in time by the current span.
22629 With prefix ARG, go backward that many times the current span."
22630 (interactive "p")
22631 (org-agenda-later (- arg)))
22633 (defun org-agenda-day-view ()
22634 "Switch to daily view for agenda."
22635 (interactive)
22636 (setq org-agenda-ndays 1)
22637 (org-agenda-change-time-span 'day))
22638 (defun org-agenda-week-view ()
22639 "Switch to daily view for agenda."
22640 (interactive)
22641 (setq org-agenda-ndays 7)
22642 (org-agenda-change-time-span 'week))
22643 (defun org-agenda-month-view ()
22644 "Switch to daily view for agenda."
22645 (interactive)
22646 (org-agenda-change-time-span 'month))
22647 (defun org-agenda-year-view ()
22648 "Switch to daily view for agenda."
22649 (interactive)
22650 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22651 (org-agenda-change-time-span 'year)
22652 (error "Abort")))
22654 (defun org-agenda-change-time-span (span)
22655 "Change the agenda view to SPAN.
22656 SPAN may be `day', `week', `month', `year'."
22657 (org-agenda-check-type t 'agenda)
22658 (if (equal org-agenda-span span)
22659 (error "Viewing span is already \"%s\"" span))
22660 (let* ((sd (or (get-text-property (point) 'day)
22661 org-starting-day))
22662 (computed (org-agenda-compute-time-span sd span))
22663 (org-agenda-overriding-arguments
22664 (list (car org-agenda-last-arguments)
22665 (car computed) (cdr computed) t)))
22666 (org-agenda-redo)
22667 (org-agenda-find-same-or-today-or-agenda))
22668 (org-agenda-set-mode-name)
22669 (message "Switched to %s view" span))
22671 (defun org-agenda-compute-time-span (sd span)
22672 "Compute starting date and number of days for agenda.
22673 SPAN may be `day', `week', `month', `year'. The return value
22674 is a cons cell with the starting date and the number of days,
22675 so that the date SD will be in that range."
22676 (let* ((greg (calendar-gregorian-from-absolute sd))
22678 (cond
22679 ((eq span 'day)
22680 (setq nd 1))
22681 ((eq span 'week)
22682 (let* ((nt (calendar-day-of-week
22683 (calendar-gregorian-from-absolute sd)))
22684 (d (if org-agenda-start-on-weekday
22685 (- nt org-agenda-start-on-weekday)
22686 0)))
22687 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22688 (setq nd 7)))
22689 ((eq span 'month)
22690 (setq sd (calendar-absolute-from-gregorian
22691 (list (car greg) 1 (nth 2 greg)))
22692 nd (- (calendar-absolute-from-gregorian
22693 (list (1+ (car greg)) 1 (nth 2 greg)))
22694 sd)))
22695 ((eq span 'year)
22696 (setq sd (calendar-absolute-from-gregorian
22697 (list 1 1 (nth 2 greg)))
22698 nd (- (calendar-absolute-from-gregorian
22699 (list 1 1 (1+ (nth 2 greg))))
22700 sd))))
22701 (cons sd nd)))
22703 ;; FIXME: does not work if user makes date format that starts with a blank
22704 (defun org-agenda-next-date-line (&optional arg)
22705 "Jump to the next line indicating a date in agenda buffer."
22706 (interactive "p")
22707 (org-agenda-check-type t 'agenda 'timeline)
22708 (beginning-of-line 1)
22709 (if (looking-at "^\\S-") (forward-char 1))
22710 (if (not (re-search-forward "^\\S-" nil t arg))
22711 (progn
22712 (backward-char 1)
22713 (error "No next date after this line in this buffer")))
22714 (goto-char (match-beginning 0)))
22716 (defun org-agenda-previous-date-line (&optional arg)
22717 "Jump to the previous line indicating a date in agenda buffer."
22718 (interactive "p")
22719 (org-agenda-check-type t 'agenda 'timeline)
22720 (beginning-of-line 1)
22721 (if (not (re-search-backward "^\\S-" nil t arg))
22722 (error "No previous date before this line in this buffer")))
22724 ;; Initialize the highlight
22725 (defvar org-hl (org-make-overlay 1 1))
22726 (org-overlay-put org-hl 'face 'highlight)
22728 (defun org-highlight (begin end &optional buffer)
22729 "Highlight a region with overlay."
22730 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22731 org-hl begin end (or buffer (current-buffer))))
22733 (defun org-unhighlight ()
22734 "Detach overlay INDEX."
22735 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22737 ;; FIXME this is currently not used.
22738 (defun org-highlight-until-next-command (beg end &optional buffer)
22739 (org-highlight beg end buffer)
22740 (add-hook 'pre-command-hook 'org-unhighlight-once))
22741 (defun org-unhighlight-once ()
22742 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22743 (org-unhighlight))
22745 (defun org-agenda-follow-mode ()
22746 "Toggle follow mode in an agenda buffer."
22747 (interactive)
22748 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22749 (org-agenda-set-mode-name)
22750 (message "Follow mode is %s"
22751 (if org-agenda-follow-mode "on" "off")))
22753 (defun org-agenda-log-mode ()
22754 "Toggle log mode in an agenda buffer."
22755 (interactive)
22756 (org-agenda-check-type t 'agenda 'timeline)
22757 (setq org-agenda-show-log (not org-agenda-show-log))
22758 (org-agenda-set-mode-name)
22759 (org-agenda-redo)
22760 (message "Log mode is %s"
22761 (if org-agenda-show-log "on" "off")))
22763 (defun org-agenda-toggle-diary ()
22764 "Toggle diary inclusion in an agenda buffer."
22765 (interactive)
22766 (org-agenda-check-type t 'agenda)
22767 (setq org-agenda-include-diary (not org-agenda-include-diary))
22768 (org-agenda-redo)
22769 (org-agenda-set-mode-name)
22770 (message "Diary inclusion turned %s"
22771 (if org-agenda-include-diary "on" "off")))
22773 (defun org-agenda-toggle-time-grid ()
22774 "Toggle time grid in an agenda buffer."
22775 (interactive)
22776 (org-agenda-check-type t 'agenda)
22777 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22778 (org-agenda-redo)
22779 (org-agenda-set-mode-name)
22780 (message "Time-grid turned %s"
22781 (if org-agenda-use-time-grid "on" "off")))
22783 (defun org-agenda-set-mode-name ()
22784 "Set the mode name to indicate all the small mode settings."
22785 (setq mode-name
22786 (concat "Org-Agenda"
22787 (if (equal org-agenda-ndays 1) " Day" "")
22788 (if (equal org-agenda-ndays 7) " Week" "")
22789 (if org-agenda-follow-mode " Follow" "")
22790 (if org-agenda-include-diary " Diary" "")
22791 (if org-agenda-use-time-grid " Grid" "")
22792 (if org-agenda-show-log " Log" "")))
22793 (force-mode-line-update))
22795 (defun org-agenda-post-command-hook ()
22796 (and (eolp) (not (bolp)) (backward-char 1))
22797 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22798 (if (and org-agenda-follow-mode
22799 (get-text-property (point) 'org-marker))
22800 (org-agenda-show)))
22802 (defun org-agenda-show-priority ()
22803 "Show the priority of the current item.
22804 This priority is composed of the main priority given with the [#A] cookies,
22805 and by additional input from the age of a schedules or deadline entry."
22806 (interactive)
22807 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22808 (message "Priority is %d" (if pri pri -1000))))
22810 (defun org-agenda-show-tags ()
22811 "Show the tags applicable to the current item."
22812 (interactive)
22813 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22814 (if tags
22815 (message "Tags are :%s:"
22816 (org-no-properties (mapconcat 'identity tags ":")))
22817 (message "No tags associated with this line"))))
22819 (defun org-agenda-goto (&optional highlight)
22820 "Go to the Org-mode file which contains the item at point."
22821 (interactive)
22822 (let* ((marker (or (get-text-property (point) 'org-marker)
22823 (org-agenda-error)))
22824 (buffer (marker-buffer marker))
22825 (pos (marker-position marker)))
22826 (switch-to-buffer-other-window buffer)
22827 (widen)
22828 (goto-char pos)
22829 (when (org-mode-p)
22830 (org-show-context 'agenda)
22831 (save-excursion
22832 (and (outline-next-heading)
22833 (org-flag-heading nil)))) ; show the next heading
22834 (recenter (/ (window-height) 2))
22835 (run-hooks 'org-agenda-after-show-hook)
22836 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22838 (defvar org-agenda-after-show-hook nil
22839 "Normal hook run after an item has been shown from the agenda.
22840 Point is in the buffer where the item originated.")
22842 (defun org-agenda-kill ()
22843 "Kill the entry or subtree belonging to the current agenda entry."
22844 (interactive)
22845 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22846 (let* ((marker (or (get-text-property (point) 'org-marker)
22847 (org-agenda-error)))
22848 (buffer (marker-buffer marker))
22849 (pos (marker-position marker))
22850 (type (get-text-property (point) 'type))
22851 dbeg dend (n 0) conf)
22852 (org-with-remote-undo buffer
22853 (with-current-buffer buffer
22854 (save-excursion
22855 (goto-char pos)
22856 (if (and (org-mode-p) (not (member type '("sexp"))))
22857 (setq dbeg (progn (org-back-to-heading t) (point))
22858 dend (org-end-of-subtree t t))
22859 (setq dbeg (point-at-bol)
22860 dend (min (point-max) (1+ (point-at-eol)))))
22861 (goto-char dbeg)
22862 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22863 (setq conf (or (eq t org-agenda-confirm-kill)
22864 (and (numberp org-agenda-confirm-kill)
22865 (> n org-agenda-confirm-kill))))
22866 (and conf
22867 (not (y-or-n-p
22868 (format "Delete entry with %d lines in buffer \"%s\"? "
22869 n (buffer-name buffer))))
22870 (error "Abort"))
22871 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22872 (with-current-buffer buffer (delete-region dbeg dend))
22873 (message "Agenda item and source killed"))))
22875 (defun org-agenda-archive ()
22876 "Kill the entry or subtree belonging to the current agenda entry."
22877 (interactive)
22878 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22879 (let* ((marker (or (get-text-property (point) 'org-marker)
22880 (org-agenda-error)))
22881 (buffer (marker-buffer marker))
22882 (pos (marker-position marker)))
22883 (org-with-remote-undo buffer
22884 (with-current-buffer buffer
22885 (if (org-mode-p)
22886 (save-excursion
22887 (goto-char pos)
22888 (org-remove-subtree-entries-from-agenda)
22889 (org-back-to-heading t)
22890 (org-archive-subtree))
22891 (error "Archiving works only in Org-mode files"))))))
22893 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22894 "Remove all lines in the agenda that correspond to a given subtree.
22895 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22896 If this information is not given, the function uses the tree at point."
22897 (let ((buf (or buf (current-buffer))) m p)
22898 (save-excursion
22899 (unless (and beg end)
22900 (org-back-to-heading t)
22901 (setq beg (point))
22902 (org-end-of-subtree t)
22903 (setq end (point)))
22904 (set-buffer (get-buffer org-agenda-buffer-name))
22905 (save-excursion
22906 (goto-char (point-max))
22907 (beginning-of-line 1)
22908 (while (not (bobp))
22909 (when (and (setq m (get-text-property (point) 'org-marker))
22910 (equal buf (marker-buffer m))
22911 (setq p (marker-position m))
22912 (>= p beg)
22913 (<= p end))
22914 (let ((inhibit-read-only t))
22915 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22916 (beginning-of-line 0))))))
22918 (defun org-agenda-open-link ()
22919 "Follow the link in the current line, if any."
22920 (interactive)
22921 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22922 (save-excursion
22923 (save-restriction
22924 (narrow-to-region (point-at-bol) (point-at-eol))
22925 (org-open-at-point))))
22927 (defun org-agenda-copy-local-variable (var)
22928 "Get a variable from a referenced buffer and install it here."
22929 (let ((m (get-text-property (point) 'org-marker)))
22930 (when (and m (buffer-live-p (marker-buffer m)))
22931 (org-set-local var (with-current-buffer (marker-buffer m)
22932 (symbol-value var))))))
22934 (defun org-agenda-switch-to (&optional delete-other-windows)
22935 "Go to the Org-mode file which contains the item at point."
22936 (interactive)
22937 (let* ((marker (or (get-text-property (point) 'org-marker)
22938 (org-agenda-error)))
22939 (buffer (marker-buffer marker))
22940 (pos (marker-position marker)))
22941 (switch-to-buffer buffer)
22942 (and delete-other-windows (delete-other-windows))
22943 (widen)
22944 (goto-char pos)
22945 (when (org-mode-p)
22946 (org-show-context 'agenda)
22947 (save-excursion
22948 (and (outline-next-heading)
22949 (org-flag-heading nil)))))) ; show the next heading
22951 (defun org-agenda-goto-mouse (ev)
22952 "Go to the Org-mode file which contains the item at the mouse click."
22953 (interactive "e")
22954 (mouse-set-point ev)
22955 (org-agenda-goto))
22957 (defun org-agenda-show ()
22958 "Display the Org-mode file which contains the item at point."
22959 (interactive)
22960 (let ((win (selected-window)))
22961 (org-agenda-goto t)
22962 (select-window win)))
22964 (defun org-agenda-recenter (arg)
22965 "Display the Org-mode file which contains the item at point and recenter."
22966 (interactive "P")
22967 (let ((win (selected-window)))
22968 (org-agenda-goto t)
22969 (recenter arg)
22970 (select-window win)))
22972 (defun org-agenda-show-mouse (ev)
22973 "Display the Org-mode file which contains the item at the mouse click."
22974 (interactive "e")
22975 (mouse-set-point ev)
22976 (org-agenda-show))
22978 (defun org-agenda-check-no-diary ()
22979 "Check if the entry is a diary link and abort if yes."
22980 (if (get-text-property (point) 'org-agenda-diary-link)
22981 (org-agenda-error)))
22983 (defun org-agenda-error ()
22984 (error "Command not allowed in this line"))
22986 (defun org-agenda-tree-to-indirect-buffer ()
22987 "Show the subtree corresponding to the current entry in an indirect buffer.
22988 This calls the command `org-tree-to-indirect-buffer' from the original
22989 Org-mode buffer.
22990 With numerical prefix arg ARG, go up to this level and then take that tree.
22991 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22992 dedicated frame)."
22993 (interactive)
22994 (org-agenda-check-no-diary)
22995 (let* ((marker (or (get-text-property (point) 'org-marker)
22996 (org-agenda-error)))
22997 (buffer (marker-buffer marker))
22998 (pos (marker-position marker)))
22999 (with-current-buffer buffer
23000 (save-excursion
23001 (goto-char pos)
23002 (call-interactively 'org-tree-to-indirect-buffer)))))
23004 (defvar org-last-heading-marker (make-marker)
23005 "Marker pointing to the headline that last changed its TODO state
23006 by a remote command from the agenda.")
23008 (defun org-agenda-todo-nextset ()
23009 "Switch TODO entry to next sequence."
23010 (interactive)
23011 (org-agenda-todo 'nextset))
23013 (defun org-agenda-todo-previousset ()
23014 "Switch TODO entry to previous sequence."
23015 (interactive)
23016 (org-agenda-todo 'previousset))
23018 (defun org-agenda-todo (&optional arg)
23019 "Cycle TODO state of line at point, also in Org-mode file.
23020 This changes the line at point, all other lines in the agenda referring to
23021 the same tree node, and the headline of the tree node in the Org-mode file."
23022 (interactive "P")
23023 (org-agenda-check-no-diary)
23024 (let* ((col (current-column))
23025 (marker (or (get-text-property (point) 'org-marker)
23026 (org-agenda-error)))
23027 (buffer (marker-buffer marker))
23028 (pos (marker-position marker))
23029 (hdmarker (get-text-property (point) 'org-hd-marker))
23030 (inhibit-read-only t)
23031 newhead)
23032 (org-with-remote-undo buffer
23033 (with-current-buffer buffer
23034 (widen)
23035 (goto-char pos)
23036 (org-show-context 'agenda)
23037 (save-excursion
23038 (and (outline-next-heading)
23039 (org-flag-heading nil))) ; show the next heading
23040 (org-todo arg)
23041 (and (bolp) (forward-char 1))
23042 (setq newhead (org-get-heading))
23043 (save-excursion
23044 (org-back-to-heading)
23045 (move-marker org-last-heading-marker (point))))
23046 (beginning-of-line 1)
23047 (save-excursion
23048 (org-agenda-change-all-lines newhead hdmarker 'fixface))
23049 (move-to-column col))))
23051 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
23052 "Change all lines in the agenda buffer which match HDMARKER.
23053 The new content of the line will be NEWHEAD (as modified by
23054 `org-format-agenda-item'). HDMARKER is checked with
23055 `equal' against all `org-hd-marker' text properties in the file.
23056 If FIXFACE is non-nil, the face of each item is modified acording to
23057 the new TODO state."
23058 (let* ((inhibit-read-only t)
23059 props m pl undone-face done-face finish new dotime cat tags)
23060 (save-excursion
23061 (goto-char (point-max))
23062 (beginning-of-line 1)
23063 (while (not finish)
23064 (setq finish (bobp))
23065 (when (and (setq m (get-text-property (point) 'org-hd-marker))
23066 (equal m hdmarker))
23067 (setq props (text-properties-at (point))
23068 dotime (get-text-property (point) 'dotime)
23069 cat (get-text-property (point) 'org-category)
23070 tags (get-text-property (point) 'tags)
23071 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
23072 pl (get-text-property (point) 'prefix-length)
23073 undone-face (get-text-property (point) 'undone-face)
23074 done-face (get-text-property (point) 'done-face))
23075 (move-to-column pl)
23076 (cond
23077 ((equal new "")
23078 (beginning-of-line 1)
23079 (and (looking-at ".*\n?") (replace-match "")))
23080 ((looking-at ".*")
23081 (replace-match new t t)
23082 (beginning-of-line 1)
23083 (add-text-properties (point-at-bol) (point-at-eol) props)
23084 (when fixface
23085 (add-text-properties
23086 (point-at-bol) (point-at-eol)
23087 (list 'face
23088 (if org-last-todo-state-is-todo
23089 undone-face done-face))))
23090 (org-agenda-highlight-todo 'line)
23091 (beginning-of-line 1))
23092 (t (error "Line update did not work"))))
23093 (beginning-of-line 0)))
23094 (org-finalize-agenda)))
23096 (defun org-agenda-align-tags (&optional line)
23097 "Align all tags in agenda items to `org-agenda-tags-column'."
23098 (let ((inhibit-read-only t) l c)
23099 (save-excursion
23100 (goto-char (if line (point-at-bol) (point-min)))
23101 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
23102 (if line (point-at-eol) nil) t)
23103 (add-text-properties
23104 (match-beginning 2) (match-end 2)
23105 (list 'face (delq nil (list 'org-tag (get-text-property
23106 (match-beginning 2) 'face)))))
23107 (setq l (- (match-end 2) (match-beginning 2))
23108 c (if (< org-agenda-tags-column 0)
23109 (- (abs org-agenda-tags-column) l)
23110 org-agenda-tags-column))
23111 (delete-region (match-beginning 1) (match-end 1))
23112 (goto-char (match-beginning 1))
23113 (insert (org-add-props
23114 (make-string (max 1 (- c (current-column))) ?\ )
23115 (text-properties-at (point))))))))
23117 (defun org-agenda-priority-up ()
23118 "Increase the priority of line at point, also in Org-mode file."
23119 (interactive)
23120 (org-agenda-priority 'up))
23122 (defun org-agenda-priority-down ()
23123 "Decrease the priority of line at point, also in Org-mode file."
23124 (interactive)
23125 (org-agenda-priority 'down))
23127 (defun org-agenda-priority (&optional force-direction)
23128 "Set the priority of line at point, also in Org-mode file.
23129 This changes the line at point, all other lines in the agenda referring to
23130 the same tree node, and the headline of the tree node in the Org-mode file."
23131 (interactive)
23132 (org-agenda-check-no-diary)
23133 (let* ((marker (or (get-text-property (point) 'org-marker)
23134 (org-agenda-error)))
23135 (hdmarker (get-text-property (point) 'org-hd-marker))
23136 (buffer (marker-buffer hdmarker))
23137 (pos (marker-position hdmarker))
23138 (inhibit-read-only t)
23139 newhead)
23140 (org-with-remote-undo buffer
23141 (with-current-buffer buffer
23142 (widen)
23143 (goto-char pos)
23144 (org-show-context 'agenda)
23145 (save-excursion
23146 (and (outline-next-heading)
23147 (org-flag-heading nil))) ; show the next heading
23148 (funcall 'org-priority force-direction)
23149 (end-of-line 1)
23150 (setq newhead (org-get-heading)))
23151 (org-agenda-change-all-lines newhead hdmarker)
23152 (beginning-of-line 1))))
23154 (defun org-get-tags-at (&optional pos)
23155 "Get a list of all headline tags applicable at POS.
23156 POS defaults to point. If tags are inherited, the list contains
23157 the targets in the same sequence as the headlines appear, i.e.
23158 the tags of the current headline come last."
23159 (interactive)
23160 (let (tags lastpos)
23161 (save-excursion
23162 (save-restriction
23163 (widen)
23164 (goto-char (or pos (point)))
23165 (save-match-data
23166 (org-back-to-heading t)
23167 (condition-case nil
23168 (while (not (equal lastpos (point)))
23169 (setq lastpos (point))
23170 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
23171 (setq tags (append (org-split-string
23172 (org-match-string-no-properties 1) ":")
23173 tags)))
23174 (or org-use-tag-inheritance (error ""))
23175 (org-up-heading-all 1))
23176 (error nil))))
23177 tags)))
23179 ;; FIXME: should fix the tags property of the agenda line.
23180 (defun org-agenda-set-tags ()
23181 "Set tags for the current headline."
23182 (interactive)
23183 (org-agenda-check-no-diary)
23184 (if (and (org-region-active-p) (interactive-p))
23185 (call-interactively 'org-change-tag-in-region)
23186 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23187 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23188 (org-agenda-error)))
23189 (buffer (marker-buffer hdmarker))
23190 (pos (marker-position hdmarker))
23191 (inhibit-read-only t)
23192 newhead)
23193 (org-with-remote-undo buffer
23194 (with-current-buffer buffer
23195 (widen)
23196 (goto-char pos)
23197 (save-excursion
23198 (org-show-context 'agenda))
23199 (save-excursion
23200 (and (outline-next-heading)
23201 (org-flag-heading nil))) ; show the next heading
23202 (goto-char pos)
23203 (call-interactively 'org-set-tags)
23204 (end-of-line 1)
23205 (setq newhead (org-get-heading)))
23206 (org-agenda-change-all-lines newhead hdmarker)
23207 (beginning-of-line 1)))))
23209 (defun org-agenda-toggle-archive-tag ()
23210 "Toggle the archive tag for the current entry."
23211 (interactive)
23212 (org-agenda-check-no-diary)
23213 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23214 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23215 (org-agenda-error)))
23216 (buffer (marker-buffer hdmarker))
23217 (pos (marker-position hdmarker))
23218 (inhibit-read-only t)
23219 newhead)
23220 (org-with-remote-undo buffer
23221 (with-current-buffer buffer
23222 (widen)
23223 (goto-char pos)
23224 (org-show-context 'agenda)
23225 (save-excursion
23226 (and (outline-next-heading)
23227 (org-flag-heading nil))) ; show the next heading
23228 (call-interactively 'org-toggle-archive-tag)
23229 (end-of-line 1)
23230 (setq newhead (org-get-heading)))
23231 (org-agenda-change-all-lines newhead hdmarker)
23232 (beginning-of-line 1))))
23234 (defun org-agenda-date-later (arg &optional what)
23235 "Change the date of this item to one day later."
23236 (interactive "p")
23237 (org-agenda-check-type t 'agenda 'timeline)
23238 (org-agenda-check-no-diary)
23239 (let* ((marker (or (get-text-property (point) 'org-marker)
23240 (org-agenda-error)))
23241 (buffer (marker-buffer marker))
23242 (pos (marker-position marker)))
23243 (org-with-remote-undo buffer
23244 (with-current-buffer buffer
23245 (widen)
23246 (goto-char pos)
23247 (if (not (org-at-timestamp-p))
23248 (error "Cannot find time stamp"))
23249 (org-timestamp-change arg (or what 'day)))
23250 (org-agenda-show-new-time marker org-last-changed-timestamp))
23251 (message "Time stamp changed to %s" org-last-changed-timestamp)))
23253 (defun org-agenda-date-earlier (arg &optional what)
23254 "Change the date of this item to one day earlier."
23255 (interactive "p")
23256 (org-agenda-date-later (- arg) what))
23258 (defun org-agenda-show-new-time (marker stamp &optional prefix)
23259 "Show new date stamp via text properties."
23260 ;; We use text properties to make this undoable
23261 (let ((inhibit-read-only t))
23262 (setq stamp (concat " " prefix " => " stamp))
23263 (save-excursion
23264 (goto-char (point-max))
23265 (while (not (bobp))
23266 (when (equal marker (get-text-property (point) 'org-marker))
23267 (move-to-column (- (window-width) (length stamp)) t)
23268 (if (featurep 'xemacs)
23269 ;; Use `duplicable' property to trigger undo recording
23270 (let ((ex (make-extent nil nil))
23271 (gl (make-glyph stamp)))
23272 (set-glyph-face gl 'secondary-selection)
23273 (set-extent-properties
23274 ex (list 'invisible t 'end-glyph gl 'duplicable t))
23275 (insert-extent ex (1- (point)) (point-at-eol)))
23276 (add-text-properties
23277 (1- (point)) (point-at-eol)
23278 (list 'display (org-add-props stamp nil
23279 'face 'secondary-selection))))
23280 (beginning-of-line 1))
23281 (beginning-of-line 0)))))
23283 (defun org-agenda-date-prompt (arg)
23284 "Change the date of this item. Date is prompted for, with default today.
23285 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23286 be used to request time specification in the time stamp."
23287 (interactive "P")
23288 (org-agenda-check-type t 'agenda 'timeline)
23289 (org-agenda-check-no-diary)
23290 (let* ((marker (or (get-text-property (point) 'org-marker)
23291 (org-agenda-error)))
23292 (buffer (marker-buffer marker))
23293 (pos (marker-position marker)))
23294 (org-with-remote-undo buffer
23295 (with-current-buffer buffer
23296 (widen)
23297 (goto-char pos)
23298 (if (not (org-at-timestamp-p))
23299 (error "Cannot find time stamp"))
23300 (org-time-stamp arg)
23301 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23303 (defun org-agenda-schedule (arg)
23304 "Schedule the item at point."
23305 (interactive "P")
23306 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23307 (org-agenda-check-no-diary)
23308 (let* ((marker (or (get-text-property (point) 'org-marker)
23309 (org-agenda-error)))
23310 (buffer (marker-buffer marker))
23311 (pos (marker-position marker))
23312 (org-insert-labeled-timestamps-at-point nil)
23314 (message "%s" (marker-insertion-type marker)) (sit-for 3)
23315 (set-marker-insertion-type marker t)
23316 (org-with-remote-undo buffer
23317 (with-current-buffer buffer
23318 (widen)
23319 (goto-char pos)
23320 (setq ts (org-schedule arg)))
23321 (org-agenda-show-new-time marker ts "S"))
23322 (message "Item scheduled for %s" ts)))
23324 (defun org-agenda-deadline (arg)
23325 "Schedule the item at point."
23326 (interactive "P")
23327 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23328 (org-agenda-check-no-diary)
23329 (let* ((marker (or (get-text-property (point) 'org-marker)
23330 (org-agenda-error)))
23331 (buffer (marker-buffer marker))
23332 (pos (marker-position marker))
23333 (org-insert-labeled-timestamps-at-point nil)
23335 (org-with-remote-undo buffer
23336 (with-current-buffer buffer
23337 (widen)
23338 (goto-char pos)
23339 (setq ts (org-deadline arg)))
23340 (org-agenda-show-new-time marker ts "S"))
23341 (message "Deadline for this item set to %s" ts)))
23343 (defun org-get-heading (&optional no-tags)
23344 "Return the heading of the current entry, without the stars."
23345 (save-excursion
23346 (org-back-to-heading t)
23347 (if (looking-at
23348 (if no-tags
23349 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23350 "\\*+[ \t]+\\([^\r\n]*\\)"))
23351 (match-string 1) "")))
23353 (defun org-agenda-clock-in (&optional arg)
23354 "Start the clock on the currently selected item."
23355 (interactive "P")
23356 (org-agenda-check-no-diary)
23357 (let* ((marker (or (get-text-property (point) 'org-marker)
23358 (org-agenda-error)))
23359 (pos (marker-position marker)))
23360 (org-with-remote-undo (marker-buffer marker)
23361 (with-current-buffer (marker-buffer marker)
23362 (widen)
23363 (goto-char pos)
23364 (org-clock-in)))))
23366 (defun org-agenda-clock-out (&optional arg)
23367 "Stop the currently running clock."
23368 (interactive "P")
23369 (unless (marker-buffer org-clock-marker)
23370 (error "No running clock"))
23371 (org-with-remote-undo (marker-buffer org-clock-marker)
23372 (org-clock-out)))
23374 (defun org-agenda-clock-cancel (&optional arg)
23375 "Cancel the currently running clock."
23376 (interactive "P")
23377 (unless (marker-buffer org-clock-marker)
23378 (error "No running clock"))
23379 (org-with-remote-undo (marker-buffer org-clock-marker)
23380 (org-clock-cancel)))
23382 (defun org-agenda-diary-entry ()
23383 "Make a diary entry, like the `i' command from the calendar.
23384 All the standard commands work: block, weekly etc."
23385 (interactive)
23386 (org-agenda-check-type t 'agenda 'timeline)
23387 (require 'diary-lib)
23388 (let* ((char (progn
23389 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23390 (read-char-exclusive)))
23391 (cmd (cdr (assoc char
23392 '((?d . insert-diary-entry)
23393 (?w . insert-weekly-diary-entry)
23394 (?m . insert-monthly-diary-entry)
23395 (?y . insert-yearly-diary-entry)
23396 (?a . insert-anniversary-diary-entry)
23397 (?b . insert-block-diary-entry)
23398 (?c . insert-cyclic-diary-entry)))))
23399 (oldf (symbol-function 'calendar-cursor-to-date))
23400 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23401 (point (point))
23402 (mark (or (mark t) (point))))
23403 (unless cmd
23404 (error "No command associated with <%c>" char))
23405 (unless (and (get-text-property point 'day)
23406 (or (not (equal ?b char))
23407 (get-text-property mark 'day)))
23408 (error "Don't know which date to use for diary entry"))
23409 ;; We implement this by hacking the `calendar-cursor-to-date' function
23410 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23411 (let ((calendar-mark-ring
23412 (list (calendar-gregorian-from-absolute
23413 (or (get-text-property mark 'day)
23414 (get-text-property point 'day))))))
23415 (unwind-protect
23416 (progn
23417 (fset 'calendar-cursor-to-date
23418 (lambda (&optional error)
23419 (calendar-gregorian-from-absolute
23420 (get-text-property point 'day))))
23421 (call-interactively cmd))
23422 (fset 'calendar-cursor-to-date oldf)))))
23425 (defun org-agenda-execute-calendar-command (cmd)
23426 "Execute a calendar command from the agenda, with the date associated to
23427 the cursor position."
23428 (org-agenda-check-type t 'agenda 'timeline)
23429 (require 'diary-lib)
23430 (unless (get-text-property (point) 'day)
23431 (error "Don't know which date to use for calendar command"))
23432 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23433 (point (point))
23434 (date (calendar-gregorian-from-absolute
23435 (get-text-property point 'day)))
23436 ;; the following 3 vars are needed in the calendar
23437 (displayed-day (extract-calendar-day date))
23438 (displayed-month (extract-calendar-month date))
23439 (displayed-year (extract-calendar-year date)))
23440 (unwind-protect
23441 (progn
23442 (fset 'calendar-cursor-to-date
23443 (lambda (&optional error)
23444 (calendar-gregorian-from-absolute
23445 (get-text-property point 'day))))
23446 (call-interactively cmd))
23447 (fset 'calendar-cursor-to-date oldf))))
23449 (defun org-agenda-phases-of-moon ()
23450 "Display the phases of the moon for the 3 months around the cursor date."
23451 (interactive)
23452 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23454 (defun org-agenda-holidays ()
23455 "Display the holidays for the 3 months around the cursor date."
23456 (interactive)
23457 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23459 (defun org-agenda-sunrise-sunset (arg)
23460 "Display sunrise and sunset for the cursor date.
23461 Latitude and longitude can be specified with the variables
23462 `calendar-latitude' and `calendar-longitude'. When called with prefix
23463 argument, latitude and longitude will be prompted for."
23464 (interactive "P")
23465 (let ((calendar-longitude (if arg nil calendar-longitude))
23466 (calendar-latitude (if arg nil calendar-latitude))
23467 (calendar-location-name
23468 (if arg "the given coordinates" calendar-location-name)))
23469 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23471 (defun org-agenda-goto-calendar ()
23472 "Open the Emacs calendar with the date at the cursor."
23473 (interactive)
23474 (org-agenda-check-type t 'agenda 'timeline)
23475 (let* ((day (or (get-text-property (point) 'day)
23476 (error "Don't know which date to open in calendar")))
23477 (date (calendar-gregorian-from-absolute day))
23478 (calendar-move-hook nil)
23479 (view-calendar-holidays-initially nil)
23480 (view-diary-entries-initially nil))
23481 (calendar)
23482 (calendar-goto-date date)))
23484 (defun org-calendar-goto-agenda ()
23485 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23486 This is a command that has to be installed in `calendar-mode-map'."
23487 (interactive)
23488 (org-agenda-list nil (calendar-absolute-from-gregorian
23489 (calendar-cursor-to-date))
23490 nil))
23492 (defun org-agenda-convert-date ()
23493 (interactive)
23494 (org-agenda-check-type t 'agenda 'timeline)
23495 (let ((day (get-text-property (point) 'day))
23496 date s)
23497 (unless day
23498 (error "Don't know which date to convert"))
23499 (setq date (calendar-gregorian-from-absolute day))
23500 (setq s (concat
23501 "Gregorian: " (calendar-date-string date) "\n"
23502 "ISO: " (calendar-iso-date-string date) "\n"
23503 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23504 "Julian: " (calendar-julian-date-string date) "\n"
23505 "Astron. JD: " (calendar-astro-date-string date)
23506 " (Julian date number at noon UTC)\n"
23507 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23508 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23509 "French: " (calendar-french-date-string date) "\n"
23510 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23511 "Mayan: " (calendar-mayan-date-string date) "\n"
23512 "Coptic: " (calendar-coptic-date-string date) "\n"
23513 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23514 "Persian: " (calendar-persian-date-string date) "\n"
23515 "Chinese: " (calendar-chinese-date-string date) "\n"))
23516 (with-output-to-temp-buffer "*Dates*"
23517 (princ s))
23518 (if (fboundp 'fit-window-to-buffer)
23519 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23522 ;;;; Embedded LaTeX
23524 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23525 "Keymap for the minor `org-cdlatex-mode'.")
23527 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23528 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23529 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23530 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23531 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23533 (defvar org-cdlatex-texmathp-advice-is-done nil
23534 "Flag remembering if we have applied the advice to texmathp already.")
23536 (define-minor-mode org-cdlatex-mode
23537 "Toggle the minor `org-cdlatex-mode'.
23538 This mode supports entering LaTeX environment and math in LaTeX fragments
23539 in Org-mode.
23540 \\{org-cdlatex-mode-map}"
23541 nil " OCDL" nil
23542 (when org-cdlatex-mode (require 'cdlatex))
23543 (unless org-cdlatex-texmathp-advice-is-done
23544 (setq org-cdlatex-texmathp-advice-is-done t)
23545 (defadvice texmathp (around org-math-always-on activate)
23546 "Always return t in org-mode buffers.
23547 This is because we want to insert math symbols without dollars even outside
23548 the LaTeX math segments. If Orgmode thinks that point is actually inside
23549 en embedded LaTeX fragement, let texmathp do its job.
23550 \\[org-cdlatex-mode-map]"
23551 (interactive)
23552 (let (p)
23553 (cond
23554 ((not (org-mode-p)) ad-do-it)
23555 ((eq this-command 'cdlatex-math-symbol)
23556 (setq ad-return-value t
23557 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23559 (let ((p (org-inside-LaTeX-fragment-p)))
23560 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23561 (setq ad-return-value t
23562 texmathp-why '("Org-mode embedded math" . 0))
23563 (if p ad-do-it)))))))))
23565 (defun turn-on-org-cdlatex ()
23566 "Unconditionally turn on `org-cdlatex-mode'."
23567 (org-cdlatex-mode 1))
23569 (defun org-inside-LaTeX-fragment-p ()
23570 "Test if point is inside a LaTeX fragment.
23571 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23572 sequence appearing also before point.
23573 Even though the matchers for math are configurable, this function assumes
23574 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23575 delimiters are skipped when they have been removed by customization.
23576 The return value is nil, or a cons cell with the delimiter and
23577 and the position of this delimiter.
23579 This function does a reasonably good job, but can locally be fooled by
23580 for example currency specifications. For example it will assume being in
23581 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23582 fragments that are properly closed, but during editing, we have to live
23583 with the uncertainty caused by missing closing delimiters. This function
23584 looks only before point, not after."
23585 (catch 'exit
23586 (let ((pos (point))
23587 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23588 (lim (progn
23589 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23590 (point)))
23591 dd-on str (start 0) m re)
23592 (goto-char pos)
23593 (when dodollar
23594 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23595 re (nth 1 (assoc "$" org-latex-regexps)))
23596 (while (string-match re str start)
23597 (cond
23598 ((= (match-end 0) (length str))
23599 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23600 ((= (match-end 0) (- (length str) 5))
23601 (throw 'exit nil))
23602 (t (setq start (match-end 0))))))
23603 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23604 (goto-char pos)
23605 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23606 (and (match-beginning 2) (throw 'exit nil))
23607 ;; count $$
23608 (while (re-search-backward "\\$\\$" lim t)
23609 (setq dd-on (not dd-on)))
23610 (goto-char pos)
23611 (if dd-on (cons "$$" m))))))
23614 (defun org-try-cdlatex-tab ()
23615 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23616 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23617 - inside a LaTeX fragment, or
23618 - after the first word in a line, where an abbreviation expansion could
23619 insert a LaTeX environment."
23620 (when org-cdlatex-mode
23621 (cond
23622 ((save-excursion
23623 (skip-chars-backward "a-zA-Z0-9*")
23624 (skip-chars-backward " \t")
23625 (bolp))
23626 (cdlatex-tab) t)
23627 ((org-inside-LaTeX-fragment-p)
23628 (cdlatex-tab) t)
23629 (t nil))))
23631 (defun org-cdlatex-underscore-caret (&optional arg)
23632 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23633 Revert to the normal definition outside of these fragments."
23634 (interactive "P")
23635 (if (org-inside-LaTeX-fragment-p)
23636 (call-interactively 'cdlatex-sub-superscript)
23637 (let (org-cdlatex-mode)
23638 (call-interactively (key-binding (vector last-input-event))))))
23640 (defun org-cdlatex-math-modify (&optional arg)
23641 "Execute `cdlatex-math-modify' in LaTeX fragments.
23642 Revert to the normal definition outside of these fragments."
23643 (interactive "P")
23644 (if (org-inside-LaTeX-fragment-p)
23645 (call-interactively 'cdlatex-math-modify)
23646 (let (org-cdlatex-mode)
23647 (call-interactively (key-binding (vector last-input-event))))))
23649 (defvar org-latex-fragment-image-overlays nil
23650 "List of overlays carrying the images of latex fragments.")
23651 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23653 (defun org-remove-latex-fragment-image-overlays ()
23654 "Remove all overlays with LaTeX fragment images in current buffer."
23655 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23656 (setq org-latex-fragment-image-overlays nil))
23658 (defun org-preview-latex-fragment (&optional subtree)
23659 "Preview the LaTeX fragment at point, or all locally or globally.
23660 If the cursor is in a LaTeX fragment, create the image and overlay
23661 it over the source code. If there is no fragment at point, display
23662 all fragments in the current text, from one headline to the next. With
23663 prefix SUBTREE, display all fragments in the current subtree. With a
23664 double prefix `C-u C-u', or when the cursor is before the first headline,
23665 display all fragments in the buffer.
23666 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23667 (interactive "P")
23668 (org-remove-latex-fragment-image-overlays)
23669 (save-excursion
23670 (save-restriction
23671 (let (beg end at msg)
23672 (cond
23673 ((or (equal subtree '(16))
23674 (not (save-excursion
23675 (re-search-backward (concat "^" outline-regexp) nil t))))
23676 (setq beg (point-min) end (point-max)
23677 msg "Creating images for buffer...%s"))
23678 ((equal subtree '(4))
23679 (org-back-to-heading)
23680 (setq beg (point) end (org-end-of-subtree t)
23681 msg "Creating images for subtree...%s"))
23683 (if (setq at (org-inside-LaTeX-fragment-p))
23684 (goto-char (max (point-min) (- (cdr at) 2)))
23685 (org-back-to-heading))
23686 (setq beg (point) end (progn (outline-next-heading) (point))
23687 msg (if at "Creating image...%s"
23688 "Creating images for entry...%s"))))
23689 (message msg "")
23690 (narrow-to-region beg end)
23691 (goto-char beg)
23692 (org-format-latex
23693 (concat "ltxpng/" (file-name-sans-extension
23694 (file-name-nondirectory
23695 buffer-file-name)))
23696 default-directory 'overlays msg at 'forbuffer)
23697 (message msg "done. Use `C-c C-c' to remove images.")))))
23699 (defvar org-latex-regexps
23700 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23701 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23702 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23703 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23704 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23705 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23706 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23707 "Regular expressions for matching embedded LaTeX.")
23709 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23710 "Replace LaTeX fragments with links to an image, and produce images."
23711 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23712 (let* ((prefixnodir (file-name-nondirectory prefix))
23713 (absprefix (expand-file-name prefix dir))
23714 (todir (file-name-directory absprefix))
23715 (opt org-format-latex-options)
23716 (matchers (plist-get opt :matchers))
23717 (re-list org-latex-regexps)
23718 (cnt 0) txt link beg end re e checkdir
23719 m n block linkfile movefile ov)
23720 ;; Check if there are old images files with this prefix, and remove them
23721 (when (file-directory-p todir)
23722 (mapc 'delete-file
23723 (directory-files
23724 todir 'full
23725 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23726 ;; Check the different regular expressions
23727 (while (setq e (pop re-list))
23728 (setq m (car e) re (nth 1 e) n (nth 2 e)
23729 block (if (nth 3 e) "\n\n" ""))
23730 (when (member m matchers)
23731 (goto-char (point-min))
23732 (while (re-search-forward re nil t)
23733 (when (or (not at) (equal (cdr at) (match-beginning n)))
23734 (setq txt (match-string n)
23735 beg (match-beginning n) end (match-end n)
23736 cnt (1+ cnt)
23737 linkfile (format "%s_%04d.png" prefix cnt)
23738 movefile (format "%s_%04d.png" absprefix cnt)
23739 link (concat block "[[file:" linkfile "]]" block))
23740 (if msg (message msg cnt))
23741 (goto-char beg)
23742 (unless checkdir ; make sure the directory exists
23743 (setq checkdir t)
23744 (or (file-directory-p todir) (make-directory todir)))
23745 (org-create-formula-image
23746 txt movefile opt forbuffer)
23747 (if overlays
23748 (progn
23749 (setq ov (org-make-overlay beg end))
23750 (if (featurep 'xemacs)
23751 (progn
23752 (org-overlay-put ov 'invisible t)
23753 (org-overlay-put
23754 ov 'end-glyph
23755 (make-glyph (vector 'png :file movefile))))
23756 (org-overlay-put
23757 ov 'display
23758 (list 'image :type 'png :file movefile :ascent 'center)))
23759 (push ov org-latex-fragment-image-overlays)
23760 (goto-char end))
23761 (delete-region beg end)
23762 (insert link))))))))
23764 ;; This function borrows from Ganesh Swami's latex2png.el
23765 (defun org-create-formula-image (string tofile options buffer)
23766 (let* ((tmpdir (if (featurep 'xemacs)
23767 (temp-directory)
23768 temporary-file-directory))
23769 (texfilebase (make-temp-name
23770 (expand-file-name "orgtex" tmpdir)))
23771 (texfile (concat texfilebase ".tex"))
23772 (dvifile (concat texfilebase ".dvi"))
23773 (pngfile (concat texfilebase ".png"))
23774 (fnh (face-attribute 'default :height nil))
23775 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23776 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23777 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23778 "Black"))
23779 (bg (or (plist-get options (if buffer :background :html-background))
23780 "Transparent")))
23781 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23782 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23783 (with-temp-file texfile
23784 (insert org-format-latex-header
23785 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23786 (let ((dir default-directory))
23787 (condition-case nil
23788 (progn
23789 (cd tmpdir)
23790 (call-process "latex" nil nil nil texfile))
23791 (error nil))
23792 (cd dir))
23793 (if (not (file-exists-p dvifile))
23794 (progn (message "Failed to create dvi file from %s" texfile) nil)
23795 (call-process "dvipng" nil nil nil
23796 "-E" "-fg" fg "-bg" bg
23797 "-D" dpi
23798 ;;"-x" scale "-y" scale
23799 "-T" "tight"
23800 "-o" pngfile
23801 dvifile)
23802 (if (not (file-exists-p pngfile))
23803 (progn (message "Failed to create png file from %s" texfile) nil)
23804 ;; Use the requested file name and clean up
23805 (copy-file pngfile tofile 'replace)
23806 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23807 (delete-file (concat texfilebase e)))
23808 pngfile))))
23810 (defun org-dvipng-color (attr)
23811 "Return an rgb color specification for dvipng."
23812 (apply 'format "rgb %s %s %s"
23813 (mapcar 'org-normalize-color
23814 (color-values (face-attribute 'default attr nil)))))
23816 (defun org-normalize-color (value)
23817 "Return string to be used as color value for an RGB component."
23818 (format "%g" (/ value 65535.0)))
23820 ;;;; Exporting
23822 ;;; Variables, constants, and parameter plists
23824 (defconst org-level-max 20)
23826 (defvar org-export-html-preamble nil
23827 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23828 (defvar org-export-html-postamble nil
23829 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23830 (defvar org-export-html-auto-preamble t
23831 "Should default preamble be inserted? Set by publishing functions.")
23832 (defvar org-export-html-auto-postamble t
23833 "Should default postamble be inserted? Set by publishing functions.")
23834 (defvar org-current-export-file nil) ; dynamically scoped parameter
23835 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23838 (defconst org-export-plist-vars
23839 '((:language . org-export-default-language)
23840 (:customtime . org-display-custom-times)
23841 (:headline-levels . org-export-headline-levels)
23842 (:section-numbers . org-export-with-section-numbers)
23843 (:table-of-contents . org-export-with-toc)
23844 (:preserve-breaks . org-export-preserve-breaks)
23845 (:archived-trees . org-export-with-archived-trees)
23846 (:emphasize . org-export-with-emphasize)
23847 (:sub-superscript . org-export-with-sub-superscripts)
23848 (:special-strings . org-export-with-special-strings)
23849 (:footnotes . org-export-with-footnotes)
23850 (:drawers . org-export-with-drawers)
23851 (:tags . org-export-with-tags)
23852 (:TeX-macros . org-export-with-TeX-macros)
23853 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23854 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23855 (:fixed-width . org-export-with-fixed-width)
23856 (:timestamps . org-export-with-timestamps)
23857 (:author-info . org-export-author-info)
23858 (:time-stamp-file . org-export-time-stamp-file)
23859 (:tables . org-export-with-tables)
23860 (:table-auto-headline . org-export-highlight-first-table-line)
23861 (:style . org-export-html-style)
23862 (:agenda-style . org-agenda-export-html-style)
23863 (:convert-org-links . org-export-html-link-org-files-as-html)
23864 (:inline-images . org-export-html-inline-images)
23865 (:html-extension . org-export-html-extension)
23866 (:html-table-tag . org-export-html-table-tag)
23867 (:expand-quoted-html . org-export-html-expand)
23868 (:timestamp . org-export-html-with-timestamp)
23869 (:publishing-directory . org-export-publishing-directory)
23870 (:preamble . org-export-html-preamble)
23871 (:postamble . org-export-html-postamble)
23872 (:auto-preamble . org-export-html-auto-preamble)
23873 (:auto-postamble . org-export-html-auto-postamble)
23874 (:author . user-full-name)
23875 (:email . user-mail-address)))
23877 (defun org-default-export-plist ()
23878 "Return the property list with default settings for the export variables."
23879 (let ((l org-export-plist-vars) rtn e)
23880 (while (setq e (pop l))
23881 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23882 rtn))
23884 (defun org-infile-export-plist ()
23885 "Return the property list with file-local settings for export."
23886 (save-excursion
23887 (save-restriction
23888 (widen)
23889 (goto-char 0)
23890 (let ((re (org-make-options-regexp
23891 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23892 p key val text options)
23893 (while (re-search-forward re nil t)
23894 (setq key (org-match-string-no-properties 1)
23895 val (org-match-string-no-properties 2))
23896 (cond
23897 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23898 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23899 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23900 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23901 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23902 ((string-equal key "TEXT")
23903 (setq text (if text (concat text "\n" val) val)))
23904 ((string-equal key "OPTIONS") (setq options val))))
23905 (setq p (plist-put p :text text))
23906 (when options
23907 (let ((op '(("H" . :headline-levels)
23908 ("num" . :section-numbers)
23909 ("toc" . :table-of-contents)
23910 ("\\n" . :preserve-breaks)
23911 ("@" . :expand-quoted-html)
23912 (":" . :fixed-width)
23913 ("|" . :tables)
23914 ("^" . :sub-superscript)
23915 ("-" . :special-strings)
23916 ("f" . :footnotes)
23917 ("d" . :drawers)
23918 ("tags" . :tags)
23919 ("*" . :emphasize)
23920 ("TeX" . :TeX-macros)
23921 ("LaTeX" . :LaTeX-fragments)
23922 ("skip" . :skip-before-1st-heading)
23923 ("author" . :author-info)
23924 ("timestamp" . :time-stamp-file)))
23926 (while (setq o (pop op))
23927 (if (string-match (concat (regexp-quote (car o))
23928 ":\\([^ \t\n\r;,.]*\\)")
23929 options)
23930 (setq p (plist-put p (cdr o)
23931 (car (read-from-string
23932 (match-string 1 options)))))))))
23933 p))))
23935 (defun org-export-directory (type plist)
23936 (let* ((val (plist-get plist :publishing-directory))
23937 (dir (if (listp val)
23938 (or (cdr (assoc type val)) ".")
23939 val)))
23940 dir))
23942 (defun org-skip-comments (lines)
23943 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23944 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23945 (re2 "^\\(\\*+\\)[ \t\n\r]")
23946 (case-fold-search nil)
23947 rtn line level)
23948 (while (setq line (pop lines))
23949 (cond
23950 ((and (string-match re1 line)
23951 (setq level (- (match-end 1) (match-beginning 1))))
23952 ;; Beginning of a COMMENT subtree. Skip it.
23953 (while (and (setq line (pop lines))
23954 (or (not (string-match re2 line))
23955 (> (- (match-end 1) (match-beginning 1)) level))))
23956 (setq lines (cons line lines)))
23957 ((string-match "^#" line)
23958 ;; an ordinary comment line
23960 ((and org-export-table-remove-special-lines
23961 (string-match "^[ \t]*|" line)
23962 (or (string-match "^[ \t]*| *[!_^] *|" line)
23963 (and (string-match "| *<[0-9]+> *|" line)
23964 (not (string-match "| *[^ <|]" line)))))
23965 ;; a special table line that should be removed
23967 (t (setq rtn (cons line rtn)))))
23968 (nreverse rtn)))
23970 (defun org-export (&optional arg)
23971 (interactive)
23972 (let ((help "[t] insert the export option template
23973 \[v] limit export to visible part of outline tree
23975 \[a] export as ASCII
23977 \[h] export as HTML
23978 \[H] export as HTML to temporary buffer
23979 \[R] export region as HTML
23980 \[b] export as HTML and browse immediately
23981 \[x] export as XOXO
23983 \[l] export as LaTeX
23984 \[L] export as LaTeX to temporary buffer
23986 \[i] export current file as iCalendar file
23987 \[I] export all agenda files as iCalendar files
23988 \[c] export agenda files into combined iCalendar file
23990 \[F] publish current file
23991 \[P] publish current project
23992 \[X] publish... (project will be prompted for)
23993 \[A] publish all projects")
23994 (cmds
23995 '((?t . org-insert-export-options-template)
23996 (?v . org-export-visible)
23997 (?a . org-export-as-ascii)
23998 (?h . org-export-as-html)
23999 (?b . org-export-as-html-and-open)
24000 (?H . org-export-as-html-to-buffer)
24001 (?R . org-export-region-as-html)
24002 (?x . org-export-as-xoxo)
24003 (?l . org-export-as-latex)
24004 (?L . org-export-as-latex-to-buffer)
24005 (?i . org-export-icalendar-this-file)
24006 (?I . org-export-icalendar-all-agenda-files)
24007 (?c . org-export-icalendar-combine-agenda-files)
24008 (?F . org-publish-current-file)
24009 (?P . org-publish-current-project)
24010 (?X . org-publish)
24011 (?A . org-publish-all)))
24012 r1 r2 ass)
24013 (save-window-excursion
24014 (delete-other-windows)
24015 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
24016 (princ help))
24017 (message "Select command: ")
24018 (setq r1 (read-char-exclusive)))
24019 (setq r2 (if (< r1 27) (+ r1 96) r1))
24020 (if (setq ass (assq r2 cmds))
24021 (call-interactively (cdr ass))
24022 (error "No command associated with key %c" r1))))
24024 (defconst org-html-entities
24025 '(("nbsp")
24026 ("iexcl")
24027 ("cent")
24028 ("pound")
24029 ("curren")
24030 ("yen")
24031 ("brvbar")
24032 ("vert" . "&#124;")
24033 ("sect")
24034 ("uml")
24035 ("copy")
24036 ("ordf")
24037 ("laquo")
24038 ("not")
24039 ("shy")
24040 ("reg")
24041 ("macr")
24042 ("deg")
24043 ("plusmn")
24044 ("sup2")
24045 ("sup3")
24046 ("acute")
24047 ("micro")
24048 ("para")
24049 ("middot")
24050 ("odot"."o")
24051 ("star"."*")
24052 ("cedil")
24053 ("sup1")
24054 ("ordm")
24055 ("raquo")
24056 ("frac14")
24057 ("frac12")
24058 ("frac34")
24059 ("iquest")
24060 ("Agrave")
24061 ("Aacute")
24062 ("Acirc")
24063 ("Atilde")
24064 ("Auml")
24065 ("Aring") ("AA"."&Aring;")
24066 ("AElig")
24067 ("Ccedil")
24068 ("Egrave")
24069 ("Eacute")
24070 ("Ecirc")
24071 ("Euml")
24072 ("Igrave")
24073 ("Iacute")
24074 ("Icirc")
24075 ("Iuml")
24076 ("ETH")
24077 ("Ntilde")
24078 ("Ograve")
24079 ("Oacute")
24080 ("Ocirc")
24081 ("Otilde")
24082 ("Ouml")
24083 ("times")
24084 ("Oslash")
24085 ("Ugrave")
24086 ("Uacute")
24087 ("Ucirc")
24088 ("Uuml")
24089 ("Yacute")
24090 ("THORN")
24091 ("szlig")
24092 ("agrave")
24093 ("aacute")
24094 ("acirc")
24095 ("atilde")
24096 ("auml")
24097 ("aring")
24098 ("aelig")
24099 ("ccedil")
24100 ("egrave")
24101 ("eacute")
24102 ("ecirc")
24103 ("euml")
24104 ("igrave")
24105 ("iacute")
24106 ("icirc")
24107 ("iuml")
24108 ("eth")
24109 ("ntilde")
24110 ("ograve")
24111 ("oacute")
24112 ("ocirc")
24113 ("otilde")
24114 ("ouml")
24115 ("divide")
24116 ("oslash")
24117 ("ugrave")
24118 ("uacute")
24119 ("ucirc")
24120 ("uuml")
24121 ("yacute")
24122 ("thorn")
24123 ("yuml")
24124 ("fnof")
24125 ("Alpha")
24126 ("Beta")
24127 ("Gamma")
24128 ("Delta")
24129 ("Epsilon")
24130 ("Zeta")
24131 ("Eta")
24132 ("Theta")
24133 ("Iota")
24134 ("Kappa")
24135 ("Lambda")
24136 ("Mu")
24137 ("Nu")
24138 ("Xi")
24139 ("Omicron")
24140 ("Pi")
24141 ("Rho")
24142 ("Sigma")
24143 ("Tau")
24144 ("Upsilon")
24145 ("Phi")
24146 ("Chi")
24147 ("Psi")
24148 ("Omega")
24149 ("alpha")
24150 ("beta")
24151 ("gamma")
24152 ("delta")
24153 ("epsilon")
24154 ("varepsilon"."&epsilon;")
24155 ("zeta")
24156 ("eta")
24157 ("theta")
24158 ("iota")
24159 ("kappa")
24160 ("lambda")
24161 ("mu")
24162 ("nu")
24163 ("xi")
24164 ("omicron")
24165 ("pi")
24166 ("rho")
24167 ("sigmaf") ("varsigma"."&sigmaf;")
24168 ("sigma")
24169 ("tau")
24170 ("upsilon")
24171 ("phi")
24172 ("chi")
24173 ("psi")
24174 ("omega")
24175 ("thetasym") ("vartheta"."&thetasym;")
24176 ("upsih")
24177 ("piv")
24178 ("bull") ("bullet"."&bull;")
24179 ("hellip") ("dots"."&hellip;")
24180 ("prime")
24181 ("Prime")
24182 ("oline")
24183 ("frasl")
24184 ("weierp")
24185 ("image")
24186 ("real")
24187 ("trade")
24188 ("alefsym")
24189 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
24190 ("uarr") ("uparrow"."&uarr;")
24191 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
24192 ("darr")("downarrow"."&darr;")
24193 ("harr") ("leftrightarrow"."&harr;")
24194 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
24195 ("lArr") ("Leftarrow"."&lArr;")
24196 ("uArr") ("Uparrow"."&uArr;")
24197 ("rArr") ("Rightarrow"."&rArr;")
24198 ("dArr") ("Downarrow"."&dArr;")
24199 ("hArr") ("Leftrightarrow"."&hArr;")
24200 ("forall")
24201 ("part") ("partial"."&part;")
24202 ("exist") ("exists"."&exist;")
24203 ("empty") ("emptyset"."&empty;")
24204 ("nabla")
24205 ("isin") ("in"."&isin;")
24206 ("notin")
24207 ("ni")
24208 ("prod")
24209 ("sum")
24210 ("minus")
24211 ("lowast") ("ast"."&lowast;")
24212 ("radic")
24213 ("prop") ("proptp"."&prop;")
24214 ("infin") ("infty"."&infin;")
24215 ("ang") ("angle"."&ang;")
24216 ("and") ("wedge"."&and;")
24217 ("or") ("vee"."&or;")
24218 ("cap")
24219 ("cup")
24220 ("int")
24221 ("there4")
24222 ("sim")
24223 ("cong") ("simeq"."&cong;")
24224 ("asymp")("approx"."&asymp;")
24225 ("ne") ("neq"."&ne;")
24226 ("equiv")
24227 ("le")
24228 ("ge")
24229 ("sub") ("subset"."&sub;")
24230 ("sup") ("supset"."&sup;")
24231 ("nsub")
24232 ("sube")
24233 ("supe")
24234 ("oplus")
24235 ("otimes")
24236 ("perp")
24237 ("sdot") ("cdot"."&sdot;")
24238 ("lceil")
24239 ("rceil")
24240 ("lfloor")
24241 ("rfloor")
24242 ("lang")
24243 ("rang")
24244 ("loz") ("Diamond"."&loz;")
24245 ("spades") ("spadesuit"."&spades;")
24246 ("clubs") ("clubsuit"."&clubs;")
24247 ("hearts") ("diamondsuit"."&hearts;")
24248 ("diams") ("diamondsuit"."&diams;")
24249 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
24250 ("quot")
24251 ("amp")
24252 ("lt")
24253 ("gt")
24254 ("OElig")
24255 ("oelig")
24256 ("Scaron")
24257 ("scaron")
24258 ("Yuml")
24259 ("circ")
24260 ("tilde")
24261 ("ensp")
24262 ("emsp")
24263 ("thinsp")
24264 ("zwnj")
24265 ("zwj")
24266 ("lrm")
24267 ("rlm")
24268 ("ndash")
24269 ("mdash")
24270 ("lsquo")
24271 ("rsquo")
24272 ("sbquo")
24273 ("ldquo")
24274 ("rdquo")
24275 ("bdquo")
24276 ("dagger")
24277 ("Dagger")
24278 ("permil")
24279 ("lsaquo")
24280 ("rsaquo")
24281 ("euro")
24283 ("arccos"."arccos")
24284 ("arcsin"."arcsin")
24285 ("arctan"."arctan")
24286 ("arg"."arg")
24287 ("cos"."cos")
24288 ("cosh"."cosh")
24289 ("cot"."cot")
24290 ("coth"."coth")
24291 ("csc"."csc")
24292 ("deg"."deg")
24293 ("det"."det")
24294 ("dim"."dim")
24295 ("exp"."exp")
24296 ("gcd"."gcd")
24297 ("hom"."hom")
24298 ("inf"."inf")
24299 ("ker"."ker")
24300 ("lg"."lg")
24301 ("lim"."lim")
24302 ("liminf"."liminf")
24303 ("limsup"."limsup")
24304 ("ln"."ln")
24305 ("log"."log")
24306 ("max"."max")
24307 ("min"."min")
24308 ("Pr"."Pr")
24309 ("sec"."sec")
24310 ("sin"."sin")
24311 ("sinh"."sinh")
24312 ("sup"."sup")
24313 ("tan"."tan")
24314 ("tanh"."tanh")
24316 "Entities for TeX->HTML translation.
24317 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24318 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24319 In that case, \"\\ent\" will be translated to \"&other;\".
24320 The list contains HTML entities for Latin-1, Greek and other symbols.
24321 It is supplemented by a number of commonly used TeX macros with appropriate
24322 translations. There is currently no way for users to extend this.")
24324 ;;; General functions for all backends
24326 (defun org-cleaned-string-for-export (string &rest parameters)
24327 "Cleanup a buffer STRING so that links can be created safely."
24328 (interactive)
24329 (let* ((re-radio (and org-target-link-regexp
24330 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24331 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24332 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24333 (re-archive (concat ":" org-archive-tag ":"))
24334 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24335 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24336 (htmlp (plist-get parameters :for-html))
24337 (asciip (plist-get parameters :for-ascii))
24338 (latexp (plist-get parameters :for-LaTeX))
24339 (commentsp (plist-get parameters :comments))
24340 (archived-trees (plist-get parameters :archived-trees))
24341 (inhibit-read-only t)
24342 (drawers org-drawers)
24343 (exp-drawers (plist-get parameters :drawers))
24344 (outline-regexp "\\*+ ")
24345 a b xx
24346 rtn p)
24347 (with-current-buffer (get-buffer-create " org-mode-tmp")
24348 (erase-buffer)
24349 (insert string)
24350 ;; Remove license-to-kill stuff
24351 (while (setq p (text-property-any (point-min) (point-max)
24352 :org-license-to-kill t))
24353 (delete-region p (next-single-property-change p :org-license-to-kill)))
24355 (let ((org-inhibit-startup t)) (org-mode))
24356 (untabify (point-min) (point-max))
24358 ;; Get rid of drawers
24359 (unless (eq t exp-drawers)
24360 (goto-char (point-min))
24361 (let ((re (concat "^[ \t]*:\\("
24362 (mapconcat
24363 'identity
24364 (org-delete-all exp-drawers
24365 (copy-sequence drawers))
24366 "\\|")
24367 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24368 (while (re-search-forward re nil t)
24369 (replace-match ""))))
24371 ;; Get the correct stuff before the first headline
24372 (when (plist-get parameters :skip-before-1st-heading)
24373 (goto-char (point-min))
24374 (when (re-search-forward "^\\*+[ \t]" nil t)
24375 (delete-region (point-min) (match-beginning 0))
24376 (goto-char (point-min))
24377 (insert "\n")))
24378 (when (plist-get parameters :add-text)
24379 (goto-char (point-min))
24380 (insert (plist-get parameters :add-text) "\n"))
24382 ;; Get rid of archived trees
24383 (when (not (eq archived-trees t))
24384 (goto-char (point-min))
24385 (while (re-search-forward re-archive nil t)
24386 (if (not (org-on-heading-p t))
24387 (org-end-of-subtree t)
24388 (beginning-of-line 1)
24389 (setq a (if archived-trees
24390 (1+ (point-at-eol)) (point))
24391 b (org-end-of-subtree t))
24392 (if (> b a) (delete-region a b)))))
24394 ;; Find targets in comments and move them out of comments,
24395 ;; but mark them as targets that should be invisible
24396 (goto-char (point-min))
24397 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24398 (replace-match "\\1(INVISIBLE)"))
24400 ;; Protect backend specific stuff, throw away the others.
24401 (let ((formatters
24402 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24403 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24404 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24405 fmt)
24406 (goto-char (point-min))
24407 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24408 (goto-char (match-end 0))
24409 (while (not (looking-at "#\\+END_EXAMPLE"))
24410 (insert ": ")
24411 (beginning-of-line 2)))
24412 (goto-char (point-min))
24413 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24414 (add-text-properties (match-beginning 0) (match-end 0)
24415 '(org-protected t)))
24416 (while formatters
24417 (setq fmt (pop formatters))
24418 (when (car fmt)
24419 (goto-char (point-min))
24420 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24421 ":[ \t]*\\(.*\\)") nil t)
24422 (replace-match "\\1" t)
24423 (add-text-properties
24424 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24425 '(org-protected t))))
24426 (goto-char (point-min))
24427 (while (re-search-forward
24428 (concat "^#\\+"
24429 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24430 (cadddr fmt) "\\>.*\n?") nil t)
24431 (if (car fmt)
24432 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24433 '(org-protected t))
24434 (delete-region (match-beginning 0) (match-end 0))))))
24436 ;; Protect quoted subtrees
24437 (goto-char (point-min))
24438 (while (re-search-forward re-quote nil t)
24439 (goto-char (match-beginning 0))
24440 (end-of-line 1)
24441 (add-text-properties (point) (org-end-of-subtree t)
24442 '(org-protected t)))
24444 ;; Protect verbatim elements
24445 (goto-char (point-min))
24446 (while (re-search-forward org-verbatim-re nil t)
24447 (add-text-properties (match-beginning 4) (match-end 4)
24448 '(org-protected t))
24449 (goto-char (1+ (match-end 4))))
24451 ;; Remove subtrees that are commented
24452 (goto-char (point-min))
24453 (while (re-search-forward re-commented nil t)
24454 (goto-char (match-beginning 0))
24455 (delete-region (point) (org-end-of-subtree t)))
24457 ;; Remove special table lines
24458 (when org-export-table-remove-special-lines
24459 (goto-char (point-min))
24460 (while (re-search-forward "^[ \t]*|" nil t)
24461 (beginning-of-line 1)
24462 (if (or (looking-at "[ \t]*| *[!_^] *|")
24463 (and (looking-at ".*?| *<[0-9]+> *|")
24464 (not (looking-at ".*?| *[^ <|]"))))
24465 (delete-region (max (point-min) (1- (point-at-bol)))
24466 (point-at-eol))
24467 (end-of-line 1))))
24469 ;; Specific LaTeX stuff
24470 (when latexp
24471 (require 'org-export-latex nil)
24472 (org-export-latex-cleaned-string))
24474 (when asciip
24475 (org-export-ascii-clean-string))
24477 ;; Specific HTML stuff
24478 (when htmlp
24479 ;; Convert LaTeX fragments to images
24480 (when (plist-get parameters :LaTeX-fragments)
24481 (org-format-latex
24482 (concat "ltxpng/" (file-name-sans-extension
24483 (file-name-nondirectory
24484 org-current-export-file)))
24485 org-current-export-dir nil "Creating LaTeX image %s"))
24486 (message "Exporting..."))
24488 ;; Remove or replace comments
24489 (goto-char (point-min))
24490 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24491 (if commentsp
24492 (progn (add-text-properties
24493 (match-beginning 0) (match-end 0) '(org-protected t))
24494 (replace-match (format commentsp (match-string 1)) t t))
24495 (replace-match "")))
24497 ;; Find matches for radio targets and turn them into internal links
24498 (goto-char (point-min))
24499 (when re-radio
24500 (while (re-search-forward re-radio nil t)
24501 (org-if-unprotected
24502 (replace-match "\\1[[\\2]]"))))
24504 ;; Find all links that contain a newline and put them into a single line
24505 (goto-char (point-min))
24506 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24507 (org-if-unprotected
24508 (replace-match "\\1 \\3")
24509 (goto-char (match-beginning 0))))
24512 ;; Normalize links: Convert angle and plain links into bracket links
24513 ;; Expand link abbreviations
24514 (goto-char (point-min))
24515 (while (re-search-forward re-plain-link nil t)
24516 (goto-char (1- (match-end 0)))
24517 (org-if-unprotected
24518 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24519 ":" (match-string 3) "]]")))
24520 ;; added 'org-link face to links
24521 (put-text-property 0 (length s) 'face 'org-link s)
24522 (replace-match s t t))))
24523 (goto-char (point-min))
24524 (while (re-search-forward re-angle-link nil t)
24525 (goto-char (1- (match-end 0)))
24526 (org-if-unprotected
24527 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24528 ":" (match-string 3) "]]")))
24529 (put-text-property 0 (length s) 'face 'org-link s)
24530 (replace-match s t t))))
24531 (goto-char (point-min))
24532 (while (re-search-forward org-bracket-link-regexp nil t)
24533 (org-if-unprotected
24534 (let* ((s (concat "[[" (setq xx (save-match-data
24535 (org-link-expand-abbrev (match-string 1))))
24537 (if (match-end 3)
24538 (match-string 2)
24539 (concat "[" xx "]"))
24540 "]")))
24541 (put-text-property 0 (length s) 'face 'org-link s)
24542 (replace-match s t t))))
24544 ;; Find multiline emphasis and put them into single line
24545 (when (plist-get parameters :emph-multiline)
24546 (goto-char (point-min))
24547 (while (re-search-forward org-emph-re nil t)
24548 (if (not (= (char-after (match-beginning 3))
24549 (char-after (match-beginning 4))))
24550 (org-if-unprotected
24551 (subst-char-in-region (match-beginning 0) (match-end 0)
24552 ?\n ?\ t)
24553 (goto-char (1- (match-end 0))))
24554 (goto-char (1+ (match-beginning 0))))))
24556 (setq rtn (buffer-string)))
24557 (kill-buffer " org-mode-tmp")
24558 rtn))
24560 (defun org-export-grab-title-from-buffer ()
24561 "Get a title for the current document, from looking at the buffer."
24562 (let ((inhibit-read-only t))
24563 (save-excursion
24564 (goto-char (point-min))
24565 (let ((end (save-excursion (outline-next-heading) (point))))
24566 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24567 ;; Mark the line so that it will not be exported as normal text.
24568 (org-unmodified
24569 (add-text-properties (match-beginning 0) (match-end 0)
24570 (list :org-license-to-kill t)))
24571 ;; Return the title string
24572 (org-trim (match-string 0)))))))
24574 (defun org-export-get-title-from-subtree ()
24575 "Return subtree title and exclude it from export."
24576 (let (title (m (mark)))
24577 (save-excursion
24578 (goto-char (region-beginning))
24579 (when (and (org-at-heading-p)
24580 (>= (org-end-of-subtree t t) (region-end)))
24581 ;; This is a subtree, we take the title from the first heading
24582 (goto-char (region-beginning))
24583 (looking-at org-todo-line-regexp)
24584 (setq title (match-string 3))
24585 (org-unmodified
24586 (add-text-properties (point) (1+ (point-at-eol))
24587 (list :org-license-to-kill t)))))
24588 title))
24590 (defun org-solidify-link-text (s &optional alist)
24591 "Take link text and make a safe target out of it."
24592 (save-match-data
24593 (let* ((rtn
24594 (mapconcat
24595 'identity
24596 (org-split-string s "[ \t\r\n]+") "--"))
24597 (a (assoc rtn alist)))
24598 (or (cdr a) rtn))))
24600 (defun org-get-min-level (lines)
24601 "Get the minimum level in LINES."
24602 (let ((re "^\\(\\*+\\) ") l min)
24603 (catch 'exit
24604 (while (setq l (pop lines))
24605 (if (string-match re l)
24606 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24607 1)))
24609 ;; Variable holding the vector with section numbers
24610 (defvar org-section-numbers (make-vector org-level-max 0))
24612 (defun org-init-section-numbers ()
24613 "Initialize the vector for the section numbers."
24614 (let* ((level -1)
24615 (numbers (nreverse (org-split-string "" "\\.")))
24616 (depth (1- (length org-section-numbers)))
24617 (i depth) number-string)
24618 (while (>= i 0)
24619 (if (> i level)
24620 (aset org-section-numbers i 0)
24621 (setq number-string (or (car numbers) "0"))
24622 (if (string-match "\\`[A-Z]\\'" number-string)
24623 (aset org-section-numbers i
24624 (- (string-to-char number-string) ?A -1))
24625 (aset org-section-numbers i (string-to-number number-string)))
24626 (pop numbers))
24627 (setq i (1- i)))))
24629 (defun org-section-number (&optional level)
24630 "Return a string with the current section number.
24631 When LEVEL is non-nil, increase section numbers on that level."
24632 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24633 (when level
24634 (when (> level -1)
24635 (aset org-section-numbers
24636 level (1+ (aref org-section-numbers level))))
24637 (setq idx (1+ level))
24638 (while (<= idx depth)
24639 (if (not (= idx 1))
24640 (aset org-section-numbers idx 0))
24641 (setq idx (1+ idx))))
24642 (setq idx 0)
24643 (while (<= idx depth)
24644 (setq n (aref org-section-numbers idx))
24645 (setq string (concat string (if (not (string= string "")) "." "")
24646 (int-to-string n)))
24647 (setq idx (1+ idx)))
24648 (save-match-data
24649 (if (string-match "\\`\\([@0]\\.\\)+" string)
24650 (setq string (replace-match "" t nil string)))
24651 (if (string-match "\\(\\.0\\)+\\'" string)
24652 (setq string (replace-match "" t nil string))))
24653 string))
24655 ;;; ASCII export
24657 (defvar org-last-level nil) ; dynamically scoped variable
24658 (defvar org-min-level nil) ; dynamically scoped variable
24659 (defvar org-levels-open nil) ; dynamically scoped parameter
24660 (defvar org-ascii-current-indentation nil) ; For communication
24662 (defun org-export-as-ascii (arg)
24663 "Export the outline as a pretty ASCII file.
24664 If there is an active region, export only the region.
24665 The prefix ARG specifies how many levels of the outline should become
24666 underlined headlines. The default is 3."
24667 (interactive "P")
24668 (setq-default org-todo-line-regexp org-todo-line-regexp)
24669 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24670 (org-infile-export-plist)))
24671 (region-p (org-region-active-p))
24672 (subtree-p
24673 (when region-p
24674 (save-excursion
24675 (goto-char (region-beginning))
24676 (and (org-at-heading-p)
24677 (>= (org-end-of-subtree t t) (region-end))))))
24678 (custom-times org-display-custom-times)
24679 (org-ascii-current-indentation '(0 . 0))
24680 (level 0) line txt
24681 (umax nil)
24682 (umax-toc nil)
24683 (case-fold-search nil)
24684 (filename (concat (file-name-as-directory
24685 (org-export-directory :ascii opt-plist))
24686 (file-name-sans-extension
24687 (or (and subtree-p
24688 (org-entry-get (region-beginning)
24689 "EXPORT_FILE_NAME" t))
24690 (file-name-nondirectory buffer-file-name)))
24691 ".txt"))
24692 (filename (if (equal (file-truename filename)
24693 (file-truename buffer-file-name))
24694 (concat filename ".txt")
24695 filename))
24696 (buffer (find-file-noselect filename))
24697 (org-levels-open (make-vector org-level-max nil))
24698 (odd org-odd-levels-only)
24699 (date (plist-get opt-plist :date))
24700 (author (plist-get opt-plist :author))
24701 (title (or (and subtree-p (org-export-get-title-from-subtree))
24702 (plist-get opt-plist :title)
24703 (and (not
24704 (plist-get opt-plist :skip-before-1st-heading))
24705 (org-export-grab-title-from-buffer))
24706 (file-name-sans-extension
24707 (file-name-nondirectory buffer-file-name))))
24708 (email (plist-get opt-plist :email))
24709 (language (plist-get opt-plist :language))
24710 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24711 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24712 (todo nil)
24713 (lang-words nil)
24714 (region
24715 (buffer-substring
24716 (if (org-region-active-p) (region-beginning) (point-min))
24717 (if (org-region-active-p) (region-end) (point-max))))
24718 (lines (org-split-string
24719 (org-cleaned-string-for-export
24720 region
24721 :for-ascii t
24722 :skip-before-1st-heading
24723 (plist-get opt-plist :skip-before-1st-heading)
24724 :drawers (plist-get opt-plist :drawers)
24725 :verbatim-multiline t
24726 :archived-trees
24727 (plist-get opt-plist :archived-trees)
24728 :add-text (plist-get opt-plist :text))
24729 "\n"))
24730 thetoc have-headings first-heading-pos
24731 table-open table-buffer)
24733 (let ((inhibit-read-only t))
24734 (org-unmodified
24735 (remove-text-properties (point-min) (point-max)
24736 '(:org-license-to-kill t))))
24738 (setq org-min-level (org-get-min-level lines))
24739 (setq org-last-level org-min-level)
24740 (org-init-section-numbers)
24742 (find-file-noselect filename)
24744 (setq lang-words (or (assoc language org-export-language-setup)
24745 (assoc "en" org-export-language-setup)))
24746 (switch-to-buffer-other-window buffer)
24747 (erase-buffer)
24748 (fundamental-mode)
24749 ;; create local variables for all options, to make sure all called
24750 ;; functions get the correct information
24751 (mapc (lambda (x)
24752 (set (make-local-variable (cdr x))
24753 (plist-get opt-plist (car x))))
24754 org-export-plist-vars)
24755 (org-set-local 'org-odd-levels-only odd)
24756 (setq umax (if arg (prefix-numeric-value arg)
24757 org-export-headline-levels))
24758 (setq umax-toc (if (integerp org-export-with-toc)
24759 (min org-export-with-toc umax)
24760 umax))
24762 ;; File header
24763 (if title (org-insert-centered title ?=))
24764 (insert "\n")
24765 (if (and (or author email)
24766 org-export-author-info)
24767 (insert (concat (nth 1 lang-words) ": " (or author "")
24768 (if email (concat " <" email ">") "")
24769 "\n")))
24771 (cond
24772 ((and date (string-match "%" date))
24773 (setq date (format-time-string date (current-time))))
24774 (date)
24775 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24777 (if (and date org-export-time-stamp-file)
24778 (insert (concat (nth 2 lang-words) ": " date"\n")))
24780 (insert "\n\n")
24782 (if org-export-with-toc
24783 (progn
24784 (push (concat (nth 3 lang-words) "\n") thetoc)
24785 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24786 (mapc '(lambda (line)
24787 (if (string-match org-todo-line-regexp
24788 line)
24789 ;; This is a headline
24790 (progn
24791 (setq have-headings t)
24792 (setq level (- (match-end 1) (match-beginning 1))
24793 level (org-tr-level level)
24794 txt (match-string 3 line)
24795 todo
24796 (or (and org-export-mark-todo-in-toc
24797 (match-beginning 2)
24798 (not (member (match-string 2 line)
24799 org-done-keywords)))
24800 ; TODO, not DONE
24801 (and org-export-mark-todo-in-toc
24802 (= level umax-toc)
24803 (org-search-todo-below
24804 line lines level))))
24805 (setq txt (org-html-expand-for-ascii txt))
24807 (while (string-match org-bracket-link-regexp txt)
24808 (setq txt
24809 (replace-match
24810 (match-string (if (match-end 2) 3 1) txt)
24811 t t txt)))
24813 (if (and (memq org-export-with-tags '(not-in-toc nil))
24814 (string-match
24815 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24816 txt))
24817 (setq txt (replace-match "" t t txt)))
24818 (if (string-match quote-re0 txt)
24819 (setq txt (replace-match "" t t txt)))
24821 (if org-export-with-section-numbers
24822 (setq txt (concat (org-section-number level)
24823 " " txt)))
24824 (if (<= level umax-toc)
24825 (progn
24826 (push
24827 (concat
24828 (make-string
24829 (* (max 0 (- level org-min-level)) 4) ?\ )
24830 (format (if todo "%s (*)\n" "%s\n") txt))
24831 thetoc)
24832 (setq org-last-level level))
24833 ))))
24834 lines)
24835 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24837 (org-init-section-numbers)
24838 (while (setq line (pop lines))
24839 ;; Remove the quoted HTML tags.
24840 (setq line (org-html-expand-for-ascii line))
24841 ;; Remove targets
24842 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24843 (setq line (replace-match "" t t line)))
24844 ;; Replace internal links
24845 (while (string-match org-bracket-link-regexp line)
24846 (setq line (replace-match
24847 (if (match-end 3) "[\\3]" "[\\1]")
24848 t nil line)))
24849 (when custom-times
24850 (setq line (org-translate-time line)))
24851 (cond
24852 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24853 ;; a Headline
24854 (setq first-heading-pos (or first-heading-pos (point)))
24855 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24856 txt (match-string 2 line))
24857 (org-ascii-level-start level txt umax lines))
24859 ((and org-export-with-tables
24860 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24861 (if (not table-open)
24862 ;; New table starts
24863 (setq table-open t table-buffer nil))
24864 ;; Accumulate lines
24865 (setq table-buffer (cons line table-buffer))
24866 (when (or (not lines)
24867 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24868 (car lines))))
24869 (setq table-open nil
24870 table-buffer (nreverse table-buffer))
24871 (insert (mapconcat
24872 (lambda (x)
24873 (org-fix-indentation x org-ascii-current-indentation))
24874 (org-format-table-ascii table-buffer)
24875 "\n") "\n")))
24877 (setq line (org-fix-indentation line org-ascii-current-indentation))
24878 (if (and org-export-with-fixed-width
24879 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24880 (setq line (replace-match "\\1" nil nil line)))
24881 (insert line "\n"))))
24883 (normal-mode)
24885 ;; insert the table of contents
24886 (when thetoc
24887 (goto-char (point-min))
24888 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24889 (progn
24890 (goto-char (match-beginning 0))
24891 (replace-match ""))
24892 (goto-char first-heading-pos))
24893 (mapc 'insert thetoc)
24894 (or (looking-at "[ \t]*\n[ \t]*\n")
24895 (insert "\n\n")))
24897 ;; Convert whitespace place holders
24898 (goto-char (point-min))
24899 (let (beg end)
24900 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24901 (setq end (next-single-property-change beg 'org-whitespace))
24902 (goto-char beg)
24903 (delete-region beg end)
24904 (insert (make-string (- end beg) ?\ ))))
24906 (save-buffer)
24907 ;; remove display and invisible chars
24908 (let (beg end)
24909 (goto-char (point-min))
24910 (while (setq beg (next-single-property-change (point) 'display))
24911 (setq end (next-single-property-change beg 'display))
24912 (delete-region beg end)
24913 (goto-char beg)
24914 (insert "=>"))
24915 (goto-char (point-min))
24916 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24917 (setq end (next-single-property-change beg 'org-cwidth))
24918 (delete-region beg end)
24919 (goto-char beg)))
24920 (goto-char (point-min))))
24922 (defun org-export-ascii-clean-string ()
24923 "Do extra work for ASCII export"
24924 (goto-char (point-min))
24925 (while (re-search-forward org-verbatim-re nil t)
24926 (goto-char (match-end 2))
24927 (backward-delete-char 1) (insert "'")
24928 (goto-char (match-beginning 2))
24929 (delete-char 1) (insert "`")
24930 (goto-char (match-end 2))))
24932 (defun org-search-todo-below (line lines level)
24933 "Search the subtree below LINE for any TODO entries."
24934 (let ((rest (cdr (memq line lines)))
24935 (re org-todo-line-regexp)
24936 line lv todo)
24937 (catch 'exit
24938 (while (setq line (pop rest))
24939 (if (string-match re line)
24940 (progn
24941 (setq lv (- (match-end 1) (match-beginning 1))
24942 todo (and (match-beginning 2)
24943 (not (member (match-string 2 line)
24944 org-done-keywords))))
24945 ; TODO, not DONE
24946 (if (<= lv level) (throw 'exit nil))
24947 (if todo (throw 'exit t))))))))
24949 (defun org-html-expand-for-ascii (line)
24950 "Handle quoted HTML for ASCII export."
24951 (if org-export-html-expand
24952 (while (string-match "@<[^<>\n]*>" line)
24953 ;; We just remove the tags for now.
24954 (setq line (replace-match "" nil nil line))))
24955 line)
24957 (defun org-insert-centered (s &optional underline)
24958 "Insert the string S centered and underline it with character UNDERLINE."
24959 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24960 (insert (make-string ind ?\ ) s "\n")
24961 (if underline
24962 (insert (make-string ind ?\ )
24963 (make-string (string-width s) underline)
24964 "\n"))))
24966 (defun org-ascii-level-start (level title umax &optional lines)
24967 "Insert a new level in ASCII export."
24968 (let (char (n (- level umax 1)) (ind 0))
24969 (if (> level umax)
24970 (progn
24971 (insert (make-string (* 2 n) ?\ )
24972 (char-to-string (nth (% n (length org-export-ascii-bullets))
24973 org-export-ascii-bullets))
24974 " " title "\n")
24975 ;; find the indentation of the next non-empty line
24976 (catch 'stop
24977 (while lines
24978 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24979 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24980 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24981 (pop lines)))
24982 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24983 (if (or (not (equal (char-before) ?\n))
24984 (not (equal (char-before (1- (point))) ?\n)))
24985 (insert "\n"))
24986 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24987 (unless org-export-with-tags
24988 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24989 (setq title (replace-match "" t t title))))
24990 (if org-export-with-section-numbers
24991 (setq title (concat (org-section-number level) " " title)))
24992 (insert title "\n" (make-string (string-width title) char) "\n")
24993 (setq org-ascii-current-indentation '(0 . 0)))))
24995 (defun org-export-visible (type arg)
24996 "Create a copy of the visible part of the current buffer, and export it.
24997 The copy is created in a temporary buffer and removed after use.
24998 TYPE is the final key (as a string) that also select the export command in
24999 the `C-c C-e' export dispatcher.
25000 As a special case, if the you type SPC at the prompt, the temporary
25001 org-mode file will not be removed but presented to you so that you can
25002 continue to use it. The prefix arg ARG is passed through to the exporting
25003 command."
25004 (interactive
25005 (list (progn
25006 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
25007 (read-char-exclusive))
25008 current-prefix-arg))
25009 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
25010 (error "Invalid export key"))
25011 (let* ((binding (cdr (assoc type
25012 '((?a . org-export-as-ascii)
25013 (?\C-a . org-export-as-ascii)
25014 (?b . org-export-as-html-and-open)
25015 (?\C-b . org-export-as-html-and-open)
25016 (?h . org-export-as-html)
25017 (?H . org-export-as-html-to-buffer)
25018 (?R . org-export-region-as-html)
25019 (?x . org-export-as-xoxo)))))
25020 (keepp (equal type ?\ ))
25021 (file buffer-file-name)
25022 (buffer (get-buffer-create "*Org Export Visible*"))
25023 s e)
25024 ;; Need to hack the drawers here.
25025 (save-excursion
25026 (goto-char (point-min))
25027 (while (re-search-forward org-drawer-regexp nil t)
25028 (goto-char (match-beginning 1))
25029 (or (org-invisible-p) (org-flag-drawer nil))))
25030 (with-current-buffer buffer (erase-buffer))
25031 (save-excursion
25032 (setq s (goto-char (point-min)))
25033 (while (not (= (point) (point-max)))
25034 (goto-char (org-find-invisible))
25035 (append-to-buffer buffer s (point))
25036 (setq s (goto-char (org-find-visible))))
25037 (org-cycle-hide-drawers 'all)
25038 (goto-char (point-min))
25039 (unless keepp
25040 ;; Copy all comment lines to the end, to make sure #+ settings are
25041 ;; still available for the second export step. Kind of a hack, but
25042 ;; does do the trick.
25043 (if (looking-at "#[^\r\n]*")
25044 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
25045 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
25046 (append-to-buffer buffer (1+ (match-beginning 0))
25047 (min (point-max) (1+ (match-end 0))))))
25048 (set-buffer buffer)
25049 (let ((buffer-file-name file)
25050 (org-inhibit-startup t))
25051 (org-mode)
25052 (show-all)
25053 (unless keepp (funcall binding arg))))
25054 (if (not keepp)
25055 (kill-buffer buffer)
25056 (switch-to-buffer-other-window buffer)
25057 (goto-char (point-min)))))
25059 (defun org-find-visible ()
25060 (let ((s (point)))
25061 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25062 (get-char-property s 'invisible)))
25064 (defun org-find-invisible ()
25065 (let ((s (point)))
25066 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25067 (not (get-char-property s 'invisible))))
25070 ;;; HTML export
25072 (defun org-get-current-options ()
25073 "Return a string with current options as keyword options.
25074 Does include HTML export options as well as TODO and CATEGORY stuff."
25075 (format
25076 "#+TITLE: %s
25077 #+AUTHOR: %s
25078 #+EMAIL: %s
25079 #+LANGUAGE: %s
25080 #+TEXT: Some descriptive text to be emitted. Several lines OK.
25081 #+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
25082 #+CATEGORY: %s
25083 #+SEQ_TODO: %s
25084 #+TYP_TODO: %s
25085 #+PRIORITIES: %c %c %c
25086 #+DRAWERS: %s
25087 #+STARTUP: %s %s %s %s %s
25088 #+TAGS: %s
25089 #+ARCHIVE: %s
25090 #+LINK: %s
25092 (buffer-name) (user-full-name) user-mail-address org-export-default-language
25093 org-export-headline-levels
25094 org-export-with-section-numbers
25095 org-export-with-toc
25096 org-export-preserve-breaks
25097 org-export-html-expand
25098 org-export-with-fixed-width
25099 org-export-with-tables
25100 org-export-with-sub-superscripts
25101 org-export-with-special-strings
25102 org-export-with-footnotes
25103 org-export-with-emphasize
25104 org-export-with-TeX-macros
25105 org-export-with-LaTeX-fragments
25106 org-export-skip-text-before-1st-heading
25107 org-export-with-drawers
25108 org-export-with-tags
25109 (file-name-nondirectory buffer-file-name)
25110 "TODO FEEDBACK VERIFY DONE"
25111 "Me Jason Marie DONE"
25112 org-highest-priority org-lowest-priority org-default-priority
25113 (mapconcat 'identity org-drawers " ")
25114 (cdr (assoc org-startup-folded
25115 '((nil . "showall") (t . "overview") (content . "content"))))
25116 (if org-odd-levels-only "odd" "oddeven")
25117 (if org-hide-leading-stars "hidestars" "showstars")
25118 (if org-startup-align-all-tables "align" "noalign")
25119 (cond ((eq org-log-done t) "logdone")
25120 ((equal org-log-done 'note) "lognotedone")
25121 ((not org-log-done) "nologdone"))
25122 (or (mapconcat (lambda (x)
25123 (cond
25124 ((equal '(:startgroup) x) "{")
25125 ((equal '(:endgroup) x) "}")
25126 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
25127 (t (car x))))
25128 (or org-tag-alist (org-get-buffer-tags)) " ") "")
25129 org-archive-location
25130 "org file:~/org/%s.org"
25133 (defun org-insert-export-options-template ()
25134 "Insert into the buffer a template with information for exporting."
25135 (interactive)
25136 (if (not (bolp)) (newline))
25137 (let ((s (org-get-current-options)))
25138 (and (string-match "#\\+CATEGORY" s)
25139 (setq s (substring s 0 (match-beginning 0))))
25140 (insert s)))
25142 (defun org-toggle-fixed-width-section (arg)
25143 "Toggle the fixed-width export.
25144 If there is no active region, the QUOTE keyword at the current headline is
25145 inserted or removed. When present, it causes the text between this headline
25146 and the next to be exported as fixed-width text, and unmodified.
25147 If there is an active region, this command adds or removes a colon as the
25148 first character of this line. If the first character of a line is a colon,
25149 this line is also exported in fixed-width font."
25150 (interactive "P")
25151 (let* ((cc 0)
25152 (regionp (org-region-active-p))
25153 (beg (if regionp (region-beginning) (point)))
25154 (end (if regionp (region-end)))
25155 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
25156 (case-fold-search nil)
25157 (re "[ \t]*\\(:\\)")
25158 off)
25159 (if regionp
25160 (save-excursion
25161 (goto-char beg)
25162 (setq cc (current-column))
25163 (beginning-of-line 1)
25164 (setq off (looking-at re))
25165 (while (> nlines 0)
25166 (setq nlines (1- nlines))
25167 (beginning-of-line 1)
25168 (cond
25169 (arg
25170 (move-to-column cc t)
25171 (insert ":\n")
25172 (forward-line -1))
25173 ((and off (looking-at re))
25174 (replace-match "" t t nil 1))
25175 ((not off) (move-to-column cc t) (insert ":")))
25176 (forward-line 1)))
25177 (save-excursion
25178 (org-back-to-heading)
25179 (if (looking-at (concat outline-regexp
25180 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
25181 (replace-match "" t t nil 1)
25182 (if (looking-at outline-regexp)
25183 (progn
25184 (goto-char (match-end 0))
25185 (insert org-quote-string " "))))))))
25187 (defun org-export-as-html-and-open (arg)
25188 "Export the outline as HTML and immediately open it with a browser.
25189 If there is an active region, export only the region.
25190 The prefix ARG specifies how many levels of the outline should become
25191 headlines. The default is 3. Lower levels will become bulleted lists."
25192 (interactive "P")
25193 (org-export-as-html arg 'hidden)
25194 (org-open-file buffer-file-name))
25196 (defun org-export-as-html-batch ()
25197 "Call `org-export-as-html', may be used in batch processing as
25198 emacs --batch
25199 --load=$HOME/lib/emacs/org.el
25200 --eval \"(setq org-export-headline-levels 2)\"
25201 --visit=MyFile --funcall org-export-as-html-batch"
25202 (org-export-as-html org-export-headline-levels 'hidden))
25204 (defun org-export-as-html-to-buffer (arg)
25205 "Call `org-exort-as-html` with output to a temporary buffer.
25206 No file is created. The prefix ARG is passed through to `org-export-as-html'."
25207 (interactive "P")
25208 (org-export-as-html arg nil nil "*Org HTML Export*")
25209 (switch-to-buffer-other-window "*Org HTML Export*"))
25211 (defun org-replace-region-by-html (beg end)
25212 "Assume the current region has org-mode syntax, and convert it to HTML.
25213 This can be used in any buffer. For example, you could write an
25214 itemized list in org-mode syntax in an HTML buffer and then use this
25215 command to convert it."
25216 (interactive "r")
25217 (let (reg html buf pop-up-frames)
25218 (save-window-excursion
25219 (if (org-mode-p)
25220 (setq html (org-export-region-as-html
25221 beg end t 'string))
25222 (setq reg (buffer-substring beg end)
25223 buf (get-buffer-create "*Org tmp*"))
25224 (with-current-buffer buf
25225 (erase-buffer)
25226 (insert reg)
25227 (org-mode)
25228 (setq html (org-export-region-as-html
25229 (point-min) (point-max) t 'string)))
25230 (kill-buffer buf)))
25231 (delete-region beg end)
25232 (insert html)))
25234 (defun org-export-region-as-html (beg end &optional body-only buffer)
25235 "Convert region from BEG to END in org-mode buffer to HTML.
25236 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
25237 contents, and only produce the region of converted text, useful for
25238 cut-and-paste operations.
25239 If BUFFER is a buffer or a string, use/create that buffer as a target
25240 of the converted HTML. If BUFFER is the symbol `string', return the
25241 produced HTML as a string and leave not buffer behind. For example,
25242 a Lisp program could call this function in the following way:
25244 (setq html (org-export-region-as-html beg end t 'string))
25246 When called interactively, the output buffer is selected, and shown
25247 in a window. A non-interactive call will only retunr the buffer."
25248 (interactive "r\nP")
25249 (when (interactive-p)
25250 (setq buffer "*Org HTML Export*"))
25251 (let ((transient-mark-mode t) (zmacs-regions t)
25252 rtn)
25253 (goto-char end)
25254 (set-mark (point)) ;; to activate the region
25255 (goto-char beg)
25256 (setq rtn (org-export-as-html
25257 nil nil nil
25258 buffer body-only))
25259 (if (fboundp 'deactivate-mark) (deactivate-mark))
25260 (if (and (interactive-p) (bufferp rtn))
25261 (switch-to-buffer-other-window rtn)
25262 rtn)))
25264 (defvar html-table-tag nil) ; dynamically scoped into this.
25265 (defun org-export-as-html (arg &optional hidden ext-plist
25266 to-buffer body-only pub-dir)
25267 "Export the outline as a pretty HTML file.
25268 If there is an active region, export only the region. The prefix
25269 ARG specifies how many levels of the outline should become
25270 headlines. The default is 3. Lower levels will become bulleted
25271 lists. When HIDDEN is non-nil, don't display the HTML buffer.
25272 EXT-PLIST is a property list with external parameters overriding
25273 org-mode's default settings, but still inferior to file-local
25274 settings. When TO-BUFFER is non-nil, create a buffer with that
25275 name and export to that buffer. If TO-BUFFER is the symbol
25276 `string', don't leave any buffer behind but just return the
25277 resulting HTML as a string. When BODY-ONLY is set, don't produce
25278 the file header and footer, simply return the content of
25279 <body>...</body>, without even the body tags themselves. When
25280 PUB-DIR is set, use this as the publishing directory."
25281 (interactive "P")
25283 ;; Make sure we have a file name when we need it.
25284 (when (and (not (or to-buffer body-only))
25285 (not buffer-file-name))
25286 (if (buffer-base-buffer)
25287 (org-set-local 'buffer-file-name
25288 (with-current-buffer (buffer-base-buffer)
25289 buffer-file-name))
25290 (error "Need a file name to be able to export.")))
25292 (message "Exporting...")
25293 (setq-default org-todo-line-regexp org-todo-line-regexp)
25294 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25295 (setq-default org-done-keywords org-done-keywords)
25296 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25297 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25298 ext-plist
25299 (org-infile-export-plist)))
25301 (style (plist-get opt-plist :style))
25302 (html-extension (plist-get opt-plist :html-extension))
25303 (link-validate (plist-get opt-plist :link-validation-function))
25304 valid thetoc have-headings first-heading-pos
25305 (odd org-odd-levels-only)
25306 (region-p (org-region-active-p))
25307 (subtree-p
25308 (when region-p
25309 (save-excursion
25310 (goto-char (region-beginning))
25311 (and (org-at-heading-p)
25312 (>= (org-end-of-subtree t t) (region-end))))))
25313 ;; The following two are dynamically scoped into other
25314 ;; routines below.
25315 (org-current-export-dir
25316 (or pub-dir (org-export-directory :html opt-plist)))
25317 (org-current-export-file buffer-file-name)
25318 (level 0) (line "") (origline "") txt todo
25319 (umax nil)
25320 (umax-toc nil)
25321 (filename (if to-buffer nil
25322 (expand-file-name
25323 (concat
25324 (file-name-sans-extension
25325 (or (and subtree-p
25326 (org-entry-get (region-beginning)
25327 "EXPORT_FILE_NAME" t))
25328 (file-name-nondirectory buffer-file-name)))
25329 "." html-extension)
25330 (file-name-as-directory
25331 (or pub-dir (org-export-directory :html opt-plist))))))
25332 (current-dir (if buffer-file-name
25333 (file-name-directory buffer-file-name)
25334 default-directory))
25335 (buffer (if to-buffer
25336 (cond
25337 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25338 (t (get-buffer-create to-buffer)))
25339 (find-file-noselect filename)))
25340 (org-levels-open (make-vector org-level-max nil))
25341 (date (plist-get opt-plist :date))
25342 (author (plist-get opt-plist :author))
25343 (title (or (and subtree-p (org-export-get-title-from-subtree))
25344 (plist-get opt-plist :title)
25345 (and (not
25346 (plist-get opt-plist :skip-before-1st-heading))
25347 (org-export-grab-title-from-buffer))
25348 (and buffer-file-name
25349 (file-name-sans-extension
25350 (file-name-nondirectory buffer-file-name)))
25351 "UNTITLED"))
25352 (html-table-tag (plist-get opt-plist :html-table-tag))
25353 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25354 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25355 (inquote nil)
25356 (infixed nil)
25357 (in-local-list nil)
25358 (local-list-num nil)
25359 (local-list-indent nil)
25360 (llt org-plain-list-ordered-item-terminator)
25361 (email (plist-get opt-plist :email))
25362 (language (plist-get opt-plist :language))
25363 (lang-words nil)
25364 (target-alist nil) tg
25365 (head-count 0) cnt
25366 (start 0)
25367 (coding-system (and (boundp 'buffer-file-coding-system)
25368 buffer-file-coding-system))
25369 (coding-system-for-write (or org-export-html-coding-system
25370 coding-system))
25371 (save-buffer-coding-system (or org-export-html-coding-system
25372 coding-system))
25373 (charset (and coding-system-for-write
25374 (fboundp 'coding-system-get)
25375 (coding-system-get coding-system-for-write
25376 'mime-charset)))
25377 (region
25378 (buffer-substring
25379 (if region-p (region-beginning) (point-min))
25380 (if region-p (region-end) (point-max))))
25381 (lines
25382 (org-split-string
25383 (org-cleaned-string-for-export
25384 region
25385 :emph-multiline t
25386 :for-html t
25387 :skip-before-1st-heading
25388 (plist-get opt-plist :skip-before-1st-heading)
25389 :drawers (plist-get opt-plist :drawers)
25390 :archived-trees
25391 (plist-get opt-plist :archived-trees)
25392 :add-text
25393 (plist-get opt-plist :text)
25394 :LaTeX-fragments
25395 (plist-get opt-plist :LaTeX-fragments))
25396 "[\r\n]"))
25397 table-open type
25398 table-buffer table-orig-buffer
25399 ind start-is-num starter didclose
25400 rpl path desc descp desc1 desc2 link
25403 (let ((inhibit-read-only t))
25404 (org-unmodified
25405 (remove-text-properties (point-min) (point-max)
25406 '(:org-license-to-kill t))))
25408 (message "Exporting...")
25410 (setq org-min-level (org-get-min-level lines))
25411 (setq org-last-level org-min-level)
25412 (org-init-section-numbers)
25414 (cond
25415 ((and date (string-match "%" date))
25416 (setq date (format-time-string date (current-time))))
25417 (date)
25418 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25420 ;; Get the language-dependent settings
25421 (setq lang-words (or (assoc language org-export-language-setup)
25422 (assoc "en" org-export-language-setup)))
25424 ;; Switch to the output buffer
25425 (set-buffer buffer)
25426 (let ((inhibit-read-only t)) (erase-buffer))
25427 (fundamental-mode)
25429 (and (fboundp 'set-buffer-file-coding-system)
25430 (set-buffer-file-coding-system coding-system-for-write))
25432 (let ((case-fold-search nil)
25433 (org-odd-levels-only odd))
25434 ;; create local variables for all options, to make sure all called
25435 ;; functions get the correct information
25436 (mapc (lambda (x)
25437 (set (make-local-variable (cdr x))
25438 (plist-get opt-plist (car x))))
25439 org-export-plist-vars)
25440 (setq umax (if arg (prefix-numeric-value arg)
25441 org-export-headline-levels))
25442 (setq umax-toc (if (integerp org-export-with-toc)
25443 (min org-export-with-toc umax)
25444 umax))
25445 (unless body-only
25446 ;; File header
25447 (insert (format
25448 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25449 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25450 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25451 lang=\"%s\" xml:lang=\"%s\">
25452 <head>
25453 <title>%s</title>
25454 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25455 <meta name=\"generator\" content=\"Org-mode\"/>
25456 <meta name=\"generated\" content=\"%s\"/>
25457 <meta name=\"author\" content=\"%s\"/>
25459 </head><body>
25461 language language (org-html-expand title)
25462 (or charset "iso-8859-1") date author style))
25464 (insert (or (plist-get opt-plist :preamble) ""))
25466 (when (plist-get opt-plist :auto-preamble)
25467 (if title (insert (format org-export-html-title-format
25468 (org-html-expand title))))))
25470 (if (and org-export-with-toc (not body-only))
25471 (progn
25472 (push (format "<h%d>%s</h%d>\n"
25473 org-export-html-toplevel-hlevel
25474 (nth 3 lang-words)
25475 org-export-html-toplevel-hlevel)
25476 thetoc)
25477 (push "<ul>\n<li>" thetoc)
25478 (setq lines
25479 (mapcar '(lambda (line)
25480 (if (string-match org-todo-line-regexp line)
25481 ;; This is a headline
25482 (progn
25483 (setq have-headings t)
25484 (setq level (- (match-end 1) (match-beginning 1))
25485 level (org-tr-level level)
25486 txt (save-match-data
25487 (org-html-expand
25488 (org-export-cleanup-toc-line
25489 (match-string 3 line))))
25490 todo
25491 (or (and org-export-mark-todo-in-toc
25492 (match-beginning 2)
25493 (not (member (match-string 2 line)
25494 org-done-keywords)))
25495 ; TODO, not DONE
25496 (and org-export-mark-todo-in-toc
25497 (= level umax-toc)
25498 (org-search-todo-below
25499 line lines level))))
25500 (if (string-match
25501 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25502 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25503 (if (string-match quote-re0 txt)
25504 (setq txt (replace-match "" t t txt)))
25505 (if org-export-with-section-numbers
25506 (setq txt (concat (org-section-number level)
25507 " " txt)))
25508 (if (<= level (max umax umax-toc))
25509 (setq head-count (+ head-count 1)))
25510 (if (<= level umax-toc)
25511 (progn
25512 (if (> level org-last-level)
25513 (progn
25514 (setq cnt (- level org-last-level))
25515 (while (>= (setq cnt (1- cnt)) 0)
25516 (push "\n<ul>\n<li>" thetoc))
25517 (push "\n" thetoc)))
25518 (if (< level org-last-level)
25519 (progn
25520 (setq cnt (- org-last-level level))
25521 (while (>= (setq cnt (1- cnt)) 0)
25522 (push "</li>\n</ul>" thetoc))
25523 (push "\n" thetoc)))
25524 ;; Check for targets
25525 (while (string-match org-target-regexp line)
25526 (setq tg (match-string 1 line)
25527 line (replace-match
25528 (concat "@<span class=\"target\">" tg "@</span> ")
25529 t t line))
25530 (push (cons (org-solidify-link-text tg)
25531 (format "sec-%d" head-count))
25532 target-alist))
25533 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25534 (setq txt (replace-match "" t t txt)))
25535 (push
25536 (format
25537 (if todo
25538 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25539 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25540 head-count txt) thetoc)
25542 (setq org-last-level level))
25544 line)
25545 lines))
25546 (while (> org-last-level (1- org-min-level))
25547 (setq org-last-level (1- org-last-level))
25548 (push "</li>\n</ul>\n" thetoc))
25549 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25551 (setq head-count 0)
25552 (org-init-section-numbers)
25554 (while (setq line (pop lines) origline line)
25555 (catch 'nextline
25557 ;; end of quote section?
25558 (when (and inquote (string-match "^\\*+ " line))
25559 (insert "</pre>\n")
25560 (setq inquote nil))
25561 ;; inside a quote section?
25562 (when inquote
25563 (insert (org-html-protect line) "\n")
25564 (throw 'nextline nil))
25566 ;; verbatim lines
25567 (when (and org-export-with-fixed-width
25568 (string-match "^[ \t]*:\\(.*\\)" line))
25569 (when (not infixed)
25570 (setq infixed t)
25571 (insert "<pre>\n"))
25572 (insert (org-html-protect (match-string 1 line)) "\n")
25573 (when (and lines
25574 (not (string-match "^[ \t]*\\(:.*\\)"
25575 (car lines))))
25576 (setq infixed nil)
25577 (insert "</pre>\n"))
25578 (throw 'nextline nil))
25580 ;; Protected HTML
25581 (when (get-text-property 0 'org-protected line)
25582 (let (par)
25583 (when (re-search-backward
25584 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25585 (setq par (match-string 1))
25586 (replace-match "\\2\n"))
25587 (insert line "\n")
25588 (while (and lines
25589 (or (= (length (car lines)) 0)
25590 (get-text-property 0 'org-protected (car lines))))
25591 (insert (pop lines) "\n"))
25592 (and par (insert "<p>\n")))
25593 (throw 'nextline nil))
25595 ;; Horizontal line
25596 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25597 (insert "\n<hr/>\n")
25598 (throw 'nextline nil))
25600 ;; make targets to anchors
25601 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25602 (cond
25603 ((match-end 2)
25604 (setq line (replace-match
25605 (concat "@<a name=\""
25606 (org-solidify-link-text (match-string 1 line))
25607 "\">\\nbsp@</a>")
25608 t t line)))
25609 ((and org-export-with-toc (equal (string-to-char line) ?*))
25610 (setq line (replace-match
25611 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25612 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25613 t t line)))
25615 (setq line (replace-match
25616 (concat "@<a name=\""
25617 (org-solidify-link-text (match-string 1 line))
25618 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25619 t t line)))))
25621 (setq line (org-html-handle-time-stamps line))
25623 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25624 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25625 ;; Also handle sub_superscripts and checkboxes
25626 (or (string-match org-table-hline-regexp line)
25627 (setq line (org-html-expand line)))
25629 ;; Format the links
25630 (setq start 0)
25631 (while (string-match org-bracket-link-analytic-regexp line start)
25632 (setq start (match-beginning 0))
25633 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25634 (setq path (match-string 3 line))
25635 (setq desc1 (if (match-end 5) (match-string 5 line))
25636 desc2 (if (match-end 2) (concat type ":" path) path)
25637 descp (and desc1 (not (equal desc1 desc2)))
25638 desc (or desc1 desc2))
25639 ;; Make an image out of the description if that is so wanted
25640 (when (and descp (org-file-image-p desc))
25641 (save-match-data
25642 (if (string-match "^file:" desc)
25643 (setq desc (substring desc (match-end 0)))))
25644 (setq desc (concat "<img src=\"" desc "\"/>")))
25645 ;; FIXME: do we need to unescape here somewhere?
25646 (cond
25647 ((equal type "internal")
25648 (setq rpl
25649 (concat
25650 "<a href=\"#"
25651 (org-solidify-link-text
25652 (save-match-data (org-link-unescape path)) target-alist)
25653 "\">" desc "</a>")))
25654 ((member type '("http" "https"))
25655 ;; standard URL, just check if we need to inline an image
25656 (if (and (or (eq t org-export-html-inline-images)
25657 (and org-export-html-inline-images (not descp)))
25658 (org-file-image-p path))
25659 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25660 (setq link (concat type ":" path))
25661 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25662 ((member type '("ftp" "mailto" "news"))
25663 ;; standard URL
25664 (setq link (concat type ":" path))
25665 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25666 ((string= type "file")
25667 ;; FILE link
25668 (let* ((filename path)
25669 (abs-p (file-name-absolute-p filename))
25670 thefile file-is-image-p search)
25671 (save-match-data
25672 (if (string-match "::\\(.*\\)" filename)
25673 (setq search (match-string 1 filename)
25674 filename (replace-match "" t nil filename)))
25675 (setq valid
25676 (if (functionp link-validate)
25677 (funcall link-validate filename current-dir)
25679 (setq file-is-image-p (org-file-image-p filename))
25680 (setq thefile (if abs-p (expand-file-name filename) filename))
25681 (when (and org-export-html-link-org-files-as-html
25682 (string-match "\\.org$" thefile))
25683 (setq thefile (concat (substring thefile 0
25684 (match-beginning 0))
25685 "." html-extension))
25686 (if (and search
25687 ;; make sure this is can be used as target search
25688 (not (string-match "^[0-9]*$" search))
25689 (not (string-match "^\\*" search))
25690 (not (string-match "^/.*/$" search)))
25691 (setq thefile (concat thefile "#"
25692 (org-solidify-link-text
25693 (org-link-unescape search)))))
25694 (when (string-match "^file:" desc)
25695 (setq desc (replace-match "" t t desc))
25696 (if (string-match "\\.org$" desc)
25697 (setq desc (replace-match "" t t desc))))))
25698 (setq rpl (if (and file-is-image-p
25699 (or (eq t org-export-html-inline-images)
25700 (and org-export-html-inline-images
25701 (not descp))))
25702 (concat "<img src=\"" thefile "\"/>")
25703 (concat "<a href=\"" thefile "\">" desc "</a>")))
25704 (if (not valid) (setq rpl desc))))
25705 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25706 (setq rpl (concat "<i>&lt;" type ":"
25707 (save-match-data (org-link-unescape path))
25708 "&gt;</i>"))))
25709 (setq line (replace-match rpl t t line)
25710 start (+ start (length rpl))))
25712 ;; TODO items
25713 (if (and (string-match org-todo-line-regexp line)
25714 (match-beginning 2))
25716 (setq line
25717 (concat (substring line 0 (match-beginning 2))
25718 "<span class=\""
25719 (if (member (match-string 2 line)
25720 org-done-keywords)
25721 "done" "todo")
25722 "\">" (match-string 2 line)
25723 "</span>" (substring line (match-end 2)))))
25725 ;; Does this contain a reference to a footnote?
25726 (when org-export-with-footnotes
25727 (setq start 0)
25728 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25729 (if (get-text-property (match-beginning 2) 'org-protected line)
25730 (setq start (match-end 2))
25731 (let ((n (match-string 2 line)))
25732 (setq line
25733 (replace-match
25734 (format
25735 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25736 (match-string 1 line) n n n)
25737 t t line))))))
25739 (cond
25740 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25741 ;; This is a headline
25742 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25743 txt (match-string 2 line))
25744 (if (string-match quote-re0 txt)
25745 (setq txt (replace-match "" t t txt)))
25746 (if (<= level (max umax umax-toc))
25747 (setq head-count (+ head-count 1)))
25748 (when in-local-list
25749 ;; Close any local lists before inserting a new header line
25750 (while local-list-num
25751 (org-close-li)
25752 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25753 (pop local-list-num))
25754 (setq local-list-indent nil
25755 in-local-list nil))
25756 (setq first-heading-pos (or first-heading-pos (point)))
25757 (org-html-level-start level txt umax
25758 (and org-export-with-toc (<= level umax))
25759 head-count)
25760 ;; QUOTES
25761 (when (string-match quote-re line)
25762 (insert "<pre>")
25763 (setq inquote t)))
25765 ((and org-export-with-tables
25766 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25767 (if (not table-open)
25768 ;; New table starts
25769 (setq table-open t table-buffer nil table-orig-buffer nil))
25770 ;; Accumulate lines
25771 (setq table-buffer (cons line table-buffer)
25772 table-orig-buffer (cons origline table-orig-buffer))
25773 (when (or (not lines)
25774 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25775 (car lines))))
25776 (setq table-open nil
25777 table-buffer (nreverse table-buffer)
25778 table-orig-buffer (nreverse table-orig-buffer))
25779 (org-close-par-maybe)
25780 (insert (org-format-table-html table-buffer table-orig-buffer))))
25782 ;; Normal lines
25783 (when (string-match
25784 (cond
25785 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25786 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25787 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25788 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25789 line)
25790 (setq ind (org-get-string-indentation line)
25791 start-is-num (match-beginning 4)
25792 starter (if (match-beginning 2)
25793 (substring (match-string 2 line) 0 -1))
25794 line (substring line (match-beginning 5)))
25795 (unless (string-match "[^ \t]" line)
25796 ;; empty line. Pretend indentation is large.
25797 (setq ind (if org-empty-line-terminates-plain-lists
25799 (1+ (or (car local-list-indent) 1)))))
25800 (setq didclose nil)
25801 (while (and in-local-list
25802 (or (and (= ind (car local-list-indent))
25803 (not starter))
25804 (< ind (car local-list-indent))))
25805 (setq didclose t)
25806 (org-close-li)
25807 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25808 (pop local-list-num) (pop local-list-indent)
25809 (setq in-local-list local-list-indent))
25810 (cond
25811 ((and starter
25812 (or (not in-local-list)
25813 (> ind (car local-list-indent))))
25814 ;; Start new (level of) list
25815 (org-close-par-maybe)
25816 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25817 (push start-is-num local-list-num)
25818 (push ind local-list-indent)
25819 (setq in-local-list t))
25820 (starter
25821 ;; continue current list
25822 (org-close-li)
25823 (insert "<li>\n"))
25824 (didclose
25825 ;; we did close a list, normal text follows: need <p>
25826 (org-open-par)))
25827 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25828 (setq line
25829 (replace-match
25830 (if (equal (match-string 1 line) "X")
25831 "<b>[X]</b>"
25832 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25833 t t line))))
25835 ;; Empty lines start a new paragraph. If hand-formatted lists
25836 ;; are not fully interpreted, lines starting with "-", "+", "*"
25837 ;; also start a new paragraph.
25838 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25840 ;; Is this the start of a footnote?
25841 (when org-export-with-footnotes
25842 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25843 (org-close-par-maybe)
25844 (let ((n (match-string 1 line)))
25845 (setq line (replace-match
25846 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25848 ;; Check if the line break needs to be conserved
25849 (cond
25850 ((string-match "\\\\\\\\[ \t]*$" line)
25851 (setq line (replace-match "<br/>" t t line)))
25852 (org-export-preserve-breaks
25853 (setq line (concat line "<br/>"))))
25855 (insert line "\n")))))
25857 ;; Properly close all local lists and other lists
25858 (when inquote (insert "</pre>\n"))
25859 (when in-local-list
25860 ;; Close any local lists before inserting a new header line
25861 (while local-list-num
25862 (org-close-li)
25863 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25864 (pop local-list-num))
25865 (setq local-list-indent nil
25866 in-local-list nil))
25867 (org-html-level-start 1 nil umax
25868 (and org-export-with-toc (<= level umax))
25869 head-count)
25871 (unless body-only
25872 (when (plist-get opt-plist :auto-postamble)
25873 (insert "<div id=\"postamble\">")
25874 (when (and org-export-author-info author)
25875 (insert "<p class=\"author\"> "
25876 (nth 1 lang-words) ": " author "\n")
25877 (when email
25878 (if (listp (split-string email ",+ *"))
25879 (mapc (lambda(e)
25880 (insert "<a href=\"mailto:" e "\">&lt;"
25881 e "&gt;</a>\n"))
25882 (split-string email ",+ *"))
25883 (insert "<a href=\"mailto:" email "\">&lt;"
25884 email "&gt;</a>\n")))
25885 (insert "</p>\n"))
25886 (when (and date org-export-time-stamp-file)
25887 (insert "<p class=\"date\"> "
25888 (nth 2 lang-words) ": "
25889 date "</p>\n"))
25890 (insert "</div>"))
25892 (if org-export-html-with-timestamp
25893 (insert org-export-html-html-helper-timestamp))
25894 (insert (or (plist-get opt-plist :postamble) ""))
25895 (insert "</body>\n</html>\n"))
25897 (normal-mode)
25898 (if (eq major-mode default-major-mode) (html-mode))
25900 ;; insert the table of contents
25901 (goto-char (point-min))
25902 (when thetoc
25903 (if (or (re-search-forward
25904 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25905 (re-search-forward
25906 "\\[TABLE-OF-CONTENTS\\]" nil t))
25907 (progn
25908 (goto-char (match-beginning 0))
25909 (replace-match ""))
25910 (goto-char first-heading-pos)
25911 (when (looking-at "\\s-*</p>")
25912 (goto-char (match-end 0))
25913 (insert "\n")))
25914 (insert "<div id=\"table-of-contents\">\n")
25915 (mapc 'insert thetoc)
25916 (insert "</div>\n"))
25917 ;; remove empty paragraphs and lists
25918 (goto-char (point-min))
25919 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25920 (replace-match ""))
25921 (goto-char (point-min))
25922 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25923 (replace-match ""))
25924 (goto-char (point-min))
25925 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
25926 (replace-match ""))
25927 ;; Convert whitespace place holders
25928 (goto-char (point-min))
25929 (let (beg end n)
25930 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25931 (setq n (get-text-property beg 'org-whitespace)
25932 end (next-single-property-change beg 'org-whitespace))
25933 (goto-char beg)
25934 (delete-region beg end)
25935 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25936 (make-string n ?x)))))
25938 (or to-buffer (progn (save-buffer) (kill-buffer (current-buffer))))
25939 (goto-char (point-min))
25940 (message "Exporting... done")
25941 (if (eq to-buffer 'string)
25942 (prog1 (buffer-substring (point-min) (point-max))
25943 (kill-buffer (current-buffer)))
25944 (current-buffer)))))
25946 (defvar org-table-colgroup-info nil)
25947 (defun org-format-table-ascii (lines)
25948 "Format a table for ascii export."
25949 (if (stringp lines)
25950 (setq lines (org-split-string lines "\n")))
25951 (if (not (string-match "^[ \t]*|" (car lines)))
25952 ;; Table made by table.el - test for spanning
25953 lines
25955 ;; A normal org table
25956 ;; Get rid of hlines at beginning and end
25957 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25958 (setq lines (nreverse lines))
25959 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25960 (setq lines (nreverse lines))
25961 (when org-export-table-remove-special-lines
25962 ;; Check if the table has a marking column. If yes remove the
25963 ;; column and the special lines
25964 (setq lines (org-table-clean-before-export lines)))
25965 ;; Get rid of the vertical lines except for grouping
25966 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25967 rtn line vl1 start)
25968 (while (setq line (pop lines))
25969 (if (string-match org-table-hline-regexp line)
25970 (and (string-match "|\\(.*\\)|" line)
25971 (setq line (replace-match " \\1" t nil line)))
25972 (setq start 0 vl1 vl)
25973 (while (string-match "|" line start)
25974 (setq start (match-end 0))
25975 (or (pop vl1) (setq line (replace-match " " t t line)))))
25976 (push line rtn))
25977 (nreverse rtn))))
25979 (defun org-colgroup-info-to-vline-list (info)
25980 (let (vl new last)
25981 (while info
25982 (setq last new new (pop info))
25983 (if (or (memq last '(:end :startend))
25984 (memq new '(:start :startend)))
25985 (push t vl)
25986 (push nil vl)))
25987 (setq vl (nreverse vl))
25988 (and vl (setcar vl nil))
25989 vl))
25991 (defun org-format-table-html (lines olines)
25992 "Find out which HTML converter to use and return the HTML code."
25993 (if (stringp lines)
25994 (setq lines (org-split-string lines "\n")))
25995 (if (string-match "^[ \t]*|" (car lines))
25996 ;; A normal org table
25997 (org-format-org-table-html lines)
25998 ;; Table made by table.el - test for spanning
25999 (let* ((hlines (delq nil (mapcar
26000 (lambda (x)
26001 (if (string-match "^[ \t]*\\+-" x) x
26002 nil))
26003 lines)))
26004 (first (car hlines))
26005 (ll (and (string-match "\\S-+" first)
26006 (match-string 0 first)))
26007 (re (concat "^[ \t]*" (regexp-quote ll)))
26008 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
26009 hlines))))
26010 (if (and (not spanning)
26011 (not org-export-prefer-native-exporter-for-tables))
26012 ;; We can use my own converter with HTML conversions
26013 (org-format-table-table-html lines)
26014 ;; Need to use the code generator in table.el, with the original text.
26015 (org-format-table-table-html-using-table-generate-source olines)))))
26017 (defun org-format-org-table-html (lines &optional splice)
26018 "Format a table into HTML."
26019 ;; Get rid of hlines at beginning and end
26020 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26021 (setq lines (nreverse lines))
26022 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26023 (setq lines (nreverse lines))
26024 (when org-export-table-remove-special-lines
26025 ;; Check if the table has a marking column. If yes remove the
26026 ;; column and the special lines
26027 (setq lines (org-table-clean-before-export lines)))
26029 (let ((head (and org-export-highlight-first-table-line
26030 (delq nil (mapcar
26031 (lambda (x) (string-match "^[ \t]*|-" x))
26032 (cdr lines)))))
26033 (nlines 0) fnum i
26034 tbopen line fields html gr colgropen)
26035 (if splice (setq head nil))
26036 (unless splice (push (if head "<thead>" "<tbody>") html))
26037 (setq tbopen t)
26038 (while (setq line (pop lines))
26039 (catch 'next-line
26040 (if (string-match "^[ \t]*|-" line)
26041 (progn
26042 (unless splice
26043 (push (if head "</thead>" "</tbody>") html)
26044 (if lines (push "<tbody>" html) (setq tbopen nil)))
26045 (setq head nil) ;; head ends here, first time around
26046 ;; ignore this line
26047 (throw 'next-line t)))
26048 ;; Break the line into fields
26049 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26050 (unless fnum (setq fnum (make-vector (length fields) 0)))
26051 (setq nlines (1+ nlines) i -1)
26052 (push (concat "<tr>"
26053 (mapconcat
26054 (lambda (x)
26055 (setq i (1+ i))
26056 (if (and (< i nlines)
26057 (string-match org-table-number-regexp x))
26058 (incf (aref fnum i)))
26059 (if head
26060 (concat (car org-export-table-header-tags) x
26061 (cdr org-export-table-header-tags))
26062 (concat (car org-export-table-data-tags) x
26063 (cdr org-export-table-data-tags))))
26064 fields "")
26065 "</tr>")
26066 html)))
26067 (unless splice (if tbopen (push "</tbody>" html)))
26068 (unless splice (push "</table>\n" html))
26069 (setq html (nreverse html))
26070 (unless splice
26071 ;; Put in col tags with the alignment (unfortuntely often ignored...)
26072 (push (mapconcat
26073 (lambda (x)
26074 (setq gr (pop org-table-colgroup-info))
26075 (format "%s<col align=\"%s\"></col>%s"
26076 (if (memq gr '(:start :startend))
26077 (prog1
26078 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
26079 (setq colgropen t))
26081 (if (> (/ (float x) nlines) org-table-number-fraction)
26082 "right" "left")
26083 (if (memq gr '(:end :startend))
26084 (progn (setq colgropen nil) "</colgroup>")
26085 "")))
26086 fnum "")
26087 html)
26088 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
26089 (push html-table-tag html))
26090 (concat (mapconcat 'identity html "\n") "\n")))
26092 (defun org-table-clean-before-export (lines)
26093 "Check if the table has a marking column.
26094 If yes remove the column and the special lines."
26095 (setq org-table-colgroup-info nil)
26096 (if (memq nil
26097 (mapcar
26098 (lambda (x) (or (string-match "^[ \t]*|-" x)
26099 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
26100 lines))
26101 (progn
26102 (setq org-table-clean-did-remove-column nil)
26103 (delq nil
26104 (mapcar
26105 (lambda (x)
26106 (cond
26107 ((string-match "^[ \t]*| */ *|" x)
26108 (setq org-table-colgroup-info
26109 (mapcar (lambda (x)
26110 (cond ((member x '("<" "&lt;")) :start)
26111 ((member x '(">" "&gt;")) :end)
26112 ((member x '("<>" "&lt;&gt;")) :startend)
26113 (t nil)))
26114 (org-split-string x "[ \t]*|[ \t]*")))
26115 nil)
26116 (t x)))
26117 lines)))
26118 (setq org-table-clean-did-remove-column t)
26119 (delq nil
26120 (mapcar
26121 (lambda (x)
26122 (cond
26123 ((string-match "^[ \t]*| */ *|" x)
26124 (setq org-table-colgroup-info
26125 (mapcar (lambda (x)
26126 (cond ((member x '("<" "&lt;")) :start)
26127 ((member x '(">" "&gt;")) :end)
26128 ((member x '("<>" "&lt;&gt;")) :startend)
26129 (t nil)))
26130 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
26131 nil)
26132 ((string-match "^[ \t]*| *[!_^/] *|" x)
26133 nil) ; ignore this line
26134 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
26135 (string-match "^\\([ \t]*\\)|[^|]*|" x))
26136 ;; remove the first column
26137 (replace-match "\\1|" t nil x))))
26138 lines))))
26140 (defun org-format-table-table-html (lines)
26141 "Format a table generated by table.el into HTML.
26142 This conversion does *not* use `table-generate-source' from table.el.
26143 This has the advantage that Org-mode's HTML conversions can be used.
26144 But it has the disadvantage, that no cell- or row-spanning is allowed."
26145 (let (line field-buffer
26146 (head org-export-highlight-first-table-line)
26147 fields html empty)
26148 (setq html (concat html-table-tag "\n"))
26149 (while (setq line (pop lines))
26150 (setq empty "&nbsp;")
26151 (catch 'next-line
26152 (if (string-match "^[ \t]*\\+-" line)
26153 (progn
26154 (if field-buffer
26155 (progn
26156 (setq
26157 html
26158 (concat
26159 html
26160 "<tr>"
26161 (mapconcat
26162 (lambda (x)
26163 (if (equal x "") (setq x empty))
26164 (if head
26165 (concat (car org-export-table-header-tags) x
26166 (cdr org-export-table-header-tags))
26167 (concat (car org-export-table-data-tags) x
26168 (cdr org-export-table-data-tags))))
26169 field-buffer "\n")
26170 "</tr>\n"))
26171 (setq head nil)
26172 (setq field-buffer nil)))
26173 ;; Ignore this line
26174 (throw 'next-line t)))
26175 ;; Break the line into fields and store the fields
26176 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26177 (if field-buffer
26178 (setq field-buffer (mapcar
26179 (lambda (x)
26180 (concat x "<br/>" (pop fields)))
26181 field-buffer))
26182 (setq field-buffer fields))))
26183 (setq html (concat html "</table>\n"))
26184 html))
26186 (defun org-format-table-table-html-using-table-generate-source (lines)
26187 "Format a table into html, using `table-generate-source' from table.el.
26188 This has the advantage that cell- or row-spanning is allowed.
26189 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
26190 (require 'table)
26191 (with-current-buffer (get-buffer-create " org-tmp1 ")
26192 (erase-buffer)
26193 (insert (mapconcat 'identity lines "\n"))
26194 (goto-char (point-min))
26195 (if (not (re-search-forward "|[^+]" nil t))
26196 (error "Error processing table"))
26197 (table-recognize-table)
26198 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
26199 (table-generate-source 'html " org-tmp2 ")
26200 (set-buffer " org-tmp2 ")
26201 (buffer-substring (point-min) (point-max))))
26203 (defun org-html-handle-time-stamps (s)
26204 "Format time stamps in string S, or remove them."
26205 (catch 'exit
26206 (let (r b)
26207 (while (string-match org-maybe-keyword-time-regexp s)
26208 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
26209 ;; never export CLOCK
26210 (throw 'exit ""))
26211 (or b (setq b (substring s 0 (match-beginning 0))))
26212 (if (not org-export-with-timestamps)
26213 (setq r (concat r (substring s 0 (match-beginning 0)))
26214 s (substring s (match-end 0)))
26215 (setq r (concat
26216 r (substring s 0 (match-beginning 0))
26217 (if (match-end 1)
26218 (format "@<span class=\"timestamp-kwd\">%s @</span>"
26219 (match-string 1 s)))
26220 (format " @<span class=\"timestamp\">%s@</span>"
26221 (substring
26222 (org-translate-time (match-string 3 s)) 1 -1)))
26223 s (substring s (match-end 0)))))
26224 ;; Line break if line started and ended with time stamp stuff
26225 (if (not r)
26227 (setq r (concat r s))
26228 (unless (string-match "\\S-" (concat b s))
26229 (setq r (concat r "@<br/>")))
26230 r))))
26232 (defun org-html-protect (s)
26233 ;; convert & to &amp;, < to &lt; and > to &gt;
26234 (let ((start 0))
26235 (while (string-match "&" s start)
26236 (setq s (replace-match "&amp;" t t s)
26237 start (1+ (match-beginning 0))))
26238 (while (string-match "<" s)
26239 (setq s (replace-match "&lt;" t t s)))
26240 (while (string-match ">" s)
26241 (setq s (replace-match "&gt;" t t s))))
26244 (defun org-export-cleanup-toc-line (s)
26245 "Remove tags and time staps from lines going into the toc."
26246 (when (memq org-export-with-tags '(not-in-toc nil))
26247 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
26248 (setq s (replace-match "" t t s))))
26249 (when org-export-remove-timestamps-from-toc
26250 (while (string-match org-maybe-keyword-time-regexp s)
26251 (setq s (replace-match "" t t s))))
26252 (while (string-match org-bracket-link-regexp s)
26253 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
26254 t t s)))
26257 (defun org-html-expand (string)
26258 "Prepare STRING for HTML export. Applies all active conversions.
26259 If there are links in the string, don't modify these."
26260 (let* ((re (concat org-bracket-link-regexp "\\|"
26261 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
26262 m s l res)
26263 (while (setq m (string-match re string))
26264 (setq s (substring string 0 m)
26265 l (match-string 0 string)
26266 string (substring string (match-end 0)))
26267 (push (org-html-do-expand s) res)
26268 (push l res))
26269 (push (org-html-do-expand string) res)
26270 (apply 'concat (nreverse res))))
26272 (defun org-html-do-expand (s)
26273 "Apply all active conversions to translate special ASCII to HTML."
26274 (setq s (org-html-protect s))
26275 (if org-export-html-expand
26276 (let ((start 0))
26277 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
26278 (setq s (replace-match "<\\1>" t nil s)))))
26279 (if org-export-with-emphasize
26280 (setq s (org-export-html-convert-emphasize s)))
26281 (if org-export-with-special-strings
26282 (setq s (org-export-html-convert-special-strings s)))
26283 (if org-export-with-sub-superscripts
26284 (setq s (org-export-html-convert-sub-super s)))
26285 (if org-export-with-TeX-macros
26286 (let ((start 0) wd ass)
26287 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26288 (if (get-text-property (match-beginning 0) 'org-protected s)
26289 (setq start (match-end 0))
26290 (setq wd (match-string 1 s))
26291 (if (setq ass (assoc wd org-html-entities))
26292 (setq s (replace-match (or (cdr ass)
26293 (concat "&" (car ass) ";"))
26294 t t s))
26295 (setq start (+ start (length wd))))))))
26298 (defun org-create-multibrace-regexp (left right n)
26299 "Create a regular expression which will match a balanced sexp.
26300 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26301 as single character strings.
26302 The regexp returned will match the entire expression including the
26303 delimiters. It will also define a single group which contains the
26304 match except for the outermost delimiters. The maximum depth of
26305 stacked delimiters is N. Escaping delimiters is not possible."
26306 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26307 (or "\\|")
26308 (re nothing)
26309 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26310 (while (> n 1)
26311 (setq n (1- n)
26312 re (concat re or next)
26313 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26314 (concat left "\\(" re "\\)" right)))
26316 (defvar org-match-substring-regexp
26317 (concat
26318 "\\([^\\]\\)\\([_^]\\)\\("
26319 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26320 "\\|"
26321 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26322 "\\|"
26323 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26324 "The regular expression matching a sub- or superscript.")
26326 (defvar org-match-substring-with-braces-regexp
26327 (concat
26328 "\\([^\\]\\)\\([_^]\\)\\("
26329 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26330 "\\)")
26331 "The regular expression matching a sub- or superscript, forcing braces.")
26333 (defconst org-export-html-special-string-regexps
26334 '(("\\\\-" . "&shy;")
26335 ("---\\([^-]\\)" . "&mdash;\\1")
26336 ("--\\([^-]\\)" . "&ndash;\\1")
26337 ("\\.\\.\\." . "&hellip;"))
26338 "Regular expressions for special string conversion.")
26340 (defun org-export-html-convert-special-strings (string)
26341 "Convert special characters in STRING to HTML."
26342 (let ((all org-export-html-special-string-regexps)
26343 e a re rpl start)
26344 (while (setq a (pop all))
26345 (setq re (car a) rpl (cdr a) start 0)
26346 (while (string-match re string start)
26347 (if (get-text-property (match-beginning 0) 'org-protected string)
26348 (setq start (match-end 0))
26349 (setq string (replace-match rpl t nil string)))))
26350 string))
26352 (defun org-export-html-convert-sub-super (string)
26353 "Convert sub- and superscripts in STRING to HTML."
26354 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26355 (while (string-match org-match-substring-regexp string s)
26356 (cond
26357 ((and requireb (match-end 8)) (setq s (match-end 2)))
26358 ((get-text-property (match-beginning 2) 'org-protected string)
26359 (setq s (match-end 2)))
26361 (setq s (match-end 1)
26362 key (if (string= (match-string 2 string) "_") "sub" "sup")
26363 c (or (match-string 8 string)
26364 (match-string 6 string)
26365 (match-string 5 string))
26366 string (replace-match
26367 (concat (match-string 1 string)
26368 "<" key ">" c "</" key ">")
26369 t t string)))))
26370 (while (string-match "\\\\\\([_^]\\)" string)
26371 (setq string (replace-match (match-string 1 string) t t string)))
26372 string))
26374 (defun org-export-html-convert-emphasize (string)
26375 "Apply emphasis."
26376 (let ((s 0) rpl)
26377 (while (string-match org-emph-re string s)
26378 (if (not (equal
26379 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26380 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26381 (setq s (match-beginning 0)
26383 (concat
26384 (match-string 1 string)
26385 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26386 (match-string 4 string)
26387 (nth 3 (assoc (match-string 3 string)
26388 org-emphasis-alist))
26389 (match-string 5 string))
26390 string (replace-match rpl t t string)
26391 s (+ s (- (length rpl) 2)))
26392 (setq s (1+ s))))
26393 string))
26395 (defvar org-par-open nil)
26396 (defun org-open-par ()
26397 "Insert <p>, but first close previous paragraph if any."
26398 (org-close-par-maybe)
26399 (insert "\n<p>")
26400 (setq org-par-open t))
26401 (defun org-close-par-maybe ()
26402 "Close paragraph if there is one open."
26403 (when org-par-open
26404 (insert "</p>")
26405 (setq org-par-open nil)))
26406 (defun org-close-li ()
26407 "Close <li> if necessary."
26408 (org-close-par-maybe)
26409 (insert "</li>\n"))
26411 (defvar body-only) ; dynamically scoped into this.
26412 (defun org-html-level-start (level title umax with-toc head-count)
26413 "Insert a new level in HTML export.
26414 When TITLE is nil, just close all open levels."
26415 (org-close-par-maybe)
26416 (let ((l org-level-max))
26417 (while (>= l level)
26418 (if (aref org-levels-open (1- l))
26419 (progn
26420 (org-html-level-close l umax)
26421 (aset org-levels-open (1- l) nil)))
26422 (setq l (1- l)))
26423 (when title
26424 ;; If title is nil, this means this function is called to close
26425 ;; all levels, so the rest is done only if title is given
26426 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26427 (setq title (replace-match
26428 (if org-export-with-tags
26429 (save-match-data
26430 (concat
26431 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26432 (mapconcat 'identity (org-split-string
26433 (match-string 1 title) ":")
26434 "&nbsp;")
26435 "</span>"))
26437 t t title)))
26438 (if (> level umax)
26439 (progn
26440 (if (aref org-levels-open (1- level))
26441 (progn
26442 (org-close-li)
26443 (insert "<li>" title "<br/>\n"))
26444 (aset org-levels-open (1- level) t)
26445 (org-close-par-maybe)
26446 (insert "<ul>\n<li>" title "<br/>\n")))
26447 (aset org-levels-open (1- level) t)
26448 (if (and org-export-with-section-numbers (not body-only))
26449 (setq title (concat (org-section-number level) " " title)))
26450 (setq level (+ level org-export-html-toplevel-hlevel -1))
26451 (if with-toc
26452 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26453 level level head-count title level))
26454 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26455 (org-open-par)))))
26457 (defun org-html-level-close (level max-outline-level)
26458 "Terminate one level in HTML export."
26459 (if (<= level max-outline-level)
26460 (insert "</div>\n")
26461 (org-close-li)
26462 (insert "</ul>\n")))
26464 ;;; iCalendar export
26466 ;;;###autoload
26467 (defun org-export-icalendar-this-file ()
26468 "Export current file as an iCalendar file.
26469 The iCalendar file will be located in the same directory as the Org-mode
26470 file, but with extension `.ics'."
26471 (interactive)
26472 (org-export-icalendar nil buffer-file-name))
26474 ;;;###autoload
26475 (defun org-export-icalendar-all-agenda-files ()
26476 "Export all files in `org-agenda-files' to iCalendar .ics files.
26477 Each iCalendar file will be located in the same directory as the Org-mode
26478 file, but with extension `.ics'."
26479 (interactive)
26480 (apply 'org-export-icalendar nil (org-agenda-files t)))
26482 ;;;###autoload
26483 (defun org-export-icalendar-combine-agenda-files ()
26484 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26485 The file is stored under the name `org-combined-agenda-icalendar-file'."
26486 (interactive)
26487 (apply 'org-export-icalendar t (org-agenda-files t)))
26489 (defun org-export-icalendar (combine &rest files)
26490 "Create iCalendar files for all elements of FILES.
26491 If COMBINE is non-nil, combine all calendar entries into a single large
26492 file and store it under the name `org-combined-agenda-icalendar-file'."
26493 (save-excursion
26494 (org-prepare-agenda-buffers files)
26495 (let* ((dir (org-export-directory
26496 :ical (list :publishing-directory
26497 org-export-publishing-directory)))
26498 file ical-file ical-buffer category started org-agenda-new-buffers)
26500 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26501 (when combine
26502 (setq ical-file
26503 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26504 org-combined-agenda-icalendar-file
26505 (expand-file-name org-combined-agenda-icalendar-file dir))
26506 ical-buffer (org-get-agenda-file-buffer ical-file))
26507 (set-buffer ical-buffer) (erase-buffer))
26508 (while (setq file (pop files))
26509 (catch 'nextfile
26510 (org-check-agenda-file file)
26511 (set-buffer (org-get-agenda-file-buffer file))
26512 (unless combine
26513 (setq ical-file (concat (file-name-as-directory dir)
26514 (file-name-sans-extension
26515 (file-name-nondirectory buffer-file-name))
26516 ".ics"))
26517 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26518 (with-current-buffer ical-buffer (erase-buffer)))
26519 (setq category (or org-category
26520 (file-name-sans-extension
26521 (file-name-nondirectory buffer-file-name))))
26522 (if (symbolp category) (setq category (symbol-name category)))
26523 (let ((standard-output ical-buffer))
26524 (if combine
26525 (and (not started) (setq started t)
26526 (org-start-icalendar-file org-icalendar-combined-name))
26527 (org-start-icalendar-file category))
26528 (org-print-icalendar-entries combine)
26529 (when (or (and combine (not files)) (not combine))
26530 (org-finish-icalendar-file)
26531 (set-buffer ical-buffer)
26532 (save-buffer)
26533 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26534 (org-release-buffers org-agenda-new-buffers))))
26536 (defvar org-after-save-iCalendar-file-hook nil
26537 "Hook run after an iCalendar file has been saved.
26538 The iCalendar buffer is still current when this hook is run.
26539 A good way to use this is to tell a desktop calenndar application to re-read
26540 the iCalendar file.")
26542 (defun org-print-icalendar-entries (&optional combine)
26543 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26544 When COMBINE is non nil, add the category to each line."
26545 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26546 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26547 (dts (org-ical-ts-to-string
26548 (format-time-string (cdr org-time-stamp-formats) (current-time))
26549 "DTSTART"))
26550 hd ts ts2 state status (inc t) pos b sexp rrule
26551 scheduledp deadlinep tmp pri category entry location summary desc
26552 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26553 (org-refresh-category-properties)
26554 (save-excursion
26555 (goto-char (point-min))
26556 (while (re-search-forward re1 nil t)
26557 (catch :skip
26558 (org-agenda-skip)
26559 (setq pos (match-beginning 0)
26560 ts (match-string 0)
26561 inc t
26562 hd (org-get-heading)
26563 summary (org-icalendar-cleanup-string
26564 (org-entry-get nil "SUMMARY"))
26565 desc (org-icalendar-cleanup-string
26566 (or (org-entry-get nil "DESCRIPTION")
26567 (and org-icalendar-include-body (org-get-entry)))
26568 t org-icalendar-include-body)
26569 location (org-icalendar-cleanup-string
26570 (org-entry-get nil "LOCATION"))
26571 category (org-get-category))
26572 (if (looking-at re2)
26573 (progn
26574 (goto-char (match-end 0))
26575 (setq ts2 (match-string 1) inc nil))
26576 (setq tmp (buffer-substring (max (point-min)
26577 (- pos org-ds-keyword-length))
26578 pos)
26579 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26580 (progn
26581 (setq inc nil)
26582 (replace-match "\\1" t nil ts))
26584 deadlinep (string-match org-deadline-regexp tmp)
26585 scheduledp (string-match org-scheduled-regexp tmp)
26586 ;; donep (org-entry-is-done-p)
26588 (if (or (string-match org-tr-regexp hd)
26589 (string-match org-ts-regexp hd))
26590 (setq hd (replace-match "" t t hd)))
26591 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26592 (setq rrule
26593 (concat "\nRRULE:FREQ="
26594 (cdr (assoc
26595 (match-string 2 ts)
26596 '(("d" . "DAILY")("w" . "WEEKLY")
26597 ("m" . "MONTHLY")("y" . "YEARLY"))))
26598 ";INTERVAL=" (match-string 1 ts)))
26599 (setq rrule ""))
26600 (setq summary (or summary hd))
26601 (if (string-match org-bracket-link-regexp summary)
26602 (setq summary
26603 (replace-match (if (match-end 3)
26604 (match-string 3 summary)
26605 (match-string 1 summary))
26606 t t summary)))
26607 (if deadlinep (setq summary (concat "DL: " summary)))
26608 (if scheduledp (setq summary (concat "S: " summary)))
26609 (if (string-match "\\`<%%" ts)
26610 (with-current-buffer sexp-buffer
26611 (insert (substring ts 1 -1) " " summary "\n"))
26612 (princ (format "BEGIN:VEVENT
26614 %s%s
26615 SUMMARY:%s%s%s
26616 CATEGORIES:%s
26617 END:VEVENT\n"
26618 (org-ical-ts-to-string ts "DTSTART")
26619 (org-ical-ts-to-string ts2 "DTEND" inc)
26620 rrule summary
26621 (if (and desc (string-match "\\S-" desc))
26622 (concat "\nDESCRIPTION: " desc) "")
26623 (if (and location (string-match "\\S-" location))
26624 (concat "\nLOCATION: " location) "")
26625 category)))))
26627 (when (and org-icalendar-include-sexps
26628 (condition-case nil (require 'icalendar) (error nil))
26629 (fboundp 'icalendar-export-region))
26630 ;; Get all the literal sexps
26631 (goto-char (point-min))
26632 (while (re-search-forward "^&?%%(" nil t)
26633 (catch :skip
26634 (org-agenda-skip)
26635 (setq b (match-beginning 0))
26636 (goto-char (1- (match-end 0)))
26637 (forward-sexp 1)
26638 (end-of-line 1)
26639 (setq sexp (buffer-substring b (point)))
26640 (with-current-buffer sexp-buffer
26641 (insert sexp "\n"))
26642 (princ (org-diary-to-ical-string sexp-buffer)))))
26644 (when org-icalendar-include-todo
26645 (goto-char (point-min))
26646 (while (re-search-forward org-todo-line-regexp nil t)
26647 (catch :skip
26648 (org-agenda-skip)
26649 (setq state (match-string 2))
26650 (setq status (if (member state org-done-keywords)
26651 "COMPLETED" "NEEDS-ACTION"))
26652 (when (and state
26653 (or (not (member state org-done-keywords))
26654 (eq org-icalendar-include-todo 'all))
26655 (not (member org-archive-tag (org-get-tags-at)))
26657 (setq hd (match-string 3)
26658 summary (org-icalendar-cleanup-string
26659 (org-entry-get nil "SUMMARY"))
26660 desc (org-icalendar-cleanup-string
26661 (or (org-entry-get nil "DESCRIPTION")
26662 (and org-icalendar-include-body (org-get-entry)))
26663 t org-icalendar-include-body)
26664 location (org-icalendar-cleanup-string
26665 (org-entry-get nil "LOCATION")))
26666 (if (string-match org-bracket-link-regexp hd)
26667 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26668 (match-string 1 hd))
26669 t t hd)))
26670 (if (string-match org-priority-regexp hd)
26671 (setq pri (string-to-char (match-string 2 hd))
26672 hd (concat (substring hd 0 (match-beginning 1))
26673 (substring hd (match-end 1))))
26674 (setq pri org-default-priority))
26675 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26676 (- org-lowest-priority org-highest-priority))))))
26678 (princ (format "BEGIN:VTODO
26680 SUMMARY:%s%s%s
26681 CATEGORIES:%s
26682 SEQUENCE:1
26683 PRIORITY:%d
26684 STATUS:%s
26685 END:VTODO\n"
26687 (or summary hd)
26688 (if (and location (string-match "\\S-" location))
26689 (concat "\nLOCATION: " location) "")
26690 (if (and desc (string-match "\\S-" desc))
26691 (concat "\nDESCRIPTION: " desc) "")
26692 category pri status)))))))))
26694 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26695 "Take out stuff and quote what needs to be quoted.
26696 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26697 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26698 characters."
26699 (if (not s)
26701 (when is-body
26702 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26703 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26704 (while (string-match re s) (setq s (replace-match "" t t s)))
26705 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26706 (let ((start 0))
26707 (while (string-match "\\([,;\\]\\)" s start)
26708 (setq start (+ (match-beginning 0) 2)
26709 s (replace-match "\\\\\\1" nil nil s))))
26710 (when is-body
26711 (while (string-match "[ \t]*\n[ \t]*" s)
26712 (setq s (replace-match "\\n" t t s))))
26713 (setq s (org-trim s))
26714 (if is-body
26715 (if maxlength
26716 (if (and (numberp maxlength)
26717 (> (length s) maxlength))
26718 (setq s (substring s 0 maxlength)))))
26721 (defun org-get-entry ()
26722 "Clean-up description string."
26723 (save-excursion
26724 (org-back-to-heading t)
26725 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26727 (defun org-start-icalendar-file (name)
26728 "Start an iCalendar file by inserting the header."
26729 (let ((user user-full-name)
26730 (name (or name "unknown"))
26731 (timezone (cadr (current-time-zone))))
26732 (princ
26733 (format "BEGIN:VCALENDAR
26734 VERSION:2.0
26735 X-WR-CALNAME:%s
26736 PRODID:-//%s//Emacs with Org-mode//EN
26737 X-WR-TIMEZONE:%s
26738 CALSCALE:GREGORIAN\n" name user timezone))))
26740 (defun org-finish-icalendar-file ()
26741 "Finish an iCalendar file by inserting the END statement."
26742 (princ "END:VCALENDAR\n"))
26744 (defun org-ical-ts-to-string (s keyword &optional inc)
26745 "Take a time string S and convert it to iCalendar format.
26746 KEYWORD is added in front, to make a complete line like DTSTART....
26747 When INC is non-nil, increase the hour by two (if time string contains
26748 a time), or the day by one (if it does not contain a time)."
26749 (let ((t1 (org-parse-time-string s 'nodefault))
26750 t2 fmt have-time time)
26751 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26752 (setq t2 t1 have-time t)
26753 (setq t2 (org-parse-time-string s)))
26754 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26755 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26756 (when inc
26757 (if have-time
26758 (if org-agenda-default-appointment-duration
26759 (setq mi (+ org-agenda-default-appointment-duration mi))
26760 (setq h (+ 2 h)))
26761 (setq d (1+ d))))
26762 (setq time (encode-time s mi h d m y)))
26763 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26764 (concat keyword (format-time-string fmt time))))
26766 ;;; XOXO export
26768 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26769 (with-current-buffer buffer
26770 (apply 'insert output)))
26771 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26773 (defun org-export-as-xoxo (&optional buffer)
26774 "Export the org buffer as XOXO.
26775 The XOXO buffer is named *xoxo-<source buffer name>*"
26776 (interactive (list (current-buffer)))
26777 ;; A quickie abstraction
26779 ;; Output everything as XOXO
26780 (with-current-buffer (get-buffer buffer)
26781 (let* ((pos (point))
26782 (opt-plist (org-combine-plists (org-default-export-plist)
26783 (org-infile-export-plist)))
26784 (filename (concat (file-name-as-directory
26785 (org-export-directory :xoxo opt-plist))
26786 (file-name-sans-extension
26787 (file-name-nondirectory buffer-file-name))
26788 ".html"))
26789 (out (find-file-noselect filename))
26790 (last-level 1)
26791 (hanging-li nil))
26792 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26793 ;; Check the output buffer is empty.
26794 (with-current-buffer out (erase-buffer))
26795 ;; Kick off the output
26796 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26797 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26798 (let* ((hd (match-string-no-properties 1))
26799 (level (length hd))
26800 (text (concat
26801 (match-string-no-properties 2)
26802 (save-excursion
26803 (goto-char (match-end 0))
26804 (let ((str ""))
26805 (catch 'loop
26806 (while 't
26807 (forward-line)
26808 (if (looking-at "^[ \t]\\(.*\\)")
26809 (setq str (concat str (match-string-no-properties 1)))
26810 (throw 'loop str)))))))))
26812 ;; Handle level rendering
26813 (cond
26814 ((> level last-level)
26815 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26817 ((< level last-level)
26818 (dotimes (- (- last-level level) 1)
26819 (if hanging-li
26820 (org-export-as-xoxo-insert-into out "</li>\n"))
26821 (org-export-as-xoxo-insert-into out "</ol>\n"))
26822 (when hanging-li
26823 (org-export-as-xoxo-insert-into out "</li>\n")
26824 (setq hanging-li nil)))
26826 ((equal level last-level)
26827 (if hanging-li
26828 (org-export-as-xoxo-insert-into out "</li>\n")))
26831 (setq last-level level)
26833 ;; And output the new li
26834 (setq hanging-li 't)
26835 (if (equal ?+ (elt text 0))
26836 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26837 (org-export-as-xoxo-insert-into out "<li>" text))))
26839 ;; Finally finish off the ol
26840 (dotimes (- last-level 1)
26841 (if hanging-li
26842 (org-export-as-xoxo-insert-into out "</li>\n"))
26843 (org-export-as-xoxo-insert-into out "</ol>\n"))
26845 (goto-char pos)
26846 ;; Finish the buffer off and clean it up.
26847 (switch-to-buffer-other-window out)
26848 (indent-region (point-min) (point-max) nil)
26849 (save-buffer)
26850 (goto-char (point-min))
26854 ;;;; Key bindings
26856 ;; Make `C-c C-x' a prefix key
26857 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26859 ;; TAB key with modifiers
26860 (org-defkey org-mode-map "\C-i" 'org-cycle)
26861 (org-defkey org-mode-map [(tab)] 'org-cycle)
26862 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26863 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26864 (org-defkey org-mode-map "\M-\t" 'org-complete)
26865 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26866 ;; The following line is necessary under Suse GNU/Linux
26867 (unless (featurep 'xemacs)
26868 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26869 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26870 (define-key org-mode-map [backtab] 'org-shifttab)
26872 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26873 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26874 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26876 ;; Cursor keys with modifiers
26877 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26878 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26879 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26880 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26882 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26883 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26884 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26885 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26887 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26888 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26889 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26890 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26892 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26893 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26895 ;;; Extra keys for tty access.
26896 ;; We only set them when really needed because otherwise the
26897 ;; menus don't show the simple keys
26899 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26900 (not window-system))
26901 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26902 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26903 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26904 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26905 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26906 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26907 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26908 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26909 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26910 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26911 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26912 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26913 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26914 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26915 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26916 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26917 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26918 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26919 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26920 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26921 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26922 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26924 ;; All the other keys
26926 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26927 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26928 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26929 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26930 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26931 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26932 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26933 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26934 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26935 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26936 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26937 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26938 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26939 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26940 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26941 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26942 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26943 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26944 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26945 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26946 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26947 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26948 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26949 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26950 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26951 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26952 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26953 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26954 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26955 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26956 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26957 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26958 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26959 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26960 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26961 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26962 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26963 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26964 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26965 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
26966 (org-defkey org-mode-map "\C-c^" 'org-sort)
26967 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26968 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26969 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26970 (org-defkey org-mode-map "\C-m" 'org-return)
26971 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26972 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26973 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26974 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26975 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26976 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26977 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26978 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26979 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26980 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26981 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26982 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26983 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26984 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26985 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26986 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26988 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26989 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26990 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26991 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26993 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26994 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26995 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26996 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26997 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26998 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26999 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
27000 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
27001 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
27002 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
27003 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
27004 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
27006 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
27008 (when (featurep 'xemacs)
27009 (org-defkey org-mode-map 'button3 'popup-mode-menu))
27011 (defsubst org-table-p () (org-at-table-p))
27013 (defun org-self-insert-command (N)
27014 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
27015 If the cursor is in a table looking at whitespace, the whitespace is
27016 overwritten, and the table is not marked as requiring realignment."
27017 (interactive "p")
27018 (if (and (org-table-p)
27019 (progn
27020 ;; check if we blank the field, and if that triggers align
27021 (and org-table-auto-blank-field
27022 (member last-command
27023 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
27024 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
27025 ;; got extra space, this field does not determine column width
27026 (let (org-table-may-need-update) (org-table-blank-field))
27027 ;; no extra space, this field may determine column width
27028 (org-table-blank-field)))
27030 (eq N 1)
27031 (looking-at "[^|\n]* |"))
27032 (let (org-table-may-need-update)
27033 (goto-char (1- (match-end 0)))
27034 (delete-backward-char 1)
27035 (goto-char (match-beginning 0))
27036 (self-insert-command N))
27037 (setq org-table-may-need-update t)
27038 (self-insert-command N)
27039 (org-fix-tags-on-the-fly)))
27041 (defun org-fix-tags-on-the-fly ()
27042 (when (and (equal (char-after (point-at-bol)) ?*)
27043 (org-on-heading-p))
27044 (org-align-tags-here org-tags-column)))
27046 (defun org-delete-backward-char (N)
27047 "Like `delete-backward-char', insert whitespace at field end in tables.
27048 When deleting backwards, in tables this function will insert whitespace in
27049 front of the next \"|\" separator, to keep the table aligned. The table will
27050 still be marked for re-alignment if the field did fill the entire column,
27051 because, in this case the deletion might narrow the column."
27052 (interactive "p")
27053 (if (and (org-table-p)
27054 (eq N 1)
27055 (string-match "|" (buffer-substring (point-at-bol) (point)))
27056 (looking-at ".*?|"))
27057 (let ((pos (point))
27058 (noalign (looking-at "[^|\n\r]* |"))
27059 (c org-table-may-need-update))
27060 (backward-delete-char N)
27061 (skip-chars-forward "^|")
27062 (insert " ")
27063 (goto-char (1- pos))
27064 ;; noalign: if there were two spaces at the end, this field
27065 ;; does not determine the width of the column.
27066 (if noalign (setq org-table-may-need-update c)))
27067 (backward-delete-char N)
27068 (org-fix-tags-on-the-fly)))
27070 (defun org-delete-char (N)
27071 "Like `delete-char', but insert whitespace at field end in tables.
27072 When deleting characters, in tables this function will insert whitespace in
27073 front of the next \"|\" separator, to keep the table aligned. The table will
27074 still be marked for re-alignment if the field did fill the entire column,
27075 because, in this case the deletion might narrow the column."
27076 (interactive "p")
27077 (if (and (org-table-p)
27078 (not (bolp))
27079 (not (= (char-after) ?|))
27080 (eq N 1))
27081 (if (looking-at ".*?|")
27082 (let ((pos (point))
27083 (noalign (looking-at "[^|\n\r]* |"))
27084 (c org-table-may-need-update))
27085 (replace-match (concat
27086 (substring (match-string 0) 1 -1)
27087 " |"))
27088 (goto-char pos)
27089 ;; noalign: if there were two spaces at the end, this field
27090 ;; does not determine the width of the column.
27091 (if noalign (setq org-table-may-need-update c)))
27092 (delete-char N))
27093 (delete-char N)
27094 (org-fix-tags-on-the-fly)))
27096 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
27097 (put 'org-self-insert-command 'delete-selection t)
27098 (put 'orgtbl-self-insert-command 'delete-selection t)
27099 (put 'org-delete-char 'delete-selection 'supersede)
27100 (put 'org-delete-backward-char 'delete-selection 'supersede)
27102 ;; Make `flyspell-mode' delay after some commands
27103 (put 'org-self-insert-command 'flyspell-delayed t)
27104 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
27105 (put 'org-delete-char 'flyspell-delayed t)
27106 (put 'org-delete-backward-char 'flyspell-delayed t)
27108 ;; Make pabbrev-mode expand after org-mode commands
27109 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
27110 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
27112 ;; How to do this: Measure non-white length of current string
27113 ;; If equal to column width, we should realign.
27115 (defun org-remap (map &rest commands)
27116 "In MAP, remap the functions given in COMMANDS.
27117 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
27118 (let (new old)
27119 (while commands
27120 (setq old (pop commands) new (pop commands))
27121 (if (fboundp 'command-remapping)
27122 (org-defkey map (vector 'remap old) new)
27123 (substitute-key-definition old new map global-map)))))
27125 (when (eq org-enable-table-editor 'optimized)
27126 ;; If the user wants maximum table support, we need to hijack
27127 ;; some standard editing functions
27128 (org-remap org-mode-map
27129 'self-insert-command 'org-self-insert-command
27130 'delete-char 'org-delete-char
27131 'delete-backward-char 'org-delete-backward-char)
27132 (org-defkey org-mode-map "|" 'org-force-self-insert))
27134 (defun org-shiftcursor-error ()
27135 "Throw an error because Shift-Cursor command was applied in wrong context."
27136 (error "This command is active in special context like tables, headlines or timestamps"))
27138 (defun org-shifttab (&optional arg)
27139 "Global visibility cycling or move to previous table field.
27140 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
27141 on context.
27142 See the individual commands for more information."
27143 (interactive "P")
27144 (cond
27145 ((org-at-table-p) (call-interactively 'org-table-previous-field))
27146 (arg (message "Content view to level: ")
27147 (org-content (prefix-numeric-value arg))
27148 (setq org-cycle-global-status 'overview))
27149 (t (call-interactively 'org-global-cycle))))
27151 (defun org-shiftmetaleft ()
27152 "Promote subtree or delete table column.
27153 Calls `org-promote-subtree', `org-outdent-item',
27154 or `org-table-delete-column', depending on context.
27155 See the individual commands for more information."
27156 (interactive)
27157 (cond
27158 ((org-at-table-p) (call-interactively 'org-table-delete-column))
27159 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
27160 ((org-at-item-p) (call-interactively 'org-outdent-item))
27161 (t (org-shiftcursor-error))))
27163 (defun org-shiftmetaright ()
27164 "Demote subtree or insert table column.
27165 Calls `org-demote-subtree', `org-indent-item',
27166 or `org-table-insert-column', depending on context.
27167 See the individual commands for more information."
27168 (interactive)
27169 (cond
27170 ((org-at-table-p) (call-interactively 'org-table-insert-column))
27171 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
27172 ((org-at-item-p) (call-interactively 'org-indent-item))
27173 (t (org-shiftcursor-error))))
27175 (defun org-shiftmetaup (&optional arg)
27176 "Move subtree up or kill table row.
27177 Calls `org-move-subtree-up' or `org-table-kill-row' or
27178 `org-move-item-up' depending on context. See the individual commands
27179 for more information."
27180 (interactive "P")
27181 (cond
27182 ((org-at-table-p) (call-interactively 'org-table-kill-row))
27183 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27184 ((org-at-item-p) (call-interactively 'org-move-item-up))
27185 (t (org-shiftcursor-error))))
27186 (defun org-shiftmetadown (&optional arg)
27187 "Move subtree down or insert table row.
27188 Calls `org-move-subtree-down' or `org-table-insert-row' or
27189 `org-move-item-down', depending on context. See the individual
27190 commands for more information."
27191 (interactive "P")
27192 (cond
27193 ((org-at-table-p) (call-interactively 'org-table-insert-row))
27194 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27195 ((org-at-item-p) (call-interactively 'org-move-item-down))
27196 (t (org-shiftcursor-error))))
27198 (defun org-metaleft (&optional arg)
27199 "Promote heading or move table column to left.
27200 Calls `org-do-promote' or `org-table-move-column', depending on context.
27201 With no specific context, calls the Emacs default `backward-word'.
27202 See the individual commands for more information."
27203 (interactive "P")
27204 (cond
27205 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
27206 ((or (org-on-heading-p) (org-region-active-p))
27207 (call-interactively 'org-do-promote))
27208 ((org-at-item-p) (call-interactively 'org-outdent-item))
27209 (t (call-interactively 'backward-word))))
27211 (defun org-metaright (&optional arg)
27212 "Demote subtree or move table column to right.
27213 Calls `org-do-demote' or `org-table-move-column', depending on context.
27214 With no specific context, calls the Emacs default `forward-word'.
27215 See the individual commands for more information."
27216 (interactive "P")
27217 (cond
27218 ((org-at-table-p) (call-interactively 'org-table-move-column))
27219 ((or (org-on-heading-p) (org-region-active-p))
27220 (call-interactively 'org-do-demote))
27221 ((org-at-item-p) (call-interactively 'org-indent-item))
27222 (t (call-interactively 'forward-word))))
27224 (defun org-metaup (&optional arg)
27225 "Move subtree up or move table row up.
27226 Calls `org-move-subtree-up' or `org-table-move-row' or
27227 `org-move-item-up', depending on context. See the individual commands
27228 for more information."
27229 (interactive "P")
27230 (cond
27231 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
27232 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27233 ((org-at-item-p) (call-interactively 'org-move-item-up))
27234 (t (transpose-lines 1) (beginning-of-line -1))))
27236 (defun org-metadown (&optional arg)
27237 "Move subtree down or move table row down.
27238 Calls `org-move-subtree-down' or `org-table-move-row' or
27239 `org-move-item-down', depending on context. See the individual
27240 commands for more information."
27241 (interactive "P")
27242 (cond
27243 ((org-at-table-p) (call-interactively 'org-table-move-row))
27244 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27245 ((org-at-item-p) (call-interactively 'org-move-item-down))
27246 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
27248 (defun org-shiftup (&optional arg)
27249 "Increase item in timestamp or increase priority of current headline.
27250 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
27251 depending on context. See the individual commands for more information."
27252 (interactive "P")
27253 (cond
27254 ((org-at-timestamp-p t)
27255 (call-interactively (if org-edit-timestamp-down-means-later
27256 'org-timestamp-down 'org-timestamp-up)))
27257 ((org-on-heading-p) (call-interactively 'org-priority-up))
27258 ((org-at-item-p) (call-interactively 'org-previous-item))
27259 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
27261 (defun org-shiftdown (&optional arg)
27262 "Decrease item in timestamp or decrease priority of current headline.
27263 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
27264 depending on context. See the individual commands for more information."
27265 (interactive "P")
27266 (cond
27267 ((org-at-timestamp-p t)
27268 (call-interactively (if org-edit-timestamp-down-means-later
27269 'org-timestamp-up 'org-timestamp-down)))
27270 ((org-on-heading-p) (call-interactively 'org-priority-down))
27271 (t (call-interactively 'org-next-item))))
27273 (defun org-shiftright ()
27274 "Next TODO keyword or timestamp one day later, depending on context."
27275 (interactive)
27276 (cond
27277 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
27278 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
27279 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
27280 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
27281 (t (org-shiftcursor-error))))
27283 (defun org-shiftleft ()
27284 "Previous TODO keyword or timestamp one day earlier, depending on context."
27285 (interactive)
27286 (cond
27287 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27288 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27289 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27290 ((org-at-property-p)
27291 (call-interactively 'org-property-previous-allowed-value))
27292 (t (org-shiftcursor-error))))
27294 (defun org-shiftcontrolright ()
27295 "Switch to next TODO set."
27296 (interactive)
27297 (cond
27298 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27299 (t (org-shiftcursor-error))))
27301 (defun org-shiftcontrolleft ()
27302 "Switch to previous TODO set."
27303 (interactive)
27304 (cond
27305 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27306 (t (org-shiftcursor-error))))
27308 (defun org-ctrl-c-ret ()
27309 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27310 (interactive)
27311 (cond
27312 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27313 (t (call-interactively 'org-insert-heading))))
27315 (defun org-copy-special ()
27316 "Copy region in table or copy current subtree.
27317 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27318 See the individual commands for more information."
27319 (interactive)
27320 (call-interactively
27321 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27323 (defun org-cut-special ()
27324 "Cut region in table or cut current subtree.
27325 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27326 See the individual commands for more information."
27327 (interactive)
27328 (call-interactively
27329 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27331 (defun org-paste-special (arg)
27332 "Paste rectangular region into table, or past subtree relative to level.
27333 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27334 See the individual commands for more information."
27335 (interactive "P")
27336 (if (org-at-table-p)
27337 (org-table-paste-rectangle)
27338 (org-paste-subtree arg)))
27340 (defun org-ctrl-c-ctrl-c (&optional arg)
27341 "Set tags in headline, or update according to changed information at point.
27343 This command does many different things, depending on context:
27345 - If the cursor is in a headline, prompt for tags and insert them
27346 into the current line, aligned to `org-tags-column'. When called
27347 with prefix arg, realign all tags in the current buffer.
27349 - If the cursor is in one of the special #+KEYWORD lines, this
27350 triggers scanning the buffer for these lines and updating the
27351 information.
27353 - If the cursor is inside a table, realign the table. This command
27354 works even if the automatic table editor has been turned off.
27356 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27357 the entire table.
27359 - If the cursor is a the beginning of a dynamic block, update it.
27361 - If the cursor is inside a table created by the table.el package,
27362 activate that table.
27364 - If the current buffer is a remember buffer, close note and file it.
27365 with a prefix argument, file it without further interaction to the default
27366 location.
27368 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27369 links in this buffer.
27371 - If the cursor is on a numbered item in a plain list, renumber the
27372 ordered list.
27374 - If the cursor is on a checkbox, toggle it."
27375 (interactive "P")
27376 (let ((org-enable-table-editor t))
27377 (cond
27378 ((or org-clock-overlays
27379 org-occur-highlights
27380 org-latex-fragment-image-overlays)
27381 (org-remove-clock-overlays)
27382 (org-remove-occur-highlights)
27383 (org-remove-latex-fragment-image-overlays)
27384 (message "Temporary highlights/overlays removed from current buffer"))
27385 ((and (local-variable-p 'org-finish-function (current-buffer))
27386 (fboundp org-finish-function))
27387 (funcall org-finish-function))
27388 ((org-at-property-p)
27389 (call-interactively 'org-property-action))
27390 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27391 ((org-on-heading-p) (call-interactively 'org-set-tags))
27392 ((org-at-table.el-p)
27393 (require 'table)
27394 (beginning-of-line 1)
27395 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27396 (call-interactively 'table-recognize-table))
27397 ((org-at-table-p)
27398 (org-table-maybe-eval-formula)
27399 (if arg
27400 (call-interactively 'org-table-recalculate)
27401 (org-table-maybe-recalculate-line))
27402 (call-interactively 'org-table-align))
27403 ((org-at-item-checkbox-p)
27404 (call-interactively 'org-toggle-checkbox))
27405 ((org-at-item-p)
27406 (call-interactively 'org-maybe-renumber-ordered-list))
27407 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27408 ;; Dynamic block
27409 (beginning-of-line 1)
27410 (org-update-dblock))
27411 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27412 (cond
27413 ((equal (match-string 1) "TBLFM")
27414 ;; Recalculate the table before this line
27415 (save-excursion
27416 (beginning-of-line 1)
27417 (skip-chars-backward " \r\n\t")
27418 (if (org-at-table-p)
27419 (org-call-with-arg 'org-table-recalculate t))))
27421 (call-interactively 'org-mode-restart))))
27422 (t (error "C-c C-c can do nothing useful at this location.")))))
27424 (defun org-mode-restart ()
27425 "Restart Org-mode, to scan again for special lines.
27426 Also updates the keyword regular expressions."
27427 (interactive)
27428 (let ((org-inhibit-startup t)) (org-mode))
27429 (message "Org-mode restarted to refresh keyword and special line setup"))
27431 (defun org-kill-note-or-show-branches ()
27432 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27433 (interactive)
27434 (if (not org-finish-function)
27435 (call-interactively 'show-branches)
27436 (let ((org-note-abort t))
27437 (funcall org-finish-function))))
27439 (defun org-return (&optional indent)
27440 "Goto next table row or insert a newline.
27441 Calls `org-table-next-row' or `newline', depending on context.
27442 See the individual commands for more information."
27443 (interactive)
27444 (cond
27445 ((bobp) (if indent (newline-and-indent) (newline)))
27446 ((and (org-at-heading-p)
27447 (looking-at
27448 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27449 (org-show-entry)
27450 (end-of-line 1)
27451 (newline))
27452 ((org-at-table-p)
27453 (org-table-justify-field-maybe)
27454 (call-interactively 'org-table-next-row))
27455 (t (if indent (newline-and-indent) (newline)))))
27457 (defun org-return-indent ()
27458 "Goto next table row or insert a newline and indent.
27459 Calls `org-table-next-row' or `newline-and-indent', depending on
27460 context. See the individual commands for more information."
27461 (interactive)
27462 (org-return t))
27464 (defun org-ctrl-c-star ()
27465 "Compute table, or change heading status of lines.
27466 Calls `org-table-recalculate' or `org-toggle-region-headlines',
27467 depending on context. This will also turn a plain list item or a normal
27468 line into a subheading."
27469 (interactive)
27470 (cond
27471 ((org-at-table-p)
27472 (call-interactively 'org-table-recalculate))
27473 ((org-region-active-p)
27474 ;; Convert all lines in region to list items
27475 (call-interactively 'org-toggle-region-headings))
27476 ((org-on-heading-p)
27477 (org-toggle-region-headings (point-at-bol)
27478 (min (1+ (point-at-eol)) (point-max))))
27479 ((org-at-item-p)
27480 ;; Convert to heading
27481 ;; FIXME: not yet implemented
27483 (t (org-toggle-region-headings (point-at-bol)
27484 (min (1+ (point-at-eol)) (point-max))))))
27486 (defun org-ctrl-c-minus ()
27487 "Insert separator line in table or modify bullet status of line.
27488 Also turns a plain line or a region of lines into list items.
27489 Calls `org-table-insert-hline', `org-toggle-region-items', or
27490 `org-cycle-list-bullet', depending on context."
27491 (interactive)
27492 (cond
27493 ((org-at-table-p)
27494 (call-interactively 'org-table-insert-hline))
27495 ((org-on-heading-p)
27496 ;; Convert to item
27497 (save-excursion
27498 (beginning-of-line 1)
27499 (if (looking-at "\\*+ ")
27500 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
27501 ((org-region-active-p)
27502 ;; Convert all lines in region to list items
27503 (call-interactively 'org-toggle-region-items))
27504 ((org-in-item-p)
27505 (call-interactively 'org-cycle-list-bullet))
27506 (t (org-toggle-region-items (point-at-bol)
27507 (min (1+ (point-at-eol)) (point-max))))))
27509 (defun org-toggle-region-items (beg end)
27510 "Convert all lines in region to list items.
27511 If the first line is already an item, convert all list items in the region
27512 to normal lines."
27513 (interactive "r")
27514 (let (l2 l)
27515 (save-excursion
27516 (goto-char end)
27517 (setq l2 (org-current-line))
27518 (goto-char beg)
27519 (beginning-of-line 1)
27520 (setq l (1- (org-current-line)))
27521 (if (org-at-item-p)
27522 ;; We already have items, de-itemize
27523 (while (< (setq l (1+ l)) l2)
27524 (when (org-at-item-p)
27525 (goto-char (match-beginning 2))
27526 (delete-region (match-beginning 2) (match-end 2))
27527 (and (looking-at "[ \t]+") (replace-match "")))
27528 (beginning-of-line 2))
27529 (while (< (setq l (1+ l)) l2)
27530 (unless (org-at-item-p)
27531 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27532 (replace-match "\\1- \\2")))
27533 (beginning-of-line 2))))))
27535 (defun org-toggle-region-headings (beg end)
27536 "Convert all lines in region to list items.
27537 If the first line is already an item, convert all list items in the region
27538 to normal lines."
27539 (interactive "r")
27540 (let (l2 l)
27541 (save-excursion
27542 (goto-char end)
27543 (setq l2 (org-current-line))
27544 (goto-char beg)
27545 (beginning-of-line 1)
27546 (setq l (1- (org-current-line)))
27547 (if (org-on-heading-p)
27548 ;; We already have headlines, de-star them
27549 (while (< (setq l (1+ l)) l2)
27550 (when (org-on-heading-p t)
27551 (and (looking-at outline-regexp) (replace-match "")))
27552 (beginning-of-line 2))
27553 (let* ((stars (save-excursion
27554 (re-search-backward org-complex-heading-regexp nil t)
27555 (or (match-string 1) "*")))
27556 (add-stars (if org-odd-levels-only "**" "*"))
27557 (rpl (concat stars add-stars " \\2")))
27558 (while (< (setq l (1+ l)) l2)
27559 (unless (org-on-heading-p)
27560 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27561 (replace-match rpl)))
27562 (beginning-of-line 2)))))))
27564 (defun org-meta-return (&optional arg)
27565 "Insert a new heading or wrap a region in a table.
27566 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27567 See the individual commands for more information."
27568 (interactive "P")
27569 (cond
27570 ((org-at-table-p)
27571 (call-interactively 'org-table-wrap-region))
27572 (t (call-interactively 'org-insert-heading))))
27574 ;;; Menu entries
27576 ;; Define the Org-mode menus
27577 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27578 '("Tbl"
27579 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27580 ["Next Field" org-cycle (org-at-table-p)]
27581 ["Previous Field" org-shifttab (org-at-table-p)]
27582 ["Next Row" org-return (org-at-table-p)]
27583 "--"
27584 ["Blank Field" org-table-blank-field (org-at-table-p)]
27585 ["Edit Field" org-table-edit-field (org-at-table-p)]
27586 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27587 "--"
27588 ("Column"
27589 ["Move Column Left" org-metaleft (org-at-table-p)]
27590 ["Move Column Right" org-metaright (org-at-table-p)]
27591 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27592 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27593 ("Row"
27594 ["Move Row Up" org-metaup (org-at-table-p)]
27595 ["Move Row Down" org-metadown (org-at-table-p)]
27596 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27597 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27598 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27599 "--"
27600 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27601 ("Rectangle"
27602 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27603 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27604 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27605 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27606 "--"
27607 ("Calculate"
27608 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27609 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27610 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27611 "--"
27612 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27613 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27614 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27615 "--"
27616 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27617 "--"
27618 ["Sum Column/Rectangle" org-table-sum
27619 (or (org-at-table-p) (org-region-active-p))]
27620 ["Which Column?" org-table-current-column (org-at-table-p)])
27621 ["Debug Formulas"
27622 org-table-toggle-formula-debugger
27623 :style toggle :selected org-table-formula-debug]
27624 ["Show Col/Row Numbers"
27625 org-table-toggle-coordinate-overlays
27626 :style toggle :selected org-table-overlay-coordinates]
27627 "--"
27628 ["Create" org-table-create (and (not (org-at-table-p))
27629 org-enable-table-editor)]
27630 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27631 ["Import from File" org-table-import (not (org-at-table-p))]
27632 ["Export to File" org-table-export (org-at-table-p)]
27633 "--"
27634 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27636 (easy-menu-define org-org-menu org-mode-map "Org menu"
27637 '("Org"
27638 ("Show/Hide"
27639 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27640 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27641 ["Sparse Tree" org-occur t]
27642 ["Reveal Context" org-reveal t]
27643 ["Show All" show-all t]
27644 "--"
27645 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27646 "--"
27647 ["New Heading" org-insert-heading t]
27648 ("Navigate Headings"
27649 ["Up" outline-up-heading t]
27650 ["Next" outline-next-visible-heading t]
27651 ["Previous" outline-previous-visible-heading t]
27652 ["Next Same Level" outline-forward-same-level t]
27653 ["Previous Same Level" outline-backward-same-level t]
27654 "--"
27655 ["Jump" org-goto t])
27656 ("Edit Structure"
27657 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27658 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27659 "--"
27660 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27661 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27662 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27663 "--"
27664 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27665 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27666 ["Demote Heading" org-metaright (not (org-at-table-p))]
27667 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27668 "--"
27669 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27670 "--"
27671 ["Convert to odd levels" org-convert-to-odd-levels t]
27672 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27673 ("Editing"
27674 ["Emphasis..." org-emphasize t])
27675 ("Archive"
27676 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27677 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27678 ; :active t :keys "C-u C-c C-x C-a"]
27679 ["Sparse trees open ARCHIVE trees"
27680 (setq org-sparse-tree-open-archived-trees
27681 (not org-sparse-tree-open-archived-trees))
27682 :style toggle :selected org-sparse-tree-open-archived-trees]
27683 ["Cycling opens ARCHIVE trees"
27684 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27685 :style toggle :selected org-cycle-open-archived-trees]
27686 ["Agenda includes ARCHIVE trees"
27687 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27688 :style toggle :selected (not org-agenda-skip-archived-trees)]
27689 "--"
27690 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27691 ; ["Check and Move Children" (org-archive-subtree '(4))
27692 ; :active t :keys "C-u C-c C-x C-s"]
27694 "--"
27695 ("TODO Lists"
27696 ["TODO/DONE/-" org-todo t]
27697 ("Select keyword"
27698 ["Next keyword" org-shiftright (org-on-heading-p)]
27699 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27700 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27701 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27702 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27703 ["Show TODO Tree" org-show-todo-tree t]
27704 ["Global TODO list" org-todo-list t]
27705 "--"
27706 ["Set Priority" org-priority t]
27707 ["Priority Up" org-shiftup t]
27708 ["Priority Down" org-shiftdown t])
27709 ("TAGS and Properties"
27710 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27711 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27712 "--"
27713 ["Set property" 'org-set-property t]
27714 ["Column view of properties" org-columns t]
27715 ["Insert Column View DBlock" org-insert-columns-dblock t])
27716 ("Dates and Scheduling"
27717 ["Timestamp" org-time-stamp t]
27718 ["Timestamp (inactive)" org-time-stamp-inactive t]
27719 ("Change Date"
27720 ["1 Day Later" org-shiftright t]
27721 ["1 Day Earlier" org-shiftleft t]
27722 ["1 ... Later" org-shiftup t]
27723 ["1 ... Earlier" org-shiftdown t])
27724 ["Compute Time Range" org-evaluate-time-range t]
27725 ["Schedule Item" org-schedule t]
27726 ["Deadline" org-deadline t]
27727 "--"
27728 ["Custom time format" org-toggle-time-stamp-overlays
27729 :style radio :selected org-display-custom-times]
27730 "--"
27731 ["Goto Calendar" org-goto-calendar t]
27732 ["Date from Calendar" org-date-from-calendar t])
27733 ("Logging work"
27734 ["Clock in" org-clock-in t]
27735 ["Clock out" org-clock-out t]
27736 ["Clock cancel" org-clock-cancel t]
27737 ["Goto running clock" org-clock-goto t]
27738 ["Display times" org-clock-display t]
27739 ["Create clock table" org-clock-report t]
27740 "--"
27741 ["Record DONE time"
27742 (progn (setq org-log-done (not org-log-done))
27743 (message "Switching to %s will %s record a timestamp"
27744 (car org-done-keywords)
27745 (if org-log-done "automatically" "not")))
27746 :style toggle :selected org-log-done])
27747 "--"
27748 ["Agenda Command..." org-agenda t]
27749 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27750 ("File List for Agenda")
27751 ("Special views current file"
27752 ["TODO Tree" org-show-todo-tree t]
27753 ["Check Deadlines" org-check-deadlines t]
27754 ["Timeline" org-timeline t]
27755 ["Tags Tree" org-tags-sparse-tree t])
27756 "--"
27757 ("Hyperlinks"
27758 ["Store Link (Global)" org-store-link t]
27759 ["Insert Link" org-insert-link t]
27760 ["Follow Link" org-open-at-point t]
27761 "--"
27762 ["Next link" org-next-link t]
27763 ["Previous link" org-previous-link t]
27764 "--"
27765 ["Descriptive Links"
27766 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27767 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27768 ["Literal Links"
27769 (progn
27770 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27771 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27772 "--"
27773 ["Export/Publish..." org-export t]
27774 ("LaTeX"
27775 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27776 :selected org-cdlatex-mode]
27777 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27778 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27779 ["Modify math symbol" org-cdlatex-math-modify
27780 (org-inside-LaTeX-fragment-p)]
27781 ["Export LaTeX fragments as images"
27782 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27783 :style toggle :selected org-export-with-LaTeX-fragments])
27784 "--"
27785 ("Documentation"
27786 ["Show Version" org-version t]
27787 ["Info Documentation" org-info t])
27788 ("Customize"
27789 ["Browse Org Group" org-customize t]
27790 "--"
27791 ["Expand This Menu" org-create-customize-menu
27792 (fboundp 'customize-menu-create)])
27793 "--"
27794 ["Refresh setup" org-mode-restart t]
27797 (defun org-info (&optional node)
27798 "Read documentation for Org-mode in the info system.
27799 With optional NODE, go directly to that node."
27800 (interactive)
27801 (require 'info)
27802 (info (format "(org)%s" (or node ""))))
27804 (defun org-install-agenda-files-menu ()
27805 (let ((bl (buffer-list)))
27806 (save-excursion
27807 (while bl
27808 (set-buffer (pop bl))
27809 (if (org-mode-p) (setq bl nil)))
27810 (when (org-mode-p)
27811 (easy-menu-change
27812 '("Org") "File List for Agenda"
27813 (append
27814 (list
27815 ["Edit File List" (org-edit-agenda-file-list) t]
27816 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27817 ["Remove Current File from List" org-remove-file t]
27818 ["Cycle through agenda files" org-cycle-agenda-files t]
27819 ["Occur in all agenda files" org-occur-in-agenda-files t]
27820 "--")
27821 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27823 ;;;; Documentation
27825 (defun org-customize ()
27826 "Call the customize function with org as argument."
27827 (interactive)
27828 (customize-browse 'org))
27830 (defun org-create-customize-menu ()
27831 "Create a full customization menu for Org-mode, insert it into the menu."
27832 (interactive)
27833 (if (fboundp 'customize-menu-create)
27834 (progn
27835 (easy-menu-change
27836 '("Org") "Customize"
27837 `(["Browse Org group" org-customize t]
27838 "--"
27839 ,(customize-menu-create 'org)
27840 ["Set" Custom-set t]
27841 ["Save" Custom-save t]
27842 ["Reset to Current" Custom-reset-current t]
27843 ["Reset to Saved" Custom-reset-saved t]
27844 ["Reset to Standard Settings" Custom-reset-standard t]))
27845 (message "\"Org\"-menu now contains full customization menu"))
27846 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27848 ;;;; Miscellaneous stuff
27851 ;;; Generally useful functions
27853 (defun org-context ()
27854 "Return a list of contexts of the current cursor position.
27855 If several contexts apply, all are returned.
27856 Each context entry is a list with a symbol naming the context, and
27857 two positions indicating start and end of the context. Possible
27858 contexts are:
27860 :headline anywhere in a headline
27861 :headline-stars on the leading stars in a headline
27862 :todo-keyword on a TODO keyword (including DONE) in a headline
27863 :tags on the TAGS in a headline
27864 :priority on the priority cookie in a headline
27865 :item on the first line of a plain list item
27866 :item-bullet on the bullet/number of a plain list item
27867 :checkbox on the checkbox in a plain list item
27868 :table in an org-mode table
27869 :table-special on a special filed in a table
27870 :table-table in a table.el table
27871 :link on a hyperlink
27872 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27873 :target on a <<target>>
27874 :radio-target on a <<<radio-target>>>
27875 :latex-fragment on a LaTeX fragment
27876 :latex-preview on a LaTeX fragment with overlayed preview image
27878 This function expects the position to be visible because it uses font-lock
27879 faces as a help to recognize the following contexts: :table-special, :link,
27880 and :keyword."
27881 (let* ((f (get-text-property (point) 'face))
27882 (faces (if (listp f) f (list f)))
27883 (p (point)) clist o)
27884 ;; First the large context
27885 (cond
27886 ((org-on-heading-p t)
27887 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27888 (when (progn
27889 (beginning-of-line 1)
27890 (looking-at org-todo-line-tags-regexp))
27891 (push (org-point-in-group p 1 :headline-stars) clist)
27892 (push (org-point-in-group p 2 :todo-keyword) clist)
27893 (push (org-point-in-group p 4 :tags) clist))
27894 (goto-char p)
27895 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27896 (if (looking-at "\\[#[A-Z0-9]\\]")
27897 (push (org-point-in-group p 0 :priority) clist)))
27899 ((org-at-item-p)
27900 (push (org-point-in-group p 2 :item-bullet) clist)
27901 (push (list :item (point-at-bol)
27902 (save-excursion (org-end-of-item) (point)))
27903 clist)
27904 (and (org-at-item-checkbox-p)
27905 (push (org-point-in-group p 0 :checkbox) clist)))
27907 ((org-at-table-p)
27908 (push (list :table (org-table-begin) (org-table-end)) clist)
27909 (if (memq 'org-formula faces)
27910 (push (list :table-special
27911 (previous-single-property-change p 'face)
27912 (next-single-property-change p 'face)) clist)))
27913 ((org-at-table-p 'any)
27914 (push (list :table-table) clist)))
27915 (goto-char p)
27917 ;; Now the small context
27918 (cond
27919 ((org-at-timestamp-p)
27920 (push (org-point-in-group p 0 :timestamp) clist))
27921 ((memq 'org-link faces)
27922 (push (list :link
27923 (previous-single-property-change p 'face)
27924 (next-single-property-change p 'face)) clist))
27925 ((memq 'org-special-keyword faces)
27926 (push (list :keyword
27927 (previous-single-property-change p 'face)
27928 (next-single-property-change p 'face)) clist))
27929 ((org-on-target-p)
27930 (push (org-point-in-group p 0 :target) clist)
27931 (goto-char (1- (match-beginning 0)))
27932 (if (looking-at org-radio-target-regexp)
27933 (push (org-point-in-group p 0 :radio-target) clist))
27934 (goto-char p))
27935 ((setq o (car (delq nil
27936 (mapcar
27937 (lambda (x)
27938 (if (memq x org-latex-fragment-image-overlays) x))
27939 (org-overlays-at (point))))))
27940 (push (list :latex-fragment
27941 (org-overlay-start o) (org-overlay-end o)) clist)
27942 (push (list :latex-preview
27943 (org-overlay-start o) (org-overlay-end o)) clist))
27944 ((org-inside-LaTeX-fragment-p)
27945 ;; FIXME: positions wrong.
27946 (push (list :latex-fragment (point) (point)) clist)))
27948 (setq clist (nreverse (delq nil clist)))
27949 clist))
27951 ;; FIXME: Compare with at-regexp-p Do we need both?
27952 (defun org-in-regexp (re &optional nlines visually)
27953 "Check if point is inside a match of regexp.
27954 Normally only the current line is checked, but you can include NLINES extra
27955 lines both before and after point into the search.
27956 If VISUALLY is set, require that the cursor is not after the match but
27957 really on, so that the block visually is on the match."
27958 (catch 'exit
27959 (let ((pos (point))
27960 (eol (point-at-eol (+ 1 (or nlines 0))))
27961 (inc (if visually 1 0)))
27962 (save-excursion
27963 (beginning-of-line (- 1 (or nlines 0)))
27964 (while (re-search-forward re eol t)
27965 (if (and (<= (match-beginning 0) pos)
27966 (>= (+ inc (match-end 0)) pos))
27967 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27969 (defun org-at-regexp-p (regexp)
27970 "Is point inside a match of REGEXP in the current line?"
27971 (catch 'exit
27972 (save-excursion
27973 (let ((pos (point)) (end (point-at-eol)))
27974 (beginning-of-line 1)
27975 (while (re-search-forward regexp end t)
27976 (if (and (<= (match-beginning 0) pos)
27977 (>= (match-end 0) pos))
27978 (throw 'exit t)))
27979 nil))))
27981 (defun org-occur-in-agenda-files (regexp &optional nlines)
27982 "Call `multi-occur' with buffers for all agenda files."
27983 (interactive "sOrg-files matching: \np")
27984 (let* ((files (org-agenda-files))
27985 (tnames (mapcar 'file-truename files))
27986 (extra org-agenda-text-search-extra-files)
27988 (while (setq f (pop extra))
27989 (unless (member (file-truename f) tnames)
27990 (add-to-list 'files f 'append)
27991 (add-to-list 'tnames (file-truename f) 'append)))
27992 (multi-occur
27993 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27994 regexp)))
27996 (if (boundp 'occur-mode-find-occurrence-hook)
27997 ;; Emacs 23
27998 (add-hook 'occur-mode-find-occurrence-hook
27999 (lambda ()
28000 (when (org-mode-p)
28001 (org-reveal))))
28002 ;; Emacs 22
28003 (defadvice occur-mode-goto-occurrence
28004 (after org-occur-reveal activate)
28005 (and (org-mode-p) (org-reveal)))
28006 (defadvice occur-mode-goto-occurrence-other-window
28007 (after org-occur-reveal activate)
28008 (and (org-mode-p) (org-reveal)))
28009 (defadvice occur-mode-display-occurrence
28010 (after org-occur-reveal activate)
28011 (when (org-mode-p)
28012 (let ((pos (occur-mode-find-occurrence)))
28013 (with-current-buffer (marker-buffer pos)
28014 (save-excursion
28015 (goto-char pos)
28016 (org-reveal)))))))
28018 (defun org-uniquify (list)
28019 "Remove duplicate elements from LIST."
28020 (let (res)
28021 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
28022 res))
28024 (defun org-delete-all (elts list)
28025 "Remove all elements in ELTS from LIST."
28026 (while elts
28027 (setq list (delete (pop elts) list)))
28028 list)
28030 (defun org-back-over-empty-lines ()
28031 "Move backwards over witespace, to the beginning of the first empty line.
28032 Returns the number o empty lines passed."
28033 (let ((pos (point)))
28034 (skip-chars-backward " \t\n\r")
28035 (beginning-of-line 2)
28036 (goto-char (min (point) pos))
28037 (count-lines (point) pos)))
28039 (defun org-skip-whitespace ()
28040 (skip-chars-forward " \t\n\r"))
28042 (defun org-point-in-group (point group &optional context)
28043 "Check if POINT is in match-group GROUP.
28044 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
28045 match. If the match group does ot exist or point is not inside it,
28046 return nil."
28047 (and (match-beginning group)
28048 (>= point (match-beginning group))
28049 (<= point (match-end group))
28050 (if context
28051 (list context (match-beginning group) (match-end group))
28052 t)))
28054 (defun org-switch-to-buffer-other-window (&rest args)
28055 "Switch to buffer in a second window on the current frame.
28056 In particular, do not allow pop-up frames."
28057 (let (pop-up-frames special-display-buffer-names special-display-regexps
28058 special-display-function)
28059 (apply 'switch-to-buffer-other-window args)))
28061 (defun org-combine-plists (&rest plists)
28062 "Create a single property list from all plists in PLISTS.
28063 The process starts by copying the first list, and then setting properties
28064 from the other lists. Settings in the last list are the most significant
28065 ones and overrule settings in the other lists."
28066 (let ((rtn (copy-sequence (pop plists)))
28067 p v ls)
28068 (while plists
28069 (setq ls (pop plists))
28070 (while ls
28071 (setq p (pop ls) v (pop ls))
28072 (setq rtn (plist-put rtn p v))))
28073 rtn))
28075 (defun org-move-line-down (arg)
28076 "Move the current line down. With prefix argument, move it past ARG lines."
28077 (interactive "p")
28078 (let ((col (current-column))
28079 beg end pos)
28080 (beginning-of-line 1) (setq beg (point))
28081 (beginning-of-line 2) (setq end (point))
28082 (beginning-of-line (+ 1 arg))
28083 (setq pos (move-marker (make-marker) (point)))
28084 (insert (delete-and-extract-region beg end))
28085 (goto-char pos)
28086 (move-to-column col)))
28088 (defun org-move-line-up (arg)
28089 "Move the current line up. With prefix argument, move it past ARG lines."
28090 (interactive "p")
28091 (let ((col (current-column))
28092 beg end pos)
28093 (beginning-of-line 1) (setq beg (point))
28094 (beginning-of-line 2) (setq end (point))
28095 (beginning-of-line (- arg))
28096 (setq pos (move-marker (make-marker) (point)))
28097 (insert (delete-and-extract-region beg end))
28098 (goto-char pos)
28099 (move-to-column col)))
28101 (defun org-replace-escapes (string table)
28102 "Replace %-escapes in STRING with values in TABLE.
28103 TABLE is an association list with keys like \"%a\" and string values.
28104 The sequences in STRING may contain normal field width and padding information,
28105 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
28106 so values can contain further %-escapes if they are define later in TABLE."
28107 (let ((case-fold-search nil)
28108 e re rpl)
28109 (while (setq e (pop table))
28110 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
28111 (while (string-match re string)
28112 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
28113 (cdr e)))
28114 (setq string (replace-match rpl t t string))))
28115 string))
28118 (defun org-sublist (list start end)
28119 "Return a section of LIST, from START to END.
28120 Counting starts at 1."
28121 (let (rtn (c start))
28122 (setq list (nthcdr (1- start) list))
28123 (while (and list (<= c end))
28124 (push (pop list) rtn)
28125 (setq c (1+ c)))
28126 (nreverse rtn)))
28128 (defun org-find-base-buffer-visiting (file)
28129 "Like `find-buffer-visiting' but alway return the base buffer and
28130 not an indirect buffer"
28131 (let ((buf (find-buffer-visiting file)))
28132 (if buf
28133 (or (buffer-base-buffer buf) buf)
28134 nil)))
28136 (defun org-image-file-name-regexp ()
28137 "Return regexp matching the file names of images."
28138 (if (fboundp 'image-file-name-regexp)
28139 (image-file-name-regexp)
28140 (let ((image-file-name-extensions
28141 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
28142 "xbm" "xpm" "pbm" "pgm" "ppm")))
28143 (concat "\\."
28144 (regexp-opt (nconc (mapcar 'upcase
28145 image-file-name-extensions)
28146 image-file-name-extensions)
28148 "\\'"))))
28150 (defun org-file-image-p (file)
28151 "Return non-nil if FILE is an image."
28152 (save-match-data
28153 (string-match (org-image-file-name-regexp) file)))
28155 ;;; Paragraph filling stuff.
28156 ;; We want this to be just right, so use the full arsenal.
28158 (defun org-indent-line-function ()
28159 "Indent line like previous, but further if previous was headline or item."
28160 (interactive)
28161 (let* ((pos (point))
28162 (itemp (org-at-item-p))
28163 column bpos bcol tpos tcol bullet btype bullet-type)
28164 ;; Find the previous relevant line
28165 (beginning-of-line 1)
28166 (cond
28167 ((looking-at "#") (setq column 0))
28168 ((looking-at "\\*+ ") (setq column 0))
28170 (beginning-of-line 0)
28171 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
28172 (beginning-of-line 0))
28173 (cond
28174 ((looking-at "\\*+[ \t]+")
28175 (goto-char (match-end 0))
28176 (setq column (current-column)))
28177 ((org-in-item-p)
28178 (org-beginning-of-item)
28179 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28180 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
28181 (setq bpos (match-beginning 1) tpos (match-end 0)
28182 bcol (progn (goto-char bpos) (current-column))
28183 tcol (progn (goto-char tpos) (current-column))
28184 bullet (match-string 1)
28185 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
28186 (if (not itemp)
28187 (setq column tcol)
28188 (goto-char pos)
28189 (beginning-of-line 1)
28190 (if (looking-at "\\S-")
28191 (progn
28192 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28193 (setq bullet (match-string 1)
28194 btype (if (string-match "[0-9]" bullet) "n" bullet))
28195 (setq column (if (equal btype bullet-type) bcol tcol)))
28196 (setq column (org-get-indentation)))))
28197 (t (setq column (org-get-indentation))))))
28198 (goto-char pos)
28199 (if (<= (current-column) (current-indentation))
28200 (indent-line-to column)
28201 (save-excursion (indent-line-to column)))
28202 (setq column (current-column))
28203 (beginning-of-line 1)
28204 (if (looking-at
28205 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
28206 (replace-match (concat "\\1" (format org-property-format
28207 (match-string 2) (match-string 3)))
28208 t nil))
28209 (move-to-column column)))
28211 (defun org-set-autofill-regexps ()
28212 (interactive)
28213 ;; In the paragraph separator we include headlines, because filling
28214 ;; text in a line directly attached to a headline would otherwise
28215 ;; fill the headline as well.
28216 (org-set-local 'comment-start-skip "^#+[ \t]*")
28217 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
28218 ;; The paragraph starter includes hand-formatted lists.
28219 (org-set-local 'paragraph-start
28220 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
28221 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
28222 ;; But only if the user has not turned off tables or fixed-width regions
28223 (org-set-local
28224 'auto-fill-inhibit-regexp
28225 (concat "\\*+ \\|#\\+"
28226 "\\|[ \t]*" org-keyword-time-regexp
28227 (if (or org-enable-table-editor org-enable-fixed-width-editor)
28228 (concat
28229 "\\|[ \t]*["
28230 (if org-enable-table-editor "|" "")
28231 (if org-enable-fixed-width-editor ":" "")
28232 "]"))))
28233 ;; We use our own fill-paragraph function, to make sure that tables
28234 ;; and fixed-width regions are not wrapped. That function will pass
28235 ;; through to `fill-paragraph' when appropriate.
28236 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
28237 ; Adaptive filling: To get full control, first make sure that
28238 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
28239 (org-set-local 'adaptive-fill-regexp "\000")
28240 (org-set-local 'adaptive-fill-function
28241 'org-adaptive-fill-function)
28242 (org-set-local
28243 'align-mode-rules-list
28244 '((org-in-buffer-settings
28245 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
28246 (modes . '(org-mode))))))
28248 (defun org-fill-paragraph (&optional justify)
28249 "Re-align a table, pass through to fill-paragraph if no table."
28250 (let ((table-p (org-at-table-p))
28251 (table.el-p (org-at-table.el-p)))
28252 (cond ((and (equal (char-after (point-at-bol)) ?*)
28253 (save-excursion (goto-char (point-at-bol))
28254 (looking-at outline-regexp)))
28255 t) ; skip headlines
28256 (table.el-p t) ; skip table.el tables
28257 (table-p (org-table-align) t) ; align org-mode tables
28258 (t nil)))) ; call paragraph-fill
28260 ;; For reference, this is the default value of adaptive-fill-regexp
28261 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
28263 (defun org-adaptive-fill-function ()
28264 "Return a fill prefix for org-mode files.
28265 In particular, this makes sure hanging paragraphs for hand-formatted lists
28266 work correctly."
28267 (cond ((looking-at "#[ \t]+")
28268 (match-string 0))
28269 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
28270 (save-excursion
28271 (goto-char (match-end 0))
28272 (make-string (current-column) ?\ )))
28273 (t nil)))
28275 ;;;; Functions extending outline functionality
28278 (defun org-beginning-of-line (&optional arg)
28279 "Go to the beginning of the current line. If that is invisible, continue
28280 to a visible line beginning. This makes the function of C-a more intuitive.
28281 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28282 first attempt, and only move to after the tags when the cursor is already
28283 beyond the end of the headline."
28284 (interactive "P")
28285 (let ((pos (point)))
28286 (beginning-of-line 1)
28287 (if (bobp)
28289 (backward-char 1)
28290 (if (org-invisible-p)
28291 (while (and (not (bobp)) (org-invisible-p))
28292 (backward-char 1)
28293 (beginning-of-line 1))
28294 (forward-char 1)))
28295 (when org-special-ctrl-a/e
28296 (cond
28297 ((and (looking-at org-todo-line-regexp)
28298 (= (char-after (match-end 1)) ?\ ))
28299 (goto-char
28300 (if (eq org-special-ctrl-a/e t)
28301 (cond ((> pos (match-beginning 3)) (match-beginning 3))
28302 ((= pos (point)) (match-beginning 3))
28303 (t (point)))
28304 (cond ((> pos (point)) (point))
28305 ((not (eq last-command this-command)) (point))
28306 (t (match-beginning 3))))))
28307 ((org-at-item-p)
28308 (goto-char
28309 (if (eq org-special-ctrl-a/e t)
28310 (cond ((> pos (match-end 4)) (match-end 4))
28311 ((= pos (point)) (match-end 4))
28312 (t (point)))
28313 (cond ((> pos (point)) (point))
28314 ((not (eq last-command this-command)) (point))
28315 (t (match-end 4))))))))))
28317 (defun org-end-of-line (&optional arg)
28318 "Go to the end of the line.
28319 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28320 first attempt, and only move to after the tags when the cursor is already
28321 beyond the end of the headline."
28322 (interactive "P")
28323 (if (or (not org-special-ctrl-a/e)
28324 (not (org-on-heading-p)))
28325 (end-of-line arg)
28326 (let ((pos (point)))
28327 (beginning-of-line 1)
28328 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
28329 (if (eq org-special-ctrl-a/e t)
28330 (if (or (< pos (match-beginning 1))
28331 (= pos (match-end 0)))
28332 (goto-char (match-beginning 1))
28333 (goto-char (match-end 0)))
28334 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
28335 (goto-char (match-end 0))
28336 (goto-char (match-beginning 1))))
28337 (end-of-line arg)))))
28339 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
28340 (define-key org-mode-map "\C-e" 'org-end-of-line)
28342 (defun org-kill-line (&optional arg)
28343 "Kill line, to tags or end of line."
28344 (interactive "P")
28345 (cond
28346 ((or (not org-special-ctrl-k)
28347 (bolp)
28348 (not (org-on-heading-p)))
28349 (call-interactively 'kill-line))
28350 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
28351 (kill-region (point) (match-beginning 1))
28352 (org-set-tags nil t))
28353 (t (kill-region (point) (point-at-eol)))))
28355 (define-key org-mode-map "\C-k" 'org-kill-line)
28357 (defun org-invisible-p ()
28358 "Check if point is at a character currently not visible."
28359 ;; Early versions of noutline don't have `outline-invisible-p'.
28360 (if (fboundp 'outline-invisible-p)
28361 (outline-invisible-p)
28362 (get-char-property (point) 'invisible)))
28364 (defun org-invisible-p2 ()
28365 "Check if point is at a character currently not visible."
28366 (save-excursion
28367 (if (and (eolp) (not (bobp))) (backward-char 1))
28368 ;; Early versions of noutline don't have `outline-invisible-p'.
28369 (if (fboundp 'outline-invisible-p)
28370 (outline-invisible-p)
28371 (get-char-property (point) 'invisible))))
28373 (defalias 'org-back-to-heading 'outline-back-to-heading)
28374 (defalias 'org-on-heading-p 'outline-on-heading-p)
28375 (defalias 'org-at-heading-p 'outline-on-heading-p)
28376 (defun org-at-heading-or-item-p ()
28377 (or (org-on-heading-p) (org-at-item-p)))
28379 (defun org-on-target-p ()
28380 (or (org-in-regexp org-radio-target-regexp)
28381 (org-in-regexp org-target-regexp)))
28383 (defun org-up-heading-all (arg)
28384 "Move to the heading line of which the present line is a subheading.
28385 This function considers both visible and invisible heading lines.
28386 With argument, move up ARG levels."
28387 (if (fboundp 'outline-up-heading-all)
28388 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28389 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28391 (defun org-up-heading-safe ()
28392 "Move to the heading line of which the present line is a subheading.
28393 This version will not throw an error. It will return the level of the
28394 headline found, or nil if no higher level is found."
28395 (let ((pos (point)) start-level level
28396 (re (concat "^" outline-regexp)))
28397 (catch 'exit
28398 (outline-back-to-heading t)
28399 (setq start-level (funcall outline-level))
28400 (if (equal start-level 1) (throw 'exit nil))
28401 (while (re-search-backward re nil t)
28402 (setq level (funcall outline-level))
28403 (if (< level start-level) (throw 'exit level)))
28404 nil)))
28406 (defun org-first-sibling-p ()
28407 "Is this heading the first child of its parents?"
28408 (interactive)
28409 (let ((re (concat "^" outline-regexp))
28410 level l)
28411 (unless (org-at-heading-p t)
28412 (error "Not at a heading"))
28413 (setq level (funcall outline-level))
28414 (save-excursion
28415 (if (not (re-search-backward re nil t))
28417 (setq l (funcall outline-level))
28418 (< l level)))))
28420 (defun org-goto-sibling (&optional previous)
28421 "Goto the next sibling, even if it is invisible.
28422 When PREVIOUS is set, go to the previous sibling instead. Returns t
28423 when a sibling was found. When none is found, return nil and don't
28424 move point."
28425 (let ((fun (if previous 're-search-backward 're-search-forward))
28426 (pos (point))
28427 (re (concat "^" outline-regexp))
28428 level l)
28429 (when (condition-case nil (org-back-to-heading t) (error nil))
28430 (setq level (funcall outline-level))
28431 (catch 'exit
28432 (or previous (forward-char 1))
28433 (while (funcall fun re nil t)
28434 (setq l (funcall outline-level))
28435 (when (< l level) (goto-char pos) (throw 'exit nil))
28436 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28437 (goto-char pos)
28438 nil))))
28440 (defun org-show-siblings ()
28441 "Show all siblings of the current headline."
28442 (save-excursion
28443 (while (org-goto-sibling) (org-flag-heading nil)))
28444 (save-excursion
28445 (while (org-goto-sibling 'previous)
28446 (org-flag-heading nil))))
28448 (defun org-show-hidden-entry ()
28449 "Show an entry where even the heading is hidden."
28450 (save-excursion
28451 (org-show-entry)))
28453 (defun org-flag-heading (flag &optional entry)
28454 "Flag the current heading. FLAG non-nil means make invisible.
28455 When ENTRY is non-nil, show the entire entry."
28456 (save-excursion
28457 (org-back-to-heading t)
28458 ;; Check if we should show the entire entry
28459 (if entry
28460 (progn
28461 (org-show-entry)
28462 (save-excursion
28463 (and (outline-next-heading)
28464 (org-flag-heading nil))))
28465 (outline-flag-region (max (point-min) (1- (point)))
28466 (save-excursion (outline-end-of-heading) (point))
28467 flag))))
28469 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28470 ;; This is an exact copy of the original function, but it uses
28471 ;; `org-back-to-heading', to make it work also in invisible
28472 ;; trees. And is uses an invisible-OK argument.
28473 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28474 (org-back-to-heading invisible-OK)
28475 (let ((first t)
28476 (level (funcall outline-level)))
28477 (while (and (not (eobp))
28478 (or first (> (funcall outline-level) level)))
28479 (setq first nil)
28480 (outline-next-heading))
28481 (unless to-heading
28482 (if (memq (preceding-char) '(?\n ?\^M))
28483 (progn
28484 ;; Go to end of line before heading
28485 (forward-char -1)
28486 (if (memq (preceding-char) '(?\n ?\^M))
28487 ;; leave blank line before heading
28488 (forward-char -1))))))
28489 (point))
28491 (defun org-show-subtree ()
28492 "Show everything after this heading at deeper levels."
28493 (outline-flag-region
28494 (point)
28495 (save-excursion
28496 (outline-end-of-subtree) (outline-next-heading) (point))
28497 nil))
28499 (defun org-show-entry ()
28500 "Show the body directly following this heading.
28501 Show the heading too, if it is currently invisible."
28502 (interactive)
28503 (save-excursion
28504 (condition-case nil
28505 (progn
28506 (org-back-to-heading t)
28507 (outline-flag-region
28508 (max (point-min) (1- (point)))
28509 (save-excursion
28510 (re-search-forward
28511 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28512 (or (match-beginning 1) (point-max)))
28513 nil))
28514 (error nil))))
28516 (defun org-make-options-regexp (kwds)
28517 "Make a regular expression for keyword lines."
28518 (concat
28520 "#?[ \t]*\\+\\("
28521 (mapconcat 'regexp-quote kwds "\\|")
28522 "\\):[ \t]*"
28523 "\\(.+\\)"))
28525 ;; Make isearch reveal the necessary context
28526 (defun org-isearch-end ()
28527 "Reveal context after isearch exits."
28528 (when isearch-success ; only if search was successful
28529 (if (featurep 'xemacs)
28530 ;; Under XEmacs, the hook is run in the correct place,
28531 ;; we directly show the context.
28532 (org-show-context 'isearch)
28533 ;; In Emacs the hook runs *before* restoring the overlays.
28534 ;; So we have to use a one-time post-command-hook to do this.
28535 ;; (Emacs 22 has a special variable, see function `org-mode')
28536 (unless (and (boundp 'isearch-mode-end-hook-quit)
28537 isearch-mode-end-hook-quit)
28538 ;; Only when the isearch was not quitted.
28539 (org-add-hook 'post-command-hook 'org-isearch-post-command
28540 'append 'local)))))
28542 (defun org-isearch-post-command ()
28543 "Remove self from hook, and show context."
28544 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28545 (org-show-context 'isearch))
28548 ;;;; Integration with and fixes for other packages
28550 ;;; Imenu support
28552 (defvar org-imenu-markers nil
28553 "All markers currently used by Imenu.")
28554 (make-variable-buffer-local 'org-imenu-markers)
28556 (defun org-imenu-new-marker (&optional pos)
28557 "Return a new marker for use by Imenu, and remember the marker."
28558 (let ((m (make-marker)))
28559 (move-marker m (or pos (point)))
28560 (push m org-imenu-markers)
28563 (defun org-imenu-get-tree ()
28564 "Produce the index for Imenu."
28565 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28566 (setq org-imenu-markers nil)
28567 (let* ((n org-imenu-depth)
28568 (re (concat "^" outline-regexp))
28569 (subs (make-vector (1+ n) nil))
28570 (last-level 0)
28571 m tree level head)
28572 (save-excursion
28573 (save-restriction
28574 (widen)
28575 (goto-char (point-max))
28576 (while (re-search-backward re nil t)
28577 (setq level (org-reduced-level (funcall outline-level)))
28578 (when (<= level n)
28579 (looking-at org-complex-heading-regexp)
28580 (setq head (org-match-string-no-properties 4)
28581 m (org-imenu-new-marker))
28582 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28583 (if (>= level last-level)
28584 (push (cons head m) (aref subs level))
28585 (push (cons head (aref subs (1+ level))) (aref subs level))
28586 (loop for i from (1+ level) to n do (aset subs i nil)))
28587 (setq last-level level)))))
28588 (aref subs 1)))
28590 (eval-after-load "imenu"
28591 '(progn
28592 (add-hook 'imenu-after-jump-hook
28593 (lambda () (org-show-context 'org-goto)))))
28595 ;; Speedbar support
28597 (defun org-speedbar-set-agenda-restriction ()
28598 "Restrict future agenda commands to the location at point in speedbar.
28599 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28600 (interactive)
28601 (let (p m tp np dir txt w)
28602 (cond
28603 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28604 'org-imenu t))
28605 (setq m (get-text-property p 'org-imenu-marker))
28606 (save-excursion
28607 (save-restriction
28608 (set-buffer (marker-buffer m))
28609 (goto-char m)
28610 (org-agenda-set-restriction-lock 'subtree))))
28611 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28612 'speedbar-function 'speedbar-find-file))
28613 (setq tp (previous-single-property-change
28614 (1+ p) 'speedbar-function)
28615 np (next-single-property-change
28616 tp 'speedbar-function)
28617 dir (speedbar-line-directory)
28618 txt (buffer-substring-no-properties (or tp (point-min))
28619 (or np (point-max))))
28620 (save-excursion
28621 (save-restriction
28622 (set-buffer (find-file-noselect
28623 (let ((default-directory dir))
28624 (expand-file-name txt))))
28625 (unless (org-mode-p)
28626 (error "Cannot restrict to non-Org-mode file"))
28627 (org-agenda-set-restriction-lock 'file))))
28628 (t (error "Don't know how to restrict Org-mode's agenda")))
28629 (org-move-overlay org-speedbar-restriction-lock-overlay
28630 (point-at-bol) (point-at-eol))
28631 (setq current-prefix-arg nil)
28632 (org-agenda-maybe-redo)))
28634 (eval-after-load "speedbar"
28635 '(progn
28636 (speedbar-add-supported-extension ".org")
28637 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28638 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28639 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28640 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28641 (add-hook 'speedbar-visiting-tag-hook
28642 (lambda () (org-show-context 'org-goto)))))
28645 ;;; Fixes and Hacks
28647 ;; Make flyspell not check words in links, to not mess up our keymap
28648 (defun org-mode-flyspell-verify ()
28649 "Don't let flyspell put overlays at active buttons."
28650 (not (get-text-property (point) 'keymap)))
28652 ;; Make `bookmark-jump' show the jump location if it was hidden.
28653 (eval-after-load "bookmark"
28654 '(if (boundp 'bookmark-after-jump-hook)
28655 ;; We can use the hook
28656 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28657 ;; Hook not available, use advice
28658 (defadvice bookmark-jump (after org-make-visible activate)
28659 "Make the position visible."
28660 (org-bookmark-jump-unhide))))
28662 (defun org-bookmark-jump-unhide ()
28663 "Unhide the current position, to show the bookmark location."
28664 (and (org-mode-p)
28665 (or (org-invisible-p)
28666 (save-excursion (goto-char (max (point-min) (1- (point))))
28667 (org-invisible-p)))
28668 (org-show-context 'bookmark-jump)))
28670 ;; Fix a bug in htmlize where there are text properties (face nil)
28671 (eval-after-load "htmlize"
28672 '(progn
28673 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28674 "Make sure there are no nil faces"
28675 (setq ad-return-value (delq nil ad-return-value)))))
28677 ;; Make session.el ignore our circular variable
28678 (eval-after-load "session"
28679 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28681 ;;;; Experimental code
28683 (defun org-closed-in-range ()
28684 "Sparse tree of items closed in a certain time range.
28685 Still experimental, may disappear in the future."
28686 (interactive)
28687 ;; Get the time interval from the user.
28688 (let* ((time1 (time-to-seconds
28689 (org-read-date nil 'to-time nil "Starting date: ")))
28690 (time2 (time-to-seconds
28691 (org-read-date nil 'to-time nil "End date:")))
28692 ;; callback function
28693 (callback (lambda ()
28694 (let ((time
28695 (time-to-seconds
28696 (apply 'encode-time
28697 (org-parse-time-string
28698 (match-string 1))))))
28699 ;; check if time in interval
28700 (and (>= time time1) (<= time time2))))))
28701 ;; make tree, check each match with the callback
28702 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28704 ;;;; Finish up
28706 (provide 'org)
28708 (run-hooks 'org-load-hook)
28710 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28711 ;;; org.el ends here