Last fixes before release.
[org-mode/org-tableheadings.git] / org.el
blobfe3d5a5a4948400e6e1b8a6aa4323480436a1ccd
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 5.22a+
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; A list of recent changes can be found at
63 ;; http://orgmode.org/Changes.html
65 ;;; Code:
67 ;;;; Require other packages
69 (eval-when-compile
70 (require 'cl)
71 (require 'gnus-sum)
72 (require 'calendar))
73 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
74 ;; the file noutline.el being loaded.
75 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
76 ;; We require noutline, which might be provided in outline.el
77 (require 'outline) (require 'noutline)
78 ;; Other stuff we need.
79 (require 'time-date)
80 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
81 (require 'easymenu)
83 ;;;; Customization variables
85 ;;; Version
87 (defconst org-version "5.22a+"
88 "The version number of the file org.el.")
90 (defun org-version (&optional here)
91 "Show the org-mode version in the echo area.
92 With prefix arg HERE, insert it at point."
93 (interactive "P")
94 (let ((version (format "Org-mode version %s" org-version)))
95 (message version)
96 (if here
97 (insert version))))
99 ;;; Compatibility constants
100 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
101 (defconst org-format-transports-properties-p
102 (let ((x "a"))
103 (add-text-properties 0 1 '(test t) x)
104 (get-text-property 0 'test (format "%s" x)))
105 "Does format transport text properties?")
107 (defmacro org-bound-and-true-p (var)
108 "Return the value of symbol VAR if it is bound, else nil."
109 `(and (boundp (quote ,var)) ,var))
111 (defmacro org-unmodified (&rest body)
112 "Execute body without changing `buffer-modified-p'."
113 `(set-buffer-modified-p
114 (prog1 (buffer-modified-p) ,@body)))
116 (defmacro org-re (s)
117 "Replace posix classes in regular expression."
118 (if (featurep 'xemacs)
119 (let ((ss s))
120 (save-match-data
121 (while (string-match "\\[:alnum:\\]" ss)
122 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
123 (while (string-match "\\[:alpha:\\]" ss)
124 (setq ss (replace-match "a-zA-Z" t t ss)))
125 ss))
128 (defmacro org-preserve-lc (&rest body)
129 `(let ((_line (org-current-line))
130 (_col (current-column)))
131 (unwind-protect
132 (progn ,@body)
133 (goto-line _line)
134 (move-to-column _col))))
136 (defmacro org-without-partial-completion (&rest body)
137 `(let ((pc-mode (and (boundp 'partial-completion-mode)
138 partial-completion-mode)))
139 (unwind-protect
140 (progn
141 (if pc-mode (partial-completion-mode -1))
142 ,@body)
143 (if pc-mode (partial-completion-mode 1)))))
145 ;;; The custom variables
147 (defgroup org nil
148 "Outline-based notes management and organizer."
149 :tag "Org"
150 :group 'outlines
151 :group 'hypermedia
152 :group 'calendar)
154 (defcustom org-load-hook nil
155 "Hook that is run after org.el has been loaded."
156 :group 'org
157 :type 'hook)
159 (defcustom org-default-extensions '(org-irc)
160 "Extensions that should always be loaded together with org.el.
161 If the description starts with <A>, this means the extension
162 will be autoloaded when needed, preloading is not necessary."
163 :group 'org
164 :type
165 '(set :greedy t
166 (const :tag " Mouse support (org-mouse.el)" org-mouse)
167 (const :tag "<A> Publishing (org-publish.el)" org-publish)
168 (const :tag "<A> LaTeX export (org-export-latex.el)" org-export-latex)
169 (const :tag " IRC/ERC links (org-irc.el)" org-irc)
170 (const :tag " Apple Mail message links under OS X (org-mac-message.el)" org-mac-message)))
172 (defun org-load-default-extensions ()
173 "Load all extensions listed in `org-default-extensions'."
174 (mapc (lambda (ext)
175 (condition-case nil (require ext)
176 (error (message "Problems while trying to load feature `%s'" ext))))
177 org-default-extensions))
179 (eval-after-load "org" '(org-load-default-extensions))
181 ;; FIXME: Needs a separate group...
182 (defcustom org-completion-fallback-command 'hippie-expand
183 "The expansion command called by \\[org-complete] in normal context.
184 Normal means, no org-mode-specific context."
185 :group 'org
186 :type 'function)
188 (defgroup org-startup nil
189 "Options concerning startup of Org-mode."
190 :tag "Org Startup"
191 :group 'org)
193 (defcustom org-startup-folded t
194 "Non-nil means, entering Org-mode will switch to OVERVIEW.
195 This can also be configured on a per-file basis by adding one of
196 the following lines anywhere in the buffer:
198 #+STARTUP: fold
199 #+STARTUP: nofold
200 #+STARTUP: content"
201 :group 'org-startup
202 :type '(choice
203 (const :tag "nofold: show all" nil)
204 (const :tag "fold: overview" t)
205 (const :tag "content: all headlines" content)))
207 (defcustom org-startup-truncated t
208 "Non-nil means, entering Org-mode will set `truncate-lines'.
209 This is useful since some lines containing links can be very long and
210 uninteresting. Also tables look terrible when wrapped."
211 :group 'org-startup
212 :type 'boolean)
214 (defcustom org-startup-align-all-tables nil
215 "Non-nil means, align all tables when visiting a file.
216 This is useful when the column width in tables is forced with <N> cookies
217 in table fields. Such tables will look correct only after the first re-align.
218 This can also be configured on a per-file basis by adding one of
219 the following lines anywhere in the buffer:
220 #+STARTUP: align
221 #+STARTUP: noalign"
222 :group 'org-startup
223 :type 'boolean)
225 (defcustom org-insert-mode-line-in-empty-file nil
226 "Non-nil means insert the first line setting Org-mode in empty files.
227 When the function `org-mode' is called interactively in an empty file, this
228 normally means that the file name does not automatically trigger Org-mode.
229 To ensure that the file will always be in Org-mode in the future, a
230 line enforcing Org-mode will be inserted into the buffer, if this option
231 has been set."
232 :group 'org-startup
233 :type 'boolean)
235 (defcustom org-replace-disputed-keys nil
236 "Non-nil means use alternative key bindings for some keys.
237 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
238 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
239 If you want to use Org-mode together with one of these other modes,
240 or more generally if you would like to move some Org-mode commands to
241 other keys, set this variable and configure the keys with the variable
242 `org-disputed-keys'.
244 This option is only relevant at load-time of Org-mode, and must be set
245 *before* org.el is loaded. Changing it requires a restart of Emacs to
246 become effective."
247 :group 'org-startup
248 :type 'boolean)
250 (if (fboundp 'defvaralias)
251 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
253 (defcustom org-disputed-keys
254 '(([(shift up)] . [(meta p)])
255 ([(shift down)] . [(meta n)])
256 ([(shift left)] . [(meta -)])
257 ([(shift right)] . [(meta +)])
258 ([(control shift right)] . [(meta shift +)])
259 ([(control shift left)] . [(meta shift -)]))
260 "Keys for which Org-mode and other modes compete.
261 This is an alist, cars are the default keys, second element specifies
262 the alternative to use when `org-replace-disputed-keys' is t.
264 Keys can be specified in any syntax supported by `define-key'.
265 The value of this option takes effect only at Org-mode's startup,
266 therefore you'll have to restart Emacs to apply it after changing."
267 :group 'org-startup
268 :type 'alist)
270 (defun org-key (key)
271 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
272 Or return the original if not disputed."
273 (if org-replace-disputed-keys
274 (let* ((nkey (key-description key))
275 (x (org-find-if (lambda (x)
276 (equal (key-description (car x)) nkey))
277 org-disputed-keys)))
278 (if x (cdr x) key))
279 key))
281 (defun org-find-if (predicate seq)
282 (catch 'exit
283 (while seq
284 (if (funcall predicate (car seq))
285 (throw 'exit (car seq))
286 (pop seq)))))
288 (defun org-defkey (keymap key def)
289 "Define a key, possibly translated, as returned by `org-key'."
290 (define-key keymap (org-key key) def))
292 (defcustom org-ellipsis nil
293 "The ellipsis to use in the Org-mode outline.
294 When nil, just use the standard three dots. When a string, use that instead,
295 When a face, use the standart 3 dots, but with the specified face.
296 The change affects only Org-mode (which will then use its own display table).
297 Changing this requires executing `M-x org-mode' in a buffer to become
298 effective."
299 :group 'org-startup
300 :type '(choice (const :tag "Default" nil)
301 (face :tag "Face" :value org-warning)
302 (string :tag "String" :value "...#")))
304 (defvar org-display-table nil
305 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
307 (defgroup org-keywords nil
308 "Keywords in Org-mode."
309 :tag "Org Keywords"
310 :group 'org)
312 (defcustom org-deadline-string "DEADLINE:"
313 "String to mark deadline entries.
314 A deadline is this string, followed by a time stamp. Should be a word,
315 terminated by a colon. You can insert a schedule keyword and
316 a timestamp with \\[org-deadline].
317 Changes become only effective after restarting Emacs."
318 :group 'org-keywords
319 :type 'string)
321 (defcustom org-scheduled-string "SCHEDULED:"
322 "String to mark scheduled TODO entries.
323 A schedule is this string, followed by a time stamp. Should be a word,
324 terminated by a colon. You can insert a schedule keyword and
325 a timestamp with \\[org-schedule].
326 Changes become only effective after restarting Emacs."
327 :group 'org-keywords
328 :type 'string)
330 (defcustom org-closed-string "CLOSED:"
331 "String used as the prefix for timestamps logging closing a TODO entry."
332 :group 'org-keywords
333 :type 'string)
335 (defcustom org-clock-string "CLOCK:"
336 "String used as prefix for timestamps clocking work hours on an item."
337 :group 'org-keywords
338 :type 'string)
340 (defcustom org-comment-string "COMMENT"
341 "Entries starting with this keyword will never be exported.
342 An entry can be toggled between COMMENT and normal with
343 \\[org-toggle-comment].
344 Changes become only effective after restarting Emacs."
345 :group 'org-keywords
346 :type 'string)
348 (defcustom org-quote-string "QUOTE"
349 "Entries starting with this keyword will be exported in fixed-width font.
350 Quoting applies only to the text in the entry following the headline, and does
351 not extend beyond the next headline, even if that is lower level.
352 An entry can be toggled between QUOTE and normal with
353 \\[org-toggle-fixed-width-section]."
354 :group 'org-keywords
355 :type 'string)
357 (defconst org-repeat-re
358 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
359 "Regular expression for specifying repeated events.
360 After a match, group 1 contains the repeat expression.")
362 (defgroup org-structure nil
363 "Options concerning the general structure of Org-mode files."
364 :tag "Org Structure"
365 :group 'org)
367 (defgroup org-reveal-location nil
368 "Options about how to make context of a location visible."
369 :tag "Org Reveal Location"
370 :group 'org-structure)
372 (defconst org-context-choice
373 '(choice
374 (const :tag "Always" t)
375 (const :tag "Never" nil)
376 (repeat :greedy t :tag "Individual contexts"
377 (cons
378 (choice :tag "Context"
379 (const agenda)
380 (const org-goto)
381 (const occur-tree)
382 (const tags-tree)
383 (const link-search)
384 (const mark-goto)
385 (const bookmark-jump)
386 (const isearch)
387 (const default))
388 (boolean))))
389 "Contexts for the reveal options.")
391 (defcustom org-show-hierarchy-above '((default . t))
392 "Non-nil means, show full hierarchy when revealing a location.
393 Org-mode often shows locations in an org-mode file which might have
394 been invisible before. When this is set, the hierarchy of headings
395 above the exposed location is shown.
396 Turning this off for example for sparse trees makes them very compact.
397 Instead of t, this can also be an alist specifying this option for different
398 contexts. Valid contexts are
399 agenda when exposing an entry from the agenda
400 org-goto when using the command `org-goto' on key C-c C-j
401 occur-tree when using the command `org-occur' on key C-c /
402 tags-tree when constructing a sparse tree based on tags matches
403 link-search when exposing search matches associated with a link
404 mark-goto when exposing the jump goal of a mark
405 bookmark-jump when exposing a bookmark location
406 isearch when exiting from an incremental search
407 default default for all contexts not set explicitly"
408 :group 'org-reveal-location
409 :type org-context-choice)
411 (defcustom org-show-following-heading '((default . nil))
412 "Non-nil means, show following heading when revealing a location.
413 Org-mode often shows locations in an org-mode file which might have
414 been invisible before. When this is set, the heading following the
415 match is shown.
416 Turning this off for example for sparse trees makes them very compact,
417 but makes it harder to edit the location of the match. In such a case,
418 use the command \\[org-reveal] to show more context.
419 Instead of t, this can also be an alist specifying this option for different
420 contexts. See `org-show-hierarchy-above' for valid contexts."
421 :group 'org-reveal-location
422 :type org-context-choice)
424 (defcustom org-show-siblings '((default . nil) (isearch t))
425 "Non-nil means, show all sibling heading when revealing a location.
426 Org-mode often shows locations in an org-mode file which might have
427 been invisible before. When this is set, the sibling of the current entry
428 heading are all made visible. If `org-show-hierarchy-above' is t,
429 the same happens on each level of the hierarchy above the current entry.
431 By default this is on for the isearch context, off for all other contexts.
432 Turning this off for example for sparse trees makes them very compact,
433 but makes it harder to edit the location of the match. In such a case,
434 use the command \\[org-reveal] to show more context.
435 Instead of t, this can also be an alist specifying this option for different
436 contexts. See `org-show-hierarchy-above' for valid contexts."
437 :group 'org-reveal-location
438 :type org-context-choice)
440 (defcustom org-show-entry-below '((default . nil))
441 "Non-nil means, show the entry below a headline when revealing a location.
442 Org-mode often shows locations in an org-mode file which might have
443 been invisible before. When this is set, the text below the headline that is
444 exposed is also shown.
446 By default this is off for all contexts.
447 Instead of t, this can also be an alist specifying this option for different
448 contexts. See `org-show-hierarchy-above' for valid contexts."
449 :group 'org-reveal-location
450 :type org-context-choice)
452 (defgroup org-cycle nil
453 "Options concerning visibility cycling in Org-mode."
454 :tag "Org Cycle"
455 :group 'org-structure)
457 (defcustom org-drawers '("PROPERTIES" "CLOCK")
458 "Names of drawers. Drawers are not opened by cycling on the headline above.
459 Drawers only open with a TAB on the drawer line itself. A drawer looks like
460 this:
461 :DRAWERNAME:
462 .....
463 :END:
464 The drawer \"PROPERTIES\" is special for capturing properties through
465 the property API.
467 Drawers can be defined on the per-file basis with a line like:
469 #+DRAWERS: HIDDEN STATE PROPERTIES"
470 :group 'org-structure
471 :type '(repeat (string :tag "Drawer Name")))
473 (defcustom org-cycle-global-at-bob nil
474 "Cycle globally if cursor is at beginning of buffer and not at a headline.
475 This makes it possible to do global cycling without having to use S-TAB or
476 C-u TAB. For this special case to work, the first line of the buffer
477 must not be a headline - it may be empty ot some other text. When used in
478 this way, `org-cycle-hook' is disables temporarily, to make sure the
479 cursor stays at the beginning of the buffer.
480 When this option is nil, don't do anything special at the beginning
481 of the buffer."
482 :group 'org-cycle
483 :type 'boolean)
485 (defcustom org-cycle-emulate-tab t
486 "Where should `org-cycle' emulate TAB.
487 nil Never
488 white Only in completely white lines
489 whitestart Only at the beginning of lines, before the first non-white char
490 t Everywhere except in headlines
491 exc-hl-bol Everywhere except at the start of a headline
492 If TAB is used in a place where it does not emulate TAB, the current subtree
493 visibility is cycled."
494 :group 'org-cycle
495 :type '(choice (const :tag "Never" nil)
496 (const :tag "Only in completely white lines" white)
497 (const :tag "Before first char in a line" whitestart)
498 (const :tag "Everywhere except in headlines" t)
499 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
502 (defcustom org-cycle-separator-lines 2
503 "Number of empty lines needed to keep an empty line between collapsed trees.
504 If you leave an empty line between the end of a subtree and the following
505 headline, this empty line is hidden when the subtree is folded.
506 Org-mode will leave (exactly) one empty line visible if the number of
507 empty lines is equal or larger to the number given in this variable.
508 So the default 2 means, at least 2 empty lines after the end of a subtree
509 are needed to produce free space between a collapsed subtree and the
510 following headline.
512 Special case: when 0, never leave empty lines in collapsed view."
513 :group 'org-cycle
514 :type 'integer)
516 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
517 org-cycle-hide-drawers
518 org-cycle-show-empty-lines
519 org-optimize-window-after-visibility-change)
520 "Hook that is run after `org-cycle' has changed the buffer visibility.
521 The function(s) in this hook must accept a single argument which indicates
522 the new state that was set by the most recent `org-cycle' command. The
523 argument is a symbol. After a global state change, it can have the values
524 `overview', `content', or `all'. After a local state change, it can have
525 the values `folded', `children', or `subtree'."
526 :group 'org-cycle
527 :type 'hook)
529 (defgroup org-edit-structure nil
530 "Options concerning structure editing in Org-mode."
531 :tag "Org Edit Structure"
532 :group 'org-structure)
534 (defcustom org-odd-levels-only nil
535 "Non-nil means, skip even levels and only use odd levels for the outline.
536 This has the effect that two stars are being added/taken away in
537 promotion/demotion commands. It also influences how levels are
538 handled by the exporters.
539 Changing it requires restart of `font-lock-mode' to become effective
540 for fontification also in regions already fontified.
541 You may also set this on a per-file basis by adding one of the following
542 lines to the buffer:
544 #+STARTUP: odd
545 #+STARTUP: oddeven"
546 :group 'org-edit-structure
547 :group 'org-font-lock
548 :type 'boolean)
550 (defcustom org-adapt-indentation t
551 "Non-nil means, adapt indentation when promoting and demoting.
552 When this is set and the *entire* text in an entry is indented, the
553 indentation is increased by one space in a demotion command, and
554 decreased by one in a promotion command. If any line in the entry
555 body starts at column 0, indentation is not changed at all."
556 :group 'org-edit-structure
557 :type 'boolean)
559 (defcustom org-special-ctrl-a/e nil
560 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
561 When t, `C-a' will bring back the cursor to the beginning of the
562 headline text, i.e. after the stars and after a possible TODO keyword.
563 In an item, this will be the position after the bullet.
564 When the cursor is already at that position, another `C-a' will bring
565 it to the beginning of the line.
566 `C-e' will jump to the end of the headline, ignoring the presence of tags
567 in the headline. A second `C-e' will then jump to the true end of the
568 line, after any tags.
569 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
570 and only a directly following, identical keypress will bring the cursor
571 to the special positions."
572 :group 'org-edit-structure
573 :type '(choice
574 (const :tag "off" nil)
575 (const :tag "after bullet first" t)
576 (const :tag "border first" reversed)))
578 (if (fboundp 'defvaralias)
579 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
581 (defcustom org-special-ctrl-k nil
582 "Non-nil means `C-k' will behave specially in headlines.
583 When nil, `C-k' will call the default `kill-line' command.
584 When t, the following will happen while the cursor is in the headline:
586 - When the cursor is at the beginning of a headline, kill the entire
587 line and possible the folded subtree below the line.
588 - When in the middle of the headline text, kill the headline up to the tags.
589 - When after the headline text, kill the tags."
590 :group 'org-edit-structure
591 :type 'boolean)
593 (defcustom org-M-RET-may-split-line '((default . t))
594 "Non-nil means, M-RET will split the line at the cursor position.
595 When nil, it will go to the end of the line before making a
596 new line.
597 You may also set this option in a different way for different
598 contexts. Valid contexts are:
600 headline when creating a new headline
601 item when creating a new item
602 table in a table field
603 default the value to be used for all contexts not explicitly
604 customized"
605 :group 'org-structure
606 :group 'org-table
607 :type '(choice
608 (const :tag "Always" t)
609 (const :tag "Never" nil)
610 (repeat :greedy t :tag "Individual contexts"
611 (cons
612 (choice :tag "Context"
613 (const headline)
614 (const item)
615 (const table)
616 (const default))
617 (boolean)))))
620 (defcustom org-blank-before-new-entry '((heading . nil)
621 (plain-list-item . nil))
622 "Should `org-insert-heading' leave a blank line before new heading/item?
623 The value is an alist, with `heading' and `plain-list-item' as car,
624 and a boolean flag as cdr."
625 :group 'org-edit-structure
626 :type '(list
627 (cons (const heading) (boolean))
628 (cons (const plain-list-item) (boolean))))
630 (defcustom org-insert-heading-hook nil
631 "Hook being run after inserting a new heading."
632 :group 'org-edit-structure
633 :type 'hook)
635 (defcustom org-enable-fixed-width-editor t
636 "Non-nil means, lines starting with \":\" are treated as fixed-width.
637 This currently only means, they are never auto-wrapped.
638 When nil, such lines will be treated like ordinary lines.
639 See also the QUOTE keyword."
640 :group 'org-edit-structure
641 :type 'boolean)
643 (defcustom org-goto-auto-isearch t
644 "Non-nil means, typing characters in org-goto starts incremental search."
645 :group 'org-edit-structure
646 :type 'boolean)
648 (defgroup org-sparse-trees nil
649 "Options concerning sparse trees in Org-mode."
650 :tag "Org Sparse Trees"
651 :group 'org-structure)
653 (defcustom org-highlight-sparse-tree-matches t
654 "Non-nil means, highlight all matches that define a sparse tree.
655 The highlights will automatically disappear the next time the buffer is
656 changed by an edit command."
657 :group 'org-sparse-trees
658 :type 'boolean)
660 (defcustom org-remove-highlights-with-change t
661 "Non-nil means, any change to the buffer will remove temporary highlights.
662 Such highlights are created by `org-occur' and `org-clock-display'.
663 When nil, `C-c C-c needs to be used to get rid of the highlights.
664 The highlights created by `org-preview-latex-fragment' always need
665 `C-c C-c' to be removed."
666 :group 'org-sparse-trees
667 :group 'org-time
668 :type 'boolean)
671 (defcustom org-occur-hook '(org-first-headline-recenter)
672 "Hook that is run after `org-occur' has constructed a sparse tree.
673 This can be used to recenter the window to show as much of the structure
674 as possible."
675 :group 'org-sparse-trees
676 :type 'hook)
678 (defgroup org-plain-lists nil
679 "Options concerning plain lists in Org-mode."
680 :tag "Org Plain lists"
681 :group 'org-structure)
683 (defcustom org-cycle-include-plain-lists nil
684 "Non-nil means, include plain lists into visibility cycling.
685 This means that during cycling, plain list items will *temporarily* be
686 interpreted as outline headlines with a level given by 1000+i where i is the
687 indentation of the bullet. In all other operations, plain list items are
688 not seen as headlines. For example, you cannot assign a TODO keyword to
689 such an item."
690 :group 'org-plain-lists
691 :type 'boolean)
693 (defcustom org-plain-list-ordered-item-terminator t
694 "The character that makes a line with leading number an ordered list item.
695 Valid values are ?. and ?\). To get both terminators, use t. While
696 ?. may look nicer, it creates the danger that a line with leading
697 number may be incorrectly interpreted as an item. ?\) therefore is
698 the safe choice."
699 :group 'org-plain-lists
700 :type '(choice (const :tag "dot like in \"2.\"" ?.)
701 (const :tag "paren like in \"2)\"" ?\))
702 (const :tab "both" t)))
704 (defcustom org-auto-renumber-ordered-lists t
705 "Non-nil means, automatically renumber ordered plain lists.
706 Renumbering happens when the sequence have been changed with
707 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
708 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
709 :group 'org-plain-lists
710 :type 'boolean)
712 (defcustom org-provide-checkbox-statistics t
713 "Non-nil means, update checkbox statistics after insert and toggle.
714 When this is set, checkbox statistics is updated each time you either insert
715 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
716 with \\[org-ctrl-c-ctrl-c\\]."
717 :group 'org-plain-lists
718 :type 'boolean)
720 (defgroup org-archive nil
721 "Options concerning archiving in Org-mode."
722 :tag "Org Archive"
723 :group 'org-structure)
725 (defcustom org-archive-tag "ARCHIVE"
726 "The tag that marks a subtree as archived.
727 An archived subtree does not open during visibility cycling, and does
728 not contribute to the agenda listings.
729 After changing this, font-lock must be restarted in the relevant buffers to
730 get the proper fontification."
731 :group 'org-archive
732 :group 'org-keywords
733 :type 'string)
735 (defcustom org-agenda-skip-archived-trees t
736 "Non-nil means, the agenda will skip any items located in archived trees.
737 An archived tree is a tree marked with the tag ARCHIVE."
738 :group 'org-archive
739 :group 'org-agenda-skip
740 :type 'boolean)
742 (defcustom org-cycle-open-archived-trees nil
743 "Non-nil means, `org-cycle' will open archived trees.
744 An archived tree is a tree marked with the tag ARCHIVE.
745 When nil, archived trees will stay folded. You can still open them with
746 normal outline commands like `show-all', but not with the cycling commands."
747 :group 'org-archive
748 :group 'org-cycle
749 :type 'boolean)
751 (defcustom org-sparse-tree-open-archived-trees nil
752 "Non-nil means sparse tree construction shows matches in archived trees.
753 When nil, matches in these trees are highlighted, but the trees are kept in
754 collapsed state."
755 :group 'org-archive
756 :group 'org-sparse-trees
757 :type 'boolean)
759 (defcustom org-archive-location "%s_archive::"
760 "The location where subtrees should be archived.
761 This string consists of two parts, separated by a double-colon.
763 The first part is a file name - when omitted, archiving happens in the same
764 file. %s will be replaced by the current file name (without directory part).
765 Archiving to a different file is useful to keep archived entries from
766 contributing to the Org-mode Agenda.
768 The part after the double colon is a headline. The archived entries will be
769 filed under that headline. When omitted, the subtrees are simply filed away
770 at the end of the file, as top-level entries.
772 Here are a few examples:
773 \"%s_archive::\"
774 If the current file is Projects.org, archive in file
775 Projects.org_archive, as top-level trees. This is the default.
777 \"::* Archived Tasks\"
778 Archive in the current file, under the top-level headline
779 \"* Archived Tasks\".
781 \"~/org/archive.org::\"
782 Archive in file ~/org/archive.org (absolute path), as top-level trees.
784 \"basement::** Finished Tasks\"
785 Archive in file ./basement (relative path), as level 3 trees
786 below the level 2 heading \"** Finished Tasks\".
788 You may set this option on a per-file basis by adding to the buffer a
789 line like
791 #+ARCHIVE: basement::** Finished Tasks"
792 :group 'org-archive
793 :type 'string)
795 (defcustom org-archive-mark-done t
796 "Non-nil means, mark entries as DONE when they are moved to the archive file.
797 This can be a string to set the keyword to use. When t, Org-mode will
798 use the first keyword in its list that means done."
799 :group 'org-archive
800 :type '(choice
801 (const :tag "No" nil)
802 (const :tag "Yes" t)
803 (string :tag "Use this keyword")))
805 (defcustom org-archive-stamp-time t
806 "Non-nil means, add a time stamp to entries moved to an archive file.
807 This variable is obsolete and has no effect anymore, instead add ot remove
808 `time' from the variablle `org-archive-save-context-info'."
809 :group 'org-archive
810 :type 'boolean)
812 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
813 "Parts of context info that should be stored as properties when archiving.
814 When a subtree is moved to an archive file, it looses information given by
815 context, like inherited tags, the category, and possibly also the TODO
816 state (depending on the variable `org-archive-mark-done').
817 This variable can be a list of any of the following symbols:
819 time The time of archiving.
820 file The file where the entry originates.
821 itags The local tags, in the headline of the subtree.
822 ltags The tags the subtree inherits from further up the hierarchy.
823 todo The pre-archive TODO state.
824 category The category, taken from file name or #+CATEGORY lines.
825 olpath The outline path to the item. These are all headlines above
826 the current item, separated by /, like a file path.
828 For each symbol present in the list, a property will be created in
829 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
830 information."
831 :group 'org-archive
832 :type '(set :greedy t
833 (const :tag "Time" time)
834 (const :tag "File" file)
835 (const :tag "Category" category)
836 (const :tag "TODO state" todo)
837 (const :tag "TODO state" priority)
838 (const :tag "Inherited tags" itags)
839 (const :tag "Outline path" olpath)
840 (const :tag "Local tags" ltags)))
842 (defgroup org-imenu-and-speedbar nil
843 "Options concerning imenu and speedbar in Org-mode."
844 :tag "Org Imenu and Speedbar"
845 :group 'org-structure)
847 (defcustom org-imenu-depth 2
848 "The maximum level for Imenu access to Org-mode headlines.
849 This also applied for speedbar access."
850 :group 'org-imenu-and-speedbar
851 :type 'number)
853 (defgroup org-table nil
854 "Options concerning tables in Org-mode."
855 :tag "Org Table"
856 :group 'org)
858 (defcustom org-enable-table-editor 'optimized
859 "Non-nil means, lines starting with \"|\" are handled by the table editor.
860 When nil, such lines will be treated like ordinary lines.
862 When equal to the symbol `optimized', the table editor will be optimized to
863 do the following:
864 - Automatic overwrite mode in front of whitespace in table fields.
865 This makes the structure of the table stay in tact as long as the edited
866 field does not exceed the column width.
867 - Minimize the number of realigns. Normally, the table is aligned each time
868 TAB or RET are pressed to move to another field. With optimization this
869 happens only if changes to a field might have changed the column width.
870 Optimization requires replacing the functions `self-insert-command',
871 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
872 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
873 very good at guessing when a re-align will be necessary, but you can always
874 force one with \\[org-ctrl-c-ctrl-c].
876 If you would like to use the optimized version in Org-mode, but the
877 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
879 This variable can be used to turn on and off the table editor during a session,
880 but in order to toggle optimization, a restart is required.
882 See also the variable `org-table-auto-blank-field'."
883 :group 'org-table
884 :type '(choice
885 (const :tag "off" nil)
886 (const :tag "on" t)
887 (const :tag "on, optimized" optimized)))
889 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
890 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
891 In the optimized version, the table editor takes over all simple keys that
892 normally just insert a character. In tables, the characters are inserted
893 in a way to minimize disturbing the table structure (i.e. in overwrite mode
894 for empty fields). Outside tables, the correct binding of the keys is
895 restored.
897 The default for this option is t if the optimized version is also used in
898 Org-mode. See the variable `org-enable-table-editor' for details. Changing
899 this variable requires a restart of Emacs to become effective."
900 :group 'org-table
901 :type 'boolean)
903 (defcustom orgtbl-radio-table-templates
904 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
905 % END RECEIVE ORGTBL %n
906 \\begin{comment}
907 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
908 | | |
909 \\end{comment}\n")
910 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
911 @c END RECEIVE ORGTBL %n
912 @ignore
913 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
914 | | |
915 @end ignore\n")
916 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
917 <!-- END RECEIVE ORGTBL %n -->
918 <!--
919 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
920 | | |
921 -->\n"))
922 "Templates for radio tables in different major modes.
923 All occurrences of %n in a template will be replaced with the name of the
924 table, obtained by prompting the user."
925 :group 'org-table
926 :type '(repeat
927 (list (symbol :tag "Major mode")
928 (string :tag "Format"))))
930 (defgroup org-table-settings nil
931 "Settings for tables in Org-mode."
932 :tag "Org Table Settings"
933 :group 'org-table)
935 (defcustom org-table-default-size "5x2"
936 "The default size for newly created tables, Columns x Rows."
937 :group 'org-table-settings
938 :type 'string)
940 (defcustom org-table-number-regexp
941 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
942 "Regular expression for recognizing numbers in table columns.
943 If a table column contains mostly numbers, it will be aligned to the
944 right. If not, it will be aligned to the left.
946 The default value of this option is a regular expression which allows
947 anything which looks remotely like a number as used in scientific
948 context. For example, all of the following will be considered a
949 number:
950 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
952 Other options offered by the customize interface are more restrictive."
953 :group 'org-table-settings
954 :type '(choice
955 (const :tag "Positive Integers"
956 "^[0-9]+$")
957 (const :tag "Integers"
958 "^[-+]?[0-9]+$")
959 (const :tag "Floating Point Numbers"
960 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
961 (const :tag "Floating Point Number or Integer"
962 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
963 (const :tag "Exponential, Floating point, Integer"
964 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
965 (const :tag "Very General Number-Like, including hex"
966 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
967 (string :tag "Regexp:")))
969 (defcustom org-table-number-fraction 0.5
970 "Fraction of numbers in a column required to make the column align right.
971 In a column all non-white fields are considered. If at least this
972 fraction of fields is matched by `org-table-number-fraction',
973 alignment to the right border applies."
974 :group 'org-table-settings
975 :type 'number)
977 (defgroup org-table-editing nil
978 "Behavior of tables during editing in Org-mode."
979 :tag "Org Table Editing"
980 :group 'org-table)
982 (defcustom org-table-automatic-realign t
983 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
984 When nil, aligning is only done with \\[org-table-align], or after column
985 removal/insertion."
986 :group 'org-table-editing
987 :type 'boolean)
989 (defcustom org-table-auto-blank-field t
990 "Non-nil means, automatically blank table field when starting to type into it.
991 This only happens when typing immediately after a field motion
992 command (TAB, S-TAB or RET).
993 Only relevant when `org-enable-table-editor' is equal to `optimized'."
994 :group 'org-table-editing
995 :type 'boolean)
997 (defcustom org-table-tab-jumps-over-hlines t
998 "Non-nil means, tab in the last column of a table with jump over a hline.
999 If a horizontal separator line is following the current line,
1000 `org-table-next-field' can either create a new row before that line, or jump
1001 over the line. When this option is nil, a new line will be created before
1002 this line."
1003 :group 'org-table-editing
1004 :type 'boolean)
1006 (defcustom org-table-tab-recognizes-table.el t
1007 "Non-nil means, TAB will automatically notice a table.el table.
1008 When it sees such a table, it moves point into it and - if necessary -
1009 calls `table-recognize-table'."
1010 :group 'org-table-editing
1011 :type 'boolean)
1013 (defgroup org-table-calculation nil
1014 "Options concerning tables in Org-mode."
1015 :tag "Org Table Calculation"
1016 :group 'org-table)
1018 (defcustom org-table-use-standard-references t
1019 "Should org-mode work with table refrences like B3 instead of @3$2?
1020 Possible values are:
1021 nil never use them
1022 from accept as input, do not present for editing
1023 t: accept as input and present for editing"
1024 :group 'org-table-calculation
1025 :type '(choice
1026 (const :tag "Never, don't even check unser input for them" nil)
1027 (const :tag "Always, both as user input, and when editing" t)
1028 (const :tag "Convert user input, don't offer during editing" 'from)))
1030 (defcustom org-table-copy-increment t
1031 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1032 :group 'org-table-calculation
1033 :type 'boolean)
1035 (defcustom org-calc-default-modes
1036 '(calc-internal-prec 12
1037 calc-float-format (float 5)
1038 calc-angle-mode deg
1039 calc-prefer-frac nil
1040 calc-symbolic-mode nil
1041 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1042 calc-display-working-message t
1044 "List with Calc mode settings for use in calc-eval for table formulas.
1045 The list must contain alternating symbols (Calc modes variables and values).
1046 Don't remove any of the default settings, just change the values. Org-mode
1047 relies on the variables to be present in the list."
1048 :group 'org-table-calculation
1049 :type 'plist)
1051 (defcustom org-table-formula-evaluate-inline t
1052 "Non-nil means, TAB and RET evaluate a formula in current table field.
1053 If the current field starts with an equal sign, it is assumed to be a formula
1054 which should be evaluated as described in the manual and in the documentation
1055 string of the command `org-table-eval-formula'. This feature requires the
1056 Emacs calc package.
1057 When this variable is nil, formula calculation is only available through
1058 the command \\[org-table-eval-formula]."
1059 :group 'org-table-calculation
1060 :type 'boolean)
1062 (defcustom org-table-formula-use-constants t
1063 "Non-nil means, interpret constants in formulas in tables.
1064 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1065 by the value given in `org-table-formula-constants', or by a value obtained
1066 from the `constants.el' package."
1067 :group 'org-table-calculation
1068 :type 'boolean)
1070 (defcustom org-table-formula-constants nil
1071 "Alist with constant names and values, for use in table formulas.
1072 The car of each element is a name of a constant, without the `$' before it.
1073 The cdr is the value as a string. For example, if you'd like to use the
1074 speed of light in a formula, you would configure
1076 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1078 and then use it in an equation like `$1*$c'.
1080 Constants can also be defined on a per-file basis using a line like
1082 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1083 :group 'org-table-calculation
1084 :type '(repeat
1085 (cons (string :tag "name")
1086 (string :tag "value"))))
1088 (defvar org-table-formula-constants-local nil
1089 "Local version of `org-table-formula-constants'.")
1090 (make-variable-buffer-local 'org-table-formula-constants-local)
1092 (defcustom org-table-allow-automatic-line-recalculation t
1093 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1094 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1095 :group 'org-table-calculation
1096 :type 'boolean)
1098 (defgroup org-link nil
1099 "Options concerning links in Org-mode."
1100 :tag "Org Link"
1101 :group 'org)
1103 (defvar org-link-abbrev-alist-local nil
1104 "Buffer-local version of `org-link-abbrev-alist', which see.
1105 The value of this is taken from the #+LINK lines.")
1106 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1108 (defcustom org-link-abbrev-alist nil
1109 "Alist of link abbreviations.
1110 The car of each element is a string, to be replaced at the start of a link.
1111 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1112 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1114 [[linkkey:tag][description]]
1116 If REPLACE is a string, the tag will simply be appended to create the link.
1117 If the string contains \"%s\", the tag will be inserted there.
1119 REPLACE may also be a function that will be called with the tag as the
1120 only argument to create the link, which should be returned as a string.
1122 See the manual for examples."
1123 :group 'org-link
1124 :type 'alist)
1126 (defcustom org-descriptive-links t
1127 "Non-nil means, hide link part and only show description of bracket links.
1128 Bracket links are like [[link][descritpion]]. This variable sets the initial
1129 state in new org-mode buffers. The setting can then be toggled on a
1130 per-buffer basis from the Org->Hyperlinks menu."
1131 :group 'org-link
1132 :type 'boolean)
1134 (defcustom org-link-file-path-type 'adaptive
1135 "How the path name in file links should be stored.
1136 Valid values are:
1138 relative Relative to the current directory, i.e. the directory of the file
1139 into which the link is being inserted.
1140 absolute Absolute path, if possible with ~ for home directory.
1141 noabbrev Absolute path, no abbreviation of home directory.
1142 adaptive Use relative path for files in the current directory and sub-
1143 directories of it. For other files, use an absolute path."
1144 :group 'org-link
1145 :type '(choice
1146 (const relative)
1147 (const absolute)
1148 (const noabbrev)
1149 (const adaptive)))
1151 (defcustom org-activate-links '(bracket angle plain radio tag date)
1152 "Types of links that should be activated in Org-mode files.
1153 This is a list of symbols, each leading to the activation of a certain link
1154 type. In principle, it does not hurt to turn on most link types - there may
1155 be a small gain when turning off unused link types. The types are:
1157 bracket The recommended [[link][description]] or [[link]] links with hiding.
1158 angular Links in angular brackes that may contain whitespace like
1159 <bbdb:Carsten Dominik>.
1160 plain Plain links in normal text, no whitespace, like http://google.com.
1161 radio Text that is matched by a radio target, see manual for details.
1162 tag Tag settings in a headline (link to tag search).
1163 date Time stamps (link to calendar).
1165 Changing this variable requires a restart of Emacs to become effective."
1166 :group 'org-link
1167 :type '(set (const :tag "Double bracket links (new style)" bracket)
1168 (const :tag "Angular bracket links (old style)" angular)
1169 (const :tag "Plain text links" plain)
1170 (const :tag "Radio target matches" radio)
1171 (const :tag "Tags" tag)
1172 (const :tag "Timestamps" date)))
1174 (defgroup org-link-store nil
1175 "Options concerning storing links in Org-mode"
1176 :tag "Org Store Link"
1177 :group 'org-link)
1179 (defcustom org-email-link-description-format "Email %c: %.30s"
1180 "Format of the description part of a link to an email or usenet message.
1181 The following %-excapes will be replaced by corresponding information:
1183 %F full \"From\" field
1184 %f name, taken from \"From\" field, address if no name
1185 %T full \"To\" field
1186 %t first name in \"To\" field, address if no name
1187 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1188 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1189 %s subject
1190 %m message-id.
1192 You may use normal field width specification between the % and the letter.
1193 This is for example useful to limit the length of the subject.
1195 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1196 :group 'org-link-store
1197 :type 'string)
1199 (defcustom org-from-is-user-regexp
1200 (let (r1 r2)
1201 (when (and user-mail-address (not (string= user-mail-address "")))
1202 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1203 (when (and user-full-name (not (string= user-full-name "")))
1204 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1205 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1206 "Regexp mached against the \"From:\" header of an email or usenet message.
1207 It should match if the message is from the user him/herself."
1208 :group 'org-link-store
1209 :type 'regexp)
1211 (defcustom org-context-in-file-links t
1212 "Non-nil means, file links from `org-store-link' contain context.
1213 A search string will be added to the file name with :: as separator and
1214 used to find the context when the link is activated by the command
1215 `org-open-at-point'.
1216 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1217 negates this setting for the duration of the command."
1218 :group 'org-link-store
1219 :type 'boolean)
1221 (defcustom org-keep-stored-link-after-insertion nil
1222 "Non-nil means, keep link in list for entire session.
1224 The command `org-store-link' adds a link pointing to the current
1225 location to an internal list. These links accumulate during a session.
1226 The command `org-insert-link' can be used to insert links into any
1227 Org-mode file (offering completion for all stored links). When this
1228 option is nil, every link which has been inserted once using \\[org-insert-link]
1229 will be removed from the list, to make completing the unused links
1230 more efficient."
1231 :group 'org-link-store
1232 :type 'boolean)
1234 (defcustom org-usenet-links-prefer-google nil
1235 "Non-nil means, `org-store-link' will create web links to Google groups.
1236 When nil, Gnus will be used for such links.
1237 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1238 negates this setting for the duration of the command."
1239 :group 'org-link-store
1240 :type 'boolean)
1242 (defgroup org-link-follow nil
1243 "Options concerning following links in Org-mode"
1244 :tag "Org Follow Link"
1245 :group 'org-link)
1247 (defcustom org-follow-link-hook nil
1248 "Hook that is run after a link has been followed."
1249 :group 'org-link-follow
1250 :type 'hook)
1252 (defcustom org-tab-follows-link nil
1253 "Non-nil means, on links TAB will follow the link.
1254 Needs to be set before org.el is loaded."
1255 :group 'org-link-follow
1256 :type 'boolean)
1258 (defcustom org-return-follows-link nil
1259 "Non-nil means, on links RET will follow the link.
1260 Needs to be set before org.el is loaded."
1261 :group 'org-link-follow
1262 :type 'boolean)
1264 (defcustom org-mouse-1-follows-link
1265 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1266 "Non-nil means, mouse-1 on a link will follow the link.
1267 A longer mouse click will still set point. Does not work on XEmacs.
1268 Needs to be set before org.el is loaded."
1269 :group 'org-link-follow
1270 :type 'boolean)
1272 (defcustom org-mark-ring-length 4
1273 "Number of different positions to be recorded in the ring
1274 Changing this requires a restart of Emacs to work correctly."
1275 :group 'org-link-follow
1276 :type 'interger)
1278 (defcustom org-link-frame-setup
1279 '((vm . vm-visit-folder-other-frame)
1280 (gnus . gnus-other-frame)
1281 (file . find-file-other-window))
1282 "Setup the frame configuration for following links.
1283 When following a link with Emacs, it may often be useful to display
1284 this link in another window or frame. This variable can be used to
1285 set this up for the different types of links.
1286 For VM, use any of
1287 `vm-visit-folder'
1288 `vm-visit-folder-other-frame'
1289 For Gnus, use any of
1290 `gnus'
1291 `gnus-other-frame'
1292 For FILE, use any of
1293 `find-file'
1294 `find-file-other-window'
1295 `find-file-other-frame'
1296 For the calendar, use the variable `calendar-setup'.
1297 For BBDB, it is currently only possible to display the matches in
1298 another window."
1299 :group 'org-link-follow
1300 :type '(list
1301 (cons (const vm)
1302 (choice
1303 (const vm-visit-folder)
1304 (const vm-visit-folder-other-window)
1305 (const vm-visit-folder-other-frame)))
1306 (cons (const gnus)
1307 (choice
1308 (const gnus)
1309 (const gnus-other-frame)))
1310 (cons (const file)
1311 (choice
1312 (const find-file)
1313 (const find-file-other-window)
1314 (const find-file-other-frame)))))
1316 (defcustom org-display-internal-link-with-indirect-buffer nil
1317 "Non-nil means, use indirect buffer to display infile links.
1318 Activating internal links (from one location in a file to another location
1319 in the same file) normally just jumps to the location. When the link is
1320 activated with a C-u prefix (or with mouse-3), the link is displayed in
1321 another window. When this option is set, the other window actually displays
1322 an indirect buffer clone of the current buffer, to avoid any visibility
1323 changes to the current buffer."
1324 :group 'org-link-follow
1325 :type 'boolean)
1327 (defcustom org-open-non-existing-files nil
1328 "Non-nil means, `org-open-file' will open non-existing files.
1329 When nil, an error will be generated."
1330 :group 'org-link-follow
1331 :type 'boolean)
1333 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1334 "Function and arguments to call for following mailto links.
1335 This is a list with the first element being a lisp function, and the
1336 remaining elements being arguments to the function. In string arguments,
1337 %a will be replaced by the address, and %s will be replaced by the subject
1338 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1339 :group 'org-link-follow
1340 :type '(choice
1341 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1342 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1343 (const :tag "message-mail" (message-mail "%a" "%s"))
1344 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1346 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1347 "Non-nil means, ask for confirmation before executing shell links.
1348 Shell links can be dangerous: just think about a link
1350 [[shell:rm -rf ~/*][Google Search]]
1352 This link would show up in your Org-mode document as \"Google Search\",
1353 but really it would remove your entire home directory.
1354 Therefore we advise against setting this variable to nil.
1355 Just change it to `y-or-n-p' of you want to confirm with a
1356 single keystroke rather than having to type \"yes\"."
1357 :group 'org-link-follow
1358 :type '(choice
1359 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1360 (const :tag "with y-or-n (faster)" y-or-n-p)
1361 (const :tag "no confirmation (dangerous)" nil)))
1363 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1364 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1365 Elisp links can be dangerous: just think about a link
1367 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1369 This link would show up in your Org-mode document as \"Google Search\",
1370 but really it would remove your entire home directory.
1371 Therefore we advise against setting this variable to nil.
1372 Just change it to `y-or-n-p' of you want to confirm with a
1373 single keystroke rather than having to type \"yes\"."
1374 :group 'org-link-follow
1375 :type '(choice
1376 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1377 (const :tag "with y-or-n (faster)" y-or-n-p)
1378 (const :tag "no confirmation (dangerous)" nil)))
1380 (defconst org-file-apps-defaults-gnu
1381 '((remote . emacs)
1382 (t . mailcap))
1383 "Default file applications on a UNIX or GNU/Linux system.
1384 See `org-file-apps'.")
1386 (defconst org-file-apps-defaults-macosx
1387 '((remote . emacs)
1388 (t . "open %s")
1389 ("ps" . "gv %s")
1390 ("ps.gz" . "gv %s")
1391 ("eps" . "gv %s")
1392 ("eps.gz" . "gv %s")
1393 ("dvi" . "xdvi %s")
1394 ("fig" . "xfig %s"))
1395 "Default file applications on a MacOS X system.
1396 The system \"open\" is known as a default, but we use X11 applications
1397 for some files for which the OS does not have a good default.
1398 See `org-file-apps'.")
1400 (defconst org-file-apps-defaults-windowsnt
1401 (list
1402 '(remote . emacs)
1403 (cons t
1404 (list (if (featurep 'xemacs)
1405 'mswindows-shell-execute
1406 'w32-shell-execute)
1407 "open" 'file)))
1408 "Default file applications on a Windows NT system.
1409 The system \"open\" is used for most files.
1410 See `org-file-apps'.")
1412 (defcustom org-file-apps
1414 ("txt" . emacs)
1415 ("tex" . emacs)
1416 ("ltx" . emacs)
1417 ("org" . emacs)
1418 ("el" . emacs)
1419 ("bib" . emacs)
1421 "External applications for opening `file:path' items in a document.
1422 Org-mode uses system defaults for different file types, but
1423 you can use this variable to set the application for a given file
1424 extension. The entries in this list are cons cells where the car identifies
1425 files and the cdr the corresponding command. Possible values for the
1426 file identifier are
1427 \"ext\" A string identifying an extension
1428 `directory' Matches a directory
1429 `remote' Matches a remote file, accessible through tramp or efs.
1430 Remote files most likely should be visited through Emacs
1431 because external applications cannot handle such paths.
1432 t Default for all remaining files
1434 Possible values for the command are:
1435 `emacs' The file will be visited by the current Emacs process.
1436 `default' Use the default application for this file type.
1437 string A command to be executed by a shell; %s will be replaced
1438 by the path to the file.
1439 sexp A Lisp form which will be evaluated. The file path will
1440 be available in the Lisp variable `file'.
1441 For more examples, see the system specific constants
1442 `org-file-apps-defaults-macosx'
1443 `org-file-apps-defaults-windowsnt'
1444 `org-file-apps-defaults-gnu'."
1445 :group 'org-link-follow
1446 :type '(repeat
1447 (cons (choice :value ""
1448 (string :tag "Extension")
1449 (const :tag "Default for unrecognized files" t)
1450 (const :tag "Remote file" remote)
1451 (const :tag "Links to a directory" directory))
1452 (choice :value ""
1453 (const :tag "Visit with Emacs" emacs)
1454 (const :tag "Use system default" default)
1455 (string :tag "Command")
1456 (sexp :tag "Lisp form")))))
1458 (defcustom org-mhe-search-all-folders nil
1459 "Non-nil means, that the search for the mh-message will be extended to
1460 all folders if the message cannot be found in the folder given in the link.
1461 Searching all folders is very efficient with one of the search engines
1462 supported by MH-E, but will be slow with pick."
1463 :group 'org-link-follow
1464 :type 'boolean)
1466 (defgroup org-remember nil
1467 "Options concerning interaction with remember.el."
1468 :tag "Org Remember"
1469 :group 'org)
1471 (defcustom org-directory "~/org"
1472 "Directory with org files.
1473 This directory will be used as default to prompt for org files.
1474 Used by the hooks for remember.el."
1475 :group 'org-remember
1476 :type 'directory)
1478 (defcustom org-default-notes-file "~/.notes"
1479 "Default target for storing notes.
1480 Used by the hooks for remember.el. This can be a string, or nil to mean
1481 the value of `remember-data-file'.
1482 You can set this on a per-template basis with the variable
1483 `org-remember-templates'."
1484 :group 'org-remember
1485 :type '(choice
1486 (const :tag "Default from remember-data-file" nil)
1487 file))
1489 (defcustom org-remember-store-without-prompt t
1490 "Non-nil means, `C-c C-c' stores remember note without further promts.
1491 In this case, you need `C-u C-c C-c' to get the prompts for
1492 note file and headline.
1493 When this variable is nil, `C-c C-c' give you the prompts, and
1494 `C-u C-c C-c' trigger the fasttrack."
1495 :group 'org-remember
1496 :type 'boolean)
1498 (defcustom org-remember-interactive-interface 'refile
1499 "The interface to be used for interactive filing of remember notes.
1500 This is only used when the interactive mode for selecting a filing
1501 location is used (see the variable `org-remember-store-without-prompt').
1502 Allowed vaues are:
1503 outline The interface shows an outline of the relevant file
1504 and the correct heading is found by moving through
1505 the outline or by searching with incremental search.
1506 outline-path-completion Headlines in the current buffer are offered via
1507 completion.
1508 refile Use the refile interface, and offer headlines,
1509 possibly from different buffers."
1510 :group 'org-remember
1511 :type '(choice
1512 (const :tag "Refile" refile)
1513 (const :tag "Outline" outline)
1514 (const :tag "Outline-path-completion" outline-path-completion)))
1516 (defcustom org-goto-interface 'outline
1517 "The default interface to be used for `org-goto'.
1518 Allowed vaues are:
1519 outline The interface shows an outline of the relevant file
1520 and the correct heading is found by moving through
1521 the outline or by searching with incremental search.
1522 outline-path-completion Headlines in the current buffer are offered via
1523 completion."
1524 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1525 :type '(choice
1526 (const :tag "Outline" outline)
1527 (const :tag "Outline-path-completion" outline-path-completion)))
1529 (defcustom org-remember-default-headline ""
1530 "The headline that should be the default location in the notes file.
1531 When filing remember notes, the cursor will start at that position.
1532 You can set this on a per-template basis with the variable
1533 `org-remember-templates'."
1534 :group 'org-remember
1535 :type 'string)
1537 (defcustom org-remember-templates nil
1538 "Templates for the creation of remember buffers.
1539 When nil, just let remember make the buffer.
1540 When not nil, this is a list of 5-element lists. In each entry, the first
1541 element is the name of the template, which should be a single short word.
1542 The second element is a character, a unique key to select this template.
1543 The third element is the template. The fourth element is optional and can
1544 specify a destination file for remember items created with this template.
1545 The default file is given by `org-default-notes-file'. An optional fifth
1546 element can specify the headline in that file that should be offered
1547 first when the user is asked to file the entry. The default headline is
1548 given in the variable `org-remember-default-headline'.
1550 An optional sixth element specifies the contexts in which the user can
1551 select the template. This element can be either a list of major modes
1552 or a function. `org-remember' will first check whether the function
1553 returns `t' or if we are in any of the listed major mode, and select
1554 the template accordingly.
1556 The template specifies the structure of the remember buffer. It should have
1557 a first line starting with a star, to act as the org-mode headline.
1558 Furthermore, the following %-escapes will be replaced with content:
1560 %^{prompt} Prompt the user for a string and replace this sequence with it.
1561 A default value and a completion table ca be specified like this:
1562 %^{prompt|default|completion2|completion3|...}
1563 %t time stamp, date only
1564 %T time stamp with date and time
1565 %u, %U like the above, but inactive time stamps
1566 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1567 You may define a prompt like %^{Please specify birthday}t
1568 %n user name (taken from `user-full-name')
1569 %a annotation, normally the link created with org-store-link
1570 %i initial content, the region active. If %i is indented,
1571 the entire inserted text will be indented as well.
1572 %c content of the clipboard, or current kill ring head
1573 %^g prompt for tags, with completion on tags in target file
1574 %^G prompt for tags, with completion all tags in all agenda files
1575 %:keyword specific information for certain link types, see below
1576 %[pathname] insert the contents of the file given by `pathname'
1577 %(sexp) evaluate elisp `(sexp)' and replace with the result
1578 %! Store this note immediately after filling the template
1580 %? After completing the template, position cursor here.
1582 Apart from these general escapes, you can access information specific to the
1583 link type that is created. For example, calling `remember' in emails or gnus
1584 will record the author and the subject of the message, which you can access
1585 with %:author and %:subject, respectively. Here is a complete list of what
1586 is recorded for each link type.
1588 Link type | Available information
1589 -------------------+------------------------------------------------------
1590 bbdb | %:type %:name %:company
1591 vm, wl, mh, rmail | %:type %:subject %:message-id
1592 | %:from %:fromname %:fromaddress
1593 | %:to %:toname %:toaddress
1594 | %:fromto (either \"to NAME\" or \"from NAME\")
1595 gnus | %:group, for messages also all email fields
1596 w3, w3m | %:type %:url
1597 info | %:type %:file %:node
1598 calendar | %:type %:date"
1599 :group 'org-remember
1600 :get (lambda (var) ; Make sure all entries have at least 5 elements
1601 (mapcar (lambda (x)
1602 (if (not (stringp (car x))) (setq x (cons "" x)))
1603 (cond ((= (length x) 4) (append x '("")))
1604 ((= (length x) 3) (append x '("" "")))
1605 (t x)))
1606 (default-value var)))
1607 :type '(repeat
1608 :tag "enabled"
1609 (list :value ("" ?a "\n" nil nil nil)
1610 (string :tag "Name")
1611 (character :tag "Selection Key")
1612 (string :tag "Template")
1613 (choice
1614 (file :tag "Destination file")
1615 (const :tag "Prompt for file" nil))
1616 (choice
1617 (string :tag "Destination headline")
1618 (const :tag "Selection interface for heading"))
1619 (choice
1620 (const :tag "Use by default" nil)
1621 (const :tag "Use in all contexts" t)
1622 (repeat :tag "Use only if in major mode"
1623 (symbol :tag "Major mode"))
1624 (function :tag "Perform a check against function")))))
1626 (defcustom org-reverse-note-order nil
1627 "Non-nil means, store new notes at the beginning of a file or entry.
1628 When nil, new notes will be filed to the end of a file or entry.
1629 This can also be a list with cons cells of regular expressions that
1630 are matched against file names, and values."
1631 :group 'org-remember
1632 :type '(choice
1633 (const :tag "Reverse always" t)
1634 (const :tag "Reverse never" nil)
1635 (repeat :tag "By file name regexp"
1636 (cons regexp boolean))))
1638 (defcustom org-refile-targets nil
1639 "Targets for refiling entries with \\[org-refile].
1640 This is list of cons cells. Each cell contains:
1641 - a specification of the files to be considered, either a list of files,
1642 or a symbol whose function or value fields will be used to retrieve
1643 a file name or a list of file names. Nil means, refile to a different
1644 heading in the current buffer.
1645 - A specification of how to find candidate refile targets. This may be
1646 any of
1647 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1648 This tag has to be present in all target headlines, inheritance will
1649 not be considered.
1650 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1651 todo keyword.
1652 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1653 headlines that are refiling targets.
1654 - a cons cell (:level . N). Any headline of level N is considered a target.
1655 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1656 ;; FIXME: what if there are a var and func with same name???
1657 :group 'org-remember
1658 :type '(repeat
1659 (cons
1660 (choice :value org-agenda-files
1661 (const :tag "All agenda files" org-agenda-files)
1662 (const :tag "Current buffer" nil)
1663 (function) (variable) (file))
1664 (choice :tag "Identify target headline by"
1665 (cons :tag "Specific tag" (const :tag) (string))
1666 (cons :tag "TODO keyword" (const :todo) (string))
1667 (cons :tag "Regular expression" (const :regexp) (regexp))
1668 (cons :tag "Level number" (const :level) (integer))
1669 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1671 (defcustom org-refile-use-outline-path nil
1672 "Non-nil means, provide refile targets as paths.
1673 So a level 3 headline will be available as level1/level2/level3.
1674 When the value is `file', also include the file name (without directory)
1675 into the path. When `full-file-path', include the full file path."
1676 :group 'org-remember
1677 :type '(choice
1678 (const :tag "Not" nil)
1679 (const :tag "Yes" t)
1680 (const :tag "Start with file name" file)
1681 (const :tag "Start with full file path" full-file-path)))
1683 (defgroup org-todo nil
1684 "Options concerning TODO items in Org-mode."
1685 :tag "Org TODO"
1686 :group 'org)
1688 (defgroup org-progress nil
1689 "Options concerning Progress logging in Org-mode."
1690 :tag "Org Progress"
1691 :group 'org-time)
1693 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1694 "List of TODO entry keyword sequences and their interpretation.
1695 \\<org-mode-map>This is a list of sequences.
1697 Each sequence starts with a symbol, either `sequence' or `type',
1698 indicating if the keywords should be interpreted as a sequence of
1699 action steps, or as different types of TODO items. The first
1700 keywords are states requiring action - these states will select a headline
1701 for inclusion into the global TODO list Org-mode produces. If one of
1702 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1703 signify that no further action is necessary. If \"|\" is not found,
1704 the last keyword is treated as the only DONE state of the sequence.
1706 The command \\[org-todo] cycles an entry through these states, and one
1707 additional state where no keyword is present. For details about this
1708 cycling, see the manual.
1710 TODO keywords and interpretation can also be set on a per-file basis with
1711 the special #+SEQ_TODO and #+TYP_TODO lines.
1713 Each keyword can optionally specify a character for fast state selection
1714 \(in combination with the variable `org-use-fast-todo-selection')
1715 and specifiers for state change logging, using the same syntax
1716 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1717 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1718 indicates to record a time stamp each time this state is selected.
1720 Each keyword may also specify if a timestamp or a note should be
1721 recorded when entering or leaving the state, by adding additional
1722 characters in the parenthesis after the keyword. This looks like this:
1723 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1724 record only the time of the state change. With X and Y being either
1725 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1726 Y when leaving the state if and only if the *target* state does not
1727 define X. You may omit any of the fast-selection key or X or /Y,
1728 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1730 For backward compatibility, this variable may also be just a list
1731 of keywords - in this case the interptetation (sequence or type) will be
1732 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1733 :group 'org-todo
1734 :group 'org-keywords
1735 :type '(choice
1736 (repeat :tag "Old syntax, just keywords"
1737 (string :tag "Keyword"))
1738 (repeat :tag "New syntax"
1739 (cons
1740 (choice
1741 :tag "Interpretation"
1742 (const :tag "Sequence (cycling hits every state)" sequence)
1743 (const :tag "Type (cycling directly to DONE)" type))
1744 (repeat
1745 (string :tag "Keyword"))))))
1747 (defvar org-todo-keywords-1 nil
1748 "All TODO and DONE keywords active in a buffer.")
1749 (make-variable-buffer-local 'org-todo-keywords-1)
1750 (defvar org-todo-keywords-for-agenda nil)
1751 (defvar org-done-keywords-for-agenda nil)
1752 (defvar org-not-done-keywords nil)
1753 (make-variable-buffer-local 'org-not-done-keywords)
1754 (defvar org-done-keywords nil)
1755 (make-variable-buffer-local 'org-done-keywords)
1756 (defvar org-todo-heads nil)
1757 (make-variable-buffer-local 'org-todo-heads)
1758 (defvar org-todo-sets nil)
1759 (make-variable-buffer-local 'org-todo-sets)
1760 (defvar org-todo-log-states nil)
1761 (make-variable-buffer-local 'org-todo-log-states)
1762 (defvar org-todo-kwd-alist nil)
1763 (make-variable-buffer-local 'org-todo-kwd-alist)
1764 (defvar org-todo-key-alist nil)
1765 (make-variable-buffer-local 'org-todo-key-alist)
1766 (defvar org-todo-key-trigger nil)
1767 (make-variable-buffer-local 'org-todo-key-trigger)
1769 (defcustom org-todo-interpretation 'sequence
1770 "Controls how TODO keywords are interpreted.
1771 This variable is in principle obsolete and is only used for
1772 backward compatibility, if the interpretation of todo keywords is
1773 not given already in `org-todo-keywords'. See that variable for
1774 more information."
1775 :group 'org-todo
1776 :group 'org-keywords
1777 :type '(choice (const sequence)
1778 (const type)))
1780 (defcustom org-use-fast-todo-selection 'prefix
1781 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1782 This variable describes if and under what circumstances the cycling
1783 mechanism for TODO keywords will be replaced by a single-key, direct
1784 selection scheme.
1786 When nil, fast selection is never used.
1788 When the symbol `prefix', it will be used when `org-todo' is called with
1789 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1790 in an agenda buffer.
1792 When t, fast selection is used by default. In this case, the prefix
1793 argument forces cycling instead.
1795 In all cases, the special interface is only used if access keys have actually
1796 been assigned by the user, i.e. if keywords in the configuration are followed
1797 by a letter in parenthesis, like TODO(t)."
1798 :group 'org-todo
1799 :type '(choice
1800 (const :tag "Never" nil)
1801 (const :tag "By default" t)
1802 (const :tag "Only with C-u C-c C-t" prefix)))
1804 (defcustom org-after-todo-state-change-hook nil
1805 "Hook which is run after the state of a TODO item was changed.
1806 The new state (a string with a TODO keyword, or nil) is available in the
1807 Lisp variable `state'."
1808 :group 'org-todo
1809 :type 'hook)
1811 (defcustom org-log-done nil
1812 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1813 When equal to the list (done), also prompt for a closing note.
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: logdone
1818 #+STARTUP: lognotedone
1819 #+STARTUP: nologdone"
1820 :group 'org-todo
1821 :group 'org-progress
1822 :type '(choice
1823 (const :tag "No logging" nil)
1824 (const :tag "Record CLOSED timestamp" time)
1825 (const :tag "Record CLOSED timestamp with closing note." note)))
1827 ;; Normalize old uses of org-log-done.
1828 (cond
1829 ((eq org-log-done t) (setq org-log-done 'time))
1830 ((and (listp org-log-done) (memq 'done org-log-done))
1831 (setq org-log-done 'note)))
1833 ;; FIXME: document
1834 (defcustom org-log-note-clock-out nil
1835 "Non-nil means, recored a note when clocking out of an item.
1836 This can also be configured on a per-file basis by adding one of
1837 the following lines anywhere in the buffer:
1839 #+STARTUP: lognoteclock-out
1840 #+STARTUP: nolognoteclock-out"
1841 :group 'org-todo
1842 :group 'org-progress
1843 :type 'boolean)
1845 (defcustom org-log-done-with-time t
1846 "Non-nil means, the CLOSED time stamp will contain date and time.
1847 When nil, only the date will be recorded."
1848 :group 'org-progress
1849 :type 'boolean)
1851 (defcustom org-log-note-headings
1852 '((done . "CLOSING NOTE %t")
1853 (state . "State %-12s %t")
1854 (clock-out . ""))
1855 "Headings for notes added when clocking out or closing TODO items.
1856 The value is an alist, with the car being a symbol indicating the note
1857 context, and the cdr is the heading to be used. The heading may also be the
1858 empty string.
1859 %t in the heading will be replaced by a time stamp.
1860 %s will be replaced by the new TODO state, in double quotes.
1861 %u will be replaced by the user name.
1862 %U will be replaced by the full user name."
1863 :group 'org-todo
1864 :group 'org-progress
1865 :type '(list :greedy t
1866 (cons (const :tag "Heading when closing an item" done) string)
1867 (cons (const :tag
1868 "Heading when changing todo state (todo sequence only)"
1869 state) string)
1870 (cons (const :tag "Heading when clocking out" clock-out) string)))
1872 (defcustom org-log-states-order-reversed t
1873 "Non-nil means, the latest state change note will be directly after heading.
1874 When nil, the notes will be orderer according to time."
1875 :group 'org-todo
1876 :group 'org-progress
1877 :type 'boolean)
1879 (defcustom org-log-repeat 'time
1880 "Non-nil means, record moving through the DONE state when triggering repeat.
1881 An auto-repeating tasks is immediately switched back to TODO when marked
1882 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1883 the TODO keyword definition, or recording a cloing note by setting
1884 `org-log-done', there will be no record of the task moving trhough DONE.
1885 This variable forces taking a note anyway. Possible values are:
1887 nil Don't force a record
1888 time Record a time stamp
1889 note Record a note
1891 This option can also be set with on a per-file-basis with
1893 #+STARTUP: logrepeat
1894 #+STARTUP: lognoterepeat
1895 #+STARTUP: nologrepeat
1897 You can have local logging settings for a subtree by setting the LOGGING
1898 property to one or more of these keywords."
1899 :group 'org-todo
1900 :group 'org-progress
1901 :type '(choice
1902 (const :tag "Don't force a record" nil)
1903 (const :tag "Force recording the DONE state" time)
1904 (const :tag "Force recording a note with the DONE state" note)))
1906 (defcustom org-clock-into-drawer 2
1907 "Should clocking info be wrapped into a drawer?
1908 When t, clocking info will always be inserted into a :CLOCK: drawer.
1909 If necessary, the drawer will be created.
1910 When nil, the drawer will not be created, but used when present.
1911 When an integer and the number of clocking entries in an item
1912 reaches or exceeds this number, a drawer will be created."
1913 :group 'org-todo
1914 :group 'org-progress
1915 :type '(choice
1916 (const :tag "Always" t)
1917 (const :tag "Only when drawer exists" nil)
1918 (integer :tag "When at least N clock entries")))
1920 (defcustom org-clock-out-when-done t
1921 "When t, the clock will be stopped when the relevant entry is marked DONE.
1922 Nil means, clock will keep running until stopped explicitly with
1923 `C-c C-x C-o', or until the clock is started in a different item."
1924 :group 'org-progress
1925 :type 'boolean)
1927 (defcustom org-clock-in-switch-to-state nil
1928 "Set task to a special todo state while clocking it.
1929 The value should be the state to which the entry should be switched."
1930 :group 'org-progress
1931 :group 'org-todo
1932 :type '(choice
1933 (const :tag "Don't force a state" nil)
1934 (string :tag "State")))
1936 (defgroup org-priorities nil
1937 "Priorities in Org-mode."
1938 :tag "Org Priorities"
1939 :group 'org-todo)
1941 (defcustom org-highest-priority ?A
1942 "The highest priority of TODO items. A character like ?A, ?B etc.
1943 Must have a smaller ASCII number than `org-lowest-priority'."
1944 :group 'org-priorities
1945 :type 'character)
1947 (defcustom org-lowest-priority ?C
1948 "The lowest priority of TODO items. A character like ?A, ?B etc.
1949 Must have a larger ASCII number than `org-highest-priority'."
1950 :group 'org-priorities
1951 :type 'character)
1953 (defcustom org-default-priority ?B
1954 "The default priority of TODO items.
1955 This is the priority an item get if no explicit priority is given."
1956 :group 'org-priorities
1957 :type 'character)
1959 (defcustom org-priority-start-cycle-with-default t
1960 "Non-nil means, start with default priority when starting to cycle.
1961 When this is nil, the first step in the cycle will be (depending on the
1962 command used) one higher or lower that the default priority."
1963 :group 'org-priorities
1964 :type 'boolean)
1966 (defgroup org-time nil
1967 "Options concerning time stamps and deadlines in Org-mode."
1968 :tag "Org Time"
1969 :group 'org)
1971 (defcustom org-insert-labeled-timestamps-at-point nil
1972 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1973 When nil, these labeled time stamps are forces into the second line of an
1974 entry, just after the headline. When scheduling from the global TODO list,
1975 the time stamp will always be forced into the second line."
1976 :group 'org-time
1977 :type 'boolean)
1979 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1980 "Formats for `format-time-string' which are used for time stamps.
1981 It is not recommended to change this constant.")
1983 (defcustom org-time-stamp-rounding-minutes '(0 5)
1984 "Number of minutes to round time stamps to.
1985 These are two values, the first applies when first creating a time stamp.
1986 The second applies when changing it with the commands `S-up' and `S-down'.
1987 When changing the time stamp, this means that it will change in steps
1988 of N minues, as given by the second value.
1990 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1991 numbers should be factors of 60, so for example 5, 10, 15.
1993 When this is larger than 1, you can still force an exact time-stamp by using
1994 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1995 and by using a prefix arg to `S-up/down' to specify the exact number
1996 of minutes to shift."
1997 :group 'org-time
1998 :get '(lambda (var) ; Make sure all entries have 5 elements
1999 (if (integerp (default-value var))
2000 (list (default-value var) 5)
2001 (default-value var)))
2002 :type '(list
2003 (integer :tag "when inserting times")
2004 (integer :tag "when modifying times")))
2006 ;; Make sure old customizations of this variable don't lead to problems.
2007 (when (integerp org-time-stamp-rounding-minutes)
2008 (setq org-time-stamp-rounding-minutes
2009 (list org-time-stamp-rounding-minutes
2010 org-time-stamp-rounding-minutes)))
2012 (defcustom org-display-custom-times nil
2013 "Non-nil means, overlay custom formats over all time stamps.
2014 The formats are defined through the variable `org-time-stamp-custom-formats'.
2015 To turn this on on a per-file basis, insert anywhere in the file:
2016 #+STARTUP: customtime"
2017 :group 'org-time
2018 :set 'set-default
2019 :type 'sexp)
2020 (make-variable-buffer-local 'org-display-custom-times)
2022 (defcustom org-time-stamp-custom-formats
2023 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2024 "Custom formats for time stamps. See `format-time-string' for the syntax.
2025 These are overlayed over the default ISO format if the variable
2026 `org-display-custom-times' is set. Time like %H:%M should be at the
2027 end of the second format."
2028 :group 'org-time
2029 :type 'sexp)
2031 (defun org-time-stamp-format (&optional long inactive)
2032 "Get the right format for a time string."
2033 (let ((f (if long (cdr org-time-stamp-formats)
2034 (car org-time-stamp-formats))))
2035 (if inactive
2036 (concat "[" (substring f 1 -1) "]")
2037 f)))
2039 (defcustom org-read-date-prefer-future t
2040 "Non-nil means, assume future for incomplete date input from user.
2041 This affects the following situations:
2042 1. The user gives a day, but no month.
2043 For example, if today is the 15th, and you enter \"3\", Org-mode will
2044 read this as the third of *next* month. However, if you enter \"17\",
2045 it will be considered as *this* month.
2046 2. The user gives a month but not a year.
2047 For example, if it is april and you enter \"feb 2\", this will be read
2048 as feb 2, *next* year. \"May 5\", however, will be this year.
2050 When this option is nil, the current month and year will always be used
2051 as defaults."
2052 :group 'org-time
2053 :type 'boolean)
2055 (defcustom org-read-date-display-live t
2056 "Non-nil means, display current interpretation of date prompt live.
2057 This display will be in an overlay, in the minibuffer."
2058 :group 'org-time
2059 :type 'boolean)
2061 (defcustom org-read-date-popup-calendar t
2062 "Non-nil means, pop up a calendar when prompting for a date.
2063 In the calendar, the date can be selected with mouse-1. However, the
2064 minibuffer will also be active, and you can simply enter the date as well.
2065 When nil, only the minibuffer will be available."
2066 :group 'org-time
2067 :type 'boolean)
2068 (if (fboundp 'defvaralias)
2069 (defvaralias 'org-popup-calendar-for-date-prompt
2070 'org-read-date-popup-calendar))
2072 (defcustom org-extend-today-until 0
2073 "The hour when your day really ends.
2074 This has influence for the following applications:
2075 - When switching the agenda to \"today\". It it is still earlier than
2076 the time given here, the day recognized as TODAY is actually yesterday.
2077 - When a date is read from the user and it is still before the time given
2078 here, the current date and time will be assumed to be yesterday, 23:59.
2080 FIXME:
2081 IMPORTANT: This is still a very experimental feature, it may disappear
2082 again or it may be extended to mean more things."
2083 :group 'org-time
2084 :type 'number)
2086 (defcustom org-edit-timestamp-down-means-later nil
2087 "Non-nil means, S-down will increase the time in a time stamp.
2088 When nil, S-up will increase."
2089 :group 'org-time
2090 :type 'boolean)
2092 (defcustom org-calendar-follow-timestamp-change t
2093 "Non-nil means, make the calendar window follow timestamp changes.
2094 When a timestamp is modified and the calendar window is visible, it will be
2095 moved to the new date."
2096 :group 'org-time
2097 :type 'boolean)
2099 (defcustom org-clock-heading-function nil
2100 "When non-nil, should be a function to create `org-clock-heading'.
2101 This is the string shown in the mode line when a clock is running.
2102 The function is called with point at the beginning of the headline."
2103 :group 'org-time ; FIXME: Should we have a separate group????
2104 :type 'function)
2106 (defgroup org-tags nil
2107 "Options concerning tags in Org-mode."
2108 :tag "Org Tags"
2109 :group 'org)
2111 (defcustom org-tag-alist nil
2112 "List of tags allowed in Org-mode files.
2113 When this list is nil, Org-mode will base TAG input on what is already in the
2114 buffer.
2115 The value of this variable is an alist, the car of each entry must be a
2116 keyword as a string, the cdr may be a character that is used to select
2117 that tag through the fast-tag-selection interface.
2118 See the manual for details."
2119 :group 'org-tags
2120 :type '(repeat
2121 (choice
2122 (cons (string :tag "Tag name")
2123 (character :tag "Access char"))
2124 (const :tag "Start radio group" (:startgroup))
2125 (const :tag "End radio group" (:endgroup)))))
2127 (defcustom org-use-fast-tag-selection 'auto
2128 "Non-nil means, use fast tag selection scheme.
2129 This is a special interface to select and deselect tags with single keys.
2130 When nil, fast selection is never used.
2131 When the symbol `auto', fast selection is used if and only if selection
2132 characters for tags have been configured, either through the variable
2133 `org-tag-alist' or through a #+TAGS line in the buffer.
2134 When t, fast selection is always used and selection keys are assigned
2135 automatically if necessary."
2136 :group 'org-tags
2137 :type '(choice
2138 (const :tag "Always" t)
2139 (const :tag "Never" nil)
2140 (const :tag "When selection characters are configured" 'auto)))
2142 (defcustom org-fast-tag-selection-single-key nil
2143 "Non-nil means, fast tag selection exits after first change.
2144 When nil, you have to press RET to exit it.
2145 During fast tag selection, you can toggle this flag with `C-c'.
2146 This variable can also have the value `expert'. In this case, the window
2147 displaying the tags menu is not even shown, until you press C-c again."
2148 :group 'org-tags
2149 :type '(choice
2150 (const :tag "No" nil)
2151 (const :tag "Yes" t)
2152 (const :tag "Expert" expert)))
2154 (defvar org-fast-tag-selection-include-todo nil
2155 "Non-nil means, fast tags selection interface will also offer TODO states.
2156 This is an undocumented feature, you should not rely on it.")
2158 (defcustom org-tags-column -80
2159 "The column to which tags should be indented in a headline.
2160 If this number is positive, it specifies the column. If it is negative,
2161 it means that the tags should be flushright to that column. For example,
2162 -80 works well for a normal 80 character screen."
2163 :group 'org-tags
2164 :type 'integer)
2166 (defcustom org-auto-align-tags t
2167 "Non-nil means, realign tags after pro/demotion of TODO state change.
2168 These operations change the length of a headline and therefore shift
2169 the tags around. With this options turned on, after each such operation
2170 the tags are again aligned to `org-tags-column'."
2171 :group 'org-tags
2172 :type 'boolean)
2174 (defcustom org-use-tag-inheritance t
2175 "Non-nil means, tags in levels apply also for sublevels.
2176 When nil, only the tags directly given in a specific line apply there.
2177 If you turn off this option, you very likely want to turn on the
2178 companion option `org-tags-match-list-sublevels'."
2179 :group 'org-tags
2180 :type 'boolean)
2182 (defcustom org-tags-match-list-sublevels nil
2183 "Non-nil means list also sublevels of headlines matching tag search.
2184 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2185 the sublevels of a headline matching a tag search often also match
2186 the same search. Listing all of them can create very long lists.
2187 Setting this variable to nil causes subtrees of a match to be skipped.
2188 This option is off by default, because inheritance in on. If you turn
2189 inheritance off, you very likely want to turn this option on.
2191 As a special case, if the tag search is restricted to TODO items, the
2192 value of this variable is ignored and sublevels are always checked, to
2193 make sure all corresponding TODO items find their way into the list."
2194 :group 'org-tags
2195 :type 'boolean)
2197 (defvar org-tags-history nil
2198 "History of minibuffer reads for tags.")
2199 (defvar org-last-tags-completion-table nil
2200 "The last used completion table for tags.")
2201 (defvar org-after-tags-change-hook nil
2202 "Hook that is run after the tags in a line have changed.")
2204 (defgroup org-properties nil
2205 "Options concerning properties in Org-mode."
2206 :tag "Org Properties"
2207 :group 'org)
2209 (defcustom org-property-format "%-10s %s"
2210 "How property key/value pairs should be formatted by `indent-line'.
2211 When `indent-line' hits a property definition, it will format the line
2212 according to this format, mainly to make sure that the values are
2213 lined-up with respect to each other."
2214 :group 'org-properties
2215 :type 'string)
2217 (defcustom org-use-property-inheritance nil
2218 "Non-nil means, properties apply also for sublevels.
2219 This setting is only relevant during property searches, not when querying
2220 an entry with `org-entry-get'. To retrieve a property with inheritance,
2221 you need to call `org-entry-get' with the inheritance flag.
2222 Turning this on can cause significant overhead when doing a search, so
2223 this is turned off by default.
2224 When nil, only the properties directly given in the current entry count.
2225 The value may also be a list of properties that shouldhave inheritance.
2227 However, note that some special properties use inheritance under special
2228 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2229 and the properties ending in \"_ALL\" when they are used as descriptor
2230 for valid values of a property."
2231 :group 'org-properties
2232 :type '(choice
2233 (const :tag "Not" nil)
2234 (const :tag "Always" nil)
2235 (repeat :tag "Specific properties" (string :tag "Property"))))
2237 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2238 "The default column format, if no other format has been defined.
2239 This variable can be set on the per-file basis by inserting a line
2241 #+COLUMNS: %25ITEM ....."
2242 :group 'org-properties
2243 :type 'string)
2245 (defcustom org-global-properties nil
2246 "List of property/value pairs that can be inherited by any entry.
2247 You can set buffer-local values for this by adding lines like
2249 #+PROPERTY: NAME VALUE"
2250 :group 'org-properties
2251 :type '(repeat
2252 (cons (string :tag "Property")
2253 (string :tag "Value"))))
2255 (defvar org-local-properties nil
2256 "List of property/value pairs that can be inherited by any entry.
2257 Valid for the current buffer.
2258 This variable is populated from #+PROPERTY lines.")
2260 (defgroup org-agenda nil
2261 "Options concerning agenda views in Org-mode."
2262 :tag "Org Agenda"
2263 :group 'org)
2265 (defvar org-category nil
2266 "Variable used by org files to set a category for agenda display.
2267 Such files should use a file variable to set it, for example
2269 # -*- mode: org; org-category: \"ELisp\"
2271 or contain a special line
2273 #+CATEGORY: ELisp
2275 If the file does not specify a category, then file's base name
2276 is used instead.")
2277 (make-variable-buffer-local 'org-category)
2279 (defcustom org-agenda-files nil
2280 "The files to be used for agenda display.
2281 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2282 \\[org-remove-file]. You can also use customize to edit the list.
2284 If an entry is a directory, all files in that directory that are matched by
2285 `org-agenda-file-regexp' will be part of the file list.
2287 If the value of the variable is not a list but a single file name, then
2288 the list of agenda files is actually stored and maintained in that file, one
2289 agenda file per line."
2290 :group 'org-agenda
2291 :type '(choice
2292 (repeat :tag "List of files and directories" file)
2293 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2295 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2296 "Regular expression to match files for `org-agenda-files'.
2297 If any element in the list in that variable contains a directory instead
2298 of a normal file, all files in that directory that are matched by this
2299 regular expression will be included."
2300 :group 'org-agenda
2301 :type 'regexp)
2303 (defcustom org-agenda-skip-unavailable-files nil
2304 "t means to just skip non-reachable files in `org-agenda-files'.
2305 Nil means to remove them, after a query, from the list."
2306 :group 'org-agenda
2307 :type 'boolean)
2309 (defcustom org-agenda-text-search-extra-files nil
2310 "List of extra files to be searched by text search commands.
2311 These files will be search in addition to the agenda files bu the
2312 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2313 Note that these files will only be searched for text search commands,
2314 not for the other agenda views like todo lists, tag earches or the weekly
2315 agenda. This variable is intended to list notes and possibly archive files
2316 that should also be searched by these two commands."
2317 :group 'org-agenda
2318 :type '(repeat file))
2320 (if (fboundp 'defvaralias)
2321 (defvaralias 'org-agenda-multi-occur-extra-files
2322 'org-agenda-text-search-extra-files))
2324 (defcustom org-agenda-confirm-kill 1
2325 "When set, remote killing from the agenda buffer needs confirmation.
2326 When t, a confirmation is always needed. When a number N, confirmation is
2327 only needed when the text to be killed contains more than N non-white lines."
2328 :group 'org-agenda
2329 :type '(choice
2330 (const :tag "Never" nil)
2331 (const :tag "Always" t)
2332 (number :tag "When more than N lines")))
2334 (defcustom org-calendar-to-agenda-key [?c]
2335 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2336 The command `org-calendar-goto-agenda' will be bound to this key. The
2337 default is the character `c' because then `c' can be used to switch back and
2338 forth between agenda and calendar."
2339 :group 'org-agenda
2340 :type 'sexp)
2342 (defcustom org-agenda-compact-blocks nil
2343 "Non-nil means, make the block agenda more compact.
2344 This is done by leaving out unnecessary lines."
2345 :group 'org-agenda
2346 :type nil)
2348 (defgroup org-agenda-export nil
2349 "Options concerning exporting agenda views in Org-mode."
2350 :tag "Org Agenda Export"
2351 :group 'org-agenda)
2353 (defcustom org-agenda-with-colors t
2354 "Non-nil means, use colors in agenda views."
2355 :group 'org-agenda-export
2356 :type 'boolean)
2358 (defcustom org-agenda-exporter-settings nil
2359 "Alist of variable/value pairs that should be active during agenda export.
2360 This is a good place to set uptions for ps-print and for htmlize."
2361 :group 'org-agenda-export
2362 :type '(repeat
2363 (list
2364 (variable)
2365 (sexp :tag "Value"))))
2367 (defcustom org-agenda-export-html-style ""
2368 "The style specification for exported HTML Agenda files.
2369 If this variable contains a string, it will replace the default <style>
2370 section as produced by `htmlize'.
2371 Since there are different ways of setting style information, this variable
2372 needs to contain the full HTML structure to provide a style, including the
2373 surrounding HTML tags. The style specifications should include definitions
2374 the fonts used by the agenda, here is an example:
2376 <style type=\"text/css\">
2377 p { font-weight: normal; color: gray; }
2378 .org-agenda-structure {
2379 font-size: 110%;
2380 color: #003399;
2381 font-weight: 600;
2383 .org-todo {
2384 color: #cc6666;
2385 font-weight: bold;
2387 .org-done {
2388 color: #339933;
2390 .title { text-align: center; }
2391 .todo, .deadline { color: red; }
2392 .done { color: green; }
2393 </style>
2395 or, if you want to keep the style in a file,
2397 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2399 As the value of this option simply gets inserted into the HTML <head> header,
2400 you can \"misuse\" it to also add other text to the header. However,
2401 <style>...</style> is required, if not present the variable will be ignored."
2402 :group 'org-agenda-export
2403 :group 'org-export-html
2404 :type 'string)
2406 (defgroup org-agenda-custom-commands nil
2407 "Options concerning agenda views in Org-mode."
2408 :tag "Org Agenda Custom Commands"
2409 :group 'org-agenda)
2411 (defconst org-sorting-choice
2412 '(choice
2413 (const time-up) (const time-down)
2414 (const category-keep) (const category-up) (const category-down)
2415 (const tag-down) (const tag-up)
2416 (const priority-up) (const priority-down))
2417 "Sorting choices.")
2419 (defconst org-agenda-custom-commands-local-options
2420 `(repeat :tag "Local settings for this command. Remember to quote values"
2421 (choice :tag "Setting"
2422 (list :tag "Any variable"
2423 (variable :tag "Variable")
2424 (sexp :tag "Value"))
2425 (list :tag "Files to be searched"
2426 (const org-agenda-files)
2427 (list
2428 (const :format "" quote)
2429 (repeat
2430 (file))))
2431 (list :tag "Sorting strategy"
2432 (const org-agenda-sorting-strategy)
2433 (list
2434 (const :format "" quote)
2435 (repeat
2436 ,org-sorting-choice)))
2437 (list :tag "Prefix format"
2438 (const org-agenda-prefix-format :value " %-12:c%?-12t% s")
2439 (string))
2440 (list :tag "Number of days in agenda"
2441 (const org-agenda-ndays)
2442 (integer :value 1))
2443 (list :tag "Fixed starting date"
2444 (const org-agenda-start-day)
2445 (string :value "2007-11-01"))
2446 (list :tag "Start on day of week"
2447 (const org-agenda-start-on-weekday)
2448 (choice :value 1
2449 (const :tag "Today" nil)
2450 (number :tag "Weekday No.")))
2451 (list :tag "Include data from diary"
2452 (const org-agenda-include-diary)
2453 (boolean))
2454 (list :tag "Deadline Warning days"
2455 (const org-deadline-warning-days)
2456 (integer :value 1))
2457 (list :tag "Standard skipping condition"
2458 :value (org-agenda-skip-function '(org-agenda-skip-entry-if))
2459 (const org-agenda-skip-function)
2460 (list
2461 (const :format "" quote)
2462 (list
2463 (choice
2464 :tag "Skiping range"
2465 (const :tag "Skip entry" org-agenda-skip-entry-if)
2466 (const :tag "Skip subtree" org-agenda-skip-subtree-if))
2467 (repeat :inline t :tag "Conditions for skipping"
2468 (choice
2469 :tag "Condition type"
2470 (list :tag "Regexp matches" :inline t (const :format "" 'regexp) (regexp))
2471 (list :tag "Regexp does not match" :inline t (const :format "" 'notregexp) (regexp))
2472 (const :tag "scheduled" 'scheduled)
2473 (const :tag "not scheduled" 'notscheduled)
2474 (const :tag "deadline" 'deadline)
2475 (const :tag "no deadline" 'notdeadline))))))
2476 (list :tag "Non-standard skipping condition"
2477 :value (org-agenda-skip-function)
2478 (list
2479 (const org-agenda-skip-function)
2480 (sexp :tag "Function or form (quoted!)")))))
2481 "Selection of examples for agenda command settings.
2482 This will be spliced into the custom type of
2483 `org-agenda-custom-commands'.")
2486 (defcustom org-agenda-custom-commands nil
2487 "Custom commands for the agenda.
2488 These commands will be offered on the splash screen displayed by the
2489 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2491 (key desc type match settings files)
2493 key The key (one or more characters as a string) to be associated
2494 with the command.
2495 desc A description of the command, when omitted or nil, a default
2496 description is built using MATCH.
2497 type The command type, any of the following symbols:
2498 agenda The daily/weekly agenda.
2499 todo Entries with a specific TODO keyword, in all agenda files.
2500 search Entries containing search words entry or headline.
2501 tags Tags/Property/TODO match in all agenda files.
2502 tags-todo Tags/P/T match in all agenda files, TODO entries only.
2503 todo-tree Sparse tree of specific TODO keyword in *current* file.
2504 tags-tree Sparse tree with all tags matches in *current* file.
2505 occur-tree Occur sparse tree for *current* file.
2506 ... A user-defined function.
2507 match What to search for:
2508 - a single keyword for TODO keyword searches
2509 - a tags match expression for tags searches
2510 - a word search expression for text searches.
2511 - a regular expression for occur searches
2512 For all other commands, this should be the empty string.
2513 settings A list of option settings, similar to that in a let form, so like
2514 this: ((opt1 val1) (opt2 val2) ...). The values will be
2515 evaluated at the moment of execution, so quote them when needed.
2516 files A list of files file to write the produced agenda buffer to
2517 with the command `org-store-agenda-views'.
2518 If a file name ends in \".html\", an HTML version of the buffer
2519 is written out. If it ends in \".ps\", a postscript version is
2520 produced. Otherwide, only the plain text is written to the file.
2522 You can also define a set of commands, to create a composite agenda buffer.
2523 In this case, an entry looks like this:
2525 (key desc (cmd1 cmd2 ...) general-settings-for-whole-set files)
2527 where
2529 desc A description string to be displayed in the dispatcher menu.
2530 cmd An agenda command, similar to the above. However, tree commands
2531 are no allowed, but instead you can get agenda and global todo list.
2532 So valid commands for a set are:
2533 (agenda \"\" settings)
2534 (alltodo \"\" settings)
2535 (stuck \"\" settings)
2536 (todo \"match\" settings files)
2537 (search \"match\" settings files)
2538 (tags \"match\" settings files)
2539 (tags-todo \"match\" settings files)
2541 Each command can carry a list of options, and another set of options can be
2542 given for the whole set of commands. Individual command options take
2543 precedence over the general options.
2545 When using several characters as key to a command, the first characters
2546 are prefix commands. For the dispatcher to display useful information, you
2547 should provide a description for the prefix, like
2549 (setq org-agenda-custom-commands
2550 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2551 (\"hl\" tags \"+HOME+Lisa\")
2552 (\"hp\" tags \"+HOME+Peter\")
2553 (\"hk\" tags \"+HOME+Kim\")))"
2554 :group 'org-agenda-custom-commands
2555 :type `(repeat
2556 (choice :value ("x" "Describe command here" tags "" nil)
2557 (list :tag "Single command"
2558 (string :tag "Access Key(s) ")
2559 (option (string :tag "Description"))
2560 (choice
2561 (const :tag "Agenda" agenda)
2562 (const :tag "TODO list" alltodo)
2563 (const :tag "Search words" search)
2564 (const :tag "Stuck projects" stuck)
2565 (const :tag "Tags search (all agenda files)" tags)
2566 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2567 (const :tag "TODO keyword search (all agenda files)" todo)
2568 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2569 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2570 (const :tag "Occur tree (current buffer)" occur-tree)
2571 (sexp :tag "Other, user-defined function"))
2572 (string :tag "Match (only for some commands)")
2573 ,org-agenda-custom-commands-local-options
2574 (option (repeat :tag "Export" (file :tag "Export to"))))
2575 (list :tag "Command series, all agenda files"
2576 (string :tag "Access Key(s)")
2577 (string :tag "Description ")
2578 (repeat :tag "Component"
2579 (choice
2580 (list :tag "Agenda"
2581 (const :format "" agenda)
2582 (const :tag "" :format "" "")
2583 ,org-agenda-custom-commands-local-options)
2584 (list :tag "TODO list (all keywords)"
2585 (const :format "" alltodo)
2586 (const :tag "" :format "" "")
2587 ,org-agenda-custom-commands-local-options)
2588 (list :tag "Search words"
2589 (const :format "" search)
2590 (string :tag "Match")
2591 ,org-agenda-custom-commands-local-options)
2592 (list :tag "Stuck projects"
2593 (const :format "" stuck)
2594 (const :tag "" :format "" "")
2595 ,org-agenda-custom-commands-local-options)
2596 (list :tag "Tags search"
2597 (const :format "" tags)
2598 (string :tag "Match")
2599 ,org-agenda-custom-commands-local-options)
2600 (list :tag "Tags search, TODO entries only"
2601 (const :format "" tags-todo)
2602 (string :tag "Match")
2603 ,org-agenda-custom-commands-local-options)
2604 (list :tag "TODO keyword search"
2605 (const :format "" todo)
2606 (string :tag "Match")
2607 ,org-agenda-custom-commands-local-options)
2608 (list :tag "Other, user-defined function"
2609 (symbol :tag "function")
2610 (string :tag "Match")
2611 ,org-agenda-custom-commands-local-options)))
2613 (repeat :tag "Settings for entire command set"
2614 (list (variable :tag "Any variable")
2615 (sexp :tag "Value")))
2616 (option (repeat :tag "Export" (file :tag "Export to"))))
2617 (cons :tag "Prefix key documentation"
2618 (string :tag "Access Key(s)")
2619 (string :tag "Description ")))))
2621 (defcustom org-agenda-query-register ?o
2622 "The register holding the current query string.
2623 The prupose of this is that if you construct a query string interactively,
2624 you can then use it to define a custom command."
2625 :group 'org-agenda-custom-commands
2626 :type 'character)
2628 (defcustom org-stuck-projects
2629 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2630 "How to identify stuck projects.
2631 This is a list of four items:
2632 1. A tags/todo matcher string that is used to identify a project.
2633 The entire tree below a headline matched by this is considered one project.
2634 2. A list of TODO keywords identifying non-stuck projects.
2635 If the project subtree contains any headline with one of these todo
2636 keywords, the project is considered to be not stuck. If you specify
2637 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2638 3. A list of tags identifying non-stuck projects.
2639 If the project subtree contains any headline with one of these tags,
2640 the project is considered to be not stuck. If you specify \"*\" as
2641 a tag, any tag will mark the project unstuck.
2642 4. An arbitrary regular expression matching non-stuck projects.
2644 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2645 or `C-c a #' to produce the list."
2646 :group 'org-agenda-custom-commands
2647 :type '(list
2648 (string :tag "Tags/TODO match to identify a project")
2649 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2650 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2651 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2654 (defgroup org-agenda-skip nil
2655 "Options concerning skipping parts of agenda files."
2656 :tag "Org Agenda Skip"
2657 :group 'org-agenda)
2659 (defcustom org-agenda-todo-list-sublevels t
2660 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2661 When nil, the sublevels of a TODO entry are not checked, resulting in
2662 potentially much shorter TODO lists."
2663 :group 'org-agenda-skip
2664 :group 'org-todo
2665 :type 'boolean)
2667 (defcustom org-agenda-todo-ignore-with-date nil
2668 "Non-nil means, don't show entries with a date in the global todo list.
2669 You can use this if you prefer to mark mere appointments with a TODO keyword,
2670 but don't want them to show up in the TODO list.
2671 When this is set, it also covers deadlines and scheduled items, the settings
2672 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2673 will be ignored."
2674 :group 'org-agenda-skip
2675 :group 'org-todo
2676 :type 'boolean)
2678 (defcustom org-agenda-todo-ignore-scheduled nil
2679 "Non-nil means, don't show scheduled entries in the global todo list.
2680 The idea behind this is that by scheduling it, you have already taken care
2681 of this item.
2682 See also `org-agenda-todo-ignore-with-date'."
2683 :group 'org-agenda-skip
2684 :group 'org-todo
2685 :type 'boolean)
2687 (defcustom org-agenda-todo-ignore-deadlines nil
2688 "Non-nil means, don't show near deadline entries in the global todo list.
2689 Near means closer than `org-deadline-warning-days' days.
2690 The idea behind this is that such items will appear in the agenda anyway.
2691 See also `org-agenda-todo-ignore-with-date'."
2692 :group 'org-agenda-skip
2693 :group 'org-todo
2694 :type 'boolean)
2696 (defcustom org-agenda-skip-scheduled-if-done nil
2697 "Non-nil means don't show scheduled items in agenda when they are done.
2698 This is relevant for the daily/weekly agenda, not for the TODO list. And
2699 it applies only to the actual date of the scheduling. Warnings about
2700 an item with a past scheduling dates are always turned off when the item
2701 is DONE."
2702 :group 'org-agenda-skip
2703 :type 'boolean)
2705 (defcustom org-agenda-skip-deadline-if-done nil
2706 "Non-nil means don't show deadines when the corresponding item is done.
2707 When nil, the deadline is still shown and should give you a happy feeling.
2708 This is relevant for the daily/weekly agenda. And it applied only to the
2709 actualy date of the deadline. Warnings about approching and past-due
2710 deadlines are always turned off when the item is DONE."
2711 :group 'org-agenda-skip
2712 :type 'boolean)
2714 (defcustom org-agenda-skip-timestamp-if-done nil
2715 "Non-nil means don't select item by timestamp or -range if it is DONE."
2716 :group 'org-agenda-skip
2717 :type 'boolean)
2719 (defcustom org-timeline-show-empty-dates 3
2720 "Non-nil means, `org-timeline' also shows dates without an entry.
2721 When nil, only the days which actually have entries are shown.
2722 When t, all days between the first and the last date are shown.
2723 When an integer, show also empty dates, but if there is a gap of more than
2724 N days, just insert a special line indicating the size of the gap."
2725 :group 'org-agenda-skip
2726 :type '(choice
2727 (const :tag "None" nil)
2728 (const :tag "All" t)
2729 (number :tag "at most")))
2732 (defgroup org-agenda-startup nil
2733 "Options concerning initial settings in the Agenda in Org Mode."
2734 :tag "Org Agenda Startup"
2735 :group 'org-agenda)
2737 (defcustom org-finalize-agenda-hook nil
2738 "Hook run just before displaying an agenda buffer."
2739 :group 'org-agenda-startup
2740 :type 'hook)
2742 (defcustom org-agenda-mouse-1-follows-link nil
2743 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2744 A longer mouse click will still set point. Does not work on XEmacs.
2745 Needs to be set before org.el is loaded."
2746 :group 'org-agenda-startup
2747 :type 'boolean)
2749 (defcustom org-agenda-start-with-follow-mode nil
2750 "The initial value of follow-mode in a newly created agenda window."
2751 :group 'org-agenda-startup
2752 :type 'boolean)
2754 (defgroup org-agenda-windows nil
2755 "Options concerning the windows used by the Agenda in Org Mode."
2756 :tag "Org Agenda Windows"
2757 :group 'org-agenda)
2759 (defcustom org-agenda-window-setup 'reorganize-frame
2760 "How the agenda buffer should be displayed.
2761 Possible values for this option are:
2763 current-window Show agenda in the current window, keeping all other windows.
2764 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2765 other-window Use `switch-to-buffer-other-window' to display agenda.
2766 reorganize-frame Show only two windows on the current frame, the current
2767 window and the agenda.
2768 See also the variable `org-agenda-restore-windows-after-quit'."
2769 :group 'org-agenda-windows
2770 :type '(choice
2771 (const current-window)
2772 (const other-frame)
2773 (const other-window)
2774 (const reorganize-frame)))
2776 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2777 "The min and max height of the agenda window as a fraction of frame height.
2778 The value of the variable is a cons cell with two numbers between 0 and 1.
2779 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2780 :group 'org-agenda-windows
2781 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2783 (defcustom org-agenda-restore-windows-after-quit nil
2784 "Non-nil means, restore window configuration open exiting agenda.
2785 Before the window configuration is changed for displaying the agenda,
2786 the current status is recorded. When the agenda is exited with
2787 `q' or `x' and this option is set, the old state is restored. If
2788 `org-agenda-window-setup' is `other-frame', the value of this
2789 option will be ignored.."
2790 :group 'org-agenda-windows
2791 :type 'boolean)
2793 (defcustom org-indirect-buffer-display 'other-window
2794 "How should indirect tree buffers be displayed?
2795 This applies to indirect buffers created with the commands
2796 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2797 Valid values are:
2798 current-window Display in the current window
2799 other-window Just display in another window.
2800 dedicated-frame Create one new frame, and re-use it each time.
2801 new-frame Make a new frame each time. Note that in this case
2802 previously-made indirect buffers are kept, and you need to
2803 kill these buffers yourself."
2804 :group 'org-structure
2805 :group 'org-agenda-windows
2806 :type '(choice
2807 (const :tag "In current window" current-window)
2808 (const :tag "In current frame, other window" other-window)
2809 (const :tag "Each time a new frame" new-frame)
2810 (const :tag "One dedicated frame" dedicated-frame)))
2812 (defgroup org-agenda-daily/weekly nil
2813 "Options concerning the daily/weekly agenda."
2814 :tag "Org Agenda Daily/Weekly"
2815 :group 'org-agenda)
2817 (defcustom org-agenda-ndays 7
2818 "Number of days to include in overview display.
2819 Should be 1 or 7."
2820 :group 'org-agenda-daily/weekly
2821 :type 'number)
2823 (defcustom org-agenda-start-on-weekday 1
2824 "Non-nil means, start the overview always on the specified weekday.
2825 0 denotes Sunday, 1 denotes Monday etc.
2826 When nil, always start on the current day."
2827 :group 'org-agenda-daily/weekly
2828 :type '(choice (const :tag "Today" nil)
2829 (number :tag "Weekday No.")))
2831 (defcustom org-agenda-show-all-dates t
2832 "Non-nil means, `org-agenda' shows every day in the selected range.
2833 When nil, only the days which actually have entries are shown."
2834 :group 'org-agenda-daily/weekly
2835 :type 'boolean)
2837 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2838 "Format string for displaying dates in the agenda.
2839 Used by the daily/weekly agenda and by the timeline. This should be
2840 a format string understood by `format-time-string', or a function returning
2841 the formatted date as a string. The function must take a single argument,
2842 a calendar-style date list like (month day year)."
2843 :group 'org-agenda-daily/weekly
2844 :type '(choice
2845 (string :tag "Format string")
2846 (function :tag "Function")))
2848 (defun org-agenda-format-date-aligned (date)
2849 "Format a date string for display in the daily/weekly agenda, or timeline.
2850 This function makes sure that dates are aligned for easy reading."
2851 (format "%-9s %2d %s %4d"
2852 (calendar-day-name date)
2853 (extract-calendar-day date)
2854 (calendar-month-name (extract-calendar-month date))
2855 (extract-calendar-year date)))
2857 (defcustom org-agenda-include-diary nil
2858 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2859 :group 'org-agenda-daily/weekly
2860 :type 'boolean)
2862 (defcustom org-agenda-include-all-todo nil
2863 "Set means weekly/daily agenda will always contain all TODO entries.
2864 The TODO entries will be listed at the top of the agenda, before
2865 the entries for specific days."
2866 :group 'org-agenda-daily/weekly
2867 :type 'boolean)
2869 (defcustom org-agenda-repeating-timestamp-show-all t
2870 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2871 When nil, only one occurence is shown, either today or the
2872 nearest into the future."
2873 :group 'org-agenda-daily/weekly
2874 :type 'boolean)
2876 (defcustom org-deadline-warning-days 14
2877 "No. of days before expiration during which a deadline becomes active.
2878 This variable governs the display in sparse trees and in the agenda.
2879 When 0 or negative, it means use this number (the absolute value of it)
2880 even if a deadline has a different individual lead time specified."
2881 :group 'org-time
2882 :group 'org-agenda-daily/weekly
2883 :type 'number)
2885 (defcustom org-scheduled-past-days 10000
2886 "No. of days to continue listing scheduled items that are not marked DONE.
2887 When an item is scheduled on a date, it shows up in the agenda on this
2888 day and will be listed until it is marked done for the number of days
2889 given here."
2890 :group 'org-agenda-daily/weekly
2891 :type 'number)
2893 (defgroup org-agenda-time-grid nil
2894 "Options concerning the time grid in the Org-mode Agenda."
2895 :tag "Org Agenda Time Grid"
2896 :group 'org-agenda)
2898 (defcustom org-agenda-use-time-grid t
2899 "Non-nil means, show a time grid in the agenda schedule.
2900 A time grid is a set of lines for specific times (like every two hours between
2901 8:00 and 20:00). The items scheduled for a day at specific times are
2902 sorted in between these lines.
2903 For details about when the grid will be shown, and what it will look like, see
2904 the variable `org-agenda-time-grid'."
2905 :group 'org-agenda-time-grid
2906 :type 'boolean)
2908 (defcustom org-agenda-time-grid
2909 '((daily today require-timed)
2910 "----------------"
2911 (800 1000 1200 1400 1600 1800 2000))
2913 "The settings for time grid for agenda display.
2914 This is a list of three items. The first item is again a list. It contains
2915 symbols specifying conditions when the grid should be displayed:
2917 daily if the agenda shows a single day
2918 weekly if the agenda shows an entire week
2919 today show grid on current date, independent of daily/weekly display
2920 require-timed show grid only if at least one item has a time specification
2922 The second item is a string which will be places behing the grid time.
2924 The third item is a list of integers, indicating the times that should have
2925 a grid line."
2926 :group 'org-agenda-time-grid
2927 :type
2928 '(list
2929 (set :greedy t :tag "Grid Display Options"
2930 (const :tag "Show grid in single day agenda display" daily)
2931 (const :tag "Show grid in weekly agenda display" weekly)
2932 (const :tag "Always show grid for today" today)
2933 (const :tag "Show grid only if any timed entries are present"
2934 require-timed)
2935 (const :tag "Skip grid times already present in an entry"
2936 remove-match))
2937 (string :tag "Grid String")
2938 (repeat :tag "Grid Times" (integer :tag "Time"))))
2940 (defgroup org-agenda-sorting nil
2941 "Options concerning sorting in the Org-mode Agenda."
2942 :tag "Org Agenda Sorting"
2943 :group 'org-agenda)
2945 (defcustom org-agenda-sorting-strategy
2946 '((agenda time-up category-keep priority-down)
2947 (todo category-keep priority-down)
2948 (tags category-keep priority-down)
2949 (search category-keep))
2950 "Sorting structure for the agenda items of a single day.
2951 This is a list of symbols which will be used in sequence to determine
2952 if an entry should be listed before another entry. The following
2953 symbols are recognized:
2955 time-up Put entries with time-of-day indications first, early first
2956 time-down Put entries with time-of-day indications first, late first
2957 category-keep Keep the default order of categories, corresponding to the
2958 sequence in `org-agenda-files'.
2959 category-up Sort alphabetically by category, A-Z.
2960 category-down Sort alphabetically by category, Z-A.
2961 tag-up Sort alphabetically by last tag, A-Z.
2962 tag-down Sort alphabetically by last tag, Z-A.
2963 priority-up Sort numerically by priority, high priority last.
2964 priority-down Sort numerically by priority, high priority first.
2966 The different possibilities will be tried in sequence, and testing stops
2967 if one comparison returns a \"not-equal\". For example, the default
2968 '(time-up category-keep priority-down)
2969 means: Pull out all entries having a specified time of day and sort them,
2970 in order to make a time schedule for the current day the first thing in the
2971 agenda listing for the day. Of the entries without a time indication, keep
2972 the grouped in categories, don't sort the categories, but keep them in
2973 the sequence given in `org-agenda-files'. Within each category sort by
2974 priority.
2976 Leaving out `category-keep' would mean that items will be sorted across
2977 categories by priority.
2979 Instead of a single list, this can also be a set of list for specific
2980 contents, with a context symbol in the car of the list, any of
2981 `agenda', `todo', `tags' for the corresponding agenda views."
2982 :group 'org-agenda-sorting
2983 :type `(choice
2984 (repeat :tag "General" ,org-sorting-choice)
2985 (list :tag "Individually"
2986 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2987 (repeat ,org-sorting-choice))
2988 (cons (const :tag "Strategy for TODO lists" todo)
2989 (repeat ,org-sorting-choice))
2990 (cons (const :tag "Strategy for Tags matches" tags)
2991 (repeat ,org-sorting-choice)))))
2993 (defcustom org-sort-agenda-notime-is-late t
2994 "Non-nil means, items without time are considered late.
2995 This is only relevant for sorting. When t, items which have no explicit
2996 time like 15:30 will be considered as 99:01, i.e. later than any items which
2997 do have a time. When nil, the default time is before 0:00. You can use this
2998 option to decide if the schedule for today should come before or after timeless
2999 agenda entries."
3000 :group 'org-agenda-sorting
3001 :type 'boolean)
3003 (defgroup org-agenda-line-format nil
3004 "Options concerning the entry prefix in the Org-mode agenda display."
3005 :tag "Org Agenda Line Format"
3006 :group 'org-agenda)
3008 (defcustom org-agenda-prefix-format
3009 '((agenda . " %-12:c%?-12t% s")
3010 (timeline . " % s")
3011 (todo . " %-12:c")
3012 (tags . " %-12:c")
3013 (search . " %-12:c"))
3014 "Format specifications for the prefix of items in the agenda views.
3015 An alist with four entries, for the different agenda types. The keys to the
3016 sublists are `agenda', `timeline', `todo', and `tags'. The values
3017 are format strings.
3018 This format works similar to a printf format, with the following meaning:
3020 %c the category of the item, \"Diary\" for entries from the diary, or
3021 as given by the CATEGORY keyword or derived from the file name.
3022 %T the *last* tag of the item. Last because inherited tags come
3023 first in the list.
3024 %t the time-of-day specification if one applies to the entry, in the
3025 format HH:MM
3026 %s Scheduling/Deadline information, a short string
3028 All specifiers work basically like the standard `%s' of printf, but may
3029 contain two additional characters: A question mark just after the `%' and
3030 a whitespace/punctuation character just before the final letter.
3032 If the first character after `%' is a question mark, the entire field
3033 will only be included if the corresponding value applies to the
3034 current entry. This is useful for fields which should have fixed
3035 width when present, but zero width when absent. For example,
3036 \"%?-12t\" will result in a 12 character time field if a time of the
3037 day is specified, but will completely disappear in entries which do
3038 not contain a time.
3040 If there is punctuation or whitespace character just before the final
3041 format letter, this character will be appended to the field value if
3042 the value is not empty. For example, the format \"%-12:c\" leads to
3043 \"Diary: \" if the category is \"Diary\". If the category were be
3044 empty, no additional colon would be interted.
3046 The default value of this option is \" %-12:c%?-12t% s\", meaning:
3047 - Indent the line with two space characters
3048 - Give the category in a 12 chars wide field, padded with whitespace on
3049 the right (because of `-'). Append a colon if there is a category
3050 (because of `:').
3051 - If there is a time-of-day, put it into a 12 chars wide field. If no
3052 time, don't put in an empty field, just skip it (because of '?').
3053 - Finally, put the scheduling information and append a whitespace.
3055 As another example, if you don't want the time-of-day of entries in
3056 the prefix, you could use:
3058 (setq org-agenda-prefix-format \" %-11:c% s\")
3060 See also the variables `org-agenda-remove-times-when-in-prefix' and
3061 `org-agenda-remove-tags'."
3062 :type '(choice
3063 (string :tag "General format")
3064 (list :greedy t :tag "View dependent"
3065 (cons (const agenda) (string :tag "Format"))
3066 (cons (const timeline) (string :tag "Format"))
3067 (cons (const todo) (string :tag "Format"))
3068 (cons (const tags) (string :tag "Format"))
3069 (cons (const search) (string :tag "Format"))))
3070 :group 'org-agenda-line-format)
3072 (defvar org-prefix-format-compiled nil
3073 "The compiled version of the most recently used prefix format.
3074 See the variable `org-agenda-prefix-format'.")
3076 (defcustom org-agenda-todo-keyword-format "%-1s"
3077 "Format for the TODO keyword in agenda lines.
3078 Set this to something like \"%-12s\" if you want all TODO keywords
3079 to occupy a fixed space in the agenda display."
3080 :group 'org-agenda-line-format
3081 :type 'string)
3083 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
3084 "Text preceeding scheduled items in the agenda view.
3085 This is a list with two strings. The first applies when the item is
3086 scheduled on the current day. The second applies when it has been scheduled
3087 previously, it may contain a %d to capture how many days ago the item was
3088 scheduled."
3089 :group 'org-agenda-line-format
3090 :type '(list
3091 (string :tag "Scheduled today ")
3092 (string :tag "Scheduled previously")))
3094 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
3095 "Text preceeding deadline items in the agenda view.
3096 This is a list with two strings. The first applies when the item has its
3097 deadline on the current day. The second applies when it is in the past or
3098 in the future, it may contain %d to capture how many days away the deadline
3099 is (was)."
3100 :group 'org-agenda-line-format
3101 :type '(list
3102 (string :tag "Deadline today ")
3103 (string :tag "Deadline relative")))
3105 (defcustom org-agenda-remove-times-when-in-prefix t
3106 "Non-nil means, remove duplicate time specifications in agenda items.
3107 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
3108 time-of-day specification in a headline or diary entry is extracted and
3109 placed into the prefix. If this option is non-nil, the original specification
3110 \(a timestamp or -range, or just a plain time(range) specification like
3111 11:30-4pm) will be removed for agenda display. This makes the agenda less
3112 cluttered.
3113 The option can be t or nil. It may also be the symbol `beg', indicating
3114 that the time should only be removed what it is located at the beginning of
3115 the headline/diary entry."
3116 :group 'org-agenda-line-format
3117 :type '(choice
3118 (const :tag "Always" t)
3119 (const :tag "Never" nil)
3120 (const :tag "When at beginning of entry" beg)))
3123 (defcustom org-agenda-default-appointment-duration nil
3124 "Default duration for appointments that only have a starting time.
3125 When nil, no duration is specified in such cases.
3126 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
3127 :group 'org-agenda-line-format
3128 :type '(choice
3129 (integer :tag "Minutes")
3130 (const :tag "No default duration")))
3133 (defcustom org-agenda-remove-tags nil
3134 "Non-nil means, remove the tags from the headline copy in the agenda.
3135 When this is the symbol `prefix', only remove tags when
3136 `org-agenda-prefix-format' contains a `%T' specifier."
3137 :group 'org-agenda-line-format
3138 :type '(choice
3139 (const :tag "Always" t)
3140 (const :tag "Never" nil)
3141 (const :tag "When prefix format contains %T" prefix)))
3143 (if (fboundp 'defvaralias)
3144 (defvaralias 'org-agenda-remove-tags-when-in-prefix
3145 'org-agenda-remove-tags))
3147 (defcustom org-agenda-tags-column -80
3148 "Shift tags in agenda items to this column.
3149 If this number is positive, it specifies the column. If it is negative,
3150 it means that the tags should be flushright to that column. For example,
3151 -80 works well for a normal 80 character screen."
3152 :group 'org-agenda-line-format
3153 :type 'integer)
3155 (if (fboundp 'defvaralias)
3156 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
3158 (defcustom org-agenda-fontify-priorities t
3159 "Non-nil means, highlight low and high priorities in agenda.
3160 When t, the highest priority entries are bold, lowest priority italic.
3161 This may also be an association list of priority faces. The face may be
3162 a names face, or a list like `(:background \"Red\")'."
3163 :group 'org-agenda-line-format
3164 :type '(choice
3165 (const :tag "Never" nil)
3166 (const :tag "Defaults" t)
3167 (repeat :tag "Specify"
3168 (list (character :tag "Priority" :value ?A)
3169 (sexp :tag "face")))))
3171 (defgroup org-latex nil
3172 "Options for embedding LaTeX code into Org-mode"
3173 :tag "Org LaTeX"
3174 :group 'org)
3176 (defcustom org-format-latex-options
3177 '(:foreground default :background default :scale 1.0
3178 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3179 :matchers ("begin" "$" "$$" "\\(" "\\["))
3180 "Options for creating images from LaTeX fragments.
3181 This is a property list with the following properties:
3182 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
3183 `default' means use the forground of the default face.
3184 :background the background color, or \"Transparent\".
3185 `default' means use the background of the default face.
3186 :scale a scaling factor for the size of the images
3187 :html-foreground, :html-background, :html-scale
3188 The same numbers for HTML export.
3189 :matchers a list indicating which matchers should be used to
3190 find LaTeX fragments. Valid members of this list are:
3191 \"begin\" find environments
3192 \"$\" find math expressions surrounded by $...$
3193 \"$$\" find math expressions surrounded by $$....$$
3194 \"\\(\" find math expressions surrounded by \\(...\\)
3195 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3196 :group 'org-latex
3197 :type 'plist)
3199 (defcustom org-format-latex-header "\\documentclass{article}
3200 \\usepackage{fullpage} % do not remove
3201 \\usepackage{amssymb}
3202 \\usepackage[usenames]{color}
3203 \\usepackage{amsmath}
3204 \\usepackage{latexsym}
3205 \\usepackage[mathscr]{eucal}
3206 \\pagestyle{empty} % do not remove"
3207 "The document header used for processing LaTeX fragments."
3208 :group 'org-latex
3209 :type 'string)
3211 (defgroup org-export nil
3212 "Options for exporting org-listings."
3213 :tag "Org Export"
3214 :group 'org)
3216 (defgroup org-export-general nil
3217 "General options for exporting Org-mode files."
3218 :tag "Org Export General"
3219 :group 'org-export)
3221 ;; FIXME
3222 (defvar org-export-publishing-directory nil)
3224 (defcustom org-export-with-special-strings t
3225 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3226 When this option is turned on, these strings will be exported as:
3228 Org HTML LaTeX
3229 -----+----------+--------
3230 \\- &shy; \\-
3231 -- &ndash; --
3232 --- &mdash; ---
3233 ... &hellip; \ldots
3235 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3236 :group 'org-export-translation
3237 :type 'boolean)
3239 (defcustom org-export-language-setup
3240 '(("en" "Author" "Date" "Table of Contents")
3241 ("cs" "Autor" "Datum" "Obsah")
3242 ("da" "Ophavsmand" "Dato" "Indhold")
3243 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3244 ("es" "Autor" "Fecha" "\xcdndice")
3245 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3246 ("it" "Autore" "Data" "Indice")
3247 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3248 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3249 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3250 "Terms used in export text, translated to different languages.
3251 Use the variable `org-export-default-language' to set the language,
3252 or use the +OPTION lines for a per-file setting."
3253 :group 'org-export-general
3254 :type '(repeat
3255 (list
3256 (string :tag "HTML language tag")
3257 (string :tag "Author")
3258 (string :tag "Date")
3259 (string :tag "Table of Contents"))))
3261 (defcustom org-export-default-language "en"
3262 "The default language of HTML export, as a string.
3263 This should have an association in `org-export-language-setup'."
3264 :group 'org-export-general
3265 :type 'string)
3267 (defcustom org-export-skip-text-before-1st-heading t
3268 "Non-nil means, skip all text before the first headline when exporting.
3269 When nil, that text is exported as well."
3270 :group 'org-export-general
3271 :type 'boolean)
3273 (defcustom org-export-headline-levels 3
3274 "The last level which is still exported as a headline.
3275 Inferior levels will produce itemize lists when exported.
3276 Note that a numeric prefix argument to an exporter function overrides
3277 this setting.
3279 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3280 :group 'org-export-general
3281 :type 'number)
3283 (defcustom org-export-with-section-numbers t
3284 "Non-nil means, add section numbers to headlines when exporting.
3286 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3287 :group 'org-export-general
3288 :type 'boolean)
3290 (defcustom org-export-with-toc t
3291 "Non-nil means, create a table of contents in exported files.
3292 The TOC contains headlines with levels up to`org-export-headline-levels'.
3293 When an integer, include levels up to N in the toc, this may then be
3294 different from `org-export-headline-levels', but it will not be allowed
3295 to be larger than the number of headline levels.
3296 When nil, no table of contents is made.
3298 Headlines which contain any TODO items will be marked with \"(*)\" in
3299 ASCII export, and with red color in HTML output, if the option
3300 `org-export-mark-todo-in-toc' is set.
3302 In HTML output, the TOC will be clickable.
3304 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3305 or \"toc:3\"."
3306 :group 'org-export-general
3307 :type '(choice
3308 (const :tag "No Table of Contents" nil)
3309 (const :tag "Full Table of Contents" t)
3310 (integer :tag "TOC to level")))
3312 (defcustom org-export-mark-todo-in-toc nil
3313 "Non-nil means, mark TOC lines that contain any open TODO items."
3314 :group 'org-export-general
3315 :type 'boolean)
3317 (defcustom org-export-preserve-breaks nil
3318 "Non-nil means, preserve all line breaks when exporting.
3319 Normally, in HTML output paragraphs will be reformatted. In ASCII
3320 export, line breaks will always be preserved, regardless of this variable.
3322 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3323 :group 'org-export-general
3324 :type 'boolean)
3326 (defcustom org-export-with-archived-trees 'headline
3327 "Whether subtrees with the ARCHIVE tag should be exported.
3328 This can have three different values
3329 nil Do not export, pretend this tree is not present
3330 t Do export the entire tree
3331 headline Only export the headline, but skip the tree below it."
3332 :group 'org-export-general
3333 :group 'org-archive
3334 :type '(choice
3335 (const :tag "not at all" nil)
3336 (const :tag "headline only" 'headline)
3337 (const :tag "entirely" t)))
3339 (defcustom org-export-author-info t
3340 "Non-nil means, insert author name and email into the exported file.
3342 This option can also be set with the +OPTIONS line,
3343 e.g. \"author-info:nil\"."
3344 :group 'org-export-general
3345 :type 'boolean)
3347 (defcustom org-export-time-stamp-file t
3348 "Non-nil means, insert a time stamp into the exported file.
3349 The time stamp shows when the file was created.
3351 This option can also be set with the +OPTIONS line,
3352 e.g. \"timestamp:nil\"."
3353 :group 'org-export-general
3354 :type 'boolean)
3356 (defcustom org-export-with-timestamps t
3357 "If nil, do not export time stamps and associated keywords."
3358 :group 'org-export-general
3359 :type 'boolean)
3361 (defcustom org-export-remove-timestamps-from-toc t
3362 "If nil, remove timestamps from the table of contents entries."
3363 :group 'org-export-general
3364 :type 'boolean)
3366 (defcustom org-export-with-tags 'not-in-toc
3367 "If nil, do not export tags, just remove them from headlines.
3368 If this is the symbol `not-in-toc', tags will be removed from table of
3369 contents entries, but still be shown in the headlines of the document.
3371 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3372 :group 'org-export-general
3373 :type '(choice
3374 (const :tag "Off" nil)
3375 (const :tag "Not in TOC" not-in-toc)
3376 (const :tag "On" t)))
3378 (defcustom org-export-with-drawers nil
3379 "Non-nil means, export with drawers like the property drawer.
3380 When t, all drawers are exported. This may also be a list of
3381 drawer names to export."
3382 :group 'org-export-general
3383 :type '(choice
3384 (const :tag "All drawers" t)
3385 (const :tag "None" nil)
3386 (repeat :tag "Selected drawers"
3387 (string :tag "Drawer name"))))
3389 (defgroup org-export-translation nil
3390 "Options for translating special ascii sequences for the export backends."
3391 :tag "Org Export Translation"
3392 :group 'org-export)
3394 (defcustom org-export-with-emphasize t
3395 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3396 If the export target supports emphasizing text, the word will be
3397 typeset in bold, italic, or underlined, respectively. Works only for
3398 single words, but you can say: I *really* *mean* *this*.
3399 Not all export backends support this.
3401 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3402 :group 'org-export-translation
3403 :type 'boolean)
3405 (defcustom org-export-with-footnotes t
3406 "If nil, export [1] as a footnote marker.
3407 Lines starting with [1] will be formatted as footnotes.
3409 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3410 :group 'org-export-translation
3411 :type 'boolean)
3413 (defcustom org-export-with-sub-superscripts t
3414 "Non-nil means, interpret \"_\" and \"^\" for export.
3415 When this option is turned on, you can use TeX-like syntax for sub- and
3416 superscripts. Several characters after \"_\" or \"^\" will be
3417 considered as a single item - so grouping with {} is normally not
3418 needed. For example, the following things will be parsed as single
3419 sub- or superscripts.
3421 10^24 or 10^tau several digits will be considered 1 item.
3422 10^-12 or 10^-tau a leading sign with digits or a word
3423 x^2-y^3 will be read as x^2 - y^3, because items are
3424 terminated by almost any nonword/nondigit char.
3425 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3427 Still, ambiguity is possible - so when in doubt use {} to enclose the
3428 sub/superscript. If you set this variable to the symbol `{}',
3429 the braces are *required* in order to trigger interpretations as
3430 sub/superscript. This can be helpful in documents that need \"_\"
3431 frequently in plain text.
3433 Not all export backends support this, but HTML does.
3435 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3436 :group 'org-export-translation
3437 :type '(choice
3438 (const :tag "Always interpret" t)
3439 (const :tag "Only with braces" {})
3440 (const :tag "Never interpret" nil)))
3442 (defcustom org-export-with-special-strings t
3443 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3444 When this option is turned on, these strings will be exported as:
3446 \\- : &shy;
3447 -- : &ndash;
3448 --- : &mdash;
3450 Not all export backends support this, but HTML does.
3452 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3453 :group 'org-export-translation
3454 :type 'boolean)
3456 (defcustom org-export-with-TeX-macros t
3457 "Non-nil means, interpret simple TeX-like macros when exporting.
3458 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3459 No only real TeX macros will work here, but the standard HTML entities
3460 for math can be used as macro names as well. For a list of supported
3461 names in HTML export, see the constant `org-html-entities'.
3462 Not all export backends support this.
3464 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3465 :group 'org-export-translation
3466 :group 'org-export-latex
3467 :type 'boolean)
3469 (defcustom org-export-with-LaTeX-fragments nil
3470 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3471 When set, the exporter will find LaTeX environments if the \\begin line is
3472 the first non-white thing on a line. It will also find the math delimiters
3473 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3474 display math.
3476 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3477 :group 'org-export-translation
3478 :group 'org-export-latex
3479 :type 'boolean)
3481 (defcustom org-export-with-fixed-width t
3482 "Non-nil means, lines starting with \":\" will be in fixed width font.
3483 This can be used to have pre-formatted text, fragments of code etc. For
3484 example:
3485 : ;; Some Lisp examples
3486 : (while (defc cnt)
3487 : (ding))
3488 will be looking just like this in also HTML. See also the QUOTE keyword.
3489 Not all export backends support this.
3491 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3492 :group 'org-export-translation
3493 :type 'boolean)
3495 (defcustom org-match-sexp-depth 3
3496 "Number of stacked braces for sub/superscript matching.
3497 This has to be set before loading org.el to be effective."
3498 :group 'org-export-translation
3499 :type 'integer)
3501 (defgroup org-export-tables nil
3502 "Options for exporting tables in Org-mode."
3503 :tag "Org Export Tables"
3504 :group 'org-export)
3506 (defcustom org-export-with-tables t
3507 "If non-nil, lines starting with \"|\" define a table.
3508 For example:
3510 | Name | Address | Birthday |
3511 |-------------+----------+-----------|
3512 | Arthur Dent | England | 29.2.2100 |
3514 Not all export backends support this.
3516 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3517 :group 'org-export-tables
3518 :type 'boolean)
3520 (defcustom org-export-highlight-first-table-line t
3521 "Non-nil means, highlight the first table line.
3522 In HTML export, this means use <th> instead of <td>.
3523 In tables created with table.el, this applies to the first table line.
3524 In Org-mode tables, all lines before the first horizontal separator
3525 line will be formatted with <th> tags."
3526 :group 'org-export-tables
3527 :type 'boolean)
3529 (defcustom org-export-table-remove-special-lines t
3530 "Remove special lines and marking characters in calculating tables.
3531 This removes the special marking character column from tables that are set
3532 up for spreadsheet calculations. It also removes the entire lines
3533 marked with `!', `_', or `^'. The lines with `$' are kept, because
3534 the values of constants may be useful to have."
3535 :group 'org-export-tables
3536 :type 'boolean)
3538 (defcustom org-export-prefer-native-exporter-for-tables nil
3539 "Non-nil means, always export tables created with table.el natively.
3540 Natively means, use the HTML code generator in table.el.
3541 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3542 the table does not use row- or column-spanning). This has the
3543 advantage, that the automatic HTML conversions for math symbols and
3544 sub/superscripts can be applied. Org-mode's HTML generator is also
3545 much faster."
3546 :group 'org-export-tables
3547 :type 'boolean)
3549 (defgroup org-export-ascii nil
3550 "Options specific for ASCII export of Org-mode files."
3551 :tag "Org Export ASCII"
3552 :group 'org-export)
3554 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3555 "Characters for underlining headings in ASCII export.
3556 In the given sequence, these characters will be used for level 1, 2, ..."
3557 :group 'org-export-ascii
3558 :type '(repeat character))
3560 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3561 "Bullet characters for headlines converted to lists in ASCII export.
3562 The first character is used for the first lest level generated in this
3563 way, and so on. If there are more levels than characters given here,
3564 the list will be repeated.
3565 Note that plain lists will keep the same bullets as the have in the
3566 Org-mode file."
3567 :group 'org-export-ascii
3568 :type '(repeat character))
3570 (defgroup org-export-xml nil
3571 "Options specific for XML export of Org-mode files."
3572 :tag "Org Export XML"
3573 :group 'org-export)
3575 (defgroup org-export-html nil
3576 "Options specific for HTML export of Org-mode files."
3577 :tag "Org Export HTML"
3578 :group 'org-export)
3580 (defcustom org-export-html-coding-system nil
3582 :group 'org-export-html
3583 :type 'coding-system)
3585 (defcustom org-export-html-extension "html"
3586 "The extension for exported HTML files."
3587 :group 'org-export-html
3588 :type 'string)
3590 (defcustom org-export-html-style
3591 "<style type=\"text/css\">
3592 html {
3593 font-family: Times, serif;
3594 font-size: 12pt;
3596 .title { text-align: center; }
3597 .todo { color: red; }
3598 .done { color: green; }
3599 .timestamp { color: grey }
3600 .timestamp-kwd { color: CadetBlue }
3601 .tag { background-color:lightblue; font-weight:normal }
3602 .target { background-color: lavender; }
3603 pre {
3604 border: 1pt solid #AEBDCC;
3605 background-color: #F3F5F7;
3606 padding: 5pt;
3607 font-family: courier, monospace;
3609 table { border-collapse: collapse; }
3610 td, th {
3611 vertical-align: top;
3612 <!--border: 1pt solid #ADB9CC;-->
3614 </style>"
3615 "The default style specification for exported HTML files.
3616 Since there are different ways of setting style information, this variable
3617 needs to contain the full HTML structure to provide a style, including the
3618 surrounding HTML tags. The style specifications should include definitions
3619 for new classes todo, done, title, and deadline. For example, valid values
3620 would be:
3622 <style type=\"text/css\">
3623 p { font-weight: normal; color: gray; }
3624 h1 { color: black; }
3625 .title { text-align: center; }
3626 .todo, .deadline { color: red; }
3627 .done { color: green; }
3628 </style>
3630 or, if you want to keep the style in a file,
3632 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3634 As the value of this option simply gets inserted into the HTML <head> header,
3635 you can \"misuse\" it to add arbitrary text to the header."
3636 :group 'org-export-html
3637 :type 'string)
3640 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3641 "Format for typesetting the document title in HTML export."
3642 :group 'org-export-html
3643 :type 'string)
3645 (defcustom org-export-html-toplevel-hlevel 2
3646 "The <H> level for level 1 headings in HTML export."
3647 :group 'org-export-html
3648 :type 'string)
3650 (defcustom org-export-html-link-org-files-as-html t
3651 "Non-nil means, make file links to `file.org' point to `file.html'.
3652 When org-mode is exporting an org-mode file to HTML, links to
3653 non-html files are directly put into a href tag in HTML.
3654 However, links to other Org-mode files (recognized by the
3655 extension `.org.) should become links to the corresponding html
3656 file, assuming that the linked org-mode file will also be
3657 converted to HTML.
3658 When nil, the links still point to the plain `.org' file."
3659 :group 'org-export-html
3660 :type 'boolean)
3662 (defcustom org-export-html-inline-images 'maybe
3663 "Non-nil means, inline images into exported HTML pages.
3664 This is done using an <img> tag. When nil, an anchor with href is used to
3665 link to the image. If this option is `maybe', then images in links with
3666 an empty description will be inlined, while images with a description will
3667 be linked only."
3668 :group 'org-export-html
3669 :type '(choice (const :tag "Never" nil)
3670 (const :tag "Always" t)
3671 (const :tag "When there is no description" maybe)))
3673 ;; FIXME: rename
3674 (defcustom org-export-html-expand t
3675 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3676 When nil, these tags will be exported as plain text and therefore
3677 not be interpreted by a browser.
3679 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3680 :group 'org-export-html
3681 :type 'boolean)
3683 (defcustom org-export-html-table-tag
3684 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3685 "The HTML tag that is used to start a table.
3686 This must be a <table> tag, but you may change the options like
3687 borders and spacing."
3688 :group 'org-export-html
3689 :type 'string)
3691 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3692 "The opening tag for table header fields.
3693 This is customizable so that alignment options can be specified."
3694 :group 'org-export-tables
3695 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3697 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3698 "The opening tag for table data fields.
3699 This is customizable so that alignment options can be specified."
3700 :group 'org-export-tables
3701 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3703 (defcustom org-export-html-with-timestamp nil
3704 "If non-nil, write `org-export-html-html-helper-timestamp'
3705 into the exported HTML text. Otherwise, the buffer will just be saved
3706 to a file."
3707 :group 'org-export-html
3708 :type 'boolean)
3710 (defcustom org-export-html-html-helper-timestamp
3711 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3712 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3713 :group 'org-export-html
3714 :type 'string)
3716 (defgroup org-export-icalendar nil
3717 "Options specific for iCalendar export of Org-mode files."
3718 :tag "Org Export iCalendar"
3719 :group 'org-export)
3721 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3722 "The file name for the iCalendar file covering all agenda files.
3723 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3724 The file name should be absolute, the file will be overwritten without warning."
3725 :group 'org-export-icalendar
3726 :type 'file)
3728 (defcustom org-icalendar-include-todo nil
3729 "Non-nil means, export to iCalendar files should also cover TODO items."
3730 :group 'org-export-icalendar
3731 :type '(choice
3732 (const :tag "None" nil)
3733 (const :tag "Unfinished" t)
3734 (const :tag "All" all)))
3736 (defcustom org-icalendar-include-sexps t
3737 "Non-nil means, export to iCalendar files should also cover sexp entries.
3738 These are entries like in the diary, but directly in an Org-mode file."
3739 :group 'org-export-icalendar
3740 :type 'boolean)
3742 (defcustom org-icalendar-include-body 100
3743 "Amount of text below headline to be included in iCalendar export.
3744 This is a number of characters that should maximally be included.
3745 Properties, scheduling and clocking lines will always be removed.
3746 The text will be inserted into the DESCRIPTION field."
3747 :group 'org-export-icalendar
3748 :type '(choice
3749 (const :tag "Nothing" nil)
3750 (const :tag "Everything" t)
3751 (integer :tag "Max characters")))
3753 (defcustom org-icalendar-combined-name "OrgMode"
3754 "Calendar name for the combined iCalendar representing all agenda files."
3755 :group 'org-export-icalendar
3756 :type 'string)
3758 (defgroup org-font-lock nil
3759 "Font-lock settings for highlighting in Org-mode."
3760 :tag "Org Font Lock"
3761 :group 'org)
3763 (defcustom org-level-color-stars-only nil
3764 "Non-nil means fontify only the stars in each headline.
3765 When nil, the entire headline is fontified.
3766 Changing it requires restart of `font-lock-mode' to become effective
3767 also in regions already fontified."
3768 :group 'org-font-lock
3769 :type 'boolean)
3771 (defcustom org-hide-leading-stars nil
3772 "Non-nil means, hide the first N-1 stars in a headline.
3773 This works by using the face `org-hide' for these stars. This
3774 face is white for a light background, and black for a dark
3775 background. You may have to customize the face `org-hide' to
3776 make this work.
3777 Changing it requires restart of `font-lock-mode' to become effective
3778 also in regions already fontified.
3779 You may also set this on a per-file basis by adding one of the following
3780 lines to the buffer:
3782 #+STARTUP: hidestars
3783 #+STARTUP: showstars"
3784 :group 'org-font-lock
3785 :type 'boolean)
3787 (defcustom org-fontify-done-headline nil
3788 "Non-nil means, change the face of a headline if it is marked DONE.
3789 Normally, only the TODO/DONE keyword indicates the state of a headline.
3790 When this is non-nil, the headline after the keyword is set to the
3791 `org-headline-done' as an additional indication."
3792 :group 'org-font-lock
3793 :type 'boolean)
3795 (defcustom org-fontify-emphasized-text t
3796 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3797 Changing this variable requires a restart of Emacs to take effect."
3798 :group 'org-font-lock
3799 :type 'boolean)
3801 (defcustom org-highlight-latex-fragments-and-specials nil
3802 "Non-nil means, fontify what is treated specially by the exporters."
3803 :group 'org-font-lock
3804 :type 'boolean)
3806 (defcustom org-hide-emphasis-markers nil
3807 "Non-nil mean font-lock should hide the emphasis marker characters."
3808 :group 'org-font-lock
3809 :type 'boolean)
3811 (defvar org-emph-re nil
3812 "Regular expression for matching emphasis.")
3813 (defvar org-verbatim-re nil
3814 "Regular expression for matching verbatim text.")
3815 (defvar org-emphasis-regexp-components) ; defined just below
3816 (defvar org-emphasis-alist) ; defined just below
3817 (defun org-set-emph-re (var val)
3818 "Set variable and compute the emphasis regular expression."
3819 (set var val)
3820 (when (and (boundp 'org-emphasis-alist)
3821 (boundp 'org-emphasis-regexp-components)
3822 org-emphasis-alist org-emphasis-regexp-components)
3823 (let* ((e org-emphasis-regexp-components)
3824 (pre (car e))
3825 (post (nth 1 e))
3826 (border (nth 2 e))
3827 (body (nth 3 e))
3828 (nl (nth 4 e))
3829 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3830 (body1 (concat body "*?"))
3831 (markers (mapconcat 'car org-emphasis-alist ""))
3832 (vmarkers (mapconcat
3833 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3834 org-emphasis-alist "")))
3835 ;; make sure special characters appear at the right position in the class
3836 (if (string-match "\\^" markers)
3837 (setq markers (concat (replace-match "" t t markers) "^")))
3838 (if (string-match "-" markers)
3839 (setq markers (concat (replace-match "" t t markers) "-")))
3840 (if (string-match "\\^" vmarkers)
3841 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3842 (if (string-match "-" vmarkers)
3843 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3844 (if (> nl 0)
3845 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3846 (int-to-string nl) "\\}")))
3847 ;; Make the regexp
3848 (setq org-emph-re
3849 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3850 "\\("
3851 "\\([" markers "]\\)"
3852 "\\("
3853 "[^" border "]\\|"
3854 "[^" border (if (and nil stacked) markers) "]"
3855 body1
3856 "[^" border (if (and nil stacked) markers) "]"
3857 "\\)"
3858 "\\3\\)"
3859 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3860 (setq org-verbatim-re
3861 (concat "\\([" pre "]\\|^\\)"
3862 "\\("
3863 "\\([" vmarkers "]\\)"
3864 "\\("
3865 "[^" border "]\\|"
3866 "[^" border "]"
3867 body1
3868 "[^" border "]"
3869 "\\)"
3870 "\\3\\)"
3871 "\\([" post "]\\|$\\)")))))
3873 (defcustom org-emphasis-regexp-components
3874 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3875 "Components used to build the regular expression for emphasis.
3876 This is a list with 6 entries. Terminology: In an emphasis string
3877 like \" *strong word* \", we call the initial space PREMATCH, the final
3878 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3879 and \"trong wor\" is the body. The different components in this variable
3880 specify what is allowed/forbidden in each part:
3882 pre Chars allowed as prematch. Beginning of line will be allowed too.
3883 post Chars allowed as postmatch. End of line will be allowed too.
3884 border The chars *forbidden* as border characters.
3885 body-regexp A regexp like \".\" to match a body character. Don't use
3886 non-shy groups here, and don't allow newline here.
3887 newline The maximum number of newlines allowed in an emphasis exp.
3889 Use customize to modify this, or restart Emacs after changing it."
3890 :group 'org-font-lock
3891 :set 'org-set-emph-re
3892 :type '(list
3893 (sexp :tag "Allowed chars in pre ")
3894 (sexp :tag "Allowed chars in post ")
3895 (sexp :tag "Forbidden chars in border ")
3896 (sexp :tag "Regexp for body ")
3897 (integer :tag "number of newlines allowed")
3898 (option (boolean :tag "Stacking (DISABLED) "))))
3900 (defcustom org-emphasis-alist
3901 '(("*" bold "<b>" "</b>")
3902 ("/" italic "<i>" "</i>")
3903 ("_" underline "<u>" "</u>")
3904 ("=" org-code "<code>" "</code>" verbatim)
3905 ("~" org-verbatim "" "" verbatim)
3906 ("+" (:strike-through t) "<del>" "</del>")
3908 "Special syntax for emphasized text.
3909 Text starting and ending with a special character will be emphasized, for
3910 example *bold*, _underlined_ and /italic/. This variable sets the marker
3911 characters, the face to be used by font-lock for highlighting in Org-mode
3912 Emacs buffers, and the HTML tags to be used for this.
3913 Use customize to modify this, or restart Emacs after changing it."
3914 :group 'org-font-lock
3915 :set 'org-set-emph-re
3916 :type '(repeat
3917 (list
3918 (string :tag "Marker character")
3919 (choice
3920 (face :tag "Font-lock-face")
3921 (plist :tag "Face property list"))
3922 (string :tag "HTML start tag")
3923 (string :tag "HTML end tag")
3924 (option (const verbatim)))))
3926 ;;; The faces
3928 (defgroup org-faces nil
3929 "Faces in Org-mode."
3930 :tag "Org Faces"
3931 :group 'org-font-lock)
3933 (defun org-compatible-face (inherits specs)
3934 "Make a compatible face specification.
3935 If INHERITS is an existing face and if the Emacs version supports it,
3936 just inherit the face. If not, use SPECS to define the face.
3937 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3938 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3939 to the top of the list. The `min-colors' attribute will be removed from
3940 any other entries, and any resulting duplicates will be removed entirely."
3941 (cond
3942 ((and inherits (facep inherits)
3943 (not (featurep 'xemacs)) (> emacs-major-version 22))
3944 ;; In Emacs 23, we use inheritance where possible.
3945 ;; We only do this in Emacs 23, because only there the outline
3946 ;; faces have been changed to the original org-mode-level-faces.
3947 (list (list t :inherit inherits)))
3948 ((or (featurep 'xemacs) (< emacs-major-version 22))
3949 ;; These do not understand the `min-colors' attribute.
3950 (let (r e a)
3951 (while (setq e (pop specs))
3952 (cond
3953 ((memq (car e) '(t default)) (push e r))
3954 ((setq a (member '(min-colors 8) (car e)))
3955 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3956 (cdr e)))))
3957 ((setq a (assq 'min-colors (car e)))
3958 (setq e (cons (delq a (car e)) (cdr e)))
3959 (or (assoc (car e) r) (push e r)))
3960 (t (or (assoc (car e) r) (push e r)))))
3961 (nreverse r)))
3962 (t specs)))
3963 (put 'org-compatible-face 'lisp-indent-function 1)
3965 (defface org-hide
3966 '((((background light)) (:foreground "white"))
3967 (((background dark)) (:foreground "black")))
3968 "Face used to hide leading stars in headlines.
3969 The forground color of this face should be equal to the background
3970 color of the frame."
3971 :group 'org-faces)
3973 (defface org-level-1 ;; font-lock-function-name-face
3974 (org-compatible-face 'outline-1
3975 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3976 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3977 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3978 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3979 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3980 (t (:bold t))))
3981 "Face used for level 1 headlines."
3982 :group 'org-faces)
3984 (defface org-level-2 ;; font-lock-variable-name-face
3985 (org-compatible-face 'outline-2
3986 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3987 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3988 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3989 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3990 (t (:bold t))))
3991 "Face used for level 2 headlines."
3992 :group 'org-faces)
3994 (defface org-level-3 ;; font-lock-keyword-face
3995 (org-compatible-face 'outline-3
3996 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3997 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3998 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3999 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
4000 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
4001 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
4002 (t (:bold t))))
4003 "Face used for level 3 headlines."
4004 :group 'org-faces)
4006 (defface org-level-4 ;; font-lock-comment-face
4007 (org-compatible-face 'outline-4
4008 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4009 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4010 (((class color) (min-colors 16) (background light)) (:foreground "red"))
4011 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
4012 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4013 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4014 (t (:bold t))))
4015 "Face used for level 4 headlines."
4016 :group 'org-faces)
4018 (defface org-level-5 ;; font-lock-type-face
4019 (org-compatible-face 'outline-5
4020 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
4021 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
4022 (((class color) (min-colors 8)) (:foreground "green"))))
4023 "Face used for level 5 headlines."
4024 :group 'org-faces)
4026 (defface org-level-6 ;; font-lock-constant-face
4027 (org-compatible-face 'outline-6
4028 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
4029 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
4030 (((class color) (min-colors 8)) (:foreground "magenta"))))
4031 "Face used for level 6 headlines."
4032 :group 'org-faces)
4034 (defface org-level-7 ;; font-lock-builtin-face
4035 (org-compatible-face 'outline-7
4036 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
4037 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
4038 (((class color) (min-colors 8)) (:foreground "blue"))))
4039 "Face used for level 7 headlines."
4040 :group 'org-faces)
4042 (defface org-level-8 ;; font-lock-string-face
4043 (org-compatible-face 'outline-8
4044 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4045 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4046 (((class color) (min-colors 8)) (:foreground "green"))))
4047 "Face used for level 8 headlines."
4048 :group 'org-faces)
4050 (defface org-special-keyword ;; font-lock-string-face
4051 (org-compatible-face nil
4052 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4053 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4054 (t (:italic t))))
4055 "Face used for special keywords."
4056 :group 'org-faces)
4058 (defface org-drawer ;; font-lock-function-name-face
4059 (org-compatible-face nil
4060 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4061 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4062 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4063 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4064 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4065 (t (:bold t))))
4066 "Face used for drawers."
4067 :group 'org-faces)
4069 (defface org-property-value nil
4070 "Face used for the value of a property."
4071 :group 'org-faces)
4073 (defface org-column
4074 (org-compatible-face nil
4075 '((((class color) (min-colors 16) (background light))
4076 (:background "grey90"))
4077 (((class color) (min-colors 16) (background dark))
4078 (:background "grey30"))
4079 (((class color) (min-colors 8))
4080 (:background "cyan" :foreground "black"))
4081 (t (:inverse-video t))))
4082 "Face for column display of entry properties."
4083 :group 'org-faces)
4085 (when (fboundp 'set-face-attribute)
4086 ;; Make sure that a fixed-width face is used when we have a column table.
4087 (set-face-attribute 'org-column nil
4088 :height (face-attribute 'default :height)
4089 :family (face-attribute 'default :family)))
4091 (defface org-warning
4092 (org-compatible-face 'font-lock-warning-face
4093 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4094 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4095 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4096 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4097 (t (:bold t))))
4098 "Face for deadlines and TODO keywords."
4099 :group 'org-faces)
4101 (defface org-archived ; similar to shadow
4102 (org-compatible-face 'shadow
4103 '((((class color grayscale) (min-colors 88) (background light))
4104 (:foreground "grey50"))
4105 (((class color grayscale) (min-colors 88) (background dark))
4106 (:foreground "grey70"))
4107 (((class color) (min-colors 8) (background light))
4108 (:foreground "green"))
4109 (((class color) (min-colors 8) (background dark))
4110 (:foreground "yellow"))))
4111 "Face for headline with the ARCHIVE tag."
4112 :group 'org-faces)
4114 (defface org-link
4115 '((((class color) (background light)) (:foreground "Purple" :underline t))
4116 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4117 (t (:underline t)))
4118 "Face for links."
4119 :group 'org-faces)
4121 (defface org-ellipsis
4122 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
4123 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
4124 (t (:strike-through t)))
4125 "Face for the ellipsis in folded text."
4126 :group 'org-faces)
4128 (defface org-target
4129 '((((class color) (background light)) (:underline t))
4130 (((class color) (background dark)) (:underline t))
4131 (t (:underline t)))
4132 "Face for links."
4133 :group 'org-faces)
4135 (defface org-date
4136 '((((class color) (background light)) (:foreground "Purple" :underline t))
4137 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4138 (t (:underline t)))
4139 "Face for links."
4140 :group 'org-faces)
4142 (defface org-sexp-date
4143 '((((class color) (background light)) (:foreground "Purple"))
4144 (((class color) (background dark)) (:foreground "Cyan"))
4145 (t (:underline t)))
4146 "Face for links."
4147 :group 'org-faces)
4149 (defface org-tag
4150 '((t (:bold t)))
4151 "Face for tags."
4152 :group 'org-faces)
4154 (defface org-todo ; font-lock-warning-face
4155 (org-compatible-face nil
4156 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4157 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4158 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4159 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4160 (t (:inverse-video t :bold t))))
4161 "Face for TODO keywords."
4162 :group 'org-faces)
4164 (defface org-done ;; font-lock-type-face
4165 (org-compatible-face nil
4166 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
4167 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
4168 (((class color) (min-colors 8)) (:foreground "green"))
4169 (t (:bold t))))
4170 "Face used for todo keywords that indicate DONE items."
4171 :group 'org-faces)
4173 (defface org-headline-done ;; font-lock-string-face
4174 (org-compatible-face nil
4175 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4176 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4177 (((class color) (min-colors 8) (background light)) (:bold nil))))
4178 "Face used to indicate that a headline is DONE.
4179 This face is only used if `org-fontify-done-headline' is set. If applies
4180 to the part of the headline after the DONE keyword."
4181 :group 'org-faces)
4183 (defcustom org-todo-keyword-faces nil
4184 "Faces for specific TODO keywords.
4185 This is a list of cons cells, with TODO keywords in the car
4186 and faces in the cdr. The face can be a symbol, or a property
4187 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
4188 :group 'org-faces
4189 :group 'org-todo
4190 :type '(repeat
4191 (cons
4192 (string :tag "keyword")
4193 (sexp :tag "face"))))
4195 (defface org-table ;; font-lock-function-name-face
4196 (org-compatible-face nil
4197 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4198 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4199 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4200 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4201 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4202 (((class color) (min-colors 8) (background dark)))))
4203 "Face used for tables."
4204 :group 'org-faces)
4206 (defface org-formula
4207 (org-compatible-face nil
4208 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4209 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4210 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4211 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4212 (t (:bold t :italic t))))
4213 "Face for formulas."
4214 :group 'org-faces)
4216 (defface org-code
4217 (org-compatible-face nil
4218 '((((class color grayscale) (min-colors 88) (background light))
4219 (:foreground "grey50"))
4220 (((class color grayscale) (min-colors 88) (background dark))
4221 (:foreground "grey70"))
4222 (((class color) (min-colors 8) (background light))
4223 (:foreground "green"))
4224 (((class color) (min-colors 8) (background dark))
4225 (:foreground "yellow"))))
4226 "Face for fixed-with text like code snippets."
4227 :group 'org-faces
4228 :version "22.1")
4230 (defface org-verbatim
4231 (org-compatible-face nil
4232 '((((class color grayscale) (min-colors 88) (background light))
4233 (:foreground "grey50" :underline t))
4234 (((class color grayscale) (min-colors 88) (background dark))
4235 (:foreground "grey70" :underline t))
4236 (((class color) (min-colors 8) (background light))
4237 (:foreground "green" :underline t))
4238 (((class color) (min-colors 8) (background dark))
4239 (:foreground "yellow" :underline t))))
4240 "Face for fixed-with text like code snippets."
4241 :group 'org-faces
4242 :version "22.1")
4244 (defface org-agenda-structure ;; font-lock-function-name-face
4245 (org-compatible-face nil
4246 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4247 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4248 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4249 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4250 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4251 (t (:bold t))))
4252 "Face used in agenda for captions and dates."
4253 :group 'org-faces)
4255 (defface org-scheduled-today
4256 (org-compatible-face nil
4257 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4258 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4259 (((class color) (min-colors 8)) (:foreground "green"))
4260 (t (:bold t :italic t))))
4261 "Face for items scheduled for a certain day."
4262 :group 'org-faces)
4264 (defface org-scheduled-previously
4265 (org-compatible-face nil
4266 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4267 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4268 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4269 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4270 (t (:bold t))))
4271 "Face for items scheduled previously, and not yet done."
4272 :group 'org-faces)
4274 (defface org-upcoming-deadline
4275 (org-compatible-face nil
4276 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4277 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4278 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4279 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4280 (t (:bold t))))
4281 "Face for items scheduled previously, and not yet done."
4282 :group 'org-faces)
4284 (defcustom org-agenda-deadline-faces
4285 '((1.0 . org-warning)
4286 (0.5 . org-upcoming-deadline)
4287 (0.0 . default))
4288 "Faces for showing deadlines in the agenda.
4289 This is a list of cons cells. The cdr of each cell is a face to be used,
4290 and it can also just be like '(:foreground \"yellow\").
4291 Each car is a fraction of the head-warning time that must have passed for
4292 this the face in the cdr to be used for display. The numbers must be
4293 given in descending order. The head-warning time is normally taken
4294 from `org-deadline-warning-days', but can also be specified in the deadline
4295 timestamp itself, like this:
4297 DEADLINE: <2007-08-13 Mon -8d>
4299 You may use d for days, w for weeks, m for months and y for years. Months
4300 and years will only be treated in an approximate fashion (30.4 days for a
4301 month and 365.24 days for a year)."
4302 :group 'org-faces
4303 :group 'org-agenda-daily/weekly
4304 :type '(repeat
4305 (cons
4306 (number :tag "Fraction of head-warning time passed")
4307 (sexp :tag "Face"))))
4309 ;; FIXME: this is not a good face yet.
4310 (defface org-agenda-restriction-lock
4311 (org-compatible-face nil
4312 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4313 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4314 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4315 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4316 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4317 (t (:inverse-video t))))
4318 "Face for showing the agenda restriction lock."
4319 :group 'org-faces)
4321 (defface org-time-grid ;; font-lock-variable-name-face
4322 (org-compatible-face nil
4323 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4324 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4325 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4326 "Face used for time grids."
4327 :group 'org-faces)
4329 (defconst org-level-faces
4330 '(org-level-1 org-level-2 org-level-3 org-level-4
4331 org-level-5 org-level-6 org-level-7 org-level-8
4334 (defcustom org-n-level-faces (length org-level-faces)
4335 "The number of different faces to be used for headlines.
4336 Org-mode defines 8 different headline faces, so this can be at most 8.
4337 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4338 :type 'number
4339 :group 'org-faces)
4341 ;;; Functions and variables from ther packages
4342 ;; Declared here to avoid compiler warnings
4344 (eval-and-compile
4345 (unless (fboundp 'declare-function)
4346 (defmacro declare-function (fn file &optional arglist fileonly))))
4348 ;; XEmacs only
4349 (defvar outline-mode-menu-heading)
4350 (defvar outline-mode-menu-show)
4351 (defvar outline-mode-menu-hide)
4352 (defvar zmacs-regions) ; XEmacs regions
4354 ;; Emacs only
4355 (defvar mark-active)
4357 ;; Various packages
4358 ;; FIXME: get the argument lists for the UNKNOWN stuff
4359 (declare-function add-to-diary-list "diary-lib"
4360 (date string specifier &optional marker globcolor literal))
4361 (declare-function table--at-cell-p "table" (position &optional object at-column))
4362 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4363 (declare-function bbdb "ext:bbdb-com" (string elidep))
4364 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4365 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4366 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4367 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4368 (declare-function bbdb-record-name "ext:bbdb" (record))
4369 (declare-function bibtex-beginning-of-entry "bibtex" ())
4370 (declare-function bibtex-generate-autokey "bibtex" ())
4371 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4372 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4373 (defvar calc-embedded-close-formula)
4374 (defvar calc-embedded-open-formula)
4375 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4376 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4377 (declare-function calendar-check-holidays "holidays" (date))
4378 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4379 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4380 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4381 (declare-function calendar-forward-day "cal-move" (arg))
4382 (declare-function calendar-french-date-string "cal-french" (&optional date))
4383 (declare-function calendar-goto-date "cal-move" (date))
4384 (declare-function calendar-goto-today "cal-move" ())
4385 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4386 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4387 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4388 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4389 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4390 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4391 (defvar calendar-mode-map)
4392 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4393 (declare-function cdlatex-tab "ext:cdlatex" ())
4394 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4395 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4396 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4397 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4398 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4399 (defvar font-lock-unfontify-region-function)
4400 (declare-function gnus-article-show-summary "gnus-art" ())
4401 (declare-function gnus-summary-last-subject "gnus-sum" ())
4402 (defvar gnus-other-frame-object)
4403 (defvar gnus-group-name)
4404 (defvar gnus-article-current)
4405 (defvar Info-current-file)
4406 (defvar Info-current-node)
4407 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4408 (declare-function mh-find-path "mh-utils" ())
4409 (declare-function mh-get-header-field "mh-utils" (field))
4410 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4411 (declare-function mh-header-display "mh-show" ())
4412 (declare-function mh-index-previous-folder "mh-search" ())
4413 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4414 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4415 (declare-function mh-search-choose "mh-search" (&optional searcher))
4416 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4417 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4418 (declare-function mh-show-header-display "mh-show" t t)
4419 (declare-function mh-show-msg "mh-show" (msg))
4420 (declare-function mh-show-show "mh-show" t t)
4421 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4422 (defvar mh-progs)
4423 (defvar mh-current-folder)
4424 (defvar mh-show-folder-buffer)
4425 (defvar mh-index-folder)
4426 (defvar mh-searcher)
4427 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4428 (declare-function parse-time-string "parse-time" (string))
4429 (declare-function remember "remember" (&optional initial))
4430 (declare-function remember-buffer-desc "remember" ())
4431 (declare-function remember-finalize "remember" ())
4432 (defvar remember-save-after-remembering)
4433 (defvar remember-data-file)
4434 (defvar remember-register)
4435 (defvar remember-buffer)
4436 (defvar remember-handler-functions)
4437 (defvar remember-annotation-functions)
4438 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4439 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4440 (declare-function rmail-what-message "rmail" ())
4441 (defvar rmail-current-message)
4442 (defvar texmathp-why)
4443 (declare-function vm-beginning-of-message "ext:vm-page" ())
4444 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4445 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4446 (declare-function vm-isearch-narrow "ext:vm-search" ())
4447 (declare-function vm-isearch-update "ext:vm-search" ())
4448 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4449 (declare-function vm-su-message-id "ext:vm-summary" (m))
4450 (declare-function vm-su-subject "ext:vm-summary" (m))
4451 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4452 (defvar vm-message-pointer)
4453 (defvar vm-folder-directory)
4454 (defvar w3m-current-url)
4455 (defvar w3m-current-title)
4456 ;; backward compatibility to old version of wl
4457 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4458 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4459 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4460 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4461 (declare-function wl-summary-line-from "ext:wl-summary" ())
4462 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4463 (declare-function wl-summary-message-number "ext:wl-summary" ())
4464 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4465 (defvar wl-summary-buffer-elmo-folder)
4466 (defvar wl-summary-buffer-folder-name)
4467 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4469 (defvar org-latex-regexps)
4470 (defvar constants-unit-system)
4472 ;;; Variables for pre-computed regular expressions, all buffer local
4474 (defvar org-drawer-regexp nil
4475 "Matches first line of a hidden block.")
4476 (make-variable-buffer-local 'org-drawer-regexp)
4477 (defvar org-todo-regexp nil
4478 "Matches any of the TODO state keywords.")
4479 (make-variable-buffer-local 'org-todo-regexp)
4480 (defvar org-not-done-regexp nil
4481 "Matches any of the TODO state keywords except the last one.")
4482 (make-variable-buffer-local 'org-not-done-regexp)
4483 (defvar org-todo-line-regexp nil
4484 "Matches a headline and puts TODO state into group 2 if present.")
4485 (make-variable-buffer-local 'org-todo-line-regexp)
4486 (defvar org-complex-heading-regexp nil
4487 "Matches a headline and puts everything into groups:
4488 group 1: the stars
4489 group 2: The todo keyword, maybe
4490 group 3: Priority cookie
4491 group 4: True headline
4492 group 5: Tags")
4493 (make-variable-buffer-local 'org-complex-heading-regexp)
4494 (defvar org-todo-line-tags-regexp nil
4495 "Matches a headline and puts TODO state into group 2 if present.
4496 Also put tags into group 4 if tags are present.")
4497 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4498 (defvar org-nl-done-regexp nil
4499 "Matches newline followed by a headline with the DONE keyword.")
4500 (make-variable-buffer-local 'org-nl-done-regexp)
4501 (defvar org-looking-at-done-regexp nil
4502 "Matches the DONE keyword a point.")
4503 (make-variable-buffer-local 'org-looking-at-done-regexp)
4504 (defvar org-ds-keyword-length 12
4505 "Maximum length of the Deadline and SCHEDULED keywords.")
4506 (make-variable-buffer-local 'org-ds-keyword-length)
4507 (defvar org-deadline-regexp nil
4508 "Matches the DEADLINE keyword.")
4509 (make-variable-buffer-local 'org-deadline-regexp)
4510 (defvar org-deadline-time-regexp nil
4511 "Matches the DEADLINE keyword together with a time stamp.")
4512 (make-variable-buffer-local 'org-deadline-time-regexp)
4513 (defvar org-deadline-line-regexp nil
4514 "Matches the DEADLINE keyword and the rest of the line.")
4515 (make-variable-buffer-local 'org-deadline-line-regexp)
4516 (defvar org-scheduled-regexp nil
4517 "Matches the SCHEDULED keyword.")
4518 (make-variable-buffer-local 'org-scheduled-regexp)
4519 (defvar org-scheduled-time-regexp nil
4520 "Matches the SCHEDULED keyword together with a time stamp.")
4521 (make-variable-buffer-local 'org-scheduled-time-regexp)
4522 (defvar org-closed-time-regexp nil
4523 "Matches the CLOSED keyword together with a time stamp.")
4524 (make-variable-buffer-local 'org-closed-time-regexp)
4526 (defvar org-keyword-time-regexp nil
4527 "Matches any of the 4 keywords, together with the time stamp.")
4528 (make-variable-buffer-local 'org-keyword-time-regexp)
4529 (defvar org-keyword-time-not-clock-regexp nil
4530 "Matches any of the 3 keywords, together with the time stamp.")
4531 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4532 (defvar org-maybe-keyword-time-regexp nil
4533 "Matches a timestamp, possibly preceeded by a keyword.")
4534 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4535 (defvar org-planning-or-clock-line-re nil
4536 "Matches a line with planning or clock info.")
4537 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4539 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4540 rear-nonsticky t mouse-map t fontified t)
4541 "Properties to remove when a string without properties is wanted.")
4543 (defsubst org-match-string-no-properties (num &optional string)
4544 (if (featurep 'xemacs)
4545 (let ((s (match-string num string)))
4546 (remove-text-properties 0 (length s) org-rm-props s)
4548 (match-string-no-properties num string)))
4550 (defsubst org-no-properties (s)
4551 (if (fboundp 'set-text-properties)
4552 (set-text-properties 0 (length s) nil s)
4553 (remove-text-properties 0 (length s) org-rm-props s))
4556 (defsubst org-get-alist-option (option key)
4557 (cond ((eq key t) t)
4558 ((eq option t) t)
4559 ((assoc key option) (cdr (assoc key option)))
4560 (t (cdr (assq 'default option)))))
4562 (defsubst org-inhibit-invisibility ()
4563 "Modified `buffer-invisibility-spec' for Emacs 21.
4564 Some ops with invisible text do not work correctly on Emacs 21. For these
4565 we turn off invisibility temporarily. Use this in a `let' form."
4566 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4568 (defsubst org-set-local (var value)
4569 "Make VAR local in current buffer and set it to VALUE."
4570 (set (make-variable-buffer-local var) value))
4572 (defsubst org-mode-p ()
4573 "Check if the current buffer is in Org-mode."
4574 (eq major-mode 'org-mode))
4576 (defsubst org-last (list)
4577 "Return the last element of LIST."
4578 (car (last list)))
4580 (defun org-let (list &rest body)
4581 (eval (cons 'let (cons list body))))
4582 (put 'org-let 'lisp-indent-function 1)
4584 (defun org-let2 (list1 list2 &rest body)
4585 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4586 (put 'org-let2 'lisp-indent-function 2)
4587 (defconst org-startup-options
4588 '(("fold" org-startup-folded t)
4589 ("overview" org-startup-folded t)
4590 ("nofold" org-startup-folded nil)
4591 ("showall" org-startup-folded nil)
4592 ("content" org-startup-folded content)
4593 ("hidestars" org-hide-leading-stars t)
4594 ("showstars" org-hide-leading-stars nil)
4595 ("odd" org-odd-levels-only t)
4596 ("oddeven" org-odd-levels-only nil)
4597 ("align" org-startup-align-all-tables t)
4598 ("noalign" org-startup-align-all-tables nil)
4599 ("customtime" org-display-custom-times t)
4600 ("logdone" org-log-done time)
4601 ("lognotedone" org-log-done note)
4602 ("nologdone" org-log-done nil)
4603 ("lognoteclock-out" org-log-note-clock-out t)
4604 ("nolognoteclock-out" org-log-note-clock-out nil)
4605 ("logrepeat" org-log-repeat state)
4606 ("lognoterepeat" org-log-repeat note)
4607 ("nologrepeat" org-log-repeat nil)
4608 ("constcgs" constants-unit-system cgs)
4609 ("constSI" constants-unit-system SI))
4610 "Variable associated with STARTUP options for org-mode.
4611 Each element is a list of three items: The startup options as written
4612 in the #+STARTUP line, the corresponding variable, and the value to
4613 set this variable to if the option is found. An optional forth element PUSH
4614 means to push this value onto the list in the variable.")
4616 (defun org-set-regexps-and-options ()
4617 "Precompute regular expressions for current buffer."
4618 (when (org-mode-p)
4619 (org-set-local 'org-todo-kwd-alist nil)
4620 (org-set-local 'org-todo-key-alist nil)
4621 (org-set-local 'org-todo-key-trigger nil)
4622 (org-set-local 'org-todo-keywords-1 nil)
4623 (org-set-local 'org-done-keywords nil)
4624 (org-set-local 'org-todo-heads nil)
4625 (org-set-local 'org-todo-sets nil)
4626 (org-set-local 'org-todo-log-states nil)
4627 (let ((re (org-make-options-regexp
4628 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4629 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4630 "CONSTANTS" "PROPERTY" "DRAWERS")))
4631 (splitre "[ \t]+")
4632 kwds kws0 kwsa key log value cat arch tags const links hw dws
4633 tail sep kws1 prio props drawers)
4634 (save-excursion
4635 (save-restriction
4636 (widen)
4637 (goto-char (point-min))
4638 (while (re-search-forward re nil t)
4639 (setq key (match-string 1) value (org-match-string-no-properties 2))
4640 (cond
4641 ((equal key "CATEGORY")
4642 (if (string-match "[ \t]+$" value)
4643 (setq value (replace-match "" t t value)))
4644 (setq cat value))
4645 ((member key '("SEQ_TODO" "TODO"))
4646 (push (cons 'sequence (org-split-string value splitre)) kwds))
4647 ((equal key "TYP_TODO")
4648 (push (cons 'type (org-split-string value splitre)) kwds))
4649 ((equal key "TAGS")
4650 (setq tags (append tags (org-split-string value splitre))))
4651 ((equal key "COLUMNS")
4652 (org-set-local 'org-columns-default-format value))
4653 ((equal key "LINK")
4654 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4655 (push (cons (match-string 1 value)
4656 (org-trim (match-string 2 value)))
4657 links)))
4658 ((equal key "PRIORITIES")
4659 (setq prio (org-split-string value " +")))
4660 ((equal key "PROPERTY")
4661 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4662 (push (cons (match-string 1 value) (match-string 2 value))
4663 props)))
4664 ((equal key "DRAWERS")
4665 (setq drawers (org-split-string value splitre)))
4666 ((equal key "CONSTANTS")
4667 (setq const (append const (org-split-string value splitre))))
4668 ((equal key "STARTUP")
4669 (let ((opts (org-split-string value splitre))
4670 l var val)
4671 (while (setq l (pop opts))
4672 (when (setq l (assoc l org-startup-options))
4673 (setq var (nth 1 l) val (nth 2 l))
4674 (if (not (nth 3 l))
4675 (set (make-local-variable var) val)
4676 (if (not (listp (symbol-value var)))
4677 (set (make-local-variable var) nil))
4678 (set (make-local-variable var) (symbol-value var))
4679 (add-to-list var val))))))
4680 ((equal key "ARCHIVE")
4681 (string-match " *$" value)
4682 (setq arch (replace-match "" t t value))
4683 (remove-text-properties 0 (length arch)
4684 '(face t fontified t) arch)))
4686 (when cat
4687 (org-set-local 'org-category (intern cat))
4688 (push (cons "CATEGORY" cat) props))
4689 (when prio
4690 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4691 (setq prio (mapcar 'string-to-char prio))
4692 (org-set-local 'org-highest-priority (nth 0 prio))
4693 (org-set-local 'org-lowest-priority (nth 1 prio))
4694 (org-set-local 'org-default-priority (nth 2 prio)))
4695 (and props (org-set-local 'org-local-properties (nreverse props)))
4696 (and drawers (org-set-local 'org-drawers drawers))
4697 (and arch (org-set-local 'org-archive-location arch))
4698 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4699 ;; Process the TODO keywords
4700 (unless kwds
4701 ;; Use the global values as if they had been given locally.
4702 (setq kwds (default-value 'org-todo-keywords))
4703 (if (stringp (car kwds))
4704 (setq kwds (list (cons org-todo-interpretation
4705 (default-value 'org-todo-keywords)))))
4706 (setq kwds (reverse kwds)))
4707 (setq kwds (nreverse kwds))
4708 (let (inter kws kw)
4709 (while (setq kws (pop kwds))
4710 (setq inter (pop kws) sep (member "|" kws)
4711 kws0 (delete "|" (copy-sequence kws))
4712 kwsa nil
4713 kws1 (mapcar
4714 (lambda (x)
4715 ;; 1 2
4716 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4717 (progn
4718 (setq kw (match-string 1 x)
4719 key (and (match-end 2) (match-string 2 x))
4720 log (org-extract-log-state-settings x))
4721 (push (cons kw (and key (string-to-char key))) kwsa)
4722 (and log (push log org-todo-log-states))
4724 (error "Invalid TODO keyword %s" x)))
4725 kws0)
4726 kwsa (if kwsa (append '((:startgroup))
4727 (nreverse kwsa)
4728 '((:endgroup))))
4729 hw (car kws1)
4730 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4731 tail (list inter hw (car dws) (org-last dws)))
4732 (add-to-list 'org-todo-heads hw 'append)
4733 (push kws1 org-todo-sets)
4734 (setq org-done-keywords (append org-done-keywords dws nil))
4735 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4736 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4737 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4738 (setq org-todo-sets (nreverse org-todo-sets)
4739 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4740 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4741 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4742 ;; Process the constants
4743 (when const
4744 (let (e cst)
4745 (while (setq e (pop const))
4746 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4747 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4748 (setq org-table-formula-constants-local cst)))
4750 ;; Process the tags.
4751 (when tags
4752 (let (e tgs)
4753 (while (setq e (pop tags))
4754 (cond
4755 ((equal e "{") (push '(:startgroup) tgs))
4756 ((equal e "}") (push '(:endgroup) tgs))
4757 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4758 (push (cons (match-string 1 e)
4759 (string-to-char (match-string 2 e)))
4760 tgs))
4761 (t (push (list e) tgs))))
4762 (org-set-local 'org-tag-alist nil)
4763 (while (setq e (pop tgs))
4764 (or (and (stringp (car e))
4765 (assoc (car e) org-tag-alist))
4766 (push e org-tag-alist))))))
4768 ;; Compute the regular expressions and other local variables
4769 (if (not org-done-keywords)
4770 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4771 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4772 (length org-scheduled-string)))
4773 org-drawer-regexp
4774 (concat "^[ \t]*:\\("
4775 (mapconcat 'regexp-quote org-drawers "\\|")
4776 "\\):[ \t]*$")
4777 org-not-done-keywords
4778 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4779 org-todo-regexp
4780 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4781 "\\|") "\\)\\>")
4782 org-not-done-regexp
4783 (concat "\\<\\("
4784 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4785 "\\)\\>")
4786 org-todo-line-regexp
4787 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4788 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4789 "\\)\\>\\)?[ \t]*\\(.*\\)")
4790 org-complex-heading-regexp
4791 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4792 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4793 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4794 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4795 org-nl-done-regexp
4796 (concat "\n\\*+[ \t]+"
4797 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4798 "\\)" "\\>")
4799 org-todo-line-tags-regexp
4800 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4801 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4802 (org-re
4803 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4804 org-looking-at-done-regexp
4805 (concat "^" "\\(?:"
4806 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4807 "\\>")
4808 org-deadline-regexp (concat "\\<" org-deadline-string)
4809 org-deadline-time-regexp
4810 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4811 org-deadline-line-regexp
4812 (concat "\\<\\(" org-deadline-string "\\).*")
4813 org-scheduled-regexp
4814 (concat "\\<" org-scheduled-string)
4815 org-scheduled-time-regexp
4816 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4817 org-closed-time-regexp
4818 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4819 org-keyword-time-regexp
4820 (concat "\\<\\(" org-scheduled-string
4821 "\\|" org-deadline-string
4822 "\\|" org-closed-string
4823 "\\|" org-clock-string "\\)"
4824 " *[[<]\\([^]>]+\\)[]>]")
4825 org-keyword-time-not-clock-regexp
4826 (concat "\\<\\(" org-scheduled-string
4827 "\\|" org-deadline-string
4828 "\\|" org-closed-string
4829 "\\)"
4830 " *[[<]\\([^]>]+\\)[]>]")
4831 org-maybe-keyword-time-regexp
4832 (concat "\\(\\<\\(" org-scheduled-string
4833 "\\|" org-deadline-string
4834 "\\|" org-closed-string
4835 "\\|" org-clock-string "\\)\\)?"
4836 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4837 org-planning-or-clock-line-re
4838 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4839 "\\|" org-deadline-string
4840 "\\|" org-closed-string "\\|" org-clock-string
4841 "\\)\\>\\)")
4843 (org-compute-latex-and-specials-regexp)
4844 (org-set-font-lock-defaults)))
4846 (defun org-extract-log-state-settings (x)
4847 "Extract the log state setting from a TODO keyword string.
4848 This will extract info from a string like \"WAIT(w@/!)\"."
4849 (let (kw key log1 log2)
4850 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4851 (setq kw (match-string 1 x)
4852 key (and (match-end 2) (match-string 2 x))
4853 log1 (and (match-end 3) (match-string 3 x))
4854 log2 (and (match-end 4) (match-string 4 x)))
4855 (and (or log1 log2)
4856 (list kw
4857 (and log1 (if (equal log1 "!") 'time 'note))
4858 (and log2 (if (equal log2 "!") 'time 'note)))))))
4860 (defun org-remove-keyword-keys (list)
4861 "Remove a pair of parenthesis at the end of each string in LIST."
4862 (mapcar (lambda (x)
4863 (if (string-match "(.*)$" x)
4864 (substring x 0 (match-beginning 0))
4866 list))
4868 ;; FIXME: this could be done much better, using second characters etc.
4869 (defun org-assign-fast-keys (alist)
4870 "Assign fast keys to a keyword-key alist.
4871 Respect keys that are already there."
4872 (let (new e k c c1 c2 (char ?a))
4873 (while (setq e (pop alist))
4874 (cond
4875 ((equal e '(:startgroup)) (push e new))
4876 ((equal e '(:endgroup)) (push e new))
4878 (setq k (car e) c2 nil)
4879 (if (cdr e)
4880 (setq c (cdr e))
4881 ;; automatically assign a character.
4882 (setq c1 (string-to-char
4883 (downcase (substring
4884 k (if (= (string-to-char k) ?@) 1 0)))))
4885 (if (or (rassoc c1 new) (rassoc c1 alist))
4886 (while (or (rassoc char new) (rassoc char alist))
4887 (setq char (1+ char)))
4888 (setq c2 c1))
4889 (setq c (or c2 char)))
4890 (push (cons k c) new))))
4891 (nreverse new)))
4893 ;;; Some variables ujsed in various places
4895 (defvar org-window-configuration nil
4896 "Used in various places to store a window configuration.")
4897 (defvar org-finish-function nil
4898 "Function to be called when `C-c C-c' is used.
4899 This is for getting out of special buffers like remember.")
4902 ;; FIXME: Occasionally check by commenting these, to make sure
4903 ;; no other functions uses these, forgetting to let-bind them.
4904 (defvar entry)
4905 (defvar state)
4906 (defvar last-state)
4907 (defvar date)
4908 (defvar description)
4910 ;; Defined somewhere in this file, but used before definition.
4911 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4912 (defvar org-agenda-buffer-name)
4913 (defvar org-agenda-undo-list)
4914 (defvar org-agenda-pending-undo-list)
4915 (defvar org-agenda-overriding-header)
4916 (defvar orgtbl-mode)
4917 (defvar org-html-entities)
4918 (defvar org-struct-menu)
4919 (defvar org-org-menu)
4920 (defvar org-tbl-menu)
4921 (defvar org-agenda-keymap)
4923 ;;;; Emacs/XEmacs compatibility
4925 ;; Overlay compatibility functions
4926 (defun org-make-overlay (beg end &optional buffer)
4927 (if (featurep 'xemacs)
4928 (make-extent beg end buffer)
4929 (make-overlay beg end buffer)))
4930 (defun org-delete-overlay (ovl)
4931 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4932 (defun org-detach-overlay (ovl)
4933 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4934 (defun org-move-overlay (ovl beg end &optional buffer)
4935 (if (featurep 'xemacs)
4936 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4937 (move-overlay ovl beg end buffer)))
4938 (defun org-overlay-put (ovl prop value)
4939 (if (featurep 'xemacs)
4940 (set-extent-property ovl prop value)
4941 (overlay-put ovl prop value)))
4942 (defun org-overlay-display (ovl text &optional face evap)
4943 "Make overlay OVL display TEXT with face FACE."
4944 (if (featurep 'xemacs)
4945 (let ((gl (make-glyph text)))
4946 (and face (set-glyph-face gl face))
4947 (set-extent-property ovl 'invisible t)
4948 (set-extent-property ovl 'end-glyph gl))
4949 (overlay-put ovl 'display text)
4950 (if face (overlay-put ovl 'face face))
4951 (if evap (overlay-put ovl 'evaporate t))))
4952 (defun org-overlay-before-string (ovl text &optional face evap)
4953 "Make overlay OVL display TEXT with face FACE."
4954 (if (featurep 'xemacs)
4955 (let ((gl (make-glyph text)))
4956 (and face (set-glyph-face gl face))
4957 (set-extent-property ovl 'begin-glyph gl))
4958 (if face (org-add-props text nil 'face face))
4959 (overlay-put ovl 'before-string text)
4960 (if evap (overlay-put ovl 'evaporate t))))
4961 (defun org-overlay-get (ovl prop)
4962 (if (featurep 'xemacs)
4963 (extent-property ovl prop)
4964 (overlay-get ovl prop)))
4965 (defun org-overlays-at (pos)
4966 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4967 (defun org-overlays-in (&optional start end)
4968 (if (featurep 'xemacs)
4969 (extent-list nil start end)
4970 (overlays-in start end)))
4971 (defun org-overlay-start (o)
4972 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4973 (defun org-overlay-end (o)
4974 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4975 (defun org-find-overlays (prop &optional pos delete)
4976 "Find all overlays specifying PROP at POS or point.
4977 If DELETE is non-nil, delete all those overlays."
4978 (let ((overlays (org-overlays-at (or pos (point))))
4979 ov found)
4980 (while (setq ov (pop overlays))
4981 (if (org-overlay-get ov prop)
4982 (if delete (org-delete-overlay ov) (push ov found))))
4983 found))
4985 ;; Region compatibility
4987 (defun org-add-hook (hook function &optional append local)
4988 "Add-hook, compatible with both Emacsen."
4989 (if (and local (featurep 'xemacs))
4990 (add-local-hook hook function append)
4991 (add-hook hook function append local)))
4993 (defvar org-ignore-region nil
4994 "To temporarily disable the active region.")
4996 (defun org-region-active-p ()
4997 "Is `transient-mark-mode' on and the region active?
4998 Works on both Emacs and XEmacs."
4999 (if org-ignore-region
5001 (if (featurep 'xemacs)
5002 (and zmacs-regions (region-active-p))
5003 (if (fboundp 'use-region-p)
5004 (use-region-p)
5005 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
5007 ;; Invisibility compatibility
5009 (defun org-add-to-invisibility-spec (arg)
5010 "Add elements to `buffer-invisibility-spec'.
5011 See documentation for `buffer-invisibility-spec' for the kind of elements
5012 that can be added."
5013 (cond
5014 ((fboundp 'add-to-invisibility-spec)
5015 (add-to-invisibility-spec arg))
5016 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
5017 (setq buffer-invisibility-spec (list arg)))
5019 (setq buffer-invisibility-spec
5020 (cons arg buffer-invisibility-spec)))))
5022 (defun org-remove-from-invisibility-spec (arg)
5023 "Remove elements from `buffer-invisibility-spec'."
5024 (if (fboundp 'remove-from-invisibility-spec)
5025 (remove-from-invisibility-spec arg)
5026 (if (consp buffer-invisibility-spec)
5027 (setq buffer-invisibility-spec
5028 (delete arg buffer-invisibility-spec)))))
5030 (defun org-in-invisibility-spec-p (arg)
5031 "Is ARG a member of `buffer-invisibility-spec'?"
5032 (if (consp buffer-invisibility-spec)
5033 (member arg buffer-invisibility-spec)
5034 nil))
5036 ;;;; Define the Org-mode
5038 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5039 (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."))
5042 ;; We use a before-change function to check if a table might need
5043 ;; an update.
5044 (defvar org-table-may-need-update t
5045 "Indicates that a table might need an update.
5046 This variable is set by `org-before-change-function'.
5047 `org-table-align' sets it back to nil.")
5048 (defvar org-mode-map)
5049 (defvar org-mode-hook nil)
5050 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5051 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5052 (defvar org-table-buffer-is-an nil)
5053 (defconst org-outline-regexp "\\*+ ")
5055 ;;;###autoload
5056 (define-derived-mode org-mode outline-mode "Org"
5057 "Outline-based notes management and organizer, alias
5058 \"Carsten's outline-mode for keeping track of everything.\"
5060 Org-mode develops organizational tasks around a NOTES file which
5061 contains information about projects as plain text. Org-mode is
5062 implemented on top of outline-mode, which is ideal to keep the content
5063 of large files well structured. It supports ToDo items, deadlines and
5064 time stamps, which magically appear in the diary listing of the Emacs
5065 calendar. Tables are easily created with a built-in table editor.
5066 Plain text URL-like links connect to websites, emails (VM), Usenet
5067 messages (Gnus), BBDB entries, and any files related to the project.
5068 For printing and sharing of notes, an Org-mode file (or a part of it)
5069 can be exported as a structured ASCII or HTML file.
5071 The following commands are available:
5073 \\{org-mode-map}"
5075 ;; Get rid of Outline menus, they are not needed
5076 ;; Need to do this here because define-derived-mode sets up
5077 ;; the keymap so late. Still, it is a waste to call this each time
5078 ;; we switch another buffer into org-mode.
5079 (if (featurep 'xemacs)
5080 (when (boundp 'outline-mode-menu-heading)
5081 ;; Assume this is Greg's port, it used easymenu
5082 (easy-menu-remove outline-mode-menu-heading)
5083 (easy-menu-remove outline-mode-menu-show)
5084 (easy-menu-remove outline-mode-menu-hide))
5085 (define-key org-mode-map [menu-bar headings] 'undefined)
5086 (define-key org-mode-map [menu-bar hide] 'undefined)
5087 (define-key org-mode-map [menu-bar show] 'undefined))
5089 (easy-menu-add org-org-menu)
5090 (easy-menu-add org-tbl-menu)
5091 (org-install-agenda-files-menu)
5092 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
5093 (org-add-to-invisibility-spec '(org-cwidth))
5094 (when (featurep 'xemacs)
5095 (org-set-local 'line-move-ignore-invisible t))
5096 (org-set-local 'outline-regexp org-outline-regexp)
5097 (org-set-local 'outline-level 'org-outline-level)
5098 (when (and org-ellipsis
5099 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5100 (fboundp 'make-glyph-code))
5101 (unless org-display-table
5102 (setq org-display-table (make-display-table)))
5103 (set-display-table-slot
5104 org-display-table 4
5105 (vconcat (mapcar
5106 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5107 org-ellipsis)))
5108 (if (stringp org-ellipsis) org-ellipsis "..."))))
5109 (setq buffer-display-table org-display-table))
5110 (org-set-regexps-and-options)
5111 ;; Calc embedded
5112 (org-set-local 'calc-embedded-open-mode "# ")
5113 (modify-syntax-entry ?# "<")
5114 (modify-syntax-entry ?@ "w")
5115 (if org-startup-truncated (setq truncate-lines t))
5116 (org-set-local 'font-lock-unfontify-region-function
5117 'org-unfontify-region)
5118 ;; Activate before-change-function
5119 (org-set-local 'org-table-may-need-update t)
5120 (org-add-hook 'before-change-functions 'org-before-change-function nil
5121 'local)
5122 ;; Check for running clock before killing a buffer
5123 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5124 ;; Paragraphs and auto-filling
5125 (org-set-autofill-regexps)
5126 (setq indent-line-function 'org-indent-line-function)
5127 (org-update-radio-target-regexp)
5129 ;; Comment characters
5130 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
5131 (org-set-local 'comment-padding " ")
5133 ;; Align options lines
5134 (org-set-local
5135 'align-mode-rules-list
5136 '((org-in-buffer-settings
5137 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5138 (modes . '(org-mode)))))
5140 ;; Imenu
5141 (org-set-local 'imenu-create-index-function
5142 'org-imenu-get-tree)
5144 ;; Make isearch reveal context
5145 (if (or (featurep 'xemacs)
5146 (not (boundp 'outline-isearch-open-invisible-function)))
5147 ;; Emacs 21 and XEmacs make use of the hook
5148 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5149 ;; Emacs 22 deals with this through a special variable
5150 (org-set-local 'outline-isearch-open-invisible-function
5151 (lambda (&rest ignore) (org-show-context 'isearch))))
5153 ;; If empty file that did not turn on org-mode automatically, make it to.
5154 (if (and org-insert-mode-line-in-empty-file
5155 (interactive-p)
5156 (= (point-min) (point-max)))
5157 (insert "# -*- mode: org -*-\n\n"))
5159 (unless org-inhibit-startup
5160 (when org-startup-align-all-tables
5161 (let ((bmp (buffer-modified-p)))
5162 (org-table-map-tables 'org-table-align)
5163 (set-buffer-modified-p bmp)))
5164 (org-cycle-hide-drawers 'all)
5165 (cond
5166 ((eq org-startup-folded t)
5167 (org-cycle '(4)))
5168 ((eq org-startup-folded 'content)
5169 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5170 (org-cycle '(4)) (org-cycle '(4)))))))
5172 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5174 (defsubst org-call-with-arg (command arg)
5175 "Call COMMAND interactively, but pretend prefix are was ARG."
5176 (let ((current-prefix-arg arg)) (call-interactively command)))
5178 (defsubst org-current-line (&optional pos)
5179 (save-excursion
5180 (and pos (goto-char pos))
5181 ;; works also in narrowed buffer, because we start at 1, not point-min
5182 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
5184 (defun org-current-time ()
5185 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5186 (if (> (car org-time-stamp-rounding-minutes) 1)
5187 (let ((r (car org-time-stamp-rounding-minutes))
5188 (time (decode-time)))
5189 (apply 'encode-time
5190 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5191 (nthcdr 2 time))))
5192 (current-time)))
5194 (defun org-add-props (string plist &rest props)
5195 "Add text properties to entire string, from beginning to end.
5196 PLIST may be a list of properties, PROPS are individual properties and values
5197 that will be added to PLIST. Returns the string that was modified."
5198 (add-text-properties
5199 0 (length string) (if props (append plist props) plist) string)
5200 string)
5201 (put 'org-add-props 'lisp-indent-function 2)
5204 ;;;; Font-Lock stuff, including the activators
5206 (defvar org-mouse-map (make-sparse-keymap))
5207 (org-defkey org-mouse-map
5208 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5209 (org-defkey org-mouse-map
5210 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5211 (when org-mouse-1-follows-link
5212 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5213 (when org-tab-follows-link
5214 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5215 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5216 (when org-return-follows-link
5217 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5218 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5220 (require 'font-lock)
5222 (defconst org-non-link-chars "]\t\n\r<>")
5223 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5224 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5225 (defvar org-link-re-with-space nil
5226 "Matches a link with spaces, optional angular brackets around it.")
5227 (defvar org-link-re-with-space2 nil
5228 "Matches a link with spaces, optional angular brackets around it.")
5229 (defvar org-angle-link-re nil
5230 "Matches link with angular brackets, spaces are allowed.")
5231 (defvar org-plain-link-re nil
5232 "Matches plain link, without spaces.")
5233 (defvar org-bracket-link-regexp nil
5234 "Matches a link in double brackets.")
5235 (defvar org-bracket-link-analytic-regexp nil
5236 "Regular expression used to analyze links.
5237 Here is what the match groups contain after a match:
5238 1: http:
5239 2: http
5240 3: path
5241 4: [desc]
5242 5: desc")
5243 (defvar org-any-link-re nil
5244 "Regular expression matching any link.")
5246 (defun org-make-link-regexps ()
5247 "Update the link regular expressions.
5248 This should be called after the variable `org-link-types' has changed."
5249 (setq org-link-re-with-space
5250 (concat
5251 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5252 "\\([^" org-non-link-chars " ]"
5253 "[^" org-non-link-chars "]*"
5254 "[^" org-non-link-chars " ]\\)>?")
5255 org-link-re-with-space2
5256 (concat
5257 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5258 "\\([^" org-non-link-chars " ]"
5259 "[^]\t\n\r]*"
5260 "[^" org-non-link-chars " ]\\)>?")
5261 org-angle-link-re
5262 (concat
5263 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5264 "\\([^" org-non-link-chars " ]"
5265 "[^" org-non-link-chars "]*"
5266 "\\)>")
5267 org-plain-link-re
5268 (concat
5269 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5270 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5271 org-bracket-link-regexp
5272 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5273 org-bracket-link-analytic-regexp
5274 (concat
5275 "\\[\\["
5276 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5277 "\\([^]]+\\)"
5278 "\\]"
5279 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5280 "\\]")
5281 org-any-link-re
5282 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5283 org-angle-link-re "\\)\\|\\("
5284 org-plain-link-re "\\)")))
5286 (org-make-link-regexps)
5288 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5289 "Regular expression for fast time stamp matching.")
5290 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5291 "Regular expression for fast time stamp matching.")
5292 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5293 "Regular expression matching time strings for analysis.
5294 This one does not require the space after the date, so it can be used
5295 on a string that terminates immediately after the date.")
5296 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5297 "Regular expression matching time strings for analysis.")
5298 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5299 "Regular expression matching time stamps, with groups.")
5300 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5301 "Regular expression matching time stamps (also [..]), with groups.")
5302 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5303 "Regular expression matching a time stamp range.")
5304 (defconst org-tr-regexp-both
5305 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5306 "Regular expression matching a time stamp range.")
5307 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5308 org-ts-regexp "\\)?")
5309 "Regular expression matching a time stamp or time stamp range.")
5310 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5311 org-ts-regexp-both "\\)?")
5312 "Regular expression matching a time stamp or time stamp range.
5313 The time stamps may be either active or inactive.")
5315 (defvar org-emph-face nil)
5317 (defun org-do-emphasis-faces (limit)
5318 "Run through the buffer and add overlays to links."
5319 (let (rtn)
5320 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5321 (if (not (= (char-after (match-beginning 3))
5322 (char-after (match-beginning 4))))
5323 (progn
5324 (setq rtn t)
5325 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5326 'face
5327 (nth 1 (assoc (match-string 3)
5328 org-emphasis-alist)))
5329 (add-text-properties (match-beginning 2) (match-end 2)
5330 '(font-lock-multiline t))
5331 (when org-hide-emphasis-markers
5332 (add-text-properties (match-end 4) (match-beginning 5)
5333 '(invisible org-link))
5334 (add-text-properties (match-beginning 3) (match-end 3)
5335 '(invisible org-link)))))
5336 (backward-char 1))
5337 rtn))
5339 (defun org-emphasize (&optional char)
5340 "Insert or change an emphasis, i.e. a font like bold or italic.
5341 If there is an active region, change that region to a new emphasis.
5342 If there is no region, just insert the marker characters and position
5343 the cursor between them.
5344 CHAR should be either the marker character, or the first character of the
5345 HTML tag associated with that emphasis. If CHAR is a space, the means
5346 to remove the emphasis of the selected region.
5347 If char is not given (for example in an interactive call) it
5348 will be prompted for."
5349 (interactive)
5350 (let ((eal org-emphasis-alist) e det
5351 (erc org-emphasis-regexp-components)
5352 (prompt "")
5353 (string "") beg end move tag c s)
5354 (if (org-region-active-p)
5355 (setq beg (region-beginning) end (region-end)
5356 string (buffer-substring beg end))
5357 (setq move t))
5359 (while (setq e (pop eal))
5360 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5361 c (aref tag 0))
5362 (push (cons c (string-to-char (car e))) det)
5363 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5364 (substring tag 1)))))
5365 (unless char
5366 (message "%s" (concat "Emphasis marker or tag:" prompt))
5367 (setq char (read-char-exclusive)))
5368 (setq char (or (cdr (assoc char det)) char))
5369 (if (equal char ?\ )
5370 (setq s "" move nil)
5371 (unless (assoc (char-to-string char) org-emphasis-alist)
5372 (error "No such emphasis marker: \"%c\"" char))
5373 (setq s (char-to-string char)))
5374 (while (and (> (length string) 1)
5375 (equal (substring string 0 1) (substring string -1))
5376 (assoc (substring string 0 1) org-emphasis-alist))
5377 (setq string (substring string 1 -1)))
5378 (setq string (concat s string s))
5379 (if beg (delete-region beg end))
5380 (unless (or (bolp)
5381 (string-match (concat "[" (nth 0 erc) "\n]")
5382 (char-to-string (char-before (point)))))
5383 (insert " "))
5384 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5385 (char-to-string (char-after (point))))
5386 (insert " ") (backward-char 1))
5387 (insert string)
5388 (and move (backward-char 1))))
5390 (defconst org-nonsticky-props
5391 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5394 (defun org-activate-plain-links (limit)
5395 "Run through the buffer and add overlays to links."
5396 (catch 'exit
5397 (let (f)
5398 (while (re-search-forward org-plain-link-re limit t)
5399 (setq f (get-text-property (match-beginning 0) 'face))
5400 (if (or (eq f 'org-tag)
5401 (and (listp f) (memq 'org-tag f)))
5403 (add-text-properties (match-beginning 0) (match-end 0)
5404 (list 'mouse-face 'highlight
5405 'rear-nonsticky org-nonsticky-props
5406 'keymap org-mouse-map
5408 (throw 'exit t))))))
5410 (defun org-activate-code (limit)
5411 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5412 (unless (get-text-property (match-beginning 1) 'face)
5413 (remove-text-properties (match-beginning 0) (match-end 0)
5414 '(display t invisible t intangible t))
5415 t)))
5417 (defun org-activate-angle-links (limit)
5418 "Run through the buffer and add overlays to links."
5419 (if (re-search-forward org-angle-link-re limit t)
5420 (progn
5421 (add-text-properties (match-beginning 0) (match-end 0)
5422 (list 'mouse-face 'highlight
5423 'rear-nonsticky org-nonsticky-props
5424 'keymap org-mouse-map
5426 t)))
5428 (defmacro org-maybe-intangible (props)
5429 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5430 In emacs 21, invisible text is not avoided by the command loop, so the
5431 intangible property is needed to make sure point skips this text.
5432 In Emacs 22, this is not necessary. The intangible text property has
5433 led to problems with flyspell. These problems are fixed in flyspell.el,
5434 but we still avoid setting the property in Emacs 22 and later.
5435 We use a macro so that the test can happen at compilation time."
5436 (if (< emacs-major-version 22)
5437 `(append '(intangible t) ,props)
5438 props))
5440 (defun org-activate-bracket-links (limit)
5441 "Run through the buffer and add overlays to bracketed links."
5442 (if (re-search-forward org-bracket-link-regexp limit t)
5443 (let* ((help (concat "LINK: "
5444 (org-match-string-no-properties 1)))
5445 ;; FIXME: above we should remove the escapes.
5446 ;; but that requires another match, protecting match data,
5447 ;; a lot of overhead for font-lock.
5448 (ip (org-maybe-intangible
5449 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5450 'keymap org-mouse-map 'mouse-face 'highlight
5451 'font-lock-multiline t 'help-echo help)))
5452 (vp (list 'rear-nonsticky org-nonsticky-props
5453 'keymap org-mouse-map 'mouse-face 'highlight
5454 ' font-lock-multiline t 'help-echo help)))
5455 ;; We need to remove the invisible property here. Table narrowing
5456 ;; may have made some of this invisible.
5457 (remove-text-properties (match-beginning 0) (match-end 0)
5458 '(invisible nil))
5459 (if (match-end 3)
5460 (progn
5461 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5462 (add-text-properties (match-beginning 3) (match-end 3) vp)
5463 (add-text-properties (match-end 3) (match-end 0) ip))
5464 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5465 (add-text-properties (match-beginning 1) (match-end 1) vp)
5466 (add-text-properties (match-end 1) (match-end 0) ip))
5467 t)))
5469 (defun org-activate-dates (limit)
5470 "Run through the buffer and add overlays to dates."
5471 (if (re-search-forward org-tsr-regexp-both limit t)
5472 (progn
5473 (add-text-properties (match-beginning 0) (match-end 0)
5474 (list 'mouse-face 'highlight
5475 'rear-nonsticky org-nonsticky-props
5476 'keymap org-mouse-map))
5477 (when org-display-custom-times
5478 (if (match-end 3)
5479 (org-display-custom-time (match-beginning 3) (match-end 3)))
5480 (org-display-custom-time (match-beginning 1) (match-end 1)))
5481 t)))
5483 (defvar org-target-link-regexp nil
5484 "Regular expression matching radio targets in plain text.")
5485 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5486 "Regular expression matching a link target.")
5487 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5488 "Regular expression matching a radio target.")
5489 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5490 "Regular expression matching any target.")
5492 (defun org-activate-target-links (limit)
5493 "Run through the buffer and add overlays to target matches."
5494 (when org-target-link-regexp
5495 (let ((case-fold-search t))
5496 (if (re-search-forward org-target-link-regexp limit t)
5497 (progn
5498 (add-text-properties (match-beginning 0) (match-end 0)
5499 (list 'mouse-face 'highlight
5500 'rear-nonsticky org-nonsticky-props
5501 'keymap org-mouse-map
5502 'help-echo "Radio target link"
5503 'org-linked-text t))
5504 t)))))
5506 (defun org-update-radio-target-regexp ()
5507 "Find all radio targets in this file and update the regular expression."
5508 (interactive)
5509 (when (memq 'radio org-activate-links)
5510 (setq org-target-link-regexp
5511 (org-make-target-link-regexp (org-all-targets 'radio)))
5512 (org-restart-font-lock)))
5514 (defun org-hide-wide-columns (limit)
5515 (let (s e)
5516 (setq s (text-property-any (point) (or limit (point-max))
5517 'org-cwidth t))
5518 (when s
5519 (setq e (next-single-property-change s 'org-cwidth))
5520 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5521 (goto-char e)
5522 t)))
5524 (defvar org-latex-and-specials-regexp nil
5525 "Regular expression for highlighting export special stuff.")
5526 (defvar org-match-substring-regexp)
5527 (defvar org-match-substring-with-braces-regexp)
5528 (defvar org-export-html-special-string-regexps)
5530 (defun org-compute-latex-and-specials-regexp ()
5531 "Compute regular expression for stuff treated specially by exporters."
5532 (if (not org-highlight-latex-fragments-and-specials)
5533 (org-set-local 'org-latex-and-specials-regexp nil)
5534 (let*
5535 ((matchers (plist-get org-format-latex-options :matchers))
5536 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5537 org-latex-regexps)))
5538 (options (org-combine-plists (org-default-export-plist)
5539 (org-infile-export-plist)))
5540 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5541 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5542 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5543 (org-export-html-expand (plist-get options :expand-quoted-html))
5544 (org-export-with-special-strings (plist-get options :special-strings))
5545 (re-sub
5546 (cond
5547 ((equal org-export-with-sub-superscripts '{})
5548 (list org-match-substring-with-braces-regexp))
5549 (org-export-with-sub-superscripts
5550 (list org-match-substring-regexp))
5551 (t nil)))
5552 (re-latex
5553 (if org-export-with-LaTeX-fragments
5554 (mapcar (lambda (x) (nth 1 x)) latexs)))
5555 (re-macros
5556 (if org-export-with-TeX-macros
5557 (list (concat "\\\\"
5558 (regexp-opt
5559 (append (mapcar 'car org-html-entities)
5560 (if (boundp 'org-latex-entities)
5561 org-latex-entities nil))
5562 'words))) ; FIXME
5564 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5565 (re-special (if org-export-with-special-strings
5566 (mapcar (lambda (x) (car x))
5567 org-export-html-special-string-regexps)))
5568 (re-rest
5569 (delq nil
5570 (list
5571 (if org-export-html-expand "@<[^>\n]+>")
5572 ))))
5573 (org-set-local
5574 'org-latex-and-specials-regexp
5575 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5576 re-rest) "\\|")))))
5578 (defface org-latex-and-export-specials
5579 (let ((font (cond ((assq :inherit custom-face-attributes)
5580 '(:inherit underline))
5581 (t '(:underline t)))))
5582 `((((class grayscale) (background light))
5583 (:foreground "DimGray" ,@font))
5584 (((class grayscale) (background dark))
5585 (:foreground "LightGray" ,@font))
5586 (((class color) (background light))
5587 (:foreground "SaddleBrown"))
5588 (((class color) (background dark))
5589 (:foreground "burlywood"))
5590 (t (,@font))))
5591 "Face used to highlight math latex and other special exporter stuff."
5592 :group 'org-faces)
5594 (defun org-do-latex-and-special-faces (limit)
5595 "Run through the buffer and add overlays to links."
5596 (when org-latex-and-specials-regexp
5597 (let (rtn d)
5598 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5599 limit t))
5600 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5601 'face))
5602 '(org-code org-verbatim underline)))
5603 (progn
5604 (setq rtn t
5605 d (cond ((member (char-after (1+ (match-beginning 0)))
5606 '(?_ ?^)) 1)
5607 (t 0)))
5608 (font-lock-prepend-text-property
5609 (+ d (match-beginning 0)) (match-end 0)
5610 'face 'org-latex-and-export-specials)
5611 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5612 '(font-lock-multiline t)))))
5613 rtn)))
5615 (defun org-restart-font-lock ()
5616 "Restart font-lock-mode, to force refontification."
5617 (when (and (boundp 'font-lock-mode) font-lock-mode)
5618 (font-lock-mode -1)
5619 (font-lock-mode 1)))
5621 (defun org-all-targets (&optional radio)
5622 "Return a list of all targets in this file.
5623 With optional argument RADIO, only find radio targets."
5624 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5625 rtn)
5626 (save-excursion
5627 (goto-char (point-min))
5628 (while (re-search-forward re nil t)
5629 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5630 rtn)))
5632 (defun org-make-target-link-regexp (targets)
5633 "Make regular expression matching all strings in TARGETS.
5634 The regular expression finds the targets also if there is a line break
5635 between words."
5636 (and targets
5637 (concat
5638 "\\<\\("
5639 (mapconcat
5640 (lambda (x)
5641 (while (string-match " +" x)
5642 (setq x (replace-match "\\s-+" t t x)))
5644 targets
5645 "\\|")
5646 "\\)\\>")))
5648 (defun org-activate-tags (limit)
5649 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5650 (progn
5651 (add-text-properties (match-beginning 1) (match-end 1)
5652 (list 'mouse-face 'highlight
5653 'rear-nonsticky org-nonsticky-props
5654 'keymap org-mouse-map))
5655 t)))
5657 (defun org-outline-level ()
5658 (save-excursion
5659 (looking-at outline-regexp)
5660 (if (match-beginning 1)
5661 (+ (org-get-string-indentation (match-string 1)) 1000)
5662 (1- (- (match-end 0) (match-beginning 0))))))
5664 (defvar org-font-lock-keywords nil)
5666 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5667 "Regular expression matching a property line.")
5669 (defun org-set-font-lock-defaults ()
5670 (let* ((em org-fontify-emphasized-text)
5671 (lk org-activate-links)
5672 (org-font-lock-extra-keywords
5673 (list
5674 ;; Headlines
5675 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5676 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5677 ;; Table lines
5678 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5679 (1 'org-table t))
5680 ;; Table internals
5681 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5682 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5683 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5684 ;; Drawers
5685 (list org-drawer-regexp '(0 'org-special-keyword t))
5686 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5687 ;; Properties
5688 (list org-property-re
5689 '(1 'org-special-keyword t)
5690 '(3 'org-property-value t))
5691 (if org-format-transports-properties-p
5692 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5693 ;; Links
5694 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5695 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5696 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5697 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5698 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5699 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5700 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5701 '(org-hide-wide-columns (0 nil append))
5702 ;; TODO lines
5703 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5704 '(1 (org-get-todo-face 1) t))
5705 ;; DONE
5706 (if org-fontify-done-headline
5707 (list (concat "^[*]+ +\\<\\("
5708 (mapconcat 'regexp-quote org-done-keywords "\\|")
5709 "\\)\\(.*\\)")
5710 '(2 'org-headline-done t))
5711 nil)
5712 ;; Priorities
5713 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5714 ;; Special keywords
5715 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5716 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5717 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5718 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5719 ;; Emphasis
5720 (if em
5721 (if (featurep 'xemacs)
5722 '(org-do-emphasis-faces (0 nil append))
5723 '(org-do-emphasis-faces)))
5724 ;; Checkboxes
5725 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5726 2 'bold prepend)
5727 (if org-provide-checkbox-statistics
5728 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5729 (0 (org-get-checkbox-statistics-face) t)))
5730 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5731 '(1 'org-archived prepend))
5732 ;; Specials
5733 '(org-do-latex-and-special-faces)
5734 ;; Code
5735 '(org-activate-code (1 'org-code t))
5736 ;; COMMENT
5737 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5738 "\\|" org-quote-string "\\)\\>")
5739 '(1 'org-special-keyword t))
5740 '("^#.*" (0 'font-lock-comment-face t))
5742 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5743 ;; Now set the full font-lock-keywords
5744 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5745 (org-set-local 'font-lock-defaults
5746 '(org-font-lock-keywords t nil nil backward-paragraph))
5747 (kill-local-variable 'font-lock-keywords) nil))
5749 (defvar org-m nil)
5750 (defvar org-l nil)
5751 (defvar org-f nil)
5752 (defun org-get-level-face (n)
5753 "Get the right face for match N in font-lock matching of healdines."
5754 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5755 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5756 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5757 (cond
5758 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5759 ((eq n 2) org-f)
5760 (t (if org-level-color-stars-only nil org-f))))
5762 (defun org-get-todo-face (kwd)
5763 "Get the right face for a TODO keyword KWD.
5764 If KWD is a number, get the corresponding match group."
5765 (if (numberp kwd) (setq kwd (match-string kwd)))
5766 (or (cdr (assoc kwd org-todo-keyword-faces))
5767 (and (member kwd org-done-keywords) 'org-done)
5768 'org-todo))
5770 (defun org-unfontify-region (beg end &optional maybe_loudly)
5771 "Remove fontification and activation overlays from links."
5772 (font-lock-default-unfontify-region beg end)
5773 (let* ((buffer-undo-list t)
5774 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5775 (inhibit-modification-hooks t)
5776 deactivate-mark buffer-file-name buffer-file-truename)
5777 (remove-text-properties beg end
5778 '(mouse-face t keymap t org-linked-text t
5779 invisible t intangible t))))
5781 ;;;; Visibility cycling, including org-goto and indirect buffer
5783 ;;; Cycling
5785 (defvar org-cycle-global-status nil)
5786 (make-variable-buffer-local 'org-cycle-global-status)
5787 (defvar org-cycle-subtree-status nil)
5788 (make-variable-buffer-local 'org-cycle-subtree-status)
5790 ;;;###autoload
5791 (defun org-cycle (&optional arg)
5792 "Visibility cycling for Org-mode.
5794 - When this function is called with a prefix argument, rotate the entire
5795 buffer through 3 states (global cycling)
5796 1. OVERVIEW: Show only top-level headlines.
5797 2. CONTENTS: Show all headlines of all levels, but no body text.
5798 3. SHOW ALL: Show everything.
5800 - When point is at the beginning of a headline, rotate the subtree started
5801 by this line through 3 different states (local cycling)
5802 1. FOLDED: Only the main headline is shown.
5803 2. CHILDREN: The main headline and the direct children are shown.
5804 From this state, you can move to one of the children
5805 and zoom in further.
5806 3. SUBTREE: Show the entire subtree, including body text.
5808 - When there is a numeric prefix, go up to a heading with level ARG, do
5809 a `show-subtree' and return to the previous cursor position. If ARG
5810 is negative, go up that many levels.
5812 - When point is not at the beginning of a headline, execute
5813 `indent-relative', like TAB normally does. See the option
5814 `org-cycle-emulate-tab' for details.
5816 - Special case: if point is at the beginning of the buffer and there is
5817 no headline in line 1, this function will act as if called with prefix arg.
5818 But only if also the variable `org-cycle-global-at-bob' is t."
5819 (interactive "P")
5820 (let* ((outline-regexp
5821 (if (and (org-mode-p) org-cycle-include-plain-lists)
5822 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5823 outline-regexp))
5824 (bob-special (and org-cycle-global-at-bob (bobp)
5825 (not (looking-at outline-regexp))))
5826 (org-cycle-hook
5827 (if bob-special
5828 (delq 'org-optimize-window-after-visibility-change
5829 (copy-sequence org-cycle-hook))
5830 org-cycle-hook))
5831 (pos (point)))
5833 (if (or bob-special (equal arg '(4)))
5834 ;; special case: use global cycling
5835 (setq arg t))
5837 (cond
5839 ((org-at-table-p 'any)
5840 ;; Enter the table or move to the next field in the table
5841 (or (org-table-recognize-table.el)
5842 (progn
5843 (if arg (org-table-edit-field t)
5844 (org-table-justify-field-maybe)
5845 (call-interactively 'org-table-next-field)))))
5847 ((eq arg t) ;; Global cycling
5849 (cond
5850 ((and (eq last-command this-command)
5851 (eq org-cycle-global-status 'overview))
5852 ;; We just created the overview - now do table of contents
5853 ;; This can be slow in very large buffers, so indicate action
5854 (message "CONTENTS...")
5855 (org-content)
5856 (message "CONTENTS...done")
5857 (setq org-cycle-global-status 'contents)
5858 (run-hook-with-args 'org-cycle-hook 'contents))
5860 ((and (eq last-command this-command)
5861 (eq org-cycle-global-status 'contents))
5862 ;; We just showed the table of contents - now show everything
5863 (show-all)
5864 (message "SHOW ALL")
5865 (setq org-cycle-global-status 'all)
5866 (run-hook-with-args 'org-cycle-hook 'all))
5869 ;; Default action: go to overview
5870 (org-overview)
5871 (message "OVERVIEW")
5872 (setq org-cycle-global-status 'overview)
5873 (run-hook-with-args 'org-cycle-hook 'overview))))
5875 ((and org-drawers org-drawer-regexp
5876 (save-excursion
5877 (beginning-of-line 1)
5878 (looking-at org-drawer-regexp)))
5879 ;; Toggle block visibility
5880 (org-flag-drawer
5881 (not (get-char-property (match-end 0) 'invisible))))
5883 ((integerp arg)
5884 ;; Show-subtree, ARG levels up from here.
5885 (save-excursion
5886 (org-back-to-heading)
5887 (outline-up-heading (if (< arg 0) (- arg)
5888 (- (funcall outline-level) arg)))
5889 (org-show-subtree)))
5891 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5892 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5893 ;; At a heading: rotate between three different views
5894 (org-back-to-heading)
5895 (let ((goal-column 0) eoh eol eos)
5896 ;; First, some boundaries
5897 (save-excursion
5898 (org-back-to-heading)
5899 (save-excursion
5900 (beginning-of-line 2)
5901 (while (and (not (eobp)) ;; this is like `next-line'
5902 (get-char-property (1- (point)) 'invisible))
5903 (beginning-of-line 2)) (setq eol (point)))
5904 (outline-end-of-heading) (setq eoh (point))
5905 (org-end-of-subtree t)
5906 (unless (eobp)
5907 (skip-chars-forward " \t\n")
5908 (beginning-of-line 1) ; in case this is an item
5910 (setq eos (1- (point))))
5911 ;; Find out what to do next and set `this-command'
5912 (cond
5913 ((= eos eoh)
5914 ;; Nothing is hidden behind this heading
5915 (message "EMPTY ENTRY")
5916 (setq org-cycle-subtree-status nil)
5917 (save-excursion
5918 (goto-char eos)
5919 (outline-next-heading)
5920 (if (org-invisible-p) (org-flag-heading nil))))
5921 ((or (>= eol eos)
5922 (not (string-match "\\S-" (buffer-substring eol eos))))
5923 ;; Entire subtree is hidden in one line: open it
5924 (org-show-entry)
5925 (show-children)
5926 (message "CHILDREN")
5927 (save-excursion
5928 (goto-char eos)
5929 (outline-next-heading)
5930 (if (org-invisible-p) (org-flag-heading nil)))
5931 (setq org-cycle-subtree-status 'children)
5932 (run-hook-with-args 'org-cycle-hook 'children))
5933 ((and (eq last-command this-command)
5934 (eq org-cycle-subtree-status 'children))
5935 ;; We just showed the children, now show everything.
5936 (org-show-subtree)
5937 (message "SUBTREE")
5938 (setq org-cycle-subtree-status 'subtree)
5939 (run-hook-with-args 'org-cycle-hook 'subtree))
5941 ;; Default action: hide the subtree.
5942 (hide-subtree)
5943 (message "FOLDED")
5944 (setq org-cycle-subtree-status 'folded)
5945 (run-hook-with-args 'org-cycle-hook 'folded)))))
5947 ;; TAB emulation
5948 (buffer-read-only (org-back-to-heading))
5950 ((org-try-cdlatex-tab))
5952 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5953 (or (not (bolp))
5954 (not (looking-at outline-regexp))))
5955 (call-interactively (global-key-binding "\t")))
5957 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5958 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5959 (or (and (eq org-cycle-emulate-tab 'white)
5960 (= (match-end 0) (point-at-eol)))
5961 (and (eq org-cycle-emulate-tab 'whitestart)
5962 (>= (match-end 0) pos))))
5964 (eq org-cycle-emulate-tab t))
5965 ; (if (and (looking-at "[ \n\r\t]")
5966 ; (string-match "^[ \t]*$" (buffer-substring
5967 ; (point-at-bol) (point))))
5968 ; (progn
5969 ; (beginning-of-line 1)
5970 ; (and (looking-at "[ \t]+") (replace-match ""))))
5971 (call-interactively (global-key-binding "\t")))
5973 (t (save-excursion
5974 (org-back-to-heading)
5975 (org-cycle))))))
5977 ;;;###autoload
5978 (defun org-global-cycle (&optional arg)
5979 "Cycle the global visibility. For details see `org-cycle'."
5980 (interactive "P")
5981 (let ((org-cycle-include-plain-lists
5982 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5983 (if (integerp arg)
5984 (progn
5985 (show-all)
5986 (hide-sublevels arg)
5987 (setq org-cycle-global-status 'contents))
5988 (org-cycle '(4)))))
5990 (defun org-overview ()
5991 "Switch to overview mode, shoing only top-level headlines.
5992 Really, this shows all headlines with level equal or greater than the level
5993 of the first headline in the buffer. This is important, because if the
5994 first headline is not level one, then (hide-sublevels 1) gives confusing
5995 results."
5996 (interactive)
5997 (let ((level (save-excursion
5998 (goto-char (point-min))
5999 (if (re-search-forward (concat "^" outline-regexp) nil t)
6000 (progn
6001 (goto-char (match-beginning 0))
6002 (funcall outline-level))))))
6003 (and level (hide-sublevels level))))
6005 (defun org-content (&optional arg)
6006 "Show all headlines in the buffer, like a table of contents.
6007 With numerical argument N, show content up to level N."
6008 (interactive "P")
6009 (save-excursion
6010 ;; Visit all headings and show their offspring
6011 (and (integerp arg) (org-overview))
6012 (goto-char (point-max))
6013 (catch 'exit
6014 (while (and (progn (condition-case nil
6015 (outline-previous-visible-heading 1)
6016 (error (goto-char (point-min))))
6018 (looking-at outline-regexp))
6019 (if (integerp arg)
6020 (show-children (1- arg))
6021 (show-branches))
6022 (if (bobp) (throw 'exit nil))))))
6025 (defun org-optimize-window-after-visibility-change (state)
6026 "Adjust the window after a change in outline visibility.
6027 This function is the default value of the hook `org-cycle-hook'."
6028 (when (get-buffer-window (current-buffer))
6029 (cond
6030 ; ((eq state 'overview) (org-first-headline-recenter 1))
6031 ; ((eq state 'overview) (org-beginning-of-line))
6032 ((eq state 'content) nil)
6033 ((eq state 'all) nil)
6034 ((eq state 'folded) nil)
6035 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6036 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6038 (defun org-compact-display-after-subtree-move ()
6039 (let (beg end)
6040 (save-excursion
6041 (if (org-up-heading-safe)
6042 (progn
6043 (hide-subtree)
6044 (show-entry)
6045 (show-children)
6046 (org-cycle-show-empty-lines 'children)
6047 (org-cycle-hide-drawers 'children))
6048 (org-overview)))))
6050 (defun org-cycle-show-empty-lines (state)
6051 "Show empty lines above all visible headlines.
6052 The region to be covered depends on STATE when called through
6053 `org-cycle-hook'. Lisp program can use t for STATE to get the
6054 entire buffer covered. Note that an empty line is only shown if there
6055 are at least `org-cycle-separator-lines' empty lines before the headeline."
6056 (when (> org-cycle-separator-lines 0)
6057 (save-excursion
6058 (let* ((n org-cycle-separator-lines)
6059 (re (cond
6060 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6061 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6062 (t (let ((ns (number-to-string (- n 2))))
6063 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6064 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6065 beg end)
6066 (cond
6067 ((memq state '(overview contents t))
6068 (setq beg (point-min) end (point-max)))
6069 ((memq state '(children folded))
6070 (setq beg (point) end (progn (org-end-of-subtree t t)
6071 (beginning-of-line 2)
6072 (point)))))
6073 (when beg
6074 (goto-char beg)
6075 (while (re-search-forward re end t)
6076 (if (not (get-char-property (match-end 1) 'invisible))
6077 (outline-flag-region
6078 (match-beginning 1) (match-end 1) nil)))))))
6079 ;; Never hide empty lines at the end of the file.
6080 (save-excursion
6081 (goto-char (point-max))
6082 (outline-previous-heading)
6083 (outline-end-of-heading)
6084 (if (and (looking-at "[ \t\n]+")
6085 (= (match-end 0) (point-max)))
6086 (outline-flag-region (point) (match-end 0) nil))))
6088 (defun org-subtree-end-visible-p ()
6089 "Is the end of the current subtree visible?"
6090 (pos-visible-in-window-p
6091 (save-excursion (org-end-of-subtree t) (point))))
6093 (defun org-first-headline-recenter (&optional N)
6094 "Move cursor to the first headline and recenter the headline.
6095 Optional argument N means, put the headline into the Nth line of the window."
6096 (goto-char (point-min))
6097 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6098 (beginning-of-line)
6099 (recenter (prefix-numeric-value N))))
6101 ;;; Org-goto
6103 (defvar org-goto-window-configuration nil)
6104 (defvar org-goto-marker nil)
6105 (defvar org-goto-map
6106 (let ((map (make-sparse-keymap)))
6107 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6108 (while (setq cmd (pop cmds))
6109 (substitute-key-definition cmd cmd map global-map)))
6110 (suppress-keymap map)
6111 (org-defkey map "\C-m" 'org-goto-ret)
6112 (org-defkey map [(return)] 'org-goto-ret)
6113 (org-defkey map [(left)] 'org-goto-left)
6114 (org-defkey map [(right)] 'org-goto-right)
6115 (org-defkey map [(control ?g)] 'org-goto-quit)
6116 (org-defkey map "\C-i" 'org-cycle)
6117 (org-defkey map [(tab)] 'org-cycle)
6118 (org-defkey map [(down)] 'outline-next-visible-heading)
6119 (org-defkey map [(up)] 'outline-previous-visible-heading)
6120 (if org-goto-auto-isearch
6121 (if (fboundp 'define-key-after)
6122 (define-key-after map [t] 'org-goto-local-auto-isearch)
6123 nil)
6124 (org-defkey map "q" 'org-goto-quit)
6125 (org-defkey map "n" 'outline-next-visible-heading)
6126 (org-defkey map "p" 'outline-previous-visible-heading)
6127 (org-defkey map "f" 'outline-forward-same-level)
6128 (org-defkey map "b" 'outline-backward-same-level)
6129 (org-defkey map "u" 'outline-up-heading))
6130 (org-defkey map "/" 'org-occur)
6131 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6132 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6133 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6134 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6135 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6136 map))
6138 (defconst org-goto-help
6139 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6140 RET=jump to location [Q]uit and return to previous location
6141 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6143 (defvar org-goto-start-pos) ; dynamically scoped parameter
6145 (defun org-goto (&optional alternative-interface)
6146 "Look up a different location in the current file, keeping current visibility.
6148 When you want look-up or go to a different location in a document, the
6149 fastest way is often to fold the entire buffer and then dive into the tree.
6150 This method has the disadvantage, that the previous location will be folded,
6151 which may not be what you want.
6153 This command works around this by showing a copy of the current buffer
6154 in an indirect buffer, in overview mode. You can dive into the tree in
6155 that copy, use org-occur and incremental search to find a location.
6156 When pressing RET or `Q', the command returns to the original buffer in
6157 which the visibility is still unchanged. After RET is will also jump to
6158 the location selected in the indirect buffer and expose the
6159 the headline hierarchy above."
6160 (interactive "P")
6161 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
6162 (org-refile-use-outline-path t)
6163 (interface
6164 (if (not alternative-interface)
6165 org-goto-interface
6166 (if (eq org-goto-interface 'outline)
6167 'outline-path-completion
6168 'outline)))
6169 (org-goto-start-pos (point))
6170 (selected-point
6171 (if (eq interface 'outline)
6172 (car (org-get-location (current-buffer) org-goto-help))
6173 (nth 3 (org-refile-get-location "Goto: ")))))
6174 (if selected-point
6175 (progn
6176 (org-mark-ring-push org-goto-start-pos)
6177 (goto-char selected-point)
6178 (if (or (org-invisible-p) (org-invisible-p2))
6179 (org-show-context 'org-goto)))
6180 (message "Quit"))))
6182 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6183 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6184 (defvar org-goto-local-auto-isearch-map) ; defined below
6186 (defun org-get-location (buf help)
6187 "Let the user select a location in the Org-mode buffer BUF.
6188 This function uses a recursive edit. It returns the selected position
6189 or nil."
6190 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6191 (isearch-hide-immediately nil)
6192 (isearch-search-fun-function
6193 (lambda () 'org-goto-local-search-forward-headings))
6194 (org-goto-selected-point org-goto-exit-command))
6195 (save-excursion
6196 (save-window-excursion
6197 (delete-other-windows)
6198 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6199 (switch-to-buffer
6200 (condition-case nil
6201 (make-indirect-buffer (current-buffer) "*org-goto*")
6202 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6203 (with-output-to-temp-buffer "*Help*"
6204 (princ help))
6205 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6206 (setq buffer-read-only nil)
6207 (let ((org-startup-truncated t)
6208 (org-startup-folded nil)
6209 (org-startup-align-all-tables nil))
6210 (org-mode)
6211 (org-overview))
6212 (setq buffer-read-only t)
6213 (if (and (boundp 'org-goto-start-pos)
6214 (integer-or-marker-p org-goto-start-pos))
6215 (let ((org-show-hierarchy-above t)
6216 (org-show-siblings t)
6217 (org-show-following-heading t))
6218 (goto-char org-goto-start-pos)
6219 (and (org-invisible-p) (org-show-context)))
6220 (goto-char (point-min)))
6221 (org-beginning-of-line)
6222 (message "Select location and press RET")
6223 (use-local-map org-goto-map)
6224 (recursive-edit)
6226 (kill-buffer "*org-goto*")
6227 (cons org-goto-selected-point org-goto-exit-command)))
6229 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6230 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6231 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6232 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6234 (defun org-goto-local-search-forward-headings (string bound noerror)
6235 "Search and make sure that anu matches are in headlines."
6236 (catch 'return
6237 (while (search-forward string bound noerror)
6238 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6239 (and (member :headline context)
6240 (not (member :tags context))))
6241 (throw 'return (point))))))
6243 (defun org-goto-local-auto-isearch ()
6244 "Start isearch."
6245 (interactive)
6246 (goto-char (point-min))
6247 (let ((keys (this-command-keys)))
6248 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6249 (isearch-mode t)
6250 (isearch-process-search-char (string-to-char keys)))))
6252 (defun org-goto-ret (&optional arg)
6253 "Finish `org-goto' by going to the new location."
6254 (interactive "P")
6255 (setq org-goto-selected-point (point)
6256 org-goto-exit-command 'return)
6257 (throw 'exit nil))
6259 (defun org-goto-left ()
6260 "Finish `org-goto' by going to the new location."
6261 (interactive)
6262 (if (org-on-heading-p)
6263 (progn
6264 (beginning-of-line 1)
6265 (setq org-goto-selected-point (point)
6266 org-goto-exit-command 'left)
6267 (throw 'exit nil))
6268 (error "Not on a heading")))
6270 (defun org-goto-right ()
6271 "Finish `org-goto' by going to the new location."
6272 (interactive)
6273 (if (org-on-heading-p)
6274 (progn
6275 (setq org-goto-selected-point (point)
6276 org-goto-exit-command 'right)
6277 (throw 'exit nil))
6278 (error "Not on a heading")))
6280 (defun org-goto-quit ()
6281 "Finish `org-goto' without cursor motion."
6282 (interactive)
6283 (setq org-goto-selected-point nil)
6284 (setq org-goto-exit-command 'quit)
6285 (throw 'exit nil))
6287 ;;; Indirect buffer display of subtrees
6289 (defvar org-indirect-dedicated-frame nil
6290 "This is the frame being used for indirect tree display.")
6291 (defvar org-last-indirect-buffer nil)
6293 (defun org-tree-to-indirect-buffer (&optional arg)
6294 "Create indirect buffer and narrow it to current subtree.
6295 With numerical prefix ARG, go up to this level and then take that tree.
6296 If ARG is negative, go up that many levels.
6297 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6298 indirect buffer previously made with this command, to avoid proliferation of
6299 indirect buffers. However, when you call the command with a `C-u' prefix, or
6300 when `org-indirect-buffer-display' is `new-frame', the last buffer
6301 is kept so that you can work with several indirect buffers at the same time.
6302 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6303 requests that a new frame be made for the new buffer, so that the dedicated
6304 frame is not changed."
6305 (interactive "P")
6306 (let ((cbuf (current-buffer))
6307 (cwin (selected-window))
6308 (pos (point))
6309 beg end level heading ibuf)
6310 (save-excursion
6311 (org-back-to-heading t)
6312 (when (numberp arg)
6313 (setq level (org-outline-level))
6314 (if (< arg 0) (setq arg (+ level arg)))
6315 (while (> (setq level (org-outline-level)) arg)
6316 (outline-up-heading 1 t)))
6317 (setq beg (point)
6318 heading (org-get-heading))
6319 (org-end-of-subtree t) (setq end (point)))
6320 (if (and (buffer-live-p org-last-indirect-buffer)
6321 (not (eq org-indirect-buffer-display 'new-frame))
6322 (not arg))
6323 (kill-buffer org-last-indirect-buffer))
6324 (setq ibuf (org-get-indirect-buffer cbuf)
6325 org-last-indirect-buffer ibuf)
6326 (cond
6327 ((or (eq org-indirect-buffer-display 'new-frame)
6328 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6329 (select-frame (make-frame))
6330 (delete-other-windows)
6331 (switch-to-buffer ibuf)
6332 (org-set-frame-title heading))
6333 ((eq org-indirect-buffer-display 'dedicated-frame)
6334 (raise-frame
6335 (select-frame (or (and org-indirect-dedicated-frame
6336 (frame-live-p org-indirect-dedicated-frame)
6337 org-indirect-dedicated-frame)
6338 (setq org-indirect-dedicated-frame (make-frame)))))
6339 (delete-other-windows)
6340 (switch-to-buffer ibuf)
6341 (org-set-frame-title (concat "Indirect: " heading)))
6342 ((eq org-indirect-buffer-display 'current-window)
6343 (switch-to-buffer ibuf))
6344 ((eq org-indirect-buffer-display 'other-window)
6345 (pop-to-buffer ibuf))
6346 (t (error "Invalid value.")))
6347 (if (featurep 'xemacs)
6348 (save-excursion (org-mode) (turn-on-font-lock)))
6349 (narrow-to-region beg end)
6350 (show-all)
6351 (goto-char pos)
6352 (and (window-live-p cwin) (select-window cwin))))
6354 (defun org-get-indirect-buffer (&optional buffer)
6355 (setq buffer (or buffer (current-buffer)))
6356 (let ((n 1) (base (buffer-name buffer)) bname)
6357 (while (buffer-live-p
6358 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6359 (setq n (1+ n)))
6360 (condition-case nil
6361 (make-indirect-buffer buffer bname 'clone)
6362 (error (make-indirect-buffer buffer bname)))))
6364 (defun org-set-frame-title (title)
6365 "Set the title of the current frame to the string TITLE."
6366 ;; FIXME: how to name a single frame in XEmacs???
6367 (unless (featurep 'xemacs)
6368 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6370 ;;;; Structure editing
6372 ;;; Inserting headlines
6374 (defun org-insert-heading (&optional force-heading)
6375 "Insert a new heading or item with same depth at point.
6376 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6377 If point is at the beginning of a headline, insert a sibling before the
6378 current headline. If point is not at the beginning, do not split the line,
6379 but create the new hedline after the current line."
6380 (interactive "P")
6381 (if (= (buffer-size) 0)
6382 (insert "\n* ")
6383 (when (or force-heading (not (org-insert-item)))
6384 (let* ((head (save-excursion
6385 (condition-case nil
6386 (progn
6387 (org-back-to-heading)
6388 (match-string 0))
6389 (error "*"))))
6390 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6391 pos)
6392 (cond
6393 ((and (org-on-heading-p) (bolp)
6394 (or (bobp)
6395 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6396 ;; insert before the current line
6397 (open-line (if blank 2 1)))
6398 ((and (bolp)
6399 (or (bobp)
6400 (save-excursion
6401 (backward-char 1) (not (org-invisible-p)))))
6402 ;; insert right here
6403 nil)
6405 ; ;; in the middle of the line
6406 ; (org-show-entry)
6407 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
6408 ; (if (and
6409 ; (org-on-heading-p)
6410 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6411 ; ;; protect the tags
6412 ;; (let ((tags (match-string 2)) pos)
6413 ; (delete-region (match-beginning 1) (match-end 1))
6414 ; (setq pos (point-at-bol))
6415 ; (newline (if blank 2 1))
6416 ; (save-excursion
6417 ; (goto-char pos)
6418 ; (end-of-line 1)
6419 ; (insert " " tags)
6420 ; (org-set-tags nil 'align)))
6421 ; (newline (if blank 2 1)))
6422 ; (newline (if blank 2 1))))
6425 ;; in the middle of the line
6426 (org-show-entry)
6427 (let ((split
6428 (org-get-alist-option org-M-RET-may-split-line 'headline))
6429 tags pos)
6430 (if (org-on-heading-p)
6431 (progn
6432 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6433 (setq tags (and (match-end 2) (match-string 2)))
6434 (and (match-end 1)
6435 (delete-region (match-beginning 1) (match-end 1)))
6436 (setq pos (point-at-bol))
6437 (or split (end-of-line 1))
6438 (delete-horizontal-space)
6439 (newline (if blank 2 1))
6440 (when tags
6441 (save-excursion
6442 (goto-char pos)
6443 (end-of-line 1)
6444 (insert " " tags)
6445 (org-set-tags nil 'align))))
6446 (or split (end-of-line 1))
6447 (newline (if blank 2 1))))))
6448 (insert head) (just-one-space)
6449 (setq pos (point))
6450 (end-of-line 1)
6451 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6452 (run-hooks 'org-insert-heading-hook)))))
6454 (defun org-insert-heading-after-current ()
6455 "Insert a new heading with same level as current, after current subtree."
6456 (interactive)
6457 (org-back-to-heading)
6458 (org-insert-heading)
6459 (org-move-subtree-down)
6460 (end-of-line 1))
6462 (defun org-insert-todo-heading (arg)
6463 "Insert a new heading with the same level and TODO state as current heading.
6464 If the heading has no TODO state, or if the state is DONE, use the first
6465 state (TODO by default). Also with prefix arg, force first state."
6466 (interactive "P")
6467 (when (not (org-insert-item 'checkbox))
6468 (org-insert-heading)
6469 (save-excursion
6470 (org-back-to-heading)
6471 (outline-previous-heading)
6472 (looking-at org-todo-line-regexp))
6473 (if (or arg
6474 (not (match-beginning 2))
6475 (member (match-string 2) org-done-keywords))
6476 (insert (car org-todo-keywords-1) " ")
6477 (insert (match-string 2) " "))))
6479 (defun org-insert-subheading (arg)
6480 "Insert a new subheading and demote it.
6481 Works for outline headings and for plain lists alike."
6482 (interactive "P")
6483 (org-insert-heading arg)
6484 (cond
6485 ((org-on-heading-p) (org-do-demote))
6486 ((org-at-item-p) (org-indent-item 1))))
6488 (defun org-insert-todo-subheading (arg)
6489 "Insert a new subheading with TODO keyword or checkbox and demote it.
6490 Works for outline headings and for plain lists alike."
6491 (interactive "P")
6492 (org-insert-todo-heading arg)
6493 (cond
6494 ((org-on-heading-p) (org-do-demote))
6495 ((org-at-item-p) (org-indent-item 1))))
6497 ;;; Promotion and Demotion
6499 (defun org-promote-subtree ()
6500 "Promote the entire subtree.
6501 See also `org-promote'."
6502 (interactive)
6503 (save-excursion
6504 (org-map-tree 'org-promote))
6505 (org-fix-position-after-promote))
6507 (defun org-demote-subtree ()
6508 "Demote the entire subtree. See `org-demote'.
6509 See also `org-promote'."
6510 (interactive)
6511 (save-excursion
6512 (org-map-tree 'org-demote))
6513 (org-fix-position-after-promote))
6516 (defun org-do-promote ()
6517 "Promote the current heading higher up the tree.
6518 If the region is active in `transient-mark-mode', promote all headings
6519 in the region."
6520 (interactive)
6521 (save-excursion
6522 (if (org-region-active-p)
6523 (org-map-region 'org-promote (region-beginning) (region-end))
6524 (org-promote)))
6525 (org-fix-position-after-promote))
6527 (defun org-do-demote ()
6528 "Demote the current heading lower down the tree.
6529 If the region is active in `transient-mark-mode', demote all headings
6530 in the region."
6531 (interactive)
6532 (save-excursion
6533 (if (org-region-active-p)
6534 (org-map-region 'org-demote (region-beginning) (region-end))
6535 (org-demote)))
6536 (org-fix-position-after-promote))
6538 (defun org-fix-position-after-promote ()
6539 "Make sure that after pro/demotion cursor position is right."
6540 (let ((pos (point)))
6541 (when (save-excursion
6542 (beginning-of-line 1)
6543 (looking-at org-todo-line-regexp)
6544 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6545 (cond ((eobp) (insert " "))
6546 ((eolp) (insert " "))
6547 ((equal (char-after) ?\ ) (forward-char 1))))))
6549 (defun org-reduced-level (l)
6550 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6552 (defun org-get-valid-level (level &optional change)
6553 "Rectify a level change under the influence of `org-odd-levels-only'
6554 LEVEL is a current level, CHANGE is by how much the level should be
6555 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6556 even level numbers will become the next higher odd number."
6557 (if org-odd-levels-only
6558 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6559 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6560 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6561 (max 1 (+ level change))))
6563 (define-obsolete-function-alias 'org-get-legal-level
6564 'org-get-valid-level "23.1")
6566 (defun org-promote ()
6567 "Promote the current heading higher up the tree.
6568 If the region is active in `transient-mark-mode', promote all headings
6569 in the region."
6570 (org-back-to-heading t)
6571 (let* ((level (save-match-data (funcall outline-level)))
6572 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6573 (diff (abs (- level (length up-head) -1))))
6574 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6575 (replace-match up-head nil t)
6576 ;; Fixup tag positioning
6577 (and org-auto-align-tags (org-set-tags nil t))
6578 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6580 (defun org-demote ()
6581 "Demote the current heading lower down the tree.
6582 If the region is active in `transient-mark-mode', demote all headings
6583 in the region."
6584 (org-back-to-heading t)
6585 (let* ((level (save-match-data (funcall outline-level)))
6586 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6587 (diff (abs (- level (length down-head) -1))))
6588 (replace-match down-head nil t)
6589 ;; Fixup tag positioning
6590 (and org-auto-align-tags (org-set-tags nil t))
6591 (if org-adapt-indentation (org-fixup-indentation diff))))
6593 (defun org-map-tree (fun)
6594 "Call FUN for every heading underneath the current one."
6595 (org-back-to-heading)
6596 (let ((level (funcall outline-level)))
6597 (save-excursion
6598 (funcall fun)
6599 (while (and (progn
6600 (outline-next-heading)
6601 (> (funcall outline-level) level))
6602 (not (eobp)))
6603 (funcall fun)))))
6605 (defun org-map-region (fun beg end)
6606 "Call FUN for every heading between BEG and END."
6607 (let ((org-ignore-region t))
6608 (save-excursion
6609 (setq end (copy-marker end))
6610 (goto-char beg)
6611 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6612 (< (point) end))
6613 (funcall fun))
6614 (while (and (progn
6615 (outline-next-heading)
6616 (< (point) end))
6617 (not (eobp)))
6618 (funcall fun)))))
6620 (defun org-fixup-indentation (diff)
6621 "Change the indentation in the current entry by DIFF
6622 However, if any line in the current entry has no indentation, or if it
6623 would end up with no indentation after the change, nothing at all is done."
6624 (save-excursion
6625 (let ((end (save-excursion (outline-next-heading)
6626 (point-marker)))
6627 (prohibit (if (> diff 0)
6628 "^\\S-"
6629 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6630 col)
6631 (unless (save-excursion (end-of-line 1)
6632 (re-search-forward prohibit end t))
6633 (while (and (< (point) end)
6634 (re-search-forward "^[ \t]+" end t))
6635 (goto-char (match-end 0))
6636 (setq col (current-column))
6637 (if (< diff 0) (replace-match ""))
6638 (indent-to (+ diff col))))
6639 (move-marker end nil))))
6641 (defun org-convert-to-odd-levels ()
6642 "Convert an org-mode file with all levels allowed to one with odd levels.
6643 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6644 level 5 etc."
6645 (interactive)
6646 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6647 (let ((org-odd-levels-only nil) n)
6648 (save-excursion
6649 (goto-char (point-min))
6650 (while (re-search-forward "^\\*\\*+ " nil t)
6651 (setq n (- (length (match-string 0)) 2))
6652 (while (>= (setq n (1- n)) 0)
6653 (org-demote))
6654 (end-of-line 1))))))
6657 (defun org-convert-to-oddeven-levels ()
6658 "Convert an org-mode file with only odd levels to one with odd and even levels.
6659 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6660 section with an even level, conversion would destroy the structure of the file. An error
6661 is signaled in this case."
6662 (interactive)
6663 (goto-char (point-min))
6664 ;; First check if there are no even levels
6665 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6666 (org-show-context t)
6667 (error "Not all levels are odd in this file. Conversion not possible."))
6668 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6669 (let ((org-odd-levels-only nil) n)
6670 (save-excursion
6671 (goto-char (point-min))
6672 (while (re-search-forward "^\\*\\*+ " nil t)
6673 (setq n (/ (1- (length (match-string 0))) 2))
6674 (while (>= (setq n (1- n)) 0)
6675 (org-promote))
6676 (end-of-line 1))))))
6678 (defun org-tr-level (n)
6679 "Make N odd if required."
6680 (if org-odd-levels-only (1+ (/ n 2)) n))
6682 ;;; Vertical tree motion, cutting and pasting of subtrees
6684 (defun org-move-subtree-up (&optional arg)
6685 "Move the current subtree up past ARG headlines of the same level."
6686 (interactive "p")
6687 (org-move-subtree-down (- (prefix-numeric-value arg))))
6689 (defun org-move-subtree-down (&optional arg)
6690 "Move the current subtree down past ARG headlines of the same level."
6691 (interactive "p")
6692 (setq arg (prefix-numeric-value arg))
6693 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6694 'outline-get-last-sibling))
6695 (ins-point (make-marker))
6696 (cnt (abs arg))
6697 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6698 ;; Select the tree
6699 (org-back-to-heading)
6700 (setq beg0 (point))
6701 (save-excursion
6702 (setq ne-beg (org-back-over-empty-lines))
6703 (setq beg (point)))
6704 (save-match-data
6705 (save-excursion (outline-end-of-heading)
6706 (setq folded (org-invisible-p)))
6707 (outline-end-of-subtree))
6708 (outline-next-heading)
6709 (setq ne-end (org-back-over-empty-lines))
6710 (setq end (point))
6711 (goto-char beg0)
6712 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6713 ;; include less whitespace
6714 (save-excursion
6715 (goto-char beg)
6716 (forward-line (- ne-beg ne-end))
6717 (setq beg (point))))
6718 ;; Find insertion point, with error handling
6719 (while (> cnt 0)
6720 (or (and (funcall movfunc) (looking-at outline-regexp))
6721 (progn (goto-char beg0)
6722 (error "Cannot move past superior level or buffer limit")))
6723 (setq cnt (1- cnt)))
6724 (if (> arg 0)
6725 ;; Moving forward - still need to move over subtree
6726 (progn (org-end-of-subtree t t)
6727 (save-excursion
6728 (org-back-over-empty-lines)
6729 (or (bolp) (newline)))))
6730 (setq ne-ins (org-back-over-empty-lines))
6731 (move-marker ins-point (point))
6732 (setq txt (buffer-substring beg end))
6733 (delete-region beg end)
6734 (outline-flag-region (1- beg) beg nil)
6735 (outline-flag-region (1- (point)) (point) nil)
6736 (insert txt)
6737 (or (bolp) (insert "\n"))
6738 (setq ins-end (point))
6739 (goto-char ins-point)
6740 (org-skip-whitespace)
6741 (when (and (< arg 0)
6742 (org-first-sibling-p)
6743 (> ne-ins ne-beg))
6744 ;; Move whitespace back to beginning
6745 (save-excursion
6746 (goto-char ins-end)
6747 (let ((kill-whole-line t))
6748 (kill-line (- ne-ins ne-beg)) (point)))
6749 (insert (make-string (- ne-ins ne-beg) ?\n)))
6750 (move-marker ins-point nil)
6751 (org-compact-display-after-subtree-move)
6752 (unless folded
6753 (org-show-entry)
6754 (show-children)
6755 (org-cycle-hide-drawers 'children))))
6757 (defvar org-subtree-clip ""
6758 "Clipboard for cut and paste of subtrees.
6759 This is actually only a copy of the kill, because we use the normal kill
6760 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6762 (defvar org-subtree-clip-folded nil
6763 "Was the last copied subtree folded?
6764 This is used to fold the tree back after pasting.")
6766 (defun org-cut-subtree (&optional n)
6767 "Cut the current subtree into the clipboard.
6768 With prefix arg N, cut this many sequential subtrees.
6769 This is a short-hand for marking the subtree and then cutting it."
6770 (interactive "p")
6771 (org-copy-subtree n 'cut))
6773 (defun org-copy-subtree (&optional n cut)
6774 "Cut the current subtree into the clipboard.
6775 With prefix arg N, cut this many sequential subtrees.
6776 This is a short-hand for marking the subtree and then copying it.
6777 If CUT is non-nil, actually cut the subtree."
6778 (interactive "p")
6779 (let (beg end folded (beg0 (point)))
6780 (if (interactive-p)
6781 (org-back-to-heading nil) ; take what looks like a subtree
6782 (org-back-to-heading t)) ; take what is really there
6783 (org-back-over-empty-lines)
6784 (setq beg (point))
6785 (skip-chars-forward " \t\r\n")
6786 (save-match-data
6787 (save-excursion (outline-end-of-heading)
6788 (setq folded (org-invisible-p)))
6789 (condition-case nil
6790 (outline-forward-same-level (1- n))
6791 (error nil))
6792 (org-end-of-subtree t t))
6793 (org-back-over-empty-lines)
6794 (setq end (point))
6795 (goto-char beg0)
6796 (when (> end beg)
6797 (setq org-subtree-clip-folded folded)
6798 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6799 (setq org-subtree-clip (current-kill 0))
6800 (message "%s: Subtree(s) with %d characters"
6801 (if cut "Cut" "Copied")
6802 (length org-subtree-clip)))))
6804 (defun org-paste-subtree (&optional level tree)
6805 "Paste the clipboard as a subtree, with modification of headline level.
6806 The entire subtree is promoted or demoted in order to match a new headline
6807 level. By default, the new level is derived from the visible headings
6808 before and after the insertion point, and taken to be the inferior headline
6809 level of the two. So if the previous visible heading is level 3 and the
6810 next is level 4 (or vice versa), level 4 will be used for insertion.
6811 This makes sure that the subtree remains an independent subtree and does
6812 not swallow low level entries.
6814 You can also force a different level, either by using a numeric prefix
6815 argument, or by inserting the heading marker by hand. For example, if the
6816 cursor is after \"*****\", then the tree will be shifted to level 5.
6818 If you want to insert the tree as is, just use \\[yank].
6820 If optional TREE is given, use this text instead of the kill ring."
6821 (interactive "P")
6822 (unless (org-kill-is-subtree-p tree)
6823 (error "%s"
6824 (substitute-command-keys
6825 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6826 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6827 (^re (concat "^\\(" outline-regexp "\\)"))
6828 (re (concat "\\(" outline-regexp "\\)"))
6829 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6831 (old-level (if (string-match ^re txt)
6832 (- (match-end 0) (match-beginning 0) 1)
6833 -1))
6834 (force-level (cond (level (prefix-numeric-value level))
6835 ((string-match
6836 ^re_ (buffer-substring (point-at-bol) (point)))
6837 (- (match-end 1) (match-beginning 1)))
6838 (t nil)))
6839 (previous-level (save-excursion
6840 (condition-case nil
6841 (progn
6842 (outline-previous-visible-heading 1)
6843 (if (looking-at re)
6844 (- (match-end 0) (match-beginning 0) 1)
6846 (error 1))))
6847 (next-level (save-excursion
6848 (condition-case nil
6849 (progn
6850 (or (looking-at outline-regexp)
6851 (outline-next-visible-heading 1))
6852 (if (looking-at re)
6853 (- (match-end 0) (match-beginning 0) 1)
6855 (error 1))))
6856 (new-level (or force-level (max previous-level next-level)))
6857 (shift (if (or (= old-level -1)
6858 (= new-level -1)
6859 (= old-level new-level))
6861 (- new-level old-level)))
6862 (delta (if (> shift 0) -1 1))
6863 (func (if (> shift 0) 'org-demote 'org-promote))
6864 (org-odd-levels-only nil)
6865 beg end)
6866 ;; Remove the forced level indicator
6867 (if force-level
6868 (delete-region (point-at-bol) (point)))
6869 ;; Paste
6870 (beginning-of-line 1)
6871 (org-back-over-empty-lines) ;; FIXME: correct fix????
6872 (setq beg (point))
6873 (insert-before-markers txt) ;; FIXME: correct fix????
6874 (unless (string-match "\n\\'" txt) (insert "\n"))
6875 (setq end (point))
6876 (goto-char beg)
6877 (skip-chars-forward " \t\n\r")
6878 (setq beg (point))
6879 ;; Shift if necessary
6880 (unless (= shift 0)
6881 (save-restriction
6882 (narrow-to-region beg end)
6883 (while (not (= shift 0))
6884 (org-map-region func (point-min) (point-max))
6885 (setq shift (+ delta shift)))
6886 (goto-char (point-min))))
6887 (when (interactive-p)
6888 (message "Clipboard pasted as level %d subtree" new-level))
6889 (if (and kill-ring
6890 (eq org-subtree-clip (current-kill 0))
6891 org-subtree-clip-folded)
6892 ;; The tree was folded before it was killed/copied
6893 (hide-subtree))))
6895 (defun org-kill-is-subtree-p (&optional txt)
6896 "Check if the current kill is an outline subtree, or a set of trees.
6897 Returns nil if kill does not start with a headline, or if the first
6898 headline level is not the largest headline level in the tree.
6899 So this will actually accept several entries of equal levels as well,
6900 which is OK for `org-paste-subtree'.
6901 If optional TXT is given, check this string instead of the current kill."
6902 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6903 (start-level (and kill
6904 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6905 org-outline-regexp "\\)")
6906 kill)
6907 (- (match-end 2) (match-beginning 2) 1)))
6908 (re (concat "^" org-outline-regexp))
6909 (start (1+ (match-beginning 2))))
6910 (if (not start-level)
6911 (progn
6912 nil) ;; does not even start with a heading
6913 (catch 'exit
6914 (while (setq start (string-match re kill (1+ start)))
6915 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6916 (throw 'exit nil)))
6917 t))))
6919 (defun org-narrow-to-subtree ()
6920 "Narrow buffer to the current subtree."
6921 (interactive)
6922 (save-excursion
6923 (save-match-data
6924 (narrow-to-region
6925 (progn (org-back-to-heading) (point))
6926 (progn (org-end-of-subtree t t) (point))))))
6929 ;;; Outline Sorting
6931 (defun org-sort (with-case)
6932 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6933 Optional argument WITH-CASE means sort case-sensitively."
6934 (interactive "P")
6935 (if (org-at-table-p)
6936 (org-call-with-arg 'org-table-sort-lines with-case)
6937 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6939 (defvar org-priority-regexp) ; defined later in the file
6941 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6942 "Sort entries on a certain level of an outline tree.
6943 If there is an active region, the entries in the region are sorted.
6944 Else, if the cursor is before the first entry, sort the top-level items.
6945 Else, the children of the entry at point are sorted.
6947 Sorting can be alphabetically, numerically, and by date/time as given by
6948 the first time stamp in the entry. The command prompts for the sorting
6949 type unless it has been given to the function through the SORTING-TYPE
6950 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6951 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6952 called with point at the beginning of the record. It must return either
6953 a string or a number that should serve as the sorting key for that record.
6955 Comparing entries ignores case by default. However, with an optional argument
6956 WITH-CASE, the sorting considers case as well."
6957 (interactive "P")
6958 (let ((case-func (if with-case 'identity 'downcase))
6959 start beg end stars re re2
6960 txt what tmp plain-list-p)
6961 ;; Find beginning and end of region to sort
6962 (cond
6963 ((org-region-active-p)
6964 ;; we will sort the region
6965 (setq end (region-end)
6966 what "region")
6967 (goto-char (region-beginning))
6968 (if (not (org-on-heading-p)) (outline-next-heading))
6969 (setq start (point)))
6970 ((org-at-item-p)
6971 ;; we will sort this plain list
6972 (org-beginning-of-item-list) (setq start (point))
6973 (org-end-of-item-list) (setq end (point))
6974 (goto-char start)
6975 (setq plain-list-p t
6976 what "plain list"))
6977 ((or (org-on-heading-p)
6978 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6979 ;; we will sort the children of the current headline
6980 (org-back-to-heading)
6981 (setq start (point)
6982 end (progn (org-end-of-subtree t t)
6983 (org-back-over-empty-lines)
6984 (point))
6985 what "children")
6986 (goto-char start)
6987 (show-subtree)
6988 (outline-next-heading))
6990 ;; we will sort the top-level entries in this file
6991 (goto-char (point-min))
6992 (or (org-on-heading-p) (outline-next-heading))
6993 (setq start (point) end (point-max) what "top-level")
6994 (goto-char start)
6995 (show-all)))
6997 (setq beg (point))
6998 (if (>= beg end) (error "Nothing to sort"))
7000 (unless plain-list-p
7001 (looking-at "\\(\\*+\\)")
7002 (setq stars (match-string 1)
7003 re (concat "^" (regexp-quote stars) " +")
7004 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7005 txt (buffer-substring beg end))
7006 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7007 (if (and (not (equal stars "*")) (string-match re2 txt))
7008 (error "Region to sort contains a level above the first entry")))
7010 (unless sorting-type
7011 (message
7012 (if plain-list-p
7013 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7014 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
7015 what)
7016 (setq sorting-type (read-char-exclusive))
7018 (and (= (downcase sorting-type) ?f)
7019 (setq getkey-func
7020 (completing-read "Sort using function: "
7021 obarray 'fboundp t nil nil))
7022 (setq getkey-func (intern getkey-func)))
7024 (and (= (downcase sorting-type) ?r)
7025 (setq property
7026 (completing-read "Property: "
7027 (mapcar 'list (org-buffer-property-keys t))
7028 nil t))))
7030 (message "Sorting entries...")
7032 (save-restriction
7033 (narrow-to-region start end)
7035 (let ((dcst (downcase sorting-type))
7036 (now (current-time)))
7037 (sort-subr
7038 (/= dcst sorting-type)
7039 ;; This function moves to the beginning character of the "record" to
7040 ;; be sorted.
7041 (if plain-list-p
7042 (lambda nil
7043 (if (org-at-item-p) t (goto-char (point-max))))
7044 (lambda nil
7045 (if (re-search-forward re nil t)
7046 (goto-char (match-beginning 0))
7047 (goto-char (point-max)))))
7048 ;; This function moves to the last character of the "record" being
7049 ;; sorted.
7050 (if plain-list-p
7051 'org-end-of-item
7052 (lambda nil
7053 (save-match-data
7054 (condition-case nil
7055 (outline-forward-same-level 1)
7056 (error
7057 (goto-char (point-max)))))))
7059 ;; This function returns the value that gets sorted against.
7060 (if plain-list-p
7061 (lambda nil
7062 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7063 (cond
7064 ((= dcst ?n)
7065 (string-to-number (buffer-substring (match-end 0)
7066 (point-at-eol))))
7067 ((= dcst ?a)
7068 (buffer-substring (match-end 0) (point-at-eol)))
7069 ((= dcst ?t)
7070 (if (re-search-forward org-ts-regexp
7071 (point-at-eol) t)
7072 (org-time-string-to-time (match-string 0))
7073 now))
7074 ((= dcst ?f)
7075 (if getkey-func
7076 (progn
7077 (setq tmp (funcall getkey-func))
7078 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7079 tmp)
7080 (error "Invalid key function `%s'" getkey-func)))
7081 (t (error "Invalid sorting type `%c'" sorting-type)))))
7082 (lambda nil
7083 (cond
7084 ((= dcst ?n)
7085 (if (looking-at outline-regexp)
7086 (string-to-number (buffer-substring (match-end 0)
7087 (point-at-eol)))
7088 nil))
7089 ((= dcst ?a)
7090 (funcall case-func (buffer-substring (point-at-bol)
7091 (point-at-eol))))
7092 ((= dcst ?t)
7093 (if (re-search-forward org-ts-regexp
7094 (save-excursion
7095 (forward-line 2)
7096 (point)) t)
7097 (org-time-string-to-time (match-string 0))
7098 now))
7099 ((= dcst ?p)
7100 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7101 (string-to-char (match-string 2))
7102 org-default-priority))
7103 ((= dcst ?r)
7104 (or (org-entry-get nil property) ""))
7105 ((= dcst ?f)
7106 (if getkey-func
7107 (progn
7108 (setq tmp (funcall getkey-func))
7109 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7110 tmp)
7111 (error "Invalid key function `%s'" getkey-func)))
7112 (t (error "Invalid sorting type `%c'" sorting-type)))))
7114 (cond
7115 ((= dcst ?a) 'string<)
7116 ((= dcst ?t) 'time-less-p)
7117 (t nil)))))
7118 (message "Sorting entries...done")))
7120 (defun org-do-sort (table what &optional with-case sorting-type)
7121 "Sort TABLE of WHAT according to SORTING-TYPE.
7122 The user will be prompted for the SORTING-TYPE if the call to this
7123 function does not specify it. WHAT is only for the prompt, to indicate
7124 what is being sorted. The sorting key will be extracted from
7125 the car of the elements of the table.
7126 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7127 (unless sorting-type
7128 (message
7129 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7130 what)
7131 (setq sorting-type (read-char-exclusive)))
7132 (let ((dcst (downcase sorting-type))
7133 extractfun comparefun)
7134 ;; Define the appropriate functions
7135 (cond
7136 ((= dcst ?n)
7137 (setq extractfun 'string-to-number
7138 comparefun (if (= dcst sorting-type) '< '>)))
7139 ((= dcst ?a)
7140 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7141 (lambda(x) (downcase (org-sort-remove-invisible x))))
7142 comparefun (if (= dcst sorting-type)
7143 'string<
7144 (lambda (a b) (and (not (string< a b))
7145 (not (string= a b)))))))
7146 ((= dcst ?t)
7147 (setq extractfun
7148 (lambda (x)
7149 (if (string-match org-ts-regexp x)
7150 (time-to-seconds
7151 (org-time-string-to-time (match-string 0 x)))
7153 comparefun (if (= dcst sorting-type) '< '>)))
7154 (t (error "Invalid sorting type `%c'" sorting-type)))
7156 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7157 table)
7158 (lambda (a b) (funcall comparefun (car a) (car b))))))
7160 ;;;; Plain list items, including checkboxes
7162 ;;; Plain list items
7164 (defun org-at-item-p ()
7165 "Is point in a line starting a hand-formatted item?"
7166 (let ((llt org-plain-list-ordered-item-terminator))
7167 (save-excursion
7168 (goto-char (point-at-bol))
7169 (looking-at
7170 (cond
7171 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7172 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7173 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7174 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7176 (defun org-in-item-p ()
7177 "It the cursor inside a plain list item.
7178 Does not have to be the first line."
7179 (save-excursion
7180 (condition-case nil
7181 (progn
7182 (org-beginning-of-item)
7183 (org-at-item-p)
7185 (error nil))))
7187 (defun org-insert-item (&optional checkbox)
7188 "Insert a new item at the current level.
7189 Return t when things worked, nil when we are not in an item."
7190 (when (save-excursion
7191 (condition-case nil
7192 (progn
7193 (org-beginning-of-item)
7194 (org-at-item-p)
7195 (if (org-invisible-p) (error "Invisible item"))
7197 (error nil)))
7198 (let* ((bul (match-string 0))
7199 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7200 (match-end 0)))
7201 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7202 pos)
7203 (cond
7204 ((and (org-at-item-p) (<= (point) eow))
7205 ;; before the bullet
7206 (beginning-of-line 1)
7207 (open-line (if blank 2 1)))
7208 ((<= (point) eow)
7209 (beginning-of-line 1))
7211 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7212 (end-of-line 1)
7213 (delete-horizontal-space))
7214 (newline (if blank 2 1))))
7215 (insert bul (if checkbox "[ ]" ""))
7216 (just-one-space)
7217 (setq pos (point))
7218 (end-of-line 1)
7219 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7220 (org-maybe-renumber-ordered-list)
7221 (and checkbox (org-update-checkbox-count-maybe))
7224 ;;; Checkboxes
7226 (defun org-at-item-checkbox-p ()
7227 "Is point at a line starting a plain-list item with a checklet?"
7228 (and (org-at-item-p)
7229 (save-excursion
7230 (goto-char (match-end 0))
7231 (skip-chars-forward " \t")
7232 (looking-at "\\[[- X]\\]"))))
7234 (defun org-toggle-checkbox (&optional arg)
7235 "Toggle the checkbox in the current line."
7236 (interactive "P")
7237 (catch 'exit
7238 (let (beg end status (firstnew 'unknown))
7239 (cond
7240 ((org-region-active-p)
7241 (setq beg (region-beginning) end (region-end)))
7242 ((org-on-heading-p)
7243 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7244 ((org-at-item-checkbox-p)
7245 (let ((pos (point)))
7246 (replace-match
7247 (cond (arg "[-]")
7248 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7249 (t "[ ]"))
7250 t t)
7251 (goto-char pos))
7252 (throw 'exit t))
7253 (t (error "Not at a checkbox or heading, and no active region")))
7254 (save-excursion
7255 (goto-char beg)
7256 (while (< (point) end)
7257 (when (org-at-item-checkbox-p)
7258 (setq status (equal (match-string 0) "[X]"))
7259 (when (eq firstnew 'unknown)
7260 (setq firstnew (not status)))
7261 (replace-match
7262 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7263 (beginning-of-line 2)))))
7264 (org-update-checkbox-count-maybe))
7266 (defun org-update-checkbox-count-maybe ()
7267 "Update checkbox statistics unless turned off by user."
7268 (when org-provide-checkbox-statistics
7269 (org-update-checkbox-count)))
7271 (defun org-update-checkbox-count (&optional all)
7272 "Update the checkbox statistics in the current section.
7273 This will find all statistic cookies like [57%] and [6/12] and update them
7274 with the current numbers. With optional prefix argument ALL, do this for
7275 the whole buffer."
7276 (interactive "P")
7277 (save-excursion
7278 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7279 (beg (condition-case nil
7280 (progn (outline-back-to-heading) (point))
7281 (error (point-min))))
7282 (end (move-marker (make-marker)
7283 (progn (outline-next-heading) (point))))
7284 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7285 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7286 (re-find (concat re "\\|" re-box))
7287 beg-cookie end-cookie is-percent c-on c-off lim
7288 eline curr-ind next-ind continue-from startsearch
7289 (cstat 0)
7291 (when all
7292 (goto-char (point-min))
7293 (outline-next-heading)
7294 (setq beg (point) end (point-max)))
7295 (goto-char end)
7296 ;; find each statistic cookie
7297 (while (re-search-backward re-find beg t)
7298 (setq beg-cookie (match-beginning 1)
7299 end-cookie (match-end 1)
7300 cstat (+ cstat (if end-cookie 1 0))
7301 startsearch (point-at-eol)
7302 continue-from (point-at-bol)
7303 is-percent (match-beginning 2)
7304 lim (cond
7305 ((org-on-heading-p) (outline-next-heading) (point))
7306 ((org-at-item-p) (org-end-of-item) (point))
7307 (t nil))
7308 c-on 0
7309 c-off 0)
7310 (when lim
7311 ;; find first checkbox for this cookie and gather
7312 ;; statistics from all that are at this indentation level
7313 (goto-char startsearch)
7314 (if (re-search-forward re-box lim t)
7315 (progn
7316 (org-beginning-of-item)
7317 (setq curr-ind (org-get-indentation))
7318 (setq next-ind curr-ind)
7319 (while (= curr-ind next-ind)
7320 (save-excursion (end-of-line) (setq eline (point)))
7321 (if (re-search-forward re-box eline t)
7322 (if (member (match-string 2) '("[ ]" "[-]"))
7323 (setq c-off (1+ c-off))
7324 (setq c-on (1+ c-on))
7327 (org-end-of-item)
7328 (setq next-ind (org-get-indentation))
7330 (goto-char continue-from)
7331 ;; update cookie
7332 (when end-cookie
7333 (delete-region beg-cookie end-cookie)
7334 (goto-char beg-cookie)
7335 (insert
7336 (if is-percent
7337 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7338 (format "[%d/%d]" c-on (+ c-on c-off)))))
7339 ;; update items checkbox if it has one
7340 (when (org-at-item-p)
7341 (org-beginning-of-item)
7342 (when (and (> (+ c-on c-off) 0)
7343 (re-search-forward re-box (point-at-eol) t))
7344 (setq beg-cookie (match-beginning 2)
7345 end-cookie (match-end 2))
7346 (delete-region beg-cookie end-cookie)
7347 (goto-char beg-cookie)
7348 (cond ((= c-off 0) (insert "[X]"))
7349 ((= c-on 0) (insert "[ ]"))
7350 (t (insert "[-]")))
7352 (goto-char continue-from))
7353 (when (interactive-p)
7354 (message "Checkbox satistics updated %s (%d places)"
7355 (if all "in entire file" "in current outline entry") cstat)))))
7357 (defun org-get-checkbox-statistics-face ()
7358 "Select the face for checkbox statistics.
7359 The face will be `org-done' when all relevant boxes are checked. Otherwise
7360 it will be `org-todo'."
7361 (if (match-end 1)
7362 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7363 (if (and (> (match-end 2) (match-beginning 2))
7364 (equal (match-string 2) (match-string 3)))
7365 'org-done
7366 'org-todo)))
7368 (defun org-get-indentation (&optional line)
7369 "Get the indentation of the current line, interpreting tabs.
7370 When LINE is given, assume it represents a line and compute its indentation."
7371 (if line
7372 (if (string-match "^ *" (org-remove-tabs line))
7373 (match-end 0))
7374 (save-excursion
7375 (beginning-of-line 1)
7376 (skip-chars-forward " \t")
7377 (current-column))))
7379 (defun org-remove-tabs (s &optional width)
7380 "Replace tabulators in S with spaces.
7381 Assumes that s is a single line, starting in column 0."
7382 (setq width (or width tab-width))
7383 (while (string-match "\t" s)
7384 (setq s (replace-match
7385 (make-string
7386 (- (* width (/ (+ (match-beginning 0) width) width))
7387 (match-beginning 0)) ?\ )
7388 t t s)))
7391 (defun org-fix-indentation (line ind)
7392 "Fix indentation in LINE.
7393 IND is a cons cell with target and minimum indentation.
7394 If the current indenation in LINE is smaller than the minimum,
7395 leave it alone. If it is larger than ind, set it to the target."
7396 (let* ((l (org-remove-tabs line))
7397 (i (org-get-indentation l))
7398 (i1 (car ind)) (i2 (cdr ind)))
7399 (if (>= i i2) (setq l (substring line i2)))
7400 (if (> i1 0)
7401 (concat (make-string i1 ?\ ) l)
7402 l)))
7404 (defcustom org-empty-line-terminates-plain-lists nil
7405 "Non-nil means, an empty line ends all plain list levels.
7406 When nil, empty lines are part of the preceeding item."
7407 :group 'org-plain-lists
7408 :type 'boolean)
7410 (defun org-beginning-of-item ()
7411 "Go to the beginning of the current hand-formatted item.
7412 If the cursor is not in an item, throw an error."
7413 (interactive)
7414 (let ((pos (point))
7415 (limit (save-excursion
7416 (condition-case nil
7417 (progn
7418 (org-back-to-heading)
7419 (beginning-of-line 2) (point))
7420 (error (point-min)))))
7421 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7422 ind ind1)
7423 (if (org-at-item-p)
7424 (beginning-of-line 1)
7425 (beginning-of-line 1)
7426 (skip-chars-forward " \t")
7427 (setq ind (current-column))
7428 (if (catch 'exit
7429 (while t
7430 (beginning-of-line 0)
7431 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7433 (if (looking-at "[ \t]*$")
7434 (setq ind1 ind-empty)
7435 (skip-chars-forward " \t")
7436 (setq ind1 (current-column)))
7437 (if (< ind1 ind)
7438 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7440 (goto-char pos)
7441 (error "Not in an item")))))
7443 (defun org-end-of-item ()
7444 "Go to the end of the current hand-formatted item.
7445 If the cursor is not in an item, throw an error."
7446 (interactive)
7447 (let* ((pos (point))
7448 ind1
7449 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7450 (limit (save-excursion (outline-next-heading) (point)))
7451 (ind (save-excursion
7452 (org-beginning-of-item)
7453 (skip-chars-forward " \t")
7454 (current-column)))
7455 (end (catch 'exit
7456 (while t
7457 (beginning-of-line 2)
7458 (if (eobp) (throw 'exit (point)))
7459 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7460 (if (looking-at "[ \t]*$")
7461 (setq ind1 ind-empty)
7462 (skip-chars-forward " \t")
7463 (setq ind1 (current-column)))
7464 (if (<= ind1 ind)
7465 (throw 'exit (point-at-bol)))))))
7466 (if end
7467 (goto-char end)
7468 (goto-char pos)
7469 (error "Not in an item"))))
7471 (defun org-next-item ()
7472 "Move to the beginning of the next item in the current plain list.
7473 Error if not at a plain list, or if this is the last item in the list."
7474 (interactive)
7475 (let (ind ind1 (pos (point)))
7476 (org-beginning-of-item)
7477 (setq ind (org-get-indentation))
7478 (org-end-of-item)
7479 (setq ind1 (org-get-indentation))
7480 (unless (and (org-at-item-p) (= ind ind1))
7481 (goto-char pos)
7482 (error "On last item"))))
7484 (defun org-previous-item ()
7485 "Move to the beginning of the previous item in the current plain list.
7486 Error if not at a plain list, or if this is the first item in the list."
7487 (interactive)
7488 (let (beg ind ind1 (pos (point)))
7489 (org-beginning-of-item)
7490 (setq beg (point))
7491 (setq ind (org-get-indentation))
7492 (goto-char beg)
7493 (catch 'exit
7494 (while t
7495 (beginning-of-line 0)
7496 (if (looking-at "[ \t]*$")
7498 (if (<= (setq ind1 (org-get-indentation)) ind)
7499 (throw 'exit t)))))
7500 (condition-case nil
7501 (if (or (not (org-at-item-p))
7502 (< ind1 (1- ind)))
7503 (error "")
7504 (org-beginning-of-item))
7505 (error (goto-char pos)
7506 (error "On first item")))))
7508 (defun org-first-list-item-p ()
7509 "Is this heading the item in a plain list?"
7510 (unless (org-at-item-p)
7511 (error "Not at a plain list item"))
7512 (org-beginning-of-item)
7513 (= (point) (save-excursion (org-beginning-of-item-list))))
7515 (defun org-move-item-down ()
7516 "Move the plain list item at point down, i.e. swap with following item.
7517 Subitems (items with larger indentation) are considered part of the item,
7518 so this really moves item trees."
7519 (interactive)
7520 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7521 (org-beginning-of-item)
7522 (setq beg0 (point))
7523 (save-excursion
7524 (setq ne-beg (org-back-over-empty-lines))
7525 (setq beg (point)))
7526 (goto-char beg0)
7527 (setq ind (org-get-indentation))
7528 (org-end-of-item)
7529 (setq end0 (point))
7530 (setq ind1 (org-get-indentation))
7531 (setq ne-end (org-back-over-empty-lines))
7532 (setq end (point))
7533 (goto-char beg0)
7534 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7535 ;; include less whitespace
7536 (save-excursion
7537 (goto-char beg)
7538 (forward-line (- ne-beg ne-end))
7539 (setq beg (point))))
7540 (goto-char end0)
7541 (if (and (org-at-item-p) (= ind ind1))
7542 (progn
7543 (org-end-of-item)
7544 (org-back-over-empty-lines)
7545 (setq txt (buffer-substring beg end))
7546 (save-excursion
7547 (delete-region beg end))
7548 (setq pos (point))
7549 (insert txt)
7550 (goto-char pos) (org-skip-whitespace)
7551 (org-maybe-renumber-ordered-list))
7552 (goto-char pos)
7553 (error "Cannot move this item further down"))))
7555 (defun org-move-item-up (arg)
7556 "Move the plain list item at point up, i.e. swap with previous item.
7557 Subitems (items with larger indentation) are considered part of the item,
7558 so this really moves item trees."
7559 (interactive "p")
7560 (let (beg beg0 end ind ind1 (pos (point)) txt
7561 ne-beg ne-ins ins-end)
7562 (org-beginning-of-item)
7563 (setq beg0 (point))
7564 (setq ind (org-get-indentation))
7565 (save-excursion
7566 (setq ne-beg (org-back-over-empty-lines))
7567 (setq beg (point)))
7568 (goto-char beg0)
7569 (org-end-of-item)
7570 (setq end (point))
7571 (goto-char beg0)
7572 (catch 'exit
7573 (while t
7574 (beginning-of-line 0)
7575 (if (looking-at "[ \t]*$")
7576 (if org-empty-line-terminates-plain-lists
7577 (progn
7578 (goto-char pos)
7579 (error "Cannot move this item further up"))
7580 nil)
7581 (if (<= (setq ind1 (org-get-indentation)) ind)
7582 (throw 'exit t)))))
7583 (condition-case nil
7584 (org-beginning-of-item)
7585 (error (goto-char beg)
7586 (error "Cannot move this item further up")))
7587 (setq ind1 (org-get-indentation))
7588 (if (and (org-at-item-p) (= ind ind1))
7589 (progn
7590 (setq ne-ins (org-back-over-empty-lines))
7591 (setq txt (buffer-substring beg end))
7592 (save-excursion
7593 (delete-region beg end))
7594 (setq pos (point))
7595 (insert txt)
7596 (setq ins-end (point))
7597 (goto-char pos) (org-skip-whitespace)
7599 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7600 ;; Move whitespace back to beginning
7601 (save-excursion
7602 (goto-char ins-end)
7603 (let ((kill-whole-line t))
7604 (kill-line (- ne-ins ne-beg)) (point)))
7605 (insert (make-string (- ne-ins ne-beg) ?\n)))
7607 (org-maybe-renumber-ordered-list))
7608 (goto-char pos)
7609 (error "Cannot move this item further up"))))
7611 (defun org-maybe-renumber-ordered-list ()
7612 "Renumber the ordered list at point if setup allows it.
7613 This tests the user option `org-auto-renumber-ordered-lists' before
7614 doing the renumbering."
7615 (interactive)
7616 (when (and org-auto-renumber-ordered-lists
7617 (org-at-item-p))
7618 (if (match-beginning 3)
7619 (org-renumber-ordered-list 1)
7620 (org-fix-bullet-type))))
7622 (defun org-maybe-renumber-ordered-list-safe ()
7623 (condition-case nil
7624 (save-excursion
7625 (org-maybe-renumber-ordered-list))
7626 (error nil)))
7628 (defun org-cycle-list-bullet (&optional which)
7629 "Cycle through the different itemize/enumerate bullets.
7630 This cycle the entire list level through the sequence:
7632 `-' -> `+' -> `*' -> `1.' -> `1)'
7634 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7635 0 meand `-', 1 means `+' etc."
7636 (interactive "P")
7637 (org-preserve-lc
7638 (org-beginning-of-item-list)
7639 (org-at-item-p)
7640 (beginning-of-line 1)
7641 (let ((current (match-string 0))
7642 (prevp (eq which 'previous))
7643 new)
7644 (setq new (cond
7645 ((and (numberp which)
7646 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7647 ((string-match "-" current) (if prevp "1)" "+"))
7648 ((string-match "\\+" current)
7649 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7650 ((string-match "\\*" current) (if prevp "+" "1."))
7651 ((string-match "\\." current) (if prevp "*" "1)"))
7652 ((string-match ")" current) (if prevp "1." "-"))
7653 (t (error "This should not happen"))))
7654 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7655 (org-fix-bullet-type)
7656 (org-maybe-renumber-ordered-list))))
7658 (defun org-get-string-indentation (s)
7659 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7660 (let ((n -1) (i 0) (w tab-width) c)
7661 (catch 'exit
7662 (while (< (setq n (1+ n)) (length s))
7663 (setq c (aref s n))
7664 (cond ((= c ?\ ) (setq i (1+ i)))
7665 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7666 (t (throw 'exit t)))))
7669 (defun org-renumber-ordered-list (arg)
7670 "Renumber an ordered plain list.
7671 Cursor needs to be in the first line of an item, the line that starts
7672 with something like \"1.\" or \"2)\"."
7673 (interactive "p")
7674 (unless (and (org-at-item-p)
7675 (match-beginning 3))
7676 (error "This is not an ordered list"))
7677 (let ((line (org-current-line))
7678 (col (current-column))
7679 (ind (org-get-string-indentation
7680 (buffer-substring (point-at-bol) (match-beginning 3))))
7681 ;; (term (substring (match-string 3) -1))
7682 ind1 (n (1- arg))
7683 fmt)
7684 ;; find where this list begins
7685 (org-beginning-of-item-list)
7686 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7687 (setq fmt (concat "%d" (match-string 1)))
7688 (beginning-of-line 0)
7689 ;; walk forward and replace these numbers
7690 (catch 'exit
7691 (while t
7692 (catch 'next
7693 (beginning-of-line 2)
7694 (if (eobp) (throw 'exit nil))
7695 (if (looking-at "[ \t]*$") (throw 'next nil))
7696 (skip-chars-forward " \t") (setq ind1 (current-column))
7697 (if (> ind1 ind) (throw 'next t))
7698 (if (< ind1 ind) (throw 'exit t))
7699 (if (not (org-at-item-p)) (throw 'exit nil))
7700 (delete-region (match-beginning 2) (match-end 2))
7701 (goto-char (match-beginning 2))
7702 (insert (format fmt (setq n (1+ n)))))))
7703 (goto-line line)
7704 (move-to-column col)))
7706 (defun org-fix-bullet-type ()
7707 "Make sure all items in this list have the same bullet as the firsst item."
7708 (interactive)
7709 (unless (org-at-item-p) (error "This is not a list"))
7710 (let ((line (org-current-line))
7711 (col (current-column))
7712 (ind (current-indentation))
7713 ind1 bullet)
7714 ;; find where this list begins
7715 (org-beginning-of-item-list)
7716 (beginning-of-line 1)
7717 ;; find out what the bullet type is
7718 (looking-at "[ \t]*\\(\\S-+\\)")
7719 (setq bullet (match-string 1))
7720 ;; walk forward and replace these numbers
7721 (beginning-of-line 0)
7722 (catch 'exit
7723 (while t
7724 (catch 'next
7725 (beginning-of-line 2)
7726 (if (eobp) (throw 'exit nil))
7727 (if (looking-at "[ \t]*$") (throw 'next nil))
7728 (skip-chars-forward " \t") (setq ind1 (current-column))
7729 (if (> ind1 ind) (throw 'next t))
7730 (if (< ind1 ind) (throw 'exit t))
7731 (if (not (org-at-item-p)) (throw 'exit nil))
7732 (skip-chars-forward " \t")
7733 (looking-at "\\S-+")
7734 (replace-match bullet))))
7735 (goto-line line)
7736 (move-to-column col)
7737 (if (string-match "[0-9]" bullet)
7738 (org-renumber-ordered-list 1))))
7740 (defun org-beginning-of-item-list ()
7741 "Go to the beginning of the current item list.
7742 I.e. to the first item in this list."
7743 (interactive)
7744 (org-beginning-of-item)
7745 (let ((pos (point-at-bol))
7746 (ind (org-get-indentation))
7747 ind1)
7748 ;; find where this list begins
7749 (catch 'exit
7750 (while t
7751 (catch 'next
7752 (beginning-of-line 0)
7753 (if (looking-at "[ \t]*$")
7754 (throw (if (bobp) 'exit 'next) t))
7755 (skip-chars-forward " \t") (setq ind1 (current-column))
7756 (if (or (< ind1 ind)
7757 (and (= ind1 ind)
7758 (not (org-at-item-p)))
7759 (bobp))
7760 (throw 'exit t)
7761 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7762 (goto-char pos)))
7765 (defun org-end-of-item-list ()
7766 "Go to the end of the current item list.
7767 I.e. to the text after the last item."
7768 (interactive)
7769 (org-beginning-of-item)
7770 (let ((pos (point-at-bol))
7771 (ind (org-get-indentation))
7772 ind1)
7773 ;; find where this list begins
7774 (catch 'exit
7775 (while t
7776 (catch 'next
7777 (beginning-of-line 2)
7778 (if (looking-at "[ \t]*$")
7779 (throw (if (eobp) 'exit 'next) t))
7780 (skip-chars-forward " \t") (setq ind1 (current-column))
7781 (if (or (< ind1 ind)
7782 (and (= ind1 ind)
7783 (not (org-at-item-p)))
7784 (eobp))
7785 (progn
7786 (setq pos (point-at-bol))
7787 (throw 'exit t))))))
7788 (goto-char pos)))
7791 (defvar org-last-indent-begin-marker (make-marker))
7792 (defvar org-last-indent-end-marker (make-marker))
7794 (defun org-outdent-item (arg)
7795 "Outdent a local list item."
7796 (interactive "p")
7797 (org-indent-item (- arg)))
7799 (defun org-indent-item (arg)
7800 "Indent a local list item."
7801 (interactive "p")
7802 (unless (org-at-item-p)
7803 (error "Not on an item"))
7804 (save-excursion
7805 (let (beg end ind ind1 tmp delta ind-down ind-up)
7806 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7807 (setq beg org-last-indent-begin-marker
7808 end org-last-indent-end-marker)
7809 (org-beginning-of-item)
7810 (setq beg (move-marker org-last-indent-begin-marker (point)))
7811 (org-end-of-item)
7812 (setq end (move-marker org-last-indent-end-marker (point))))
7813 (goto-char beg)
7814 (setq tmp (org-item-indent-positions)
7815 ind (car tmp)
7816 ind-down (nth 2 tmp)
7817 ind-up (nth 1 tmp)
7818 delta (if (> arg 0)
7819 (if ind-down (- ind-down ind) 2)
7820 (if ind-up (- ind-up ind) -2)))
7821 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7822 (while (< (point) end)
7823 (beginning-of-line 1)
7824 (skip-chars-forward " \t") (setq ind1 (current-column))
7825 (delete-region (point-at-bol) (point))
7826 (or (eolp) (indent-to-column (+ ind1 delta)))
7827 (beginning-of-line 2))))
7828 (org-fix-bullet-type)
7829 (org-maybe-renumber-ordered-list-safe)
7830 (save-excursion
7831 (beginning-of-line 0)
7832 (condition-case nil (org-beginning-of-item) (error nil))
7833 (org-maybe-renumber-ordered-list-safe)))
7835 (defun org-item-indent-positions ()
7836 "Return indentation for plain list items.
7837 This returns a list with three values: The current indentation, the
7838 parent indentation and the indentation a child should habe.
7839 Assumes cursor in item line."
7840 (let* ((bolpos (point-at-bol))
7841 (ind (org-get-indentation))
7842 ind-down ind-up pos)
7843 (save-excursion
7844 (org-beginning-of-item-list)
7845 (skip-chars-backward "\n\r \t")
7846 (when (org-in-item-p)
7847 (org-beginning-of-item)
7848 (setq ind-up (org-get-indentation))))
7849 (setq pos (point))
7850 (save-excursion
7851 (cond
7852 ((and (condition-case nil (progn (org-previous-item) t)
7853 (error nil))
7854 (or (forward-char 1) t)
7855 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7856 (setq ind-down (org-get-indentation)))
7857 ((and (goto-char pos)
7858 (org-at-item-p))
7859 (goto-char (match-end 0))
7860 (skip-chars-forward " \t")
7861 (setq ind-down (current-column)))))
7862 (list ind ind-up ind-down)))
7864 ;;; The orgstruct minor mode
7866 ;; Define a minor mode which can be used in other modes in order to
7867 ;; integrate the org-mode structure editing commands.
7869 ;; This is really a hack, because the org-mode structure commands use
7870 ;; keys which normally belong to the major mode. Here is how it
7871 ;; works: The minor mode defines all the keys necessary to operate the
7872 ;; structure commands, but wraps the commands into a function which
7873 ;; tests if the cursor is currently at a headline or a plain list
7874 ;; item. If that is the case, the structure command is used,
7875 ;; temporarily setting many Org-mode variables like regular
7876 ;; expressions for filling etc. However, when any of those keys is
7877 ;; used at a different location, function uses `key-binding' to look
7878 ;; up if the key has an associated command in another currently active
7879 ;; keymap (minor modes, major mode, global), and executes that
7880 ;; command. There might be problems if any of the keys is otherwise
7881 ;; used as a prefix key.
7883 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7884 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7885 ;; addresses this by checking explicitly for both bindings.
7887 (defvar orgstruct-mode-map (make-sparse-keymap)
7888 "Keymap for the minor `orgstruct-mode'.")
7890 (defvar org-local-vars nil
7891 "List of local variables, for use by `orgstruct-mode'")
7893 ;;;###autoload
7894 (define-minor-mode orgstruct-mode
7895 "Toggle the minor more `orgstruct-mode'.
7896 This mode is for using Org-mode structure commands in other modes.
7897 The following key behave as if Org-mode was active, if the cursor
7898 is on a headline, or on a plain list item (both in the definition
7899 of Org-mode).
7901 M-up Move entry/item up
7902 M-down Move entry/item down
7903 M-left Promote
7904 M-right Demote
7905 M-S-up Move entry/item up
7906 M-S-down Move entry/item down
7907 M-S-left Promote subtree
7908 M-S-right Demote subtree
7909 M-q Fill paragraph and items like in Org-mode
7910 C-c ^ Sort entries
7911 C-c - Cycle list bullet
7912 TAB Cycle item visibility
7913 M-RET Insert new heading/item
7914 S-M-RET Insert new TODO heading / Chekbox item
7915 C-c C-c Set tags / toggle checkbox"
7916 nil " OrgStruct" nil
7917 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7919 ;;;###autoload
7920 (defun turn-on-orgstruct ()
7921 "Unconditionally turn on `orgstruct-mode'."
7922 (orgstruct-mode 1))
7924 ;;;###autoload
7925 (defun turn-on-orgstruct++ ()
7926 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7927 In addition to setting orgstruct-mode, this also exports all indentation and
7928 autofilling variables from org-mode into the buffer. Note that turning
7929 off orgstruct-mode will *not* remove these additional settings."
7930 (orgstruct-mode 1)
7931 (let (var val)
7932 (mapc
7933 (lambda (x)
7934 (when (string-match
7935 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7936 (symbol-name (car x)))
7937 (setq var (car x) val (nth 1 x))
7938 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7939 org-local-vars)))
7941 (defun orgstruct-error ()
7942 "Error when there is no default binding for a structure key."
7943 (interactive)
7944 (error "This key has no function outside structure elements"))
7946 (defun orgstruct-setup ()
7947 "Setup orgstruct keymaps."
7948 (let ((nfunc 0)
7949 (bindings
7950 (list
7951 '([(meta up)] org-metaup)
7952 '([(meta down)] org-metadown)
7953 '([(meta left)] org-metaleft)
7954 '([(meta right)] org-metaright)
7955 '([(meta shift up)] org-shiftmetaup)
7956 '([(meta shift down)] org-shiftmetadown)
7957 '([(meta shift left)] org-shiftmetaleft)
7958 '([(meta shift right)] org-shiftmetaright)
7959 '([(shift up)] org-shiftup)
7960 '([(shift down)] org-shiftdown)
7961 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7962 '("\M-q" fill-paragraph)
7963 '("\C-c^" org-sort)
7964 '("\C-c-" org-cycle-list-bullet)))
7965 elt key fun cmd)
7966 (while (setq elt (pop bindings))
7967 (setq nfunc (1+ nfunc))
7968 (setq key (org-key (car elt))
7969 fun (nth 1 elt)
7970 cmd (orgstruct-make-binding fun nfunc key))
7971 (org-defkey orgstruct-mode-map key cmd))
7973 ;; Special treatment needed for TAB and RET
7974 (org-defkey orgstruct-mode-map [(tab)]
7975 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7976 (org-defkey orgstruct-mode-map "\C-i"
7977 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7979 (org-defkey orgstruct-mode-map "\M-\C-m"
7980 (orgstruct-make-binding 'org-insert-heading 105
7981 "\M-\C-m" [(meta return)]))
7982 (org-defkey orgstruct-mode-map [(meta return)]
7983 (orgstruct-make-binding 'org-insert-heading 106
7984 [(meta return)] "\M-\C-m"))
7986 (org-defkey orgstruct-mode-map [(shift meta return)]
7987 (orgstruct-make-binding 'org-insert-todo-heading 107
7988 [(meta return)] "\M-\C-m"))
7990 (unless org-local-vars
7991 (setq org-local-vars (org-get-local-variables)))
7995 (defun orgstruct-make-binding (fun n &rest keys)
7996 "Create a function for binding in the structure minor mode.
7997 FUN is the command to call inside a table. N is used to create a unique
7998 command name. KEYS are keys that should be checked in for a command
7999 to execute outside of tables."
8000 (eval
8001 (list 'defun
8002 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8003 '(arg)
8004 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8005 "Outside of structure, run the binding of `"
8006 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8007 "'.")
8008 '(interactive "p")
8009 (list 'if
8010 '(org-context-p 'headline 'item)
8011 (list 'org-run-like-in-org-mode (list 'quote fun))
8012 (list 'let '(orgstruct-mode)
8013 (list 'call-interactively
8014 (append '(or)
8015 (mapcar (lambda (k)
8016 (list 'key-binding k))
8017 keys)
8018 '('orgstruct-error))))))))
8020 (defun org-context-p (&rest contexts)
8021 "Check if local context is and of CONTEXTS.
8022 Possible values in the list of contexts are `table', `headline', and `item'."
8023 (let ((pos (point)))
8024 (goto-char (point-at-bol))
8025 (prog1 (or (and (memq 'table contexts)
8026 (looking-at "[ \t]*|"))
8027 (and (memq 'headline contexts)
8028 (looking-at "\\*+"))
8029 (and (memq 'item contexts)
8030 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
8031 (goto-char pos))))
8033 (defun org-get-local-variables ()
8034 "Return a list of all local variables in an org-mode buffer."
8035 (let (varlist)
8036 (with-current-buffer (get-buffer-create "*Org tmp*")
8037 (erase-buffer)
8038 (org-mode)
8039 (setq varlist (buffer-local-variables)))
8040 (kill-buffer "*Org tmp*")
8041 (delq nil
8042 (mapcar
8043 (lambda (x)
8044 (setq x
8045 (if (symbolp x)
8046 (list x)
8047 (list (car x) (list 'quote (cdr x)))))
8048 (if (string-match
8049 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8050 (symbol-name (car x)))
8051 x nil))
8052 varlist))))
8054 ;;;###autoload
8055 (defun org-run-like-in-org-mode (cmd)
8056 (unless org-local-vars
8057 (setq org-local-vars (org-get-local-variables)))
8058 (eval (list 'let org-local-vars
8059 (list 'call-interactively (list 'quote cmd)))))
8061 ;;;; Archiving
8063 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
8065 (defun org-archive-subtree (&optional find-done)
8066 "Move the current subtree to the archive.
8067 The archive can be a certain top-level heading in the current file, or in
8068 a different file. The tree will be moved to that location, the subtree
8069 heading be marked DONE, and the current time will be added.
8071 When called with prefix argument FIND-DONE, find whole trees without any
8072 open TODO items and archive them (after getting confirmation from the user).
8073 If the cursor is not at a headline when this comand is called, try all level
8074 1 trees. If the cursor is on a headline, only try the direct children of
8075 this heading."
8076 (interactive "P")
8077 (if find-done
8078 (org-archive-all-done)
8079 ;; Save all relevant TODO keyword-relatex variables
8081 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
8082 (tr-org-todo-keywords-1 org-todo-keywords-1)
8083 (tr-org-todo-kwd-alist org-todo-kwd-alist)
8084 (tr-org-done-keywords org-done-keywords)
8085 (tr-org-todo-regexp org-todo-regexp)
8086 (tr-org-todo-line-regexp org-todo-line-regexp)
8087 (tr-org-odd-levels-only org-odd-levels-only)
8088 (this-buffer (current-buffer))
8089 (org-archive-location org-archive-location)
8090 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
8091 ;; start of variables that will be used for saving context
8092 ;; The compiler complains about them - keep them anyway!
8093 (file (abbreviate-file-name (buffer-file-name)))
8094 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
8095 (time (format-time-string
8096 (substring (cdr org-time-stamp-formats) 1 -1)
8097 (current-time)))
8098 afile heading buffer level newfile-p
8099 category todo priority
8100 ;; start of variables that will be used for savind context
8101 ltags itags prop)
8103 ;; Try to find a local archive location
8104 (save-excursion
8105 (save-restriction
8106 (widen)
8107 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
8108 (if (and prop (string-match "\\S-" prop))
8109 (setq org-archive-location prop)
8110 (if (or (re-search-backward re nil t)
8111 (re-search-forward re nil t))
8112 (setq org-archive-location (match-string 1))))))
8114 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
8115 (progn
8116 (setq afile (format (match-string 1 org-archive-location)
8117 (file-name-nondirectory buffer-file-name))
8118 heading (match-string 2 org-archive-location)))
8119 (error "Invalid `org-archive-location'"))
8120 (if (> (length afile) 0)
8121 (setq newfile-p (not (file-exists-p afile))
8122 buffer (find-file-noselect afile))
8123 (setq buffer (current-buffer)))
8124 (unless buffer
8125 (error "Cannot access file \"%s\"" afile))
8126 (if (and (> (length heading) 0)
8127 (string-match "^\\*+" heading))
8128 (setq level (match-end 0))
8129 (setq heading nil level 0))
8130 (save-excursion
8131 (org-back-to-heading t)
8132 ;; Get context information that will be lost by moving the tree
8133 (org-refresh-category-properties)
8134 (setq category (org-get-category)
8135 todo (and (looking-at org-todo-line-regexp)
8136 (match-string 2))
8137 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
8138 ltags (org-get-tags)
8139 itags (org-delete-all ltags (org-get-tags-at)))
8140 (setq ltags (mapconcat 'identity ltags " ")
8141 itags (mapconcat 'identity itags " "))
8142 ;; We first only copy, in case something goes wrong
8143 ;; we need to protect this-command, to avoid kill-region sets it,
8144 ;; which would lead to duplication of subtrees
8145 (let (this-command) (org-copy-subtree))
8146 (set-buffer buffer)
8147 ;; Enforce org-mode for the archive buffer
8148 (if (not (org-mode-p))
8149 ;; Force the mode for future visits.
8150 (let ((org-insert-mode-line-in-empty-file t)
8151 (org-inhibit-startup t))
8152 (call-interactively 'org-mode)))
8153 (when newfile-p
8154 (goto-char (point-max))
8155 (insert (format "\nArchived entries from file %s\n\n"
8156 (buffer-file-name this-buffer))))
8157 ;; Force the TODO keywords of the original buffer
8158 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
8159 (org-todo-keywords-1 tr-org-todo-keywords-1)
8160 (org-todo-kwd-alist tr-org-todo-kwd-alist)
8161 (org-done-keywords tr-org-done-keywords)
8162 (org-todo-regexp tr-org-todo-regexp)
8163 (org-todo-line-regexp tr-org-todo-line-regexp)
8164 (org-odd-levels-only
8165 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8166 org-odd-levels-only
8167 tr-org-odd-levels-only)))
8168 (goto-char (point-min))
8169 (show-all)
8170 (if heading
8171 (progn
8172 (if (re-search-forward
8173 (concat "^" (regexp-quote heading)
8174 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8175 nil t)
8176 (goto-char (match-end 0))
8177 ;; Heading not found, just insert it at the end
8178 (goto-char (point-max))
8179 (or (bolp) (insert "\n"))
8180 (insert "\n" heading "\n")
8181 (end-of-line 0))
8182 ;; Make the subtree visible
8183 (show-subtree)
8184 (org-end-of-subtree t)
8185 (skip-chars-backward " \t\r\n")
8186 (and (looking-at "[ \t\r\n]*")
8187 (replace-match "\n\n")))
8188 ;; No specific heading, just go to end of file.
8189 (goto-char (point-max)) (insert "\n"))
8190 ;; Paste
8191 (org-paste-subtree (org-get-valid-level level 1))
8193 ;; Mark the entry as done
8194 (when (and org-archive-mark-done
8195 (looking-at org-todo-line-regexp)
8196 (or (not (match-end 2))
8197 (not (member (match-string 2) org-done-keywords))))
8198 (let (org-log-done org-todo-log-states)
8199 (org-todo
8200 (car (or (member org-archive-mark-done org-done-keywords)
8201 org-done-keywords)))))
8203 ;; Add the context info
8204 (when org-archive-save-context-info
8205 (let ((l org-archive-save-context-info) e n v)
8206 (while (setq e (pop l))
8207 (when (and (setq v (symbol-value e))
8208 (stringp v) (string-match "\\S-" v))
8209 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8210 (org-entry-put (point) n v)))))
8212 ;; Save and kill the buffer, if it is not the same buffer.
8213 (if (not (eq this-buffer buffer))
8214 (progn (save-buffer) (kill-buffer buffer)))))
8215 ;; Here we are back in the original buffer. Everything seems to have
8216 ;; worked. So now cut the tree and finish up.
8217 (let (this-command) (org-cut-subtree))
8218 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8219 (message "Subtree archived %s"
8220 (if (eq this-buffer buffer)
8221 (concat "under heading: " heading)
8222 (concat "in file: " (abbreviate-file-name afile)))))))
8224 (defun org-refresh-category-properties ()
8225 "Refresh category text properties in teh buffer."
8226 (let ((def-cat (cond
8227 ((null org-category)
8228 (if buffer-file-name
8229 (file-name-sans-extension
8230 (file-name-nondirectory buffer-file-name))
8231 "???"))
8232 ((symbolp org-category) (symbol-name org-category))
8233 (t org-category)))
8234 beg end cat pos optionp)
8235 (org-unmodified
8236 (save-excursion
8237 (save-restriction
8238 (widen)
8239 (goto-char (point-min))
8240 (put-text-property (point) (point-max) 'org-category def-cat)
8241 (while (re-search-forward
8242 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8243 (setq pos (match-end 0)
8244 optionp (equal (char-after (match-beginning 0)) ?#)
8245 cat (org-trim (match-string 2)))
8246 (if optionp
8247 (setq beg (point-at-bol) end (point-max))
8248 (org-back-to-heading t)
8249 (setq beg (point) end (org-end-of-subtree t t)))
8250 (put-text-property beg end 'org-category cat)
8251 (goto-char pos)))))))
8253 (defun org-archive-all-done (&optional tag)
8254 "Archive sublevels of the current tree without open TODO items.
8255 If the cursor is not on a headline, try all level 1 trees. If
8256 it is on a headline, try all direct children.
8257 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8258 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8259 (rea (concat ".*:" org-archive-tag ":"))
8260 (begm (make-marker))
8261 (endm (make-marker))
8262 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8263 "Move subtree to archive (no open TODO items)? "))
8264 beg end (cntarch 0))
8265 (if (org-on-heading-p)
8266 (progn
8267 (setq re1 (concat "^" (regexp-quote
8268 (make-string
8269 (1+ (- (match-end 0) (match-beginning 0) 1))
8270 ?*))
8271 " "))
8272 (move-marker begm (point))
8273 (move-marker endm (org-end-of-subtree t)))
8274 (setq re1 "^* ")
8275 (move-marker begm (point-min))
8276 (move-marker endm (point-max)))
8277 (save-excursion
8278 (goto-char begm)
8279 (while (re-search-forward re1 endm t)
8280 (setq beg (match-beginning 0)
8281 end (save-excursion (org-end-of-subtree t) (point)))
8282 (goto-char beg)
8283 (if (re-search-forward re end t)
8284 (goto-char end)
8285 (goto-char beg)
8286 (if (and (or (not tag) (not (looking-at rea)))
8287 (y-or-n-p question))
8288 (progn
8289 (if tag
8290 (org-toggle-tag org-archive-tag 'on)
8291 (org-archive-subtree))
8292 (setq cntarch (1+ cntarch)))
8293 (goto-char end)))))
8294 (message "%d trees archived" cntarch)))
8296 (defun org-cycle-hide-drawers (state)
8297 "Re-hide all drawers after a visibility state change."
8298 (when (and (org-mode-p)
8299 (not (memq state '(overview folded))))
8300 (save-excursion
8301 (let* ((globalp (memq state '(contents all)))
8302 (beg (if globalp (point-min) (point)))
8303 (end (if globalp (point-max) (org-end-of-subtree t))))
8304 (goto-char beg)
8305 (while (re-search-forward org-drawer-regexp end t)
8306 (org-flag-drawer t))))))
8308 (defun org-flag-drawer (flag)
8309 (save-excursion
8310 (beginning-of-line 1)
8311 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8312 (let ((b (match-end 0))
8313 (outline-regexp org-outline-regexp))
8314 (if (re-search-forward
8315 "^[ \t]*:END:"
8316 (save-excursion (outline-next-heading) (point)) t)
8317 (outline-flag-region b (point-at-eol) flag)
8318 (error ":END: line missing"))))))
8320 (defun org-cycle-hide-archived-subtrees (state)
8321 "Re-hide all archived subtrees after a visibility state change."
8322 (when (and (not org-cycle-open-archived-trees)
8323 (not (memq state '(overview folded))))
8324 (save-excursion
8325 (let* ((globalp (memq state '(contents all)))
8326 (beg (if globalp (point-min) (point)))
8327 (end (if globalp (point-max) (org-end-of-subtree t))))
8328 (org-hide-archived-subtrees beg end)
8329 (goto-char beg)
8330 (if (looking-at (concat ".*:" org-archive-tag ":"))
8331 (message "%s" (substitute-command-keys
8332 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8334 (defun org-force-cycle-archived ()
8335 "Cycle subtree even if it is archived."
8336 (interactive)
8337 (setq this-command 'org-cycle)
8338 (let ((org-cycle-open-archived-trees t))
8339 (call-interactively 'org-cycle)))
8341 (defun org-hide-archived-subtrees (beg end)
8342 "Re-hide all archived subtrees after a visibility state change."
8343 (save-excursion
8344 (let* ((re (concat ":" org-archive-tag ":")))
8345 (goto-char beg)
8346 (while (re-search-forward re end t)
8347 (and (org-on-heading-p) (hide-subtree))
8348 (org-end-of-subtree t)))))
8350 (defun org-toggle-tag (tag &optional onoff)
8351 "Toggle the tag TAG for the current line.
8352 If ONOFF is `on' or `off', don't toggle but set to this state."
8353 (unless (org-on-heading-p t) (error "Not on headling"))
8354 (let (res current)
8355 (save-excursion
8356 (beginning-of-line)
8357 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8358 (point-at-eol) t)
8359 (progn
8360 (setq current (match-string 1))
8361 (replace-match ""))
8362 (setq current ""))
8363 (setq current (nreverse (org-split-string current ":")))
8364 (cond
8365 ((eq onoff 'on)
8366 (setq res t)
8367 (or (member tag current) (push tag current)))
8368 ((eq onoff 'off)
8369 (or (not (member tag current)) (setq current (delete tag current))))
8370 (t (if (member tag current)
8371 (setq current (delete tag current))
8372 (setq res t)
8373 (push tag current))))
8374 (end-of-line 1)
8375 (if current
8376 (progn
8377 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8378 (org-set-tags nil t))
8379 (delete-horizontal-space))
8380 (run-hooks 'org-after-tags-change-hook))
8381 res))
8383 (defun org-toggle-archive-tag (&optional arg)
8384 "Toggle the archive tag for the current headline.
8385 With prefix ARG, check all children of current headline and offer tagging
8386 the children that do not contain any open TODO items."
8387 (interactive "P")
8388 (if arg
8389 (org-archive-all-done 'tag)
8390 (let (set)
8391 (save-excursion
8392 (org-back-to-heading t)
8393 (setq set (org-toggle-tag org-archive-tag))
8394 (when set (hide-subtree)))
8395 (and set (beginning-of-line 1))
8396 (message "Subtree %s" (if set "archived" "unarchived")))))
8399 ;;;; Tables
8401 ;;; The table editor
8403 ;; Watch out: Here we are talking about two different kind of tables.
8404 ;; Most of the code is for the tables created with the Org-mode table editor.
8405 ;; Sometimes, we talk about tables created and edited with the table.el
8406 ;; Emacs package. We call the former org-type tables, and the latter
8407 ;; table.el-type tables.
8409 (defun org-before-change-function (beg end)
8410 "Every change indicates that a table might need an update."
8411 (setq org-table-may-need-update t))
8413 (defconst org-table-line-regexp "^[ \t]*|"
8414 "Detects an org-type table line.")
8415 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8416 "Detects an org-type table line.")
8417 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8418 "Detects a table line marked for automatic recalculation.")
8419 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8420 "Detects a table line marked for automatic recalculation.")
8421 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8422 "Detects a table line marked for automatic recalculation.")
8423 (defconst org-table-hline-regexp "^[ \t]*|-"
8424 "Detects an org-type table hline.")
8425 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8426 "Detects a table-type table hline.")
8427 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8428 "Detects an org-type or table-type table.")
8429 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8430 "Searching from within a table (any type) this finds the first line
8431 outside the table.")
8432 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8433 "Searching from within a table (any type) this finds the first line
8434 outside the table.")
8436 (defvar org-table-last-highlighted-reference nil)
8437 (defvar org-table-formula-history nil)
8439 (defvar org-table-column-names nil
8440 "Alist with column names, derived from the `!' line.")
8441 (defvar org-table-column-name-regexp nil
8442 "Regular expression matching the current column names.")
8443 (defvar org-table-local-parameters nil
8444 "Alist with parameter names, derived from the `$' line.")
8445 (defvar org-table-named-field-locations nil
8446 "Alist with locations of named fields.")
8448 (defvar org-table-current-line-types nil
8449 "Table row types, non-nil only for the duration of a comand.")
8450 (defvar org-table-current-begin-line nil
8451 "Table begin line, non-nil only for the duration of a comand.")
8452 (defvar org-table-current-begin-pos nil
8453 "Table begin position, non-nil only for the duration of a comand.")
8454 (defvar org-table-dlines nil
8455 "Vector of data line line numbers in the current table.")
8456 (defvar org-table-hlines nil
8457 "Vector of hline line numbers in the current table.")
8459 (defconst org-table-range-regexp
8460 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8461 ;; 1 2 3 4 5
8462 "Regular expression for matching ranges in formulas.")
8464 (defconst org-table-range-regexp2
8465 (concat
8466 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8467 "\\.\\."
8468 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8469 "Match a range for reference display.")
8471 (defconst org-table-translate-regexp
8472 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8473 "Match a reference that needs translation, for reference display.")
8475 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8477 (defun org-table-create-with-table.el ()
8478 "Use the table.el package to insert a new table.
8479 If there is already a table at point, convert between Org-mode tables
8480 and table.el tables."
8481 (interactive)
8482 (require 'table)
8483 (cond
8484 ((org-at-table.el-p)
8485 (if (y-or-n-p "Convert table to Org-mode table? ")
8486 (org-table-convert)))
8487 ((org-at-table-p)
8488 (if (y-or-n-p "Convert table to table.el table? ")
8489 (org-table-convert)))
8490 (t (call-interactively 'table-insert))))
8492 (defun org-table-create-or-convert-from-region (arg)
8493 "Convert region to table, or create an empty table.
8494 If there is an active region, convert it to a table, using the function
8495 `org-table-convert-region'. See the documentation of that function
8496 to learn how the prefix argument is interpreted to determine the field
8497 separator.
8498 If there is no such region, create an empty table with `org-table-create'."
8499 (interactive "P")
8500 (if (org-region-active-p)
8501 (org-table-convert-region (region-beginning) (region-end) arg)
8502 (org-table-create arg)))
8504 (defun org-table-create (&optional size)
8505 "Query for a size and insert a table skeleton.
8506 SIZE is a string Columns x Rows like for example \"3x2\"."
8507 (interactive "P")
8508 (unless size
8509 (setq size (read-string
8510 (concat "Table size Columns x Rows [e.g. "
8511 org-table-default-size "]: ")
8512 "" nil org-table-default-size)))
8514 (let* ((pos (point))
8515 (indent (make-string (current-column) ?\ ))
8516 (split (org-split-string size " *x *"))
8517 (rows (string-to-number (nth 1 split)))
8518 (columns (string-to-number (car split)))
8519 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8520 "\n")))
8521 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8522 (point-at-bol) (point)))
8523 (beginning-of-line 1)
8524 (newline))
8525 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8526 (dotimes (i rows) (insert line))
8527 (goto-char pos)
8528 (if (> rows 1)
8529 ;; Insert a hline after the first row.
8530 (progn
8531 (end-of-line 1)
8532 (insert "\n|-")
8533 (goto-char pos)))
8534 (org-table-align)))
8536 (defun org-table-convert-region (beg0 end0 &optional separator)
8537 "Convert region to a table.
8538 The region goes from BEG0 to END0, but these borders will be moved
8539 slightly, to make sure a beginning of line in the first line is included.
8541 SEPARATOR specifies the field separator in the lines. It can have the
8542 following values:
8544 '(4) Use the comma as a field separator
8545 '(16) Use a TAB as field separator
8546 integer When a number, use that many spaces as field separator
8547 nil When nil, the command tries to be smart and figure out the
8548 separator in the following way:
8549 - when each line contains a TAB, assume TAB-separated material
8550 - when each line contains a comme, assume CSV material
8551 - else, assume one or more SPACE charcters as separator."
8552 (interactive "rP")
8553 (let* ((beg (min beg0 end0))
8554 (end (max beg0 end0))
8556 (goto-char beg)
8557 (beginning-of-line 1)
8558 (setq beg (move-marker (make-marker) (point)))
8559 (goto-char end)
8560 (if (bolp) (backward-char 1) (end-of-line 1))
8561 (setq end (move-marker (make-marker) (point)))
8562 ;; Get the right field separator
8563 (unless separator
8564 (goto-char beg)
8565 (setq separator
8566 (cond
8567 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8568 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8569 (t 1))))
8570 (setq re (cond
8571 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8572 ((equal separator '(16)) "^\\|\t")
8573 ((integerp separator)
8574 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8575 (t (error "This should not happen"))))
8576 (goto-char beg)
8577 (while (re-search-forward re end t)
8578 (replace-match "| " t t))
8579 (goto-char beg)
8580 (insert " ")
8581 (org-table-align)))
8583 (defun org-table-import (file arg)
8584 "Import FILE as a table.
8585 The file is assumed to be tab-separated. Such files can be produced by most
8586 spreadsheet and database applications. If no tabs (at least one per line)
8587 are found, lines will be split on whitespace into fields."
8588 (interactive "f\nP")
8589 (or (bolp) (newline))
8590 (let ((beg (point))
8591 (pm (point-max)))
8592 (insert-file-contents file)
8593 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8595 (defun org-table-export ()
8596 "Export table as a tab-separated file.
8597 Such a file can be imported into a spreadsheet program like Excel."
8598 (interactive)
8599 (let* ((beg (org-table-begin))
8600 (end (org-table-end))
8601 (table (buffer-substring beg end))
8602 (file (read-file-name "Export table to: "))
8603 buf)
8604 (unless (or (not (file-exists-p file))
8605 (y-or-n-p (format "Overwrite file %s? " file)))
8606 (error "Abort"))
8607 (with-current-buffer (find-file-noselect file)
8608 (setq buf (current-buffer))
8609 (erase-buffer)
8610 (fundamental-mode)
8611 (insert table)
8612 (goto-char (point-min))
8613 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8614 (replace-match "" t t)
8615 (end-of-line 1))
8616 (goto-char (point-min))
8617 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8618 (replace-match "" t t)
8619 (goto-char (min (1+ (point)) (point-max))))
8620 (goto-char (point-min))
8621 (while (re-search-forward "^-[-+]*$" nil t)
8622 (replace-match "")
8623 (if (looking-at "\n")
8624 (delete-char 1)))
8625 (goto-char (point-min))
8626 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8627 (replace-match "\t" t t))
8628 (save-buffer))
8629 (kill-buffer buf)))
8631 (defvar org-table-aligned-begin-marker (make-marker)
8632 "Marker at the beginning of the table last aligned.
8633 Used to check if cursor still is in that table, to minimize realignment.")
8634 (defvar org-table-aligned-end-marker (make-marker)
8635 "Marker at the end of the table last aligned.
8636 Used to check if cursor still is in that table, to minimize realignment.")
8637 (defvar org-table-last-alignment nil
8638 "List of flags for flushright alignment, from the last re-alignment.
8639 This is being used to correctly align a single field after TAB or RET.")
8640 (defvar org-table-last-column-widths nil
8641 "List of max width of fields in each column.
8642 This is being used to correctly align a single field after TAB or RET.")
8643 (defvar org-table-overlay-coordinates nil
8644 "Overlay coordinates after each align of a table.")
8645 (make-variable-buffer-local 'org-table-overlay-coordinates)
8647 (defvar org-last-recalc-line nil)
8648 (defconst org-narrow-column-arrow "=>"
8649 "Used as display property in narrowed table columns.")
8651 (defun org-table-align ()
8652 "Align the table at point by aligning all vertical bars."
8653 (interactive)
8654 (let* (
8655 ;; Limits of table
8656 (beg (org-table-begin))
8657 (end (org-table-end))
8658 ;; Current cursor position
8659 (linepos (org-current-line))
8660 (colpos (org-table-current-column))
8661 (winstart (window-start))
8662 (winstartline (org-current-line (min winstart (1- (point-max)))))
8663 lines (new "") lengths l typenums ty fields maxfields i
8664 column
8665 (indent "") cnt frac
8666 rfmt hfmt
8667 (spaces '(1 . 1))
8668 (sp1 (car spaces))
8669 (sp2 (cdr spaces))
8670 (rfmt1 (concat
8671 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8672 (hfmt1 (concat
8673 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8674 emptystrings links dates emph narrow fmax f1 len c e)
8675 (untabify beg end)
8676 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8677 ;; Check if we have links or dates
8678 (goto-char beg)
8679 (setq links (re-search-forward org-bracket-link-regexp end t))
8680 (goto-char beg)
8681 (setq emph (and org-hide-emphasis-markers
8682 (re-search-forward org-emph-re end t)))
8683 (goto-char beg)
8684 (setq dates (and org-display-custom-times
8685 (re-search-forward org-ts-regexp-both end t)))
8686 ;; Make sure the link properties are right
8687 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8688 ;; Make sure the date properties are right
8689 (when dates (goto-char beg) (while (org-activate-dates end)))
8690 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8692 ;; Check if we are narrowing any columns
8693 (goto-char beg)
8694 (setq narrow (and org-format-transports-properties-p
8695 (re-search-forward "<[0-9]+>" end t)))
8696 ;; Get the rows
8697 (setq lines (org-split-string
8698 (buffer-substring beg end) "\n"))
8699 ;; Store the indentation of the first line
8700 (if (string-match "^ *" (car lines))
8701 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8702 ;; Mark the hlines by setting the corresponding element to nil
8703 ;; At the same time, we remove trailing space.
8704 (setq lines (mapcar (lambda (l)
8705 (if (string-match "^ *|-" l)
8707 (if (string-match "[ \t]+$" l)
8708 (substring l 0 (match-beginning 0))
8709 l)))
8710 lines))
8711 ;; Get the data fields by splitting the lines.
8712 (setq fields (mapcar
8713 (lambda (l)
8714 (org-split-string l " *| *"))
8715 (delq nil (copy-sequence lines))))
8716 ;; How many fields in the longest line?
8717 (condition-case nil
8718 (setq maxfields (apply 'max (mapcar 'length fields)))
8719 (error
8720 (kill-region beg end)
8721 (org-table-create org-table-default-size)
8722 (error "Empty table - created default table")))
8723 ;; A list of empty strings to fill any short rows on output
8724 (setq emptystrings (make-list maxfields ""))
8725 ;; Check for special formatting.
8726 (setq i -1)
8727 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8728 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8729 ;; Check if there is an explicit width specified
8730 (when narrow
8731 (setq c column fmax nil)
8732 (while c
8733 (setq e (pop c))
8734 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8735 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8736 ;; Find fields that are wider than fmax, and shorten them
8737 (when fmax
8738 (loop for xx in column do
8739 (when (and (stringp xx)
8740 (> (org-string-width xx) fmax))
8741 (org-add-props xx nil
8742 'help-echo
8743 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8744 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8745 (unless (> f1 1)
8746 (error "Cannot narrow field starting with wide link \"%s\""
8747 (match-string 0 xx)))
8748 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8749 (add-text-properties (- f1 2) f1
8750 (list 'display org-narrow-column-arrow)
8751 xx)))))
8752 ;; Get the maximum width for each column
8753 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8754 ;; Get the fraction of numbers, to decide about alignment of the column
8755 (setq cnt 0 frac 0.0)
8756 (loop for x in column do
8757 (if (equal x "")
8759 (setq frac ( / (+ (* frac cnt)
8760 (if (string-match org-table-number-regexp x) 1 0))
8761 (setq cnt (1+ cnt))))))
8762 (push (>= frac org-table-number-fraction) typenums))
8763 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8765 ;; Store the alignment of this table, for later editing of single fields
8766 (setq org-table-last-alignment typenums
8767 org-table-last-column-widths lengths)
8769 ;; With invisible characters, `format' does not get the field width right
8770 ;; So we need to make these fields wide by hand.
8771 (when (or links emph)
8772 (loop for i from 0 upto (1- maxfields) do
8773 (setq len (nth i lengths))
8774 (loop for j from 0 upto (1- (length fields)) do
8775 (setq c (nthcdr i (car (nthcdr j fields))))
8776 (if (and (stringp (car c))
8777 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8778 ; (string-match org-bracket-link-regexp (car c))
8779 (< (org-string-width (car c)) len))
8780 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8782 ;; Compute the formats needed for output of the table
8783 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8784 (while (setq l (pop lengths))
8785 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8786 (setq rfmt (concat rfmt (format rfmt1 ty l))
8787 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8788 (setq rfmt (concat rfmt "\n")
8789 hfmt (concat (substring hfmt 0 -1) "|\n"))
8791 (setq new (mapconcat
8792 (lambda (l)
8793 (if l (apply 'format rfmt
8794 (append (pop fields) emptystrings))
8795 hfmt))
8796 lines ""))
8797 ;; Replace the old one
8798 (delete-region beg end)
8799 (move-marker end nil)
8800 (move-marker org-table-aligned-begin-marker (point))
8801 (insert new)
8802 (move-marker org-table-aligned-end-marker (point))
8803 (when (and orgtbl-mode (not (org-mode-p)))
8804 (goto-char org-table-aligned-begin-marker)
8805 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8806 ;; Try to move to the old location
8807 (goto-line winstartline)
8808 (setq winstart (point-at-bol))
8809 (goto-line linepos)
8810 (set-window-start (selected-window) winstart 'noforce)
8811 (org-table-goto-column colpos)
8812 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8813 (setq org-table-may-need-update nil)
8816 (defun org-string-width (s)
8817 "Compute width of string, ignoring invisible characters.
8818 This ignores character with invisibility property `org-link', and also
8819 characters with property `org-cwidth', because these will become invisible
8820 upon the next fontification round."
8821 (let (b l)
8822 (when (or (eq t buffer-invisibility-spec)
8823 (assq 'org-link buffer-invisibility-spec))
8824 (while (setq b (text-property-any 0 (length s)
8825 'invisible 'org-link s))
8826 (setq s (concat (substring s 0 b)
8827 (substring s (or (next-single-property-change
8828 b 'invisible s) (length s)))))))
8829 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8830 (setq s (concat (substring s 0 b)
8831 (substring s (or (next-single-property-change
8832 b 'org-cwidth s) (length s))))))
8833 (setq l (string-width s) b -1)
8834 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8835 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8838 (defun org-table-begin (&optional table-type)
8839 "Find the beginning of the table and return its position.
8840 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8841 (save-excursion
8842 (if (not (re-search-backward
8843 (if table-type org-table-any-border-regexp
8844 org-table-border-regexp)
8845 nil t))
8846 (progn (goto-char (point-min)) (point))
8847 (goto-char (match-beginning 0))
8848 (beginning-of-line 2)
8849 (point))))
8851 (defun org-table-end (&optional table-type)
8852 "Find the end of the table and return its position.
8853 With argument TABLE-TYPE, go to the end of a table.el-type table."
8854 (save-excursion
8855 (if (not (re-search-forward
8856 (if table-type org-table-any-border-regexp
8857 org-table-border-regexp)
8858 nil t))
8859 (goto-char (point-max))
8860 (goto-char (match-beginning 0)))
8861 (point-marker)))
8863 (defun org-table-justify-field-maybe (&optional new)
8864 "Justify the current field, text to left, number to right.
8865 Optional argument NEW may specify text to replace the current field content."
8866 (cond
8867 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8868 ((org-at-table-hline-p))
8869 ((and (not new)
8870 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8871 (current-buffer)))
8872 (< (point) org-table-aligned-begin-marker)
8873 (>= (point) org-table-aligned-end-marker)))
8874 ;; This is not the same table, force a full re-align
8875 (setq org-table-may-need-update t))
8876 (t ;; realign the current field, based on previous full realign
8877 (let* ((pos (point)) s
8878 (col (org-table-current-column))
8879 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8880 l f n o e)
8881 (when (> col 0)
8882 (skip-chars-backward "^|\n")
8883 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8884 (progn
8885 (setq s (match-string 1)
8886 o (match-string 0)
8887 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8888 e (not (= (match-beginning 2) (match-end 2))))
8889 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8890 l (if e "|" (setq org-table-may-need-update t) ""))
8891 n (format f s))
8892 (if new
8893 (if (<= (length new) l) ;; FIXME: length -> str-width?
8894 (setq n (format f new))
8895 (setq n (concat new "|") org-table-may-need-update t)))
8896 (or (equal n o)
8897 (let (org-table-may-need-update)
8898 (replace-match n t t))))
8899 (setq org-table-may-need-update t))
8900 (goto-char pos))))))
8902 (defun org-table-next-field ()
8903 "Go to the next field in the current table, creating new lines as needed.
8904 Before doing so, re-align the table if necessary."
8905 (interactive)
8906 (org-table-maybe-eval-formula)
8907 (org-table-maybe-recalculate-line)
8908 (if (and org-table-automatic-realign
8909 org-table-may-need-update)
8910 (org-table-align))
8911 (let ((end (org-table-end)))
8912 (if (org-at-table-hline-p)
8913 (end-of-line 1))
8914 (condition-case nil
8915 (progn
8916 (re-search-forward "|" end)
8917 (if (looking-at "[ \t]*$")
8918 (re-search-forward "|" end))
8919 (if (and (looking-at "-")
8920 org-table-tab-jumps-over-hlines
8921 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8922 (goto-char (match-beginning 1)))
8923 (if (looking-at "-")
8924 (progn
8925 (beginning-of-line 0)
8926 (org-table-insert-row 'below))
8927 (if (looking-at " ") (forward-char 1))))
8928 (error
8929 (org-table-insert-row 'below)))))
8931 (defun org-table-previous-field ()
8932 "Go to the previous field in the table.
8933 Before doing so, re-align the table if necessary."
8934 (interactive)
8935 (org-table-justify-field-maybe)
8936 (org-table-maybe-recalculate-line)
8937 (if (and org-table-automatic-realign
8938 org-table-may-need-update)
8939 (org-table-align))
8940 (if (org-at-table-hline-p)
8941 (end-of-line 1))
8942 (re-search-backward "|" (org-table-begin))
8943 (re-search-backward "|" (org-table-begin))
8944 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8945 (re-search-backward "|" (org-table-begin)))
8946 (if (looking-at "| ?")
8947 (goto-char (match-end 0))))
8949 (defun org-table-next-row ()
8950 "Go to the next row (same column) in the current table.
8951 Before doing so, re-align the table if necessary."
8952 (interactive)
8953 (org-table-maybe-eval-formula)
8954 (org-table-maybe-recalculate-line)
8955 (if (or (looking-at "[ \t]*$")
8956 (save-excursion (skip-chars-backward " \t") (bolp)))
8957 (newline)
8958 (if (and org-table-automatic-realign
8959 org-table-may-need-update)
8960 (org-table-align))
8961 (let ((col (org-table-current-column)))
8962 (beginning-of-line 2)
8963 (if (or (not (org-at-table-p))
8964 (org-at-table-hline-p))
8965 (progn
8966 (beginning-of-line 0)
8967 (org-table-insert-row 'below)))
8968 (org-table-goto-column col)
8969 (skip-chars-backward "^|\n\r")
8970 (if (looking-at " ") (forward-char 1)))))
8972 (defun org-table-copy-down (n)
8973 "Copy a field down in the current column.
8974 If the field at the cursor is empty, copy into it the content of the nearest
8975 non-empty field above. With argument N, use the Nth non-empty field.
8976 If the current field is not empty, it is copied down to the next row, and
8977 the cursor is moved with it. Therefore, repeating this command causes the
8978 column to be filled row-by-row.
8979 If the variable `org-table-copy-increment' is non-nil and the field is an
8980 integer or a timestamp, it will be incremented while copying. In the case of
8981 a timestamp, if the cursor is on the year, change the year. If it is on the
8982 month or the day, change that. Point will stay on the current date field
8983 in order to easily repeat the interval."
8984 (interactive "p")
8985 (let* ((colpos (org-table-current-column))
8986 (col (current-column))
8987 (field (org-table-get-field))
8988 (non-empty (string-match "[^ \t]" field))
8989 (beg (org-table-begin))
8990 txt)
8991 (org-table-check-inside-data-field)
8992 (if non-empty
8993 (progn
8994 (setq txt (org-trim field))
8995 (org-table-next-row)
8996 (org-table-blank-field))
8997 (save-excursion
8998 (setq txt
8999 (catch 'exit
9000 (while (progn (beginning-of-line 1)
9001 (re-search-backward org-table-dataline-regexp
9002 beg t))
9003 (org-table-goto-column colpos t)
9004 (if (and (looking-at
9005 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
9006 (= (setq n (1- n)) 0))
9007 (throw 'exit (match-string 1))))))))
9008 (if txt
9009 (progn
9010 (if (and org-table-copy-increment
9011 (string-match "^[0-9]+$" txt))
9012 (setq txt (format "%d" (+ (string-to-number txt) 1))))
9013 (insert txt)
9014 (move-to-column col)
9015 (if (and org-table-copy-increment (org-at-timestamp-p t))
9016 (org-timestamp-up 1)
9017 (org-table-maybe-recalculate-line))
9018 (org-table-align)
9019 (move-to-column col))
9020 (error "No non-empty field found"))))
9022 (defun org-table-check-inside-data-field ()
9023 "Is point inside a table data field?
9024 I.e. not on a hline or before the first or after the last column?
9025 This actually throws an error, so it aborts the current command."
9026 (if (or (not (org-at-table-p))
9027 (= (org-table-current-column) 0)
9028 (org-at-table-hline-p)
9029 (looking-at "[ \t]*$"))
9030 (error "Not in table data field")))
9032 (defvar org-table-clip nil
9033 "Clipboard for table regions.")
9035 (defun org-table-blank-field ()
9036 "Blank the current table field or active region."
9037 (interactive)
9038 (org-table-check-inside-data-field)
9039 (if (and (interactive-p) (org-region-active-p))
9040 (let (org-table-clip)
9041 (org-table-cut-region (region-beginning) (region-end)))
9042 (skip-chars-backward "^|")
9043 (backward-char 1)
9044 (if (looking-at "|[^|\n]+")
9045 (let* ((pos (match-beginning 0))
9046 (match (match-string 0))
9047 (len (org-string-width match)))
9048 (replace-match (concat "|" (make-string (1- len) ?\ )))
9049 (goto-char (+ 2 pos))
9050 (substring match 1)))))
9052 (defun org-table-get-field (&optional n replace)
9053 "Return the value of the field in column N of current row.
9054 N defaults to current field.
9055 If REPLACE is a string, replace field with this value. The return value
9056 is always the old value."
9057 (and n (org-table-goto-column n))
9058 (skip-chars-backward "^|\n")
9059 (backward-char 1)
9060 (if (looking-at "|[^|\r\n]*")
9061 (let* ((pos (match-beginning 0))
9062 (val (buffer-substring (1+ pos) (match-end 0))))
9063 (if replace
9064 (replace-match (concat "|" replace) t t))
9065 (goto-char (min (point-at-eol) (+ 2 pos)))
9066 val)
9067 (forward-char 1) ""))
9069 (defun org-table-field-info (arg)
9070 "Show info about the current field, and highlight any reference at point."
9071 (interactive "P")
9072 (org-table-get-specials)
9073 (save-excursion
9074 (let* ((pos (point))
9075 (col (org-table-current-column))
9076 (cname (car (rassoc (int-to-string col) org-table-column-names)))
9077 (name (car (rassoc (list (org-current-line) col)
9078 org-table-named-field-locations)))
9079 (eql (org-table-get-stored-formulas))
9080 (dline (org-table-current-dline))
9081 (ref (format "@%d$%d" dline col))
9082 (ref1 (org-table-convert-refs-to-an ref))
9083 (fequation (or (assoc name eql) (assoc ref eql)))
9084 (cequation (assoc (int-to-string col) eql))
9085 (eqn (or fequation cequation)))
9086 (goto-char pos)
9087 (condition-case nil
9088 (org-table-show-reference 'local)
9089 (error nil))
9090 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
9091 dline col
9092 (if cname (concat " or $" cname) "")
9093 dline col ref1
9094 (if name (concat " or $" name) "")
9095 ;; FIXME: formula info not correct if special table line
9096 (if eqn
9097 (concat ", formula: "
9098 (org-table-formula-to-user
9099 (concat
9100 (if (string-match "^[$@]"(car eqn)) "" "$")
9101 (car eqn) "=" (cdr eqn))))
9102 "")))))
9104 (defun org-table-current-column ()
9105 "Find out which column we are in.
9106 When called interactively, column is also displayed in echo area."
9107 (interactive)
9108 (if (interactive-p) (org-table-check-inside-data-field))
9109 (save-excursion
9110 (let ((cnt 0) (pos (point)))
9111 (beginning-of-line 1)
9112 (while (search-forward "|" pos t)
9113 (setq cnt (1+ cnt)))
9114 (if (interactive-p) (message "This is table column %d" cnt))
9115 cnt)))
9117 (defun org-table-current-dline ()
9118 "Find out what table data line we are in.
9119 Only datalins count for this."
9120 (interactive)
9121 (if (interactive-p) (org-table-check-inside-data-field))
9122 (save-excursion
9123 (let ((cnt 0) (pos (point)))
9124 (goto-char (org-table-begin))
9125 (while (<= (point) pos)
9126 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
9127 (beginning-of-line 2))
9128 (if (interactive-p) (message "This is table line %d" cnt))
9129 cnt)))
9131 (defun org-table-goto-column (n &optional on-delim force)
9132 "Move the cursor to the Nth column in the current table line.
9133 With optional argument ON-DELIM, stop with point before the left delimiter
9134 of the field.
9135 If there are less than N fields, just go to after the last delimiter.
9136 However, when FORCE is non-nil, create new columns if necessary."
9137 (interactive "p")
9138 (let ((pos (point-at-eol)))
9139 (beginning-of-line 1)
9140 (when (> n 0)
9141 (while (and (> (setq n (1- n)) -1)
9142 (or (search-forward "|" pos t)
9143 (and force
9144 (progn (end-of-line 1)
9145 (skip-chars-backward "^|")
9146 (insert " | "))))))
9147 ; (backward-char 2) t)))))
9148 (when (and force (not (looking-at ".*|")))
9149 (save-excursion (end-of-line 1) (insert " | ")))
9150 (if on-delim
9151 (backward-char 1)
9152 (if (looking-at " ") (forward-char 1))))))
9154 (defun org-at-table-p (&optional table-type)
9155 "Return t if the cursor is inside an org-type table.
9156 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9157 (if org-enable-table-editor
9158 (save-excursion
9159 (beginning-of-line 1)
9160 (looking-at (if table-type org-table-any-line-regexp
9161 org-table-line-regexp)))
9162 nil))
9164 (defun org-at-table.el-p ()
9165 "Return t if and only if we are at a table.el table."
9166 (and (org-at-table-p 'any)
9167 (save-excursion
9168 (goto-char (org-table-begin 'any))
9169 (looking-at org-table1-hline-regexp))))
9171 (defun org-table-recognize-table.el ()
9172 "If there is a table.el table nearby, recognize it and move into it."
9173 (if org-table-tab-recognizes-table.el
9174 (if (org-at-table.el-p)
9175 (progn
9176 (beginning-of-line 1)
9177 (if (looking-at org-table-dataline-regexp)
9179 (if (looking-at org-table1-hline-regexp)
9180 (progn
9181 (beginning-of-line 2)
9182 (if (looking-at org-table-any-border-regexp)
9183 (beginning-of-line -1)))))
9184 (if (re-search-forward "|" (org-table-end t) t)
9185 (progn
9186 (require 'table)
9187 (if (table--at-cell-p (point))
9189 (message "recognizing table.el table...")
9190 (table-recognize-table)
9191 (message "recognizing table.el table...done")))
9192 (error "This should not happen..."))
9194 nil)
9195 nil))
9197 (defun org-at-table-hline-p ()
9198 "Return t if the cursor is inside a hline in a table."
9199 (if org-enable-table-editor
9200 (save-excursion
9201 (beginning-of-line 1)
9202 (looking-at org-table-hline-regexp))
9203 nil))
9205 (defun org-table-insert-column ()
9206 "Insert a new column into the table."
9207 (interactive)
9208 (if (not (org-at-table-p))
9209 (error "Not at a table"))
9210 (org-table-find-dataline)
9211 (let* ((col (max 1 (org-table-current-column)))
9212 (beg (org-table-begin))
9213 (end (org-table-end))
9214 ;; Current cursor position
9215 (linepos (org-current-line))
9216 (colpos col))
9217 (goto-char beg)
9218 (while (< (point) end)
9219 (if (org-at-table-hline-p)
9221 (org-table-goto-column col t)
9222 (insert "| "))
9223 (beginning-of-line 2))
9224 (move-marker end nil)
9225 (goto-line linepos)
9226 (org-table-goto-column colpos)
9227 (org-table-align)
9228 (org-table-fix-formulas "$" nil (1- col) 1)))
9230 (defun org-table-find-dataline ()
9231 "Find a dataline in the current table, which is needed for column commands."
9232 (if (and (org-at-table-p)
9233 (not (org-at-table-hline-p)))
9235 (let ((col (current-column))
9236 (end (org-table-end)))
9237 (move-to-column col)
9238 (while (and (< (point) end)
9239 (or (not (= (current-column) col))
9240 (org-at-table-hline-p)))
9241 (beginning-of-line 2)
9242 (move-to-column col))
9243 (if (and (org-at-table-p)
9244 (not (org-at-table-hline-p)))
9246 (error
9247 "Please position cursor in a data line for column operations")))))
9249 (defun org-table-delete-column ()
9250 "Delete a column from the table."
9251 (interactive)
9252 (if (not (org-at-table-p))
9253 (error "Not at a table"))
9254 (org-table-find-dataline)
9255 (org-table-check-inside-data-field)
9256 (let* ((col (org-table-current-column))
9257 (beg (org-table-begin))
9258 (end (org-table-end))
9259 ;; Current cursor position
9260 (linepos (org-current-line))
9261 (colpos col))
9262 (goto-char beg)
9263 (while (< (point) end)
9264 (if (org-at-table-hline-p)
9266 (org-table-goto-column col t)
9267 (and (looking-at "|[^|\n]+|")
9268 (replace-match "|")))
9269 (beginning-of-line 2))
9270 (move-marker end nil)
9271 (goto-line linepos)
9272 (org-table-goto-column colpos)
9273 (org-table-align)
9274 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9275 col -1 col)))
9277 (defun org-table-move-column-right ()
9278 "Move column to the right."
9279 (interactive)
9280 (org-table-move-column nil))
9281 (defun org-table-move-column-left ()
9282 "Move column to the left."
9283 (interactive)
9284 (org-table-move-column 'left))
9286 (defun org-table-move-column (&optional left)
9287 "Move the current column to the right. With arg LEFT, move to the left."
9288 (interactive "P")
9289 (if (not (org-at-table-p))
9290 (error "Not at a table"))
9291 (org-table-find-dataline)
9292 (org-table-check-inside-data-field)
9293 (let* ((col (org-table-current-column))
9294 (col1 (if left (1- col) col))
9295 (beg (org-table-begin))
9296 (end (org-table-end))
9297 ;; Current cursor position
9298 (linepos (org-current-line))
9299 (colpos (if left (1- col) (1+ col))))
9300 (if (and left (= col 1))
9301 (error "Cannot move column further left"))
9302 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9303 (error "Cannot move column further right"))
9304 (goto-char beg)
9305 (while (< (point) end)
9306 (if (org-at-table-hline-p)
9308 (org-table-goto-column col1 t)
9309 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9310 (replace-match "|\\2|\\1|")))
9311 (beginning-of-line 2))
9312 (move-marker end nil)
9313 (goto-line linepos)
9314 (org-table-goto-column colpos)
9315 (org-table-align)
9316 (org-table-fix-formulas
9317 "$" (list (cons (number-to-string col) (number-to-string colpos))
9318 (cons (number-to-string colpos) (number-to-string col))))))
9320 (defun org-table-move-row-down ()
9321 "Move table row down."
9322 (interactive)
9323 (org-table-move-row nil))
9324 (defun org-table-move-row-up ()
9325 "Move table row up."
9326 (interactive)
9327 (org-table-move-row 'up))
9329 (defun org-table-move-row (&optional up)
9330 "Move the current table line down. With arg UP, move it up."
9331 (interactive "P")
9332 (let* ((col (current-column))
9333 (pos (point))
9334 (hline1p (save-excursion (beginning-of-line 1)
9335 (looking-at org-table-hline-regexp)))
9336 (dline1 (org-table-current-dline))
9337 (dline2 (+ dline1 (if up -1 1)))
9338 (tonew (if up 0 2))
9339 txt hline2p)
9340 (beginning-of-line tonew)
9341 (unless (org-at-table-p)
9342 (goto-char pos)
9343 (error "Cannot move row further"))
9344 (setq hline2p (looking-at org-table-hline-regexp))
9345 (goto-char pos)
9346 (beginning-of-line 1)
9347 (setq pos (point))
9348 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9349 (delete-region (point) (1+ (point-at-eol)))
9350 (beginning-of-line tonew)
9351 (insert txt)
9352 (beginning-of-line 0)
9353 (move-to-column col)
9354 (unless (or hline1p hline2p)
9355 (org-table-fix-formulas
9356 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9357 (cons (number-to-string dline2) (number-to-string dline1)))))))
9359 (defun org-table-insert-row (&optional arg)
9360 "Insert a new row above the current line into the table.
9361 With prefix ARG, insert below the current line."
9362 (interactive "P")
9363 (if (not (org-at-table-p))
9364 (error "Not at a table"))
9365 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9366 (new (org-table-clean-line line)))
9367 ;; Fix the first field if necessary
9368 (if (string-match "^[ \t]*| *[#$] *|" line)
9369 (setq new (replace-match (match-string 0 line) t t new)))
9370 (beginning-of-line (if arg 2 1))
9371 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9372 (beginning-of-line 0)
9373 (re-search-forward "| ?" (point-at-eol) t)
9374 (and (or org-table-may-need-update org-table-overlay-coordinates)
9375 (org-table-align))
9376 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9378 (defun org-table-insert-hline (&optional above)
9379 "Insert a horizontal-line below the current line into the table.
9380 With prefix ABOVE, insert above the current line."
9381 (interactive "P")
9382 (if (not (org-at-table-p))
9383 (error "Not at a table"))
9384 (let ((line (org-table-clean-line
9385 (buffer-substring (point-at-bol) (point-at-eol))))
9386 (col (current-column)))
9387 (while (string-match "|\\( +\\)|" line)
9388 (setq line (replace-match
9389 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9390 ?-) "|") t t line)))
9391 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9392 (beginning-of-line (if above 1 2))
9393 (insert line "\n")
9394 (beginning-of-line (if above 1 -1))
9395 (move-to-column col)
9396 (and org-table-overlay-coordinates (org-table-align))))
9398 (defun org-table-hline-and-move (&optional same-column)
9399 "Insert a hline and move to the row below that line."
9400 (interactive "P")
9401 (let ((col (org-table-current-column)))
9402 (org-table-maybe-eval-formula)
9403 (org-table-maybe-recalculate-line)
9404 (org-table-insert-hline)
9405 (end-of-line 2)
9406 (if (looking-at "\n[ \t]*|-")
9407 (progn (insert "\n|") (org-table-align))
9408 (org-table-next-field))
9409 (if same-column (org-table-goto-column col))))
9411 (defun org-table-clean-line (s)
9412 "Convert a table line S into a string with only \"|\" and space.
9413 In particular, this does handle wide and invisible characters."
9414 (if (string-match "^[ \t]*|-" s)
9415 ;; It's a hline, just map the characters
9416 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9417 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9418 (setq s (replace-match
9419 (concat "|" (make-string (org-string-width (match-string 1 s))
9420 ?\ ) "|")
9421 t t s)))
9424 (defun org-table-kill-row ()
9425 "Delete the current row or horizontal line from the table."
9426 (interactive)
9427 (if (not (org-at-table-p))
9428 (error "Not at a table"))
9429 (let ((col (current-column))
9430 (dline (org-table-current-dline)))
9431 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9432 (if (not (org-at-table-p)) (beginning-of-line 0))
9433 (move-to-column col)
9434 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9435 dline -1 dline)))
9437 (defun org-table-sort-lines (with-case &optional sorting-type)
9438 "Sort table lines according to the column at point.
9440 The position of point indicates the column to be used for
9441 sorting, and the range of lines is the range between the nearest
9442 horizontal separator lines, or the entire table of no such lines
9443 exist. If point is before the first column, you will be prompted
9444 for the sorting column. If there is an active region, the mark
9445 specifies the first line and the sorting column, while point
9446 should be in the last line to be included into the sorting.
9448 The command then prompts for the sorting type which can be
9449 alphabetically, numerically, or by time (as given in a time stamp
9450 in the field). Sorting in reverse order is also possible.
9452 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9454 If SORTING-TYPE is specified when this function is called from a Lisp
9455 program, no prompting will take place. SORTING-TYPE must be a character,
9456 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9457 should be done in reverse order."
9458 (interactive "P")
9459 (let* ((thisline (org-current-line))
9460 (thiscol (org-table-current-column))
9461 beg end bcol ecol tend tbeg column lns pos)
9462 (when (equal thiscol 0)
9463 (if (interactive-p)
9464 (setq thiscol
9465 (string-to-number
9466 (read-string "Use column N for sorting: ")))
9467 (setq thiscol 1))
9468 (org-table-goto-column thiscol))
9469 (org-table-check-inside-data-field)
9470 (if (org-region-active-p)
9471 (progn
9472 (setq beg (region-beginning) end (region-end))
9473 (goto-char beg)
9474 (setq column (org-table-current-column)
9475 beg (point-at-bol))
9476 (goto-char end)
9477 (setq end (point-at-bol 2)))
9478 (setq column (org-table-current-column)
9479 pos (point)
9480 tbeg (org-table-begin)
9481 tend (org-table-end))
9482 (if (re-search-backward org-table-hline-regexp tbeg t)
9483 (setq beg (point-at-bol 2))
9484 (goto-char tbeg)
9485 (setq beg (point-at-bol 1)))
9486 (goto-char pos)
9487 (if (re-search-forward org-table-hline-regexp tend t)
9488 (setq end (point-at-bol 1))
9489 (goto-char tend)
9490 (setq end (point-at-bol))))
9491 (setq beg (move-marker (make-marker) beg)
9492 end (move-marker (make-marker) end))
9493 (untabify beg end)
9494 (goto-char beg)
9495 (org-table-goto-column column)
9496 (skip-chars-backward "^|")
9497 (setq bcol (current-column))
9498 (org-table-goto-column (1+ column))
9499 (skip-chars-backward "^|")
9500 (setq ecol (1- (current-column)))
9501 (org-table-goto-column column)
9502 (setq lns (mapcar (lambda(x) (cons
9503 (org-sort-remove-invisible
9504 (nth (1- column)
9505 (org-split-string x "[ \t]*|[ \t]*")))
9507 (org-split-string (buffer-substring beg end) "\n")))
9508 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9509 (delete-region beg end)
9510 (move-marker beg nil)
9511 (move-marker end nil)
9512 (insert (mapconcat 'cdr lns "\n") "\n")
9513 (goto-line thisline)
9514 (org-table-goto-column thiscol)
9515 (message "%d lines sorted, based on column %d" (length lns) column)))
9517 ;; FIXME: maybe we will not need this? Table sorting is broken....
9518 (defun org-sort-remove-invisible (s)
9519 (remove-text-properties 0 (length s) org-rm-props s)
9520 (while (string-match org-bracket-link-regexp s)
9521 (setq s (replace-match (if (match-end 2)
9522 (match-string 3 s)
9523 (match-string 1 s)) t t s)))
9526 (defun org-table-cut-region (beg end)
9527 "Copy region in table to the clipboard and blank all relevant fields."
9528 (interactive "r")
9529 (org-table-copy-region beg end 'cut))
9531 (defun org-table-copy-region (beg end &optional cut)
9532 "Copy rectangular region in table to clipboard.
9533 A special clipboard is used which can only be accessed
9534 with `org-table-paste-rectangle'."
9535 (interactive "rP")
9536 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9537 region cols
9538 (rpl (if cut " " nil)))
9539 (goto-char beg)
9540 (org-table-check-inside-data-field)
9541 (setq l01 (org-current-line)
9542 c01 (org-table-current-column))
9543 (goto-char end)
9544 (org-table-check-inside-data-field)
9545 (setq l02 (org-current-line)
9546 c02 (org-table-current-column))
9547 (setq l1 (min l01 l02) l2 (max l01 l02)
9548 c1 (min c01 c02) c2 (max c01 c02))
9549 (catch 'exit
9550 (while t
9551 (catch 'nextline
9552 (if (> l1 l2) (throw 'exit t))
9553 (goto-line l1)
9554 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9555 (setq cols nil ic1 c1 ic2 c2)
9556 (while (< ic1 (1+ ic2))
9557 (push (org-table-get-field ic1 rpl) cols)
9558 (setq ic1 (1+ ic1)))
9559 (push (nreverse cols) region)
9560 (setq l1 (1+ l1)))))
9561 (setq org-table-clip (nreverse region))
9562 (if cut (org-table-align))
9563 org-table-clip))
9565 (defun org-table-paste-rectangle ()
9566 "Paste a rectangular region into a table.
9567 The upper right corner ends up in the current field. All involved fields
9568 will be overwritten. If the rectangle does not fit into the present table,
9569 the table is enlarged as needed. The process ignores horizontal separator
9570 lines."
9571 (interactive)
9572 (unless (and org-table-clip (listp org-table-clip))
9573 (error "First cut/copy a region to paste!"))
9574 (org-table-check-inside-data-field)
9575 (let* ((clip org-table-clip)
9576 (line (org-current-line))
9577 (col (org-table-current-column))
9578 (org-enable-table-editor t)
9579 (org-table-automatic-realign nil)
9580 c cols field)
9581 (while (setq cols (pop clip))
9582 (while (org-at-table-hline-p) (beginning-of-line 2))
9583 (if (not (org-at-table-p))
9584 (progn (end-of-line 0) (org-table-next-field)))
9585 (setq c col)
9586 (while (setq field (pop cols))
9587 (org-table-goto-column c nil 'force)
9588 (org-table-get-field nil field)
9589 (setq c (1+ c)))
9590 (beginning-of-line 2))
9591 (goto-line line)
9592 (org-table-goto-column col)
9593 (org-table-align)))
9595 (defun org-table-convert ()
9596 "Convert from `org-mode' table to table.el and back.
9597 Obviously, this only works within limits. When an Org-mode table is
9598 converted to table.el, all horizontal separator lines get lost, because
9599 table.el uses these as cell boundaries and has no notion of horizontal lines.
9600 A table.el table can be converted to an Org-mode table only if it does not
9601 do row or column spanning. Multiline cells will become multiple cells.
9602 Beware, Org-mode does not test if the table can be successfully converted - it
9603 blindly applies a recipe that works for simple tables."
9604 (interactive)
9605 (require 'table)
9606 (if (org-at-table.el-p)
9607 ;; convert to Org-mode table
9608 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9609 (end (move-marker (make-marker) (org-table-end t))))
9610 (table-unrecognize-region beg end)
9611 (goto-char beg)
9612 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9613 (replace-match ""))
9614 (goto-char beg))
9615 (if (org-at-table-p)
9616 ;; convert to table.el table
9617 (let ((beg (move-marker (make-marker) (org-table-begin)))
9618 (end (move-marker (make-marker) (org-table-end))))
9619 ;; first, get rid of all horizontal lines
9620 (goto-char beg)
9621 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9622 (replace-match ""))
9623 ;; insert a hline before first
9624 (goto-char beg)
9625 (org-table-insert-hline 'above)
9626 (beginning-of-line -1)
9627 ;; insert a hline after each line
9628 (while (progn (beginning-of-line 3) (< (point) end))
9629 (org-table-insert-hline))
9630 (goto-char beg)
9631 (setq end (move-marker end (org-table-end)))
9632 ;; replace "+" at beginning and ending of hlines
9633 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9634 (replace-match "\\1+-"))
9635 (goto-char beg)
9636 (while (re-search-forward "-|[ \t]*$" end t)
9637 (replace-match "-+"))
9638 (goto-char beg)))))
9640 (defun org-table-wrap-region (arg)
9641 "Wrap several fields in a column like a paragraph.
9642 This is useful if you'd like to spread the contents of a field over several
9643 lines, in order to keep the table compact.
9645 If there is an active region, and both point and mark are in the same column,
9646 the text in the column is wrapped to minimum width for the given number of
9647 lines. Generally, this makes the table more compact. A prefix ARG may be
9648 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9649 formats the selected text to two lines. If the region was longer than two
9650 lines, the remaining lines remain empty. A negative prefix argument reduces
9651 the current number of lines by that amount. The wrapped text is pasted back
9652 into the table. If you formatted it to more lines than it was before, fields
9653 further down in the table get overwritten - so you might need to make space in
9654 the table first.
9656 If there is no region, the current field is split at the cursor position and
9657 the text fragment to the right of the cursor is prepended to the field one
9658 line down.
9660 If there is no region, but you specify a prefix ARG, the current field gets
9661 blank, and the content is appended to the field above."
9662 (interactive "P")
9663 (org-table-check-inside-data-field)
9664 (if (org-region-active-p)
9665 ;; There is a region: fill as a paragraph
9666 (let* ((beg (region-beginning))
9667 (cline (save-excursion (goto-char beg) (org-current-line)))
9668 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9669 nlines)
9670 (org-table-cut-region (region-beginning) (region-end))
9671 (if (> (length (car org-table-clip)) 1)
9672 (error "Region must be limited to single column"))
9673 (setq nlines (if arg
9674 (if (< arg 1)
9675 (+ (length org-table-clip) arg)
9676 arg)
9677 (length org-table-clip)))
9678 (setq org-table-clip
9679 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9680 nil nlines)))
9681 (goto-line cline)
9682 (org-table-goto-column ccol)
9683 (org-table-paste-rectangle))
9684 ;; No region, split the current field at point
9685 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9686 (skip-chars-forward "^\r\n|"))
9687 (if arg
9688 ;; combine with field above
9689 (let ((s (org-table-blank-field))
9690 (col (org-table-current-column)))
9691 (beginning-of-line 0)
9692 (while (org-at-table-hline-p) (beginning-of-line 0))
9693 (org-table-goto-column col)
9694 (skip-chars-forward "^|")
9695 (skip-chars-backward " ")
9696 (insert " " (org-trim s))
9697 (org-table-align))
9698 ;; split field
9699 (if (looking-at "\\([^|]+\\)+|")
9700 (let ((s (match-string 1)))
9701 (replace-match " |")
9702 (goto-char (match-beginning 0))
9703 (org-table-next-row)
9704 (insert (org-trim s) " ")
9705 (org-table-align))
9706 (org-table-next-row)))))
9708 (defvar org-field-marker nil)
9710 (defun org-table-edit-field (arg)
9711 "Edit table field in a different window.
9712 This is mainly useful for fields that contain hidden parts.
9713 When called with a \\[universal-argument] prefix, just make the full field visible so that
9714 it can be edited in place."
9715 (interactive "P")
9716 (if arg
9717 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9718 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9719 (remove-text-properties b e '(org-cwidth t invisible t
9720 display t intangible t))
9721 (if (and (boundp 'font-lock-mode) font-lock-mode)
9722 (font-lock-fontify-block)))
9723 (let ((pos (move-marker (make-marker) (point)))
9724 (field (org-table-get-field))
9725 (cw (current-window-configuration))
9727 (org-switch-to-buffer-other-window "*Org tmp*")
9728 (erase-buffer)
9729 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9730 (let ((org-inhibit-startup t)) (org-mode))
9731 (goto-char (setq p (point-max)))
9732 (insert (org-trim field))
9733 (remove-text-properties p (point-max)
9734 '(invisible t org-cwidth t display t
9735 intangible t))
9736 (goto-char p)
9737 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9738 (org-set-local 'org-window-configuration cw)
9739 (org-set-local 'org-field-marker pos)
9740 (message "Edit and finish with C-c C-c"))))
9742 (defun org-table-finish-edit-field ()
9743 "Finish editing a table data field.
9744 Remove all newline characters, insert the result into the table, realign
9745 the table and kill the editing buffer."
9746 (let ((pos org-field-marker)
9747 (cw org-window-configuration)
9748 (cb (current-buffer))
9749 text)
9750 (goto-char (point-min))
9751 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9752 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9753 (replace-match " "))
9754 (setq text (org-trim (buffer-string)))
9755 (set-window-configuration cw)
9756 (kill-buffer cb)
9757 (select-window (get-buffer-window (marker-buffer pos)))
9758 (goto-char pos)
9759 (move-marker pos nil)
9760 (org-table-check-inside-data-field)
9761 (org-table-get-field nil text)
9762 (org-table-align)
9763 (message "New field value inserted")))
9765 (defun org-trim (s)
9766 "Remove whitespace at beginning and end of string."
9767 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9768 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9771 (defun org-wrap (string &optional width lines)
9772 "Wrap string to either a number of lines, or a width in characters.
9773 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9774 that costs. If there is a word longer than WIDTH, the text is actually
9775 wrapped to the length of that word.
9776 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9777 many lines, whatever width that takes.
9778 The return value is a list of lines, without newlines at the end."
9779 (let* ((words (org-split-string string "[ \t\n]+"))
9780 (maxword (apply 'max (mapcar 'org-string-width words)))
9781 w ll)
9782 (cond (width
9783 (org-do-wrap words (max maxword width)))
9784 (lines
9785 (setq w maxword)
9786 (setq ll (org-do-wrap words maxword))
9787 (if (<= (length ll) lines)
9789 (setq ll words)
9790 (while (> (length ll) lines)
9791 (setq w (1+ w))
9792 (setq ll (org-do-wrap words w)))
9793 ll))
9794 (t (error "Cannot wrap this")))))
9797 (defun org-do-wrap (words width)
9798 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9799 (let (lines line)
9800 (while words
9801 (setq line (pop words))
9802 (while (and words (< (+ (length line) (length (car words))) width))
9803 (setq line (concat line " " (pop words))))
9804 (setq lines (push line lines)))
9805 (nreverse lines)))
9807 (defun org-split-string (string &optional separators)
9808 "Splits STRING into substrings at SEPARATORS.
9809 No empty strings are returned if there are matches at the beginning
9810 and end of string."
9811 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9812 (start 0)
9813 notfirst
9814 (list nil))
9815 (while (and (string-match rexp string
9816 (if (and notfirst
9817 (= start (match-beginning 0))
9818 (< start (length string)))
9819 (1+ start) start))
9820 (< (match-beginning 0) (length string)))
9821 (setq notfirst t)
9822 (or (eq (match-beginning 0) 0)
9823 (and (eq (match-beginning 0) (match-end 0))
9824 (eq (match-beginning 0) start))
9825 (setq list
9826 (cons (substring string start (match-beginning 0))
9827 list)))
9828 (setq start (match-end 0)))
9829 (or (eq start (length string))
9830 (setq list
9831 (cons (substring string start)
9832 list)))
9833 (nreverse list)))
9835 (defun org-table-map-tables (function)
9836 "Apply FUNCTION to the start of all tables in the buffer."
9837 (save-excursion
9838 (save-restriction
9839 (widen)
9840 (goto-char (point-min))
9841 (while (re-search-forward org-table-any-line-regexp nil t)
9842 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9843 (beginning-of-line 1)
9844 (if (looking-at org-table-line-regexp)
9845 (save-excursion (funcall function)))
9846 (re-search-forward org-table-any-border-regexp nil 1))))
9847 (message "Mapping tables: done"))
9849 (defvar org-timecnt) ; dynamically scoped parameter
9851 (defun org-table-sum (&optional beg end nlast)
9852 "Sum numbers in region of current table column.
9853 The result will be displayed in the echo area, and will be available
9854 as kill to be inserted with \\[yank].
9856 If there is an active region, it is interpreted as a rectangle and all
9857 numbers in that rectangle will be summed. If there is no active
9858 region and point is located in a table column, sum all numbers in that
9859 column.
9861 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9862 numbers are assumed to be times as well (in decimal hours) and the
9863 numbers are added as such.
9865 If NLAST is a number, only the NLAST fields will actually be summed."
9866 (interactive)
9867 (save-excursion
9868 (let (col (org-timecnt 0) diff h m s org-table-clip)
9869 (cond
9870 ((and beg end)) ; beg and end given explicitly
9871 ((org-region-active-p)
9872 (setq beg (region-beginning) end (region-end)))
9874 (setq col (org-table-current-column))
9875 (goto-char (org-table-begin))
9876 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9877 (error "No table data"))
9878 (org-table-goto-column col)
9879 (setq beg (point))
9880 (goto-char (org-table-end))
9881 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9882 (error "No table data"))
9883 (org-table-goto-column col)
9884 (setq end (point))))
9885 (let* ((items (apply 'append (org-table-copy-region beg end)))
9886 (items1 (cond ((not nlast) items)
9887 ((>= nlast (length items)) items)
9888 (t (setq items (reverse items))
9889 (setcdr (nthcdr (1- nlast) items) nil)
9890 (nreverse items))))
9891 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9892 items1)))
9893 (res (apply '+ numbers))
9894 (sres (if (= org-timecnt 0)
9895 (format "%g" res)
9896 (setq diff (* 3600 res)
9897 h (floor (/ diff 3600)) diff (mod diff 3600)
9898 m (floor (/ diff 60)) diff (mod diff 60)
9899 s diff)
9900 (format "%d:%02d:%02d" h m s))))
9901 (kill-new sres)
9902 (if (interactive-p)
9903 (message "%s"
9904 (substitute-command-keys
9905 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9906 (length numbers) sres))))
9907 sres))))
9909 (defun org-table-get-number-for-summing (s)
9910 (let (n)
9911 (if (string-match "^ *|? *" s)
9912 (setq s (replace-match "" nil nil s)))
9913 (if (string-match " *|? *$" s)
9914 (setq s (replace-match "" nil nil s)))
9915 (setq n (string-to-number s))
9916 (cond
9917 ((and (string-match "0" s)
9918 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9919 ((string-match "\\`[ \t]+\\'" s) nil)
9920 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9921 (let ((h (string-to-number (or (match-string 1 s) "0")))
9922 (m (string-to-number (or (match-string 2 s) "0")))
9923 (s (string-to-number (or (match-string 4 s) "0"))))
9924 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9925 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9926 ((equal n 0) nil)
9927 (t n))))
9929 (defun org-table-current-field-formula (&optional key noerror)
9930 "Return the formula active for the current field.
9931 Assumes that specials are in place.
9932 If KEY is given, return the key to this formula.
9933 Otherwise return the formula preceeded with \"=\" or \":=\"."
9934 (let* ((name (car (rassoc (list (org-current-line)
9935 (org-table-current-column))
9936 org-table-named-field-locations)))
9937 (col (org-table-current-column))
9938 (scol (int-to-string col))
9939 (ref (format "@%d$%d" (org-table-current-dline) col))
9940 (stored-list (org-table-get-stored-formulas noerror))
9941 (ass (or (assoc name stored-list)
9942 (assoc ref stored-list)
9943 (assoc scol stored-list))))
9944 (if key
9945 (car ass)
9946 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9947 (cdr ass))))))
9949 (defun org-table-get-formula (&optional equation named)
9950 "Read a formula from the minibuffer, offer stored formula as default.
9951 When NAMED is non-nil, look for a named equation."
9952 (let* ((stored-list (org-table-get-stored-formulas))
9953 (name (car (rassoc (list (org-current-line)
9954 (org-table-current-column))
9955 org-table-named-field-locations)))
9956 (ref (format "@%d$%d" (org-table-current-dline)
9957 (org-table-current-column)))
9958 (refass (assoc ref stored-list))
9959 (scol (if named
9960 (if name name ref)
9961 (int-to-string (org-table-current-column))))
9962 (dummy (and (or name refass) (not named)
9963 (not (y-or-n-p "Replace field formula with column formula? " ))
9964 (error "Abort")))
9965 (name (or name ref))
9966 (org-table-may-need-update nil)
9967 (stored (cdr (assoc scol stored-list)))
9968 (eq (cond
9969 ((and stored equation (string-match "^ *=? *$" equation))
9970 stored)
9971 ((stringp equation)
9972 equation)
9973 (t (org-table-formula-from-user
9974 (read-string
9975 (org-table-formula-to-user
9976 (format "%s formula %s%s="
9977 (if named "Field" "Column")
9978 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9979 scol))
9980 (if stored (org-table-formula-to-user stored) "")
9981 'org-table-formula-history
9982 )))))
9983 mustsave)
9984 (when (not (string-match "\\S-" eq))
9985 ;; remove formula
9986 (setq stored-list (delq (assoc scol stored-list) stored-list))
9987 (org-table-store-formulas stored-list)
9988 (error "Formula removed"))
9989 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9990 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9991 (if (and name (not named))
9992 ;; We set the column equation, delete the named one.
9993 (setq stored-list (delq (assoc name stored-list) stored-list)
9994 mustsave t))
9995 (if stored
9996 (setcdr (assoc scol stored-list) eq)
9997 (setq stored-list (cons (cons scol eq) stored-list)))
9998 (if (or mustsave (not (equal stored eq)))
9999 (org-table-store-formulas stored-list))
10000 eq))
10002 (defun org-table-store-formulas (alist)
10003 "Store the list of formulas below the current table."
10004 (setq alist (sort alist 'org-table-formula-less-p))
10005 (save-excursion
10006 (goto-char (org-table-end))
10007 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
10008 (progn
10009 ;; don't overwrite TBLFM, we might use text properties to store stuff
10010 (goto-char (match-beginning 2))
10011 (delete-region (match-beginning 2) (match-end 0)))
10012 (insert "#+TBLFM:"))
10013 (insert " "
10014 (mapconcat (lambda (x)
10015 (concat
10016 (if (equal (string-to-char (car x)) ?@) "" "$")
10017 (car x) "=" (cdr x)))
10018 alist "::")
10019 "\n")))
10021 (defsubst org-table-formula-make-cmp-string (a)
10022 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
10023 (concat
10024 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
10025 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
10026 (if (match-end 5) (concat "@@" (match-string 5 a))))))
10028 (defun org-table-formula-less-p (a b)
10029 "Compare two formulas for sorting."
10030 (let ((as (org-table-formula-make-cmp-string (car a)))
10031 (bs (org-table-formula-make-cmp-string (car b))))
10032 (and as bs (string< as bs))))
10034 (defun org-table-get-stored-formulas (&optional noerror)
10035 "Return an alist with the stored formulas directly after current table."
10036 (interactive)
10037 (let (scol eq eq-alist strings string seen)
10038 (save-excursion
10039 (goto-char (org-table-end))
10040 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
10041 (setq strings (org-split-string (match-string 2) " *:: *"))
10042 (while (setq string (pop strings))
10043 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
10044 (setq scol (if (match-end 2)
10045 (match-string 2 string)
10046 (match-string 1 string))
10047 eq (match-string 3 string)
10048 eq-alist (cons (cons scol eq) eq-alist))
10049 (if (member scol seen)
10050 (if noerror
10051 (progn
10052 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
10053 (ding)
10054 (sit-for 2))
10055 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
10056 (push scol seen))))))
10057 (nreverse eq-alist)))
10059 (defun org-table-fix-formulas (key replace &optional limit delta remove)
10060 "Modify the equations after the table structure has been edited.
10061 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
10062 For all numbers larger than LIMIT, shift them by DELTA."
10063 (save-excursion
10064 (goto-char (org-table-end))
10065 (when (looking-at "#\\+TBLFM:")
10066 (let ((re (concat key "\\([0-9]+\\)"))
10067 (re2
10068 (when remove
10069 (if (equal key "$")
10070 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
10071 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
10072 s n a)
10073 (when remove
10074 (while (re-search-forward re2 (point-at-eol) t)
10075 (replace-match "")))
10076 (while (re-search-forward re (point-at-eol) t)
10077 (setq s (match-string 1) n (string-to-number s))
10078 (cond
10079 ((setq a (assoc s replace))
10080 (replace-match (concat key (cdr a)) t t))
10081 ((and limit (> n limit))
10082 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
10084 (defun org-table-get-specials ()
10085 "Get the column names and local parameters for this table."
10086 (save-excursion
10087 (let ((beg (org-table-begin)) (end (org-table-end))
10088 names name fields fields1 field cnt
10089 c v l line col types dlines hlines)
10090 (setq org-table-column-names nil
10091 org-table-local-parameters nil
10092 org-table-named-field-locations nil
10093 org-table-current-begin-line nil
10094 org-table-current-begin-pos nil
10095 org-table-current-line-types nil)
10096 (goto-char beg)
10097 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10098 (setq names (org-split-string (match-string 1) " *| *")
10099 cnt 1)
10100 (while (setq name (pop names))
10101 (setq cnt (1+ cnt))
10102 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10103 (push (cons name (int-to-string cnt)) org-table-column-names))))
10104 (setq org-table-column-names (nreverse org-table-column-names))
10105 (setq org-table-column-name-regexp
10106 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10107 (goto-char beg)
10108 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10109 (setq fields (org-split-string (match-string 1) " *| *"))
10110 (while (setq field (pop fields))
10111 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10112 (push (cons (match-string 1 field) (match-string 2 field))
10113 org-table-local-parameters))))
10114 (goto-char beg)
10115 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10116 (setq c (match-string 1)
10117 fields (org-split-string (match-string 2) " *| *"))
10118 (save-excursion
10119 (beginning-of-line (if (equal c "_") 2 0))
10120 (setq line (org-current-line) col 1)
10121 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10122 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10123 (while (and fields1 (setq field (pop fields)))
10124 (setq v (pop fields1) col (1+ col))
10125 (when (and (stringp field) (stringp v)
10126 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10127 (push (cons field v) org-table-local-parameters)
10128 (push (list field line col) org-table-named-field-locations))))
10129 ;; Analyse the line types
10130 (goto-char beg)
10131 (setq org-table-current-begin-line (org-current-line)
10132 org-table-current-begin-pos (point)
10133 l org-table-current-begin-line)
10134 (while (looking-at "[ \t]*|\\(-\\)?")
10135 (push (if (match-end 1) 'hline 'dline) types)
10136 (if (match-end 1) (push l hlines) (push l dlines))
10137 (beginning-of-line 2)
10138 (setq l (1+ l)))
10139 (setq org-table-current-line-types (apply 'vector (nreverse types))
10140 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
10141 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
10143 (defun org-table-maybe-eval-formula ()
10144 "Check if the current field starts with \"=\" or \":=\".
10145 If yes, store the formula and apply it."
10146 ;; We already know we are in a table. Get field will only return a formula
10147 ;; when appropriate. It might return a separator line, but no problem.
10148 (when org-table-formula-evaluate-inline
10149 (let* ((field (org-trim (or (org-table-get-field) "")))
10150 named eq)
10151 (when (string-match "^:?=\\(.*\\)" field)
10152 (setq named (equal (string-to-char field) ?:)
10153 eq (match-string 1 field))
10154 (if (or (fboundp 'calc-eval)
10155 (equal (substring eq 0 (min 2 (length eq))) "'("))
10156 (org-table-eval-formula (if named '(4) nil)
10157 (org-table-formula-from-user eq))
10158 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10160 (defvar org-recalc-commands nil
10161 "List of commands triggering the recalculation of a line.
10162 Will be filled automatically during use.")
10164 (defvar org-recalc-marks
10165 '((" " . "Unmarked: no special line, no automatic recalculation")
10166 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10167 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10168 ("!" . "Column name definition line. Reference in formula as $name.")
10169 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10170 ("_" . "Names for values in row below this one.")
10171 ("^" . "Names for values in row above this one.")))
10173 (defun org-table-rotate-recalc-marks (&optional newchar)
10174 "Rotate the recalculation mark in the first column.
10175 If in any row, the first field is not consistent with a mark,
10176 insert a new column for the markers.
10177 When there is an active region, change all the lines in the region,
10178 after prompting for the marking character.
10179 After each change, a message will be displayed indicating the meaning
10180 of the new mark."
10181 (interactive)
10182 (unless (org-at-table-p) (error "Not at a table"))
10183 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10184 (beg (org-table-begin))
10185 (end (org-table-end))
10186 (l (org-current-line))
10187 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10188 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10189 (have-col
10190 (save-excursion
10191 (goto-char beg)
10192 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10193 (col (org-table-current-column))
10194 (forcenew (car (assoc newchar org-recalc-marks)))
10195 epos new)
10196 (when l1
10197 (message "Change region to what mark? Type # * ! $ or SPC: ")
10198 (setq newchar (char-to-string (read-char-exclusive))
10199 forcenew (car (assoc newchar org-recalc-marks))))
10200 (if (and newchar (not forcenew))
10201 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10202 newchar))
10203 (if l1 (goto-line l1))
10204 (save-excursion
10205 (beginning-of-line 1)
10206 (unless (looking-at org-table-dataline-regexp)
10207 (error "Not at a table data line")))
10208 (unless have-col
10209 (org-table-goto-column 1)
10210 (org-table-insert-column)
10211 (org-table-goto-column (1+ col)))
10212 (setq epos (point-at-eol))
10213 (save-excursion
10214 (beginning-of-line 1)
10215 (org-table-get-field
10216 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10217 (concat " "
10218 (setq new (or forcenew
10219 (cadr (member (match-string 1) marks))))
10220 " ")
10221 " # ")))
10222 (if (and l1 l2)
10223 (progn
10224 (goto-line l1)
10225 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10226 (and (looking-at org-table-dataline-regexp)
10227 (org-table-get-field 1 (concat " " new " "))))
10228 (goto-line l1)))
10229 (if (not (= epos (point-at-eol))) (org-table-align))
10230 (goto-line l)
10231 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10233 (defun org-table-maybe-recalculate-line ()
10234 "Recompute the current line if marked for it, and if we haven't just done it."
10235 (interactive)
10236 (and org-table-allow-automatic-line-recalculation
10237 (not (and (memq last-command org-recalc-commands)
10238 (equal org-last-recalc-line (org-current-line))))
10239 (save-excursion (beginning-of-line 1)
10240 (looking-at org-table-auto-recalculate-regexp))
10241 (org-table-recalculate) t))
10243 (defvar org-table-formula-debug nil
10244 "Non-nil means, debug table formulas.
10245 When nil, simply write \"#ERROR\" in corrupted fields.")
10246 (make-variable-buffer-local 'org-table-formula-debug)
10248 (defvar modes)
10249 (defsubst org-set-calc-mode (var &optional value)
10250 (if (stringp var)
10251 (setq var (assoc var '(("D" calc-angle-mode deg)
10252 ("R" calc-angle-mode rad)
10253 ("F" calc-prefer-frac t)
10254 ("S" calc-symbolic-mode t)))
10255 value (nth 2 var) var (nth 1 var)))
10256 (if (memq var modes)
10257 (setcar (cdr (memq var modes)) value)
10258 (cons var (cons value modes)))
10259 modes)
10261 (defun org-table-eval-formula (&optional arg equation
10262 suppress-align suppress-const
10263 suppress-store suppress-analysis)
10264 "Replace the table field value at the cursor by the result of a calculation.
10266 This function makes use of Dave Gillespie's Calc package, in my view the
10267 most exciting program ever written for GNU Emacs. So you need to have Calc
10268 installed in order to use this function.
10270 In a table, this command replaces the value in the current field with the
10271 result of a formula. It also installs the formula as the \"current\" column
10272 formula, by storing it in a special line below the table. When called
10273 with a `C-u' prefix, the current field must ba a named field, and the
10274 formula is installed as valid in only this specific field.
10276 When called with two `C-u' prefixes, insert the active equation
10277 for the field back into the current field, so that it can be
10278 edited there. This is useful in order to use \\[org-table-show-reference]
10279 to check the referenced fields.
10281 When called, the command first prompts for a formula, which is read in
10282 the minibuffer. Previously entered formulas are available through the
10283 history list, and the last used formula is offered as a default.
10284 These stored formulas are adapted correctly when moving, inserting, or
10285 deleting columns with the corresponding commands.
10287 The formula can be any algebraic expression understood by the Calc package.
10288 For details, see the Org-mode manual.
10290 This function can also be called from Lisp programs and offers
10291 additional arguments: EQUATION can be the formula to apply. If this
10292 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10293 used to speed-up recursive calls by by-passing unnecessary aligns.
10294 SUPPRESS-CONST suppresses the interpretation of constants in the
10295 formula, assuming that this has been done already outside the function.
10296 SUPPRESS-STORE means the formula should not be stored, either because
10297 it is already stored, or because it is a modified equation that should
10298 not overwrite the stored one."
10299 (interactive "P")
10300 (org-table-check-inside-data-field)
10301 (or suppress-analysis (org-table-get-specials))
10302 (if (equal arg '(16))
10303 (let ((eq (org-table-current-field-formula)))
10304 (or eq (error "No equation active for current field"))
10305 (org-table-get-field nil eq)
10306 (org-table-align)
10307 (setq org-table-may-need-update t))
10308 (let* (fields
10309 (ndown (if (integerp arg) arg 1))
10310 (org-table-automatic-realign nil)
10311 (case-fold-search nil)
10312 (down (> ndown 1))
10313 (formula (if (and equation suppress-store)
10314 equation
10315 (org-table-get-formula equation (equal arg '(4)))))
10316 (n0 (org-table-current-column))
10317 (modes (copy-sequence org-calc-default-modes))
10318 (numbers nil) ; was a variable, now fixed default
10319 (keep-empty nil)
10320 n form form0 bw fmt x ev orig c lispp literal)
10321 ;; Parse the format string. Since we have a lot of modes, this is
10322 ;; a lot of work. However, I think calc still uses most of the time.
10323 (if (string-match ";" formula)
10324 (let ((tmp (org-split-string formula ";")))
10325 (setq formula (car tmp)
10326 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10327 (nth 1 tmp)))
10328 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10329 (setq c (string-to-char (match-string 1 fmt))
10330 n (string-to-number (match-string 2 fmt)))
10331 (if (= c ?p)
10332 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10333 (setq modes (org-set-calc-mode
10334 'calc-float-format
10335 (list (cdr (assoc c '((?n . float) (?f . fix)
10336 (?s . sci) (?e . eng))))
10337 n))))
10338 (setq fmt (replace-match "" t t fmt)))
10339 (if (string-match "[NT]" fmt)
10340 (setq numbers (equal (match-string 0 fmt) "N")
10341 fmt (replace-match "" t t fmt)))
10342 (if (string-match "L" fmt)
10343 (setq literal t
10344 fmt (replace-match "" t t fmt)))
10345 (if (string-match "E" fmt)
10346 (setq keep-empty t
10347 fmt (replace-match "" t t fmt)))
10348 (while (string-match "[DRFS]" fmt)
10349 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10350 (setq fmt (replace-match "" t t fmt)))
10351 (unless (string-match "\\S-" fmt)
10352 (setq fmt nil))))
10353 (if (and (not suppress-const) org-table-formula-use-constants)
10354 (setq formula (org-table-formula-substitute-names formula)))
10355 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10356 (while (> ndown 0)
10357 (setq fields (org-split-string
10358 (org-no-properties
10359 (buffer-substring (point-at-bol) (point-at-eol)))
10360 " *| *"))
10361 (if (eq numbers t)
10362 (setq fields (mapcar
10363 (lambda (x) (number-to-string (string-to-number x)))
10364 fields)))
10365 (setq ndown (1- ndown))
10366 (setq form (copy-sequence formula)
10367 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10368 (if (and lispp literal) (setq lispp 'literal))
10369 ;; Check for old vertical references
10370 (setq form (org-rewrite-old-row-references form))
10371 ;; Insert complex ranges
10372 (while (string-match org-table-range-regexp form)
10373 (setq form
10374 (replace-match
10375 (save-match-data
10376 (org-table-make-reference
10377 (org-table-get-range (match-string 0 form) nil n0)
10378 keep-empty numbers lispp))
10379 t t form)))
10380 ;; Insert simple ranges
10381 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10382 (setq form
10383 (replace-match
10384 (save-match-data
10385 (org-table-make-reference
10386 (org-sublist
10387 fields (string-to-number (match-string 1 form))
10388 (string-to-number (match-string 2 form)))
10389 keep-empty numbers lispp))
10390 t t form)))
10391 (setq form0 form)
10392 ;; Insert the references to fields in same row
10393 (while (string-match "\\$\\([0-9]+\\)" form)
10394 (setq n (string-to-number (match-string 1 form))
10395 x (nth (1- (if (= n 0) n0 n)) fields))
10396 (unless x (error "Invalid field specifier \"%s\""
10397 (match-string 0 form)))
10398 (setq form (replace-match
10399 (save-match-data
10400 (org-table-make-reference x nil numbers lispp))
10401 t t form)))
10403 (if lispp
10404 (setq ev (condition-case nil
10405 (eval (eval (read form)))
10406 (error "#ERROR"))
10407 ev (if (numberp ev) (number-to-string ev) ev))
10408 (or (fboundp 'calc-eval)
10409 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10410 (setq ev (calc-eval (cons form modes)
10411 (if numbers 'num))))
10413 (when org-table-formula-debug
10414 (with-output-to-temp-buffer "*Substitution History*"
10415 (princ (format "Substitution history of formula
10416 Orig: %s
10417 $xyz-> %s
10418 @r$c-> %s
10419 $1-> %s\n" orig formula form0 form))
10420 (if (listp ev)
10421 (princ (format " %s^\nError: %s"
10422 (make-string (car ev) ?\-) (nth 1 ev)))
10423 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10424 ev (or fmt "NONE")
10425 (if fmt (format fmt (string-to-number ev)) ev)))))
10426 (setq bw (get-buffer-window "*Substitution History*"))
10427 (shrink-window-if-larger-than-buffer bw)
10428 (unless (and (interactive-p) (not ndown))
10429 (unless (let (inhibit-redisplay)
10430 (y-or-n-p "Debugging Formula. Continue to next? "))
10431 (org-table-align)
10432 (error "Abort"))
10433 (delete-window bw)
10434 (message "")))
10435 (if (listp ev) (setq fmt nil ev "#ERROR"))
10436 (org-table-justify-field-maybe
10437 (if fmt (format fmt (string-to-number ev)) ev))
10438 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10439 (call-interactively 'org-return)
10440 (setq ndown 0)))
10441 (and down (org-table-maybe-recalculate-line))
10442 (or suppress-align (and org-table-may-need-update
10443 (org-table-align))))))
10445 (defun org-table-put-field-property (prop value)
10446 (save-excursion
10447 (put-text-property (progn (skip-chars-backward "^|") (point))
10448 (progn (skip-chars-forward "^|") (point))
10449 prop value)))
10451 (defun org-table-get-range (desc &optional tbeg col highlight)
10452 "Get a calc vector from a column, accorting to descriptor DESC.
10453 Optional arguments TBEG and COL can give the beginning of the table and
10454 the current column, to avoid unnecessary parsing.
10455 HIGHLIGHT means, just highlight the range."
10456 (if (not (equal (string-to-char desc) ?@))
10457 (setq desc (concat "@" desc)))
10458 (save-excursion
10459 (or tbeg (setq tbeg (org-table-begin)))
10460 (or col (setq col (org-table-current-column)))
10461 (let ((thisline (org-current-line))
10462 beg end c1 c2 r1 r2 rangep tmp)
10463 (unless (string-match org-table-range-regexp desc)
10464 (error "Invalid table range specifier `%s'" desc))
10465 (setq rangep (match-end 3)
10466 r1 (and (match-end 1) (match-string 1 desc))
10467 r2 (and (match-end 4) (match-string 4 desc))
10468 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10469 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10471 (and c1 (setq c1 (+ (string-to-number c1)
10472 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10473 (and c2 (setq c2 (+ (string-to-number c2)
10474 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10475 (if (equal r1 "") (setq r1 nil))
10476 (if (equal r2 "") (setq r2 nil))
10477 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10478 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10479 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10480 (if (not r1) (setq r1 thisline))
10481 (if (not r2) (setq r2 thisline))
10482 (if (not c1) (setq c1 col))
10483 (if (not c2) (setq c2 col))
10484 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10485 ;; just one field
10486 (progn
10487 (goto-line r1)
10488 (while (not (looking-at org-table-dataline-regexp))
10489 (beginning-of-line 2))
10490 (prog1 (org-trim (org-table-get-field c1))
10491 (if highlight (org-table-highlight-rectangle (point) (point)))))
10492 ;; A range, return a vector
10493 ;; First sort the numbers to get a regular ractangle
10494 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10495 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10496 (goto-line r1)
10497 (while (not (looking-at org-table-dataline-regexp))
10498 (beginning-of-line 2))
10499 (org-table-goto-column c1)
10500 (setq beg (point))
10501 (goto-line r2)
10502 (while (not (looking-at org-table-dataline-regexp))
10503 (beginning-of-line 0))
10504 (org-table-goto-column c2)
10505 (setq end (point))
10506 (if highlight
10507 (org-table-highlight-rectangle
10508 beg (progn (skip-chars-forward "^|\n") (point))))
10509 ;; return string representation of calc vector
10510 (mapcar 'org-trim
10511 (apply 'append (org-table-copy-region beg end)))))))
10513 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10514 "Analyze descriptor DESC and retrieve the corresponding line number.
10515 The cursor is currently in line CLINE, the table begins in line BLINE,
10516 and TABLE is a vector with line types."
10517 (if (string-match "^[0-9]+$" desc)
10518 (aref org-table-dlines (string-to-number desc))
10519 (setq cline (or cline (org-current-line))
10520 bline (or bline org-table-current-begin-line)
10521 table (or table org-table-current-line-types))
10522 (if (or
10523 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10524 ;; 1 2 3 4 5 6
10525 (and (not (match-end 3)) (not (match-end 6)))
10526 (and (match-end 3) (match-end 6) (not (match-end 5))))
10527 (error "invalid row descriptor `%s'" desc))
10528 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10529 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10530 (odir (and (match-end 5) (match-string 5 desc)))
10531 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10532 (i (- cline bline))
10533 (rel (and (match-end 6)
10534 (or (and (match-end 1) (not (match-end 3)))
10535 (match-end 5)))))
10536 (if (and hn (not hdir))
10537 (progn
10538 (setq i 0 hdir "+")
10539 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10540 (if (and (not hn) on (not odir))
10541 (error "should never happen");;(aref org-table-dlines on)
10542 (if (and hn (> hn 0))
10543 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10544 (if on
10545 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10546 (+ bline i)))))
10548 (defun org-find-row-type (table i type backwards relative n)
10549 (let ((l (length table)))
10550 (while (> n 0)
10551 (while (and (setq i (+ i (if backwards -1 1)))
10552 (>= i 0) (< i l)
10553 (not (eq (aref table i) type))
10554 (if (and relative (eq (aref table i) 'hline))
10555 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10556 t)))
10557 (setq n (1- n)))
10558 (if (or (< i 0) (>= i l))
10559 (error "Row descriptior leads outside table")
10560 i)))
10562 (defun org-rewrite-old-row-references (s)
10563 (if (string-match "&[-+0-9I]" s)
10564 (error "Formula contains old &row reference, please rewrite using @-syntax")
10567 (defun org-table-make-reference (elements keep-empty numbers lispp)
10568 "Convert list ELEMENTS to something appropriate to insert into formula.
10569 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10570 NUMBERS indicates that everything should be converted to numbers.
10571 LISPP means to return something appropriate for a Lisp list."
10572 (if (stringp elements) ; just a single val
10573 (if lispp
10574 (if (eq lispp 'literal)
10575 elements
10576 (prin1-to-string (if numbers (string-to-number elements) elements)))
10577 (if (equal elements "") (setq elements "0"))
10578 (if numbers (number-to-string (string-to-number elements)) elements))
10579 (unless keep-empty
10580 (setq elements
10581 (delq nil
10582 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10583 elements))))
10584 (setq elements (or elements '("0")))
10585 (if lispp
10586 (mapconcat
10587 (lambda (x)
10588 (if (eq lispp 'literal)
10590 (prin1-to-string (if numbers (string-to-number x) x))))
10591 elements " ")
10592 (concat "[" (mapconcat
10593 (lambda (x)
10594 (if numbers (number-to-string (string-to-number x)) x))
10595 elements
10596 ",") "]"))))
10598 (defun org-table-recalculate (&optional all noalign)
10599 "Recalculate the current table line by applying all stored formulas.
10600 With prefix arg ALL, do this for all lines in the table."
10601 (interactive "P")
10602 (or (memq this-command org-recalc-commands)
10603 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10604 (unless (org-at-table-p) (error "Not at a table"))
10605 (if (equal all '(16))
10606 (org-table-iterate)
10607 (org-table-get-specials)
10608 (let* ((eqlist (sort (org-table-get-stored-formulas)
10609 (lambda (a b) (string< (car a) (car b)))))
10610 (inhibit-redisplay (not debug-on-error))
10611 (line-re org-table-dataline-regexp)
10612 (thisline (org-current-line))
10613 (thiscol (org-table-current-column))
10614 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10615 ;; Insert constants in all formulas
10616 (setq eqlist
10617 (mapcar (lambda (x)
10618 (setcdr x (org-table-formula-substitute-names (cdr x)))
10620 eqlist))
10621 ;; Split the equation list
10622 (while (setq eq (pop eqlist))
10623 (if (<= (string-to-char (car eq)) ?9)
10624 (push eq eqlnum)
10625 (push eq eqlname)))
10626 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10627 (if all
10628 (progn
10629 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10630 (goto-char (setq beg (org-table-begin)))
10631 (if (re-search-forward org-table-calculate-mark-regexp end t)
10632 ;; This is a table with marked lines, compute selected lines
10633 (setq line-re org-table-recalculate-regexp)
10634 ;; Move forward to the first non-header line
10635 (if (and (re-search-forward org-table-dataline-regexp end t)
10636 (re-search-forward org-table-hline-regexp end t)
10637 (re-search-forward org-table-dataline-regexp end t))
10638 (setq beg (match-beginning 0))
10639 nil))) ;; just leave beg where it is
10640 (setq beg (point-at-bol)
10641 end (move-marker (make-marker) (1+ (point-at-eol)))))
10642 (goto-char beg)
10643 (and all (message "Re-applying formulas to full table..."))
10645 ;; First find the named fields, and mark them untouchanble
10646 (remove-text-properties beg end '(org-untouchable t))
10647 (while (setq eq (pop eqlname))
10648 (setq name (car eq)
10649 a (assoc name org-table-named-field-locations))
10650 (and (not a)
10651 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10652 (setq a (list name
10653 (aref org-table-dlines
10654 (string-to-number (match-string 1 name)))
10655 (string-to-number (match-string 2 name)))))
10656 (when (and a (or all (equal (nth 1 a) thisline)))
10657 (message "Re-applying formula to field: %s" name)
10658 (goto-line (nth 1 a))
10659 (org-table-goto-column (nth 2 a))
10660 (push (append a (list (cdr eq))) eqlname1)
10661 (org-table-put-field-property :org-untouchable t)))
10663 ;; Now evauluate the column formulas, but skip fields covered by
10664 ;; field formulas
10665 (goto-char beg)
10666 (while (re-search-forward line-re end t)
10667 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10668 ;; Unprotected line, recalculate
10669 (and all (message "Re-applying formulas to full table...(line %d)"
10670 (setq cnt (1+ cnt))))
10671 (setq org-last-recalc-line (org-current-line))
10672 (setq eql eqlnum)
10673 (while (setq entry (pop eql))
10674 (goto-line org-last-recalc-line)
10675 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10676 (unless (get-text-property (point) :org-untouchable)
10677 (org-table-eval-formula nil (cdr entry)
10678 'noalign 'nocst 'nostore 'noanalysis)))))
10680 ;; Now evaluate the field formulas
10681 (while (setq eq (pop eqlname1))
10682 (message "Re-applying formula to field: %s" (car eq))
10683 (goto-line (nth 1 eq))
10684 (org-table-goto-column (nth 2 eq))
10685 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10686 'nostore 'noanalysis))
10688 (goto-line thisline)
10689 (org-table-goto-column thiscol)
10690 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10691 (or noalign (and org-table-may-need-update (org-table-align))
10692 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10694 ;; back to initial position
10695 (message "Re-applying formulas...done")
10696 (goto-line thisline)
10697 (org-table-goto-column thiscol)
10698 (or noalign (and org-table-may-need-update (org-table-align))
10699 (and all (message "Re-applying formulas...done"))))))
10701 (defun org-table-iterate (&optional arg)
10702 "Recalculate the table until it does not change anymore."
10703 (interactive "P")
10704 (let ((imax (if arg (prefix-numeric-value arg) 10))
10705 (i 0)
10706 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10707 thistbl)
10708 (catch 'exit
10709 (while (< i imax)
10710 (setq i (1+ i))
10711 (org-table-recalculate 'all)
10712 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10713 (if (not (string= lasttbl thistbl))
10714 (setq lasttbl thistbl)
10715 (if (> i 1)
10716 (message "Convergence after %d iterations" i)
10717 (message "Table was already stable"))
10718 (throw 'exit t)))
10719 (error "No convergence after %d iterations" i))))
10721 (defun org-table-formula-substitute-names (f)
10722 "Replace $const with values in string F."
10723 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10724 ;; First, check for column names
10725 (while (setq start (string-match org-table-column-name-regexp f start))
10726 (setq start (1+ start))
10727 (setq a (assoc (match-string 1 f) org-table-column-names))
10728 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10729 ;; Parameters and constants
10730 (setq start 0)
10731 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10732 (setq start (1+ start))
10733 (if (setq a (save-match-data
10734 (org-table-get-constant (match-string 1 f))))
10735 (setq f (replace-match
10736 (concat (if pp "(") a (if pp ")")) t t f))))
10737 (if org-table-formula-debug
10738 (put-text-property 0 (length f) :orig-formula f1 f))
10741 (defun org-table-get-constant (const)
10742 "Find the value for a parameter or constant in a formula.
10743 Parameters get priority."
10744 (or (cdr (assoc const org-table-local-parameters))
10745 (cdr (assoc const org-table-formula-constants-local))
10746 (cdr (assoc const org-table-formula-constants))
10747 (and (fboundp 'constants-get) (constants-get const))
10748 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10749 (org-entry-get nil (substring const 5) 'inherit))
10750 "#UNDEFINED_NAME"))
10752 (defvar org-table-fedit-map
10753 (let ((map (make-sparse-keymap)))
10754 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10755 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10756 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10757 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10758 (org-defkey map "\C-c?" 'org-table-show-reference)
10759 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10760 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10761 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10762 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10763 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10764 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10765 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10766 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10767 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10768 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10769 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10770 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10771 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10772 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10773 map))
10775 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10776 '("Edit-Formulas"
10777 ["Finish and Install" org-table-fedit-finish t]
10778 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10779 ["Abort" org-table-fedit-abort t]
10780 "--"
10781 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10782 ["Complete Lisp Symbol" lisp-complete-symbol t]
10783 "--"
10784 "Shift Reference at Point"
10785 ["Up" org-table-fedit-ref-up t]
10786 ["Down" org-table-fedit-ref-down t]
10787 ["Left" org-table-fedit-ref-left t]
10788 ["Right" org-table-fedit-ref-right t]
10790 "Change Test Row for Column Formulas"
10791 ["Up" org-table-fedit-line-up t]
10792 ["Down" org-table-fedit-line-down t]
10793 "--"
10794 ["Scroll Table Window" org-table-fedit-scroll t]
10795 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10796 ["Show Table Grid" org-table-fedit-toggle-coordinates
10797 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10798 org-table-overlay-coordinates)]
10799 "--"
10800 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10801 :style toggle :selected org-table-buffer-is-an]))
10803 (defvar org-pos)
10805 (defun org-table-edit-formulas ()
10806 "Edit the formulas of the current table in a separate buffer."
10807 (interactive)
10808 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10809 (beginning-of-line 0))
10810 (unless (org-at-table-p) (error "Not at a table"))
10811 (org-table-get-specials)
10812 (let ((key (org-table-current-field-formula 'key 'noerror))
10813 (eql (sort (org-table-get-stored-formulas 'noerror)
10814 'org-table-formula-less-p))
10815 (pos (move-marker (make-marker) (point)))
10816 (startline 1)
10817 (wc (current-window-configuration))
10818 (titles '((column . "# Column Formulas\n")
10819 (field . "# Field Formulas\n")
10820 (named . "# Named Field Formulas\n")))
10821 entry s type title)
10822 (org-switch-to-buffer-other-window "*Edit Formulas*")
10823 (erase-buffer)
10824 ;; Keep global-font-lock-mode from turning on font-lock-mode
10825 (let ((font-lock-global-modes '(not fundamental-mode)))
10826 (fundamental-mode))
10827 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10828 (org-set-local 'org-pos pos)
10829 (org-set-local 'org-window-configuration wc)
10830 (use-local-map org-table-fedit-map)
10831 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10832 (easy-menu-add org-table-fedit-menu)
10833 (setq startline (org-current-line))
10834 (while (setq entry (pop eql))
10835 (setq type (cond
10836 ((equal (string-to-char (car entry)) ?@) 'field)
10837 ((string-match "^[0-9]" (car entry)) 'column)
10838 (t 'named)))
10839 (when (setq title (assq type titles))
10840 (or (bobp) (insert "\n"))
10841 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10842 (setq titles (delq title titles)))
10843 (if (equal key (car entry)) (setq startline (org-current-line)))
10844 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10845 (car entry) " = " (cdr entry) "\n"))
10846 (remove-text-properties 0 (length s) '(face nil) s)
10847 (insert s))
10848 (if (eq org-table-use-standard-references t)
10849 (org-table-fedit-toggle-ref-type))
10850 (goto-line startline)
10851 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10853 (defun org-table-fedit-post-command ()
10854 (when (not (memq this-command '(lisp-complete-symbol)))
10855 (let ((win (selected-window)))
10856 (save-excursion
10857 (condition-case nil
10858 (org-table-show-reference)
10859 (error nil))
10860 (select-window win)))))
10862 (defun org-table-formula-to-user (s)
10863 "Convert a formula from internal to user representation."
10864 (if (eq org-table-use-standard-references t)
10865 (org-table-convert-refs-to-an s)
10868 (defun org-table-formula-from-user (s)
10869 "Convert a formula from user to internal representation."
10870 (if org-table-use-standard-references
10871 (org-table-convert-refs-to-rc s)
10874 (defun org-table-convert-refs-to-rc (s)
10875 "Convert spreadsheet references from AB7 to @7$28.
10876 Works for single references, but also for entire formulas and even the
10877 full TBLFM line."
10878 (let ((start 0))
10879 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10880 (cond
10881 ((match-end 3)
10882 ;; format match, just advance
10883 (setq start (match-end 0)))
10884 ((and (> (match-beginning 0) 0)
10885 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10886 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10887 ;; 3.e5 or something like this.
10888 (setq start (match-end 0)))
10890 (setq start (match-beginning 0)
10891 s (replace-match
10892 (if (equal (match-string 2 s) "&")
10893 (format "$%d" (org-letters-to-number (match-string 1 s)))
10894 (format "@%d$%d"
10895 (string-to-number (match-string 2 s))
10896 (org-letters-to-number (match-string 1 s))))
10897 t t s)))))
10900 (defun org-table-convert-refs-to-an (s)
10901 "Convert spreadsheet references from to @7$28 to AB7.
10902 Works for single references, but also for entire formulas and even the
10903 full TBLFM line."
10904 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10905 (setq s (replace-match
10906 (format "%s%d"
10907 (org-number-to-letters
10908 (string-to-number (match-string 2 s)))
10909 (string-to-number (match-string 1 s)))
10910 t t s)))
10911 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10912 (setq s (replace-match (concat "\\1"
10913 (org-number-to-letters
10914 (string-to-number (match-string 2 s))) "&")
10915 t nil s)))
10918 (defun org-letters-to-number (s)
10919 "Convert a base 26 number represented by letters into an integer.
10920 For example: AB -> 28."
10921 (let ((n 0))
10922 (setq s (upcase s))
10923 (while (> (length s) 0)
10924 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10925 s (substring s 1)))
10928 (defun org-number-to-letters (n)
10929 "Convert an integer into a base 26 number represented by letters.
10930 For example: 28 -> AB."
10931 (let ((s ""))
10932 (while (> n 0)
10933 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10934 n (/ (1- n) 26)))
10937 (defun org-table-fedit-convert-buffer (function)
10938 "Convert all references in this buffer, using FUNTION."
10939 (let ((line (org-current-line)))
10940 (goto-char (point-min))
10941 (while (not (eobp))
10942 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10943 (delete-region (point) (point-at-eol))
10944 (or (eobp) (forward-char 1)))
10945 (goto-line line)))
10947 (defun org-table-fedit-toggle-ref-type ()
10948 "Convert all references in the buffer from B3 to @3$2 and back."
10949 (interactive)
10950 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10951 (org-table-fedit-convert-buffer
10952 (if org-table-buffer-is-an
10953 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10954 (message "Reference type switched to %s"
10955 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10957 (defun org-table-fedit-ref-up ()
10958 "Shift the reference at point one row/hline up."
10959 (interactive)
10960 (org-table-fedit-shift-reference 'up))
10961 (defun org-table-fedit-ref-down ()
10962 "Shift the reference at point one row/hline down."
10963 (interactive)
10964 (org-table-fedit-shift-reference 'down))
10965 (defun org-table-fedit-ref-left ()
10966 "Shift the reference at point one field to the left."
10967 (interactive)
10968 (org-table-fedit-shift-reference 'left))
10969 (defun org-table-fedit-ref-right ()
10970 "Shift the reference at point one field to the right."
10971 (interactive)
10972 (org-table-fedit-shift-reference 'right))
10974 (defun org-table-fedit-shift-reference (dir)
10975 (cond
10976 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10977 (if (memq dir '(left right))
10978 (org-rematch-and-replace 1 (eq dir 'left))
10979 (error "Cannot shift reference in this direction")))
10980 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10981 ;; A B3-like reference
10982 (if (memq dir '(up down))
10983 (org-rematch-and-replace 2 (eq dir 'up))
10984 (org-rematch-and-replace 1 (eq dir 'left))))
10985 ((org-at-regexp-p
10986 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10987 ;; An internal reference
10988 (if (memq dir '(up down))
10989 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10990 (org-rematch-and-replace 5 (eq dir 'left))))))
10992 (defun org-rematch-and-replace (n &optional decr hline)
10993 "Re-match the group N, and replace it with the shifted refrence."
10994 (or (match-end n) (error "Cannot shift reference in this direction"))
10995 (goto-char (match-beginning n))
10996 (and (looking-at (regexp-quote (match-string n)))
10997 (replace-match (org-shift-refpart (match-string 0) decr hline)
10998 t t)))
11000 (defun org-shift-refpart (ref &optional decr hline)
11001 "Shift a refrence part REF.
11002 If DECR is set, decrease the references row/column, else increase.
11003 If HLINE is set, this may be a hline reference, it certainly is not
11004 a translation reference."
11005 (save-match-data
11006 (let* ((sign (string-match "^[-+]" ref)) n)
11008 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
11009 (cond
11010 ((and hline (string-match "^I+" ref))
11011 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
11012 (setq n (+ n (if decr -1 1)))
11013 (if (= n 0) (setq n (+ n (if decr -1 1))))
11014 (if sign
11015 (setq sign (if (< n 0) "-" "+") n (abs n))
11016 (setq n (max 1 n)))
11017 (concat sign (make-string n ?I)))
11019 ((string-match "^[0-9]+" ref)
11020 (setq n (string-to-number (concat sign ref)))
11021 (setq n (+ n (if decr -1 1)))
11022 (if sign
11023 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
11024 (number-to-string (max 1 n))))
11026 ((string-match "^[a-zA-Z]+" ref)
11027 (org-number-to-letters
11028 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
11030 (t (error "Cannot shift reference"))))))
11032 (defun org-table-fedit-toggle-coordinates ()
11033 "Toggle the display of coordinates in the refrenced table."
11034 (interactive)
11035 (let ((pos (marker-position org-pos)))
11036 (with-current-buffer (marker-buffer org-pos)
11037 (save-excursion
11038 (goto-char pos)
11039 (org-table-toggle-coordinate-overlays)))))
11041 (defun org-table-fedit-finish (&optional arg)
11042 "Parse the buffer for formula definitions and install them.
11043 With prefix ARG, apply the new formulas to the table."
11044 (interactive "P")
11045 (org-table-remove-rectangle-highlight)
11046 (if org-table-use-standard-references
11047 (progn
11048 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
11049 (setq org-table-buffer-is-an nil)))
11050 (let ((pos org-pos) eql var form)
11051 (goto-char (point-min))
11052 (while (re-search-forward
11053 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
11054 nil t)
11055 (setq var (if (match-end 2) (match-string 2) (match-string 1))
11056 form (match-string 3))
11057 (setq form (org-trim form))
11058 (when (not (equal form ""))
11059 (while (string-match "[ \t]*\n[ \t]*" form)
11060 (setq form (replace-match " " t t form)))
11061 (when (assoc var eql)
11062 (error "Double formulas for %s" var))
11063 (push (cons var form) eql)))
11064 (setq org-pos nil)
11065 (set-window-configuration org-window-configuration)
11066 (select-window (get-buffer-window (marker-buffer pos)))
11067 (goto-char pos)
11068 (unless (org-at-table-p)
11069 (error "Lost table position - cannot install formulae"))
11070 (org-table-store-formulas eql)
11071 (move-marker pos nil)
11072 (kill-buffer "*Edit Formulas*")
11073 (if arg
11074 (org-table-recalculate 'all)
11075 (message "New formulas installed - press C-u C-c C-c to apply."))))
11077 (defun org-table-fedit-abort ()
11078 "Abort editing formulas, without installing the changes."
11079 (interactive)
11080 (org-table-remove-rectangle-highlight)
11081 (let ((pos org-pos))
11082 (set-window-configuration org-window-configuration)
11083 (select-window (get-buffer-window (marker-buffer pos)))
11084 (goto-char pos)
11085 (move-marker pos nil)
11086 (message "Formula editing aborted without installing changes")))
11088 (defun org-table-fedit-lisp-indent ()
11089 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
11090 (interactive)
11091 (let ((pos (point)) beg end ind)
11092 (beginning-of-line 1)
11093 (cond
11094 ((looking-at "[ \t]")
11095 (goto-char pos)
11096 (call-interactively 'lisp-indent-line))
11097 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
11098 ((not (fboundp 'pp-buffer))
11099 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
11100 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
11101 (goto-char (- (match-end 0) 2))
11102 (setq beg (point))
11103 (setq ind (make-string (current-column) ?\ ))
11104 (condition-case nil (forward-sexp 1)
11105 (error
11106 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
11107 (setq end (point))
11108 (save-restriction
11109 (narrow-to-region beg end)
11110 (if (eq last-command this-command)
11111 (progn
11112 (goto-char (point-min))
11113 (setq this-command nil)
11114 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
11115 (replace-match " ")))
11116 (pp-buffer)
11117 (untabify (point-min) (point-max))
11118 (goto-char (1+ (point-min)))
11119 (while (re-search-forward "^." nil t)
11120 (beginning-of-line 1)
11121 (insert ind))
11122 (goto-char (point-max))
11123 (backward-delete-char 1)))
11124 (goto-char beg))
11125 (t nil))))
11127 (defvar org-show-positions nil)
11129 (defun org-table-show-reference (&optional local)
11130 "Show the location/value of the $ expression at point."
11131 (interactive)
11132 (org-table-remove-rectangle-highlight)
11133 (catch 'exit
11134 (let ((pos (if local (point) org-pos))
11135 (face2 'highlight)
11136 (org-inhibit-highlight-removal t)
11137 (win (selected-window))
11138 (org-show-positions nil)
11139 var name e what match dest)
11140 (if local (org-table-get-specials))
11141 (setq what (cond
11142 ((or (org-at-regexp-p org-table-range-regexp2)
11143 (org-at-regexp-p org-table-translate-regexp)
11144 (org-at-regexp-p org-table-range-regexp))
11145 (setq match
11146 (save-match-data
11147 (org-table-convert-refs-to-rc (match-string 0))))
11148 'range)
11149 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11150 ((org-at-regexp-p "\\$[0-9]+") 'column)
11151 ((not local) nil)
11152 (t (error "No reference at point")))
11153 match (and what (or match (match-string 0))))
11154 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11155 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11156 'secondary-selection))
11157 (org-add-hook 'before-change-functions
11158 'org-table-remove-rectangle-highlight)
11159 (if (eq what 'name) (setq var (substring match 1)))
11160 (when (eq what 'range)
11161 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11162 (setq match (org-table-formula-substitute-names match)))
11163 (unless local
11164 (save-excursion
11165 (end-of-line 1)
11166 (re-search-backward "^\\S-" nil t)
11167 (beginning-of-line 1)
11168 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11169 (setq dest
11170 (save-match-data
11171 (org-table-convert-refs-to-rc (match-string 1))))
11172 (org-table-add-rectangle-overlay
11173 (match-beginning 1) (match-end 1) face2))))
11174 (if (and (markerp pos) (marker-buffer pos))
11175 (if (get-buffer-window (marker-buffer pos))
11176 (select-window (get-buffer-window (marker-buffer pos)))
11177 (org-switch-to-buffer-other-window (get-buffer-window
11178 (marker-buffer pos)))))
11179 (goto-char pos)
11180 (org-table-force-dataline)
11181 (when dest
11182 (setq name (substring dest 1))
11183 (cond
11184 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11185 (setq e (assoc name org-table-named-field-locations))
11186 (goto-line (nth 1 e))
11187 (org-table-goto-column (nth 2 e)))
11188 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11189 (let ((l (string-to-number (match-string 1 dest)))
11190 (c (string-to-number (match-string 2 dest))))
11191 (goto-line (aref org-table-dlines l))
11192 (org-table-goto-column c)))
11193 (t (org-table-goto-column (string-to-number name))))
11194 (move-marker pos (point))
11195 (org-table-highlight-rectangle nil nil face2))
11196 (cond
11197 ((equal dest match))
11198 ((not match))
11199 ((eq what 'range)
11200 (condition-case nil
11201 (save-excursion
11202 (org-table-get-range match nil nil 'highlight))
11203 (error nil)))
11204 ((setq e (assoc var org-table-named-field-locations))
11205 (goto-line (nth 1 e))
11206 (org-table-goto-column (nth 2 e))
11207 (org-table-highlight-rectangle (point) (point))
11208 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11209 ((setq e (assoc var org-table-column-names))
11210 (org-table-goto-column (string-to-number (cdr e)))
11211 (org-table-highlight-rectangle (point) (point))
11212 (goto-char (org-table-begin))
11213 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11214 (org-table-end) t)
11215 (progn
11216 (goto-char (match-beginning 1))
11217 (org-table-highlight-rectangle)
11218 (message "Named column (column %s)" (cdr e)))
11219 (error "Column name not found")))
11220 ((eq what 'column)
11221 ;; column number
11222 (org-table-goto-column (string-to-number (substring match 1)))
11223 (org-table-highlight-rectangle (point) (point))
11224 (message "Column %s" (substring match 1)))
11225 ((setq e (assoc var org-table-local-parameters))
11226 (goto-char (org-table-begin))
11227 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11228 (progn
11229 (goto-char (match-beginning 1))
11230 (org-table-highlight-rectangle)
11231 (message "Local parameter."))
11232 (error "Parameter not found")))
11234 (cond
11235 ((not var) (error "No reference at point"))
11236 ((setq e (assoc var org-table-formula-constants-local))
11237 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11238 var (cdr e)))
11239 ((setq e (assoc var org-table-formula-constants))
11240 (message "Constant: $%s=%s in `org-table-formula-constants'."
11241 var (cdr e)))
11242 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11243 (message "Constant: $%s=%s, from `constants.el'%s."
11244 var e (format " (%s units)" constants-unit-system)))
11245 (t (error "Undefined name $%s" var)))))
11246 (goto-char pos)
11247 (when (and org-show-positions
11248 (not (memq this-command '(org-table-fedit-scroll
11249 org-table-fedit-scroll-down))))
11250 (push pos org-show-positions)
11251 (push org-table-current-begin-pos org-show-positions)
11252 (let ((min (apply 'min org-show-positions))
11253 (max (apply 'max org-show-positions)))
11254 (goto-char min) (recenter 0)
11255 (goto-char max)
11256 (or (pos-visible-in-window-p max) (recenter -1))))
11257 (select-window win))))
11259 (defun org-table-force-dataline ()
11260 "Make sure the cursor is in a dataline in a table."
11261 (unless (save-excursion
11262 (beginning-of-line 1)
11263 (looking-at org-table-dataline-regexp))
11264 (let* ((re org-table-dataline-regexp)
11265 (p1 (save-excursion (re-search-forward re nil 'move)))
11266 (p2 (save-excursion (re-search-backward re nil 'move))))
11267 (cond ((and p1 p2)
11268 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11269 p1 p2)))
11270 ((or p1 p2) (goto-char (or p1 p2)))
11271 (t (error "No table dataline around here"))))))
11273 (defun org-table-fedit-line-up ()
11274 "Move cursor one line up in the window showing the table."
11275 (interactive)
11276 (org-table-fedit-move 'previous-line))
11278 (defun org-table-fedit-line-down ()
11279 "Move cursor one line down in the window showing the table."
11280 (interactive)
11281 (org-table-fedit-move 'next-line))
11283 (defun org-table-fedit-move (command)
11284 "Move the cursor in the window shoinw the table.
11285 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11286 (let ((org-table-allow-automatic-line-recalculation nil)
11287 (pos org-pos) (win (selected-window)) p)
11288 (select-window (get-buffer-window (marker-buffer org-pos)))
11289 (setq p (point))
11290 (call-interactively command)
11291 (while (and (org-at-table-p)
11292 (org-at-table-hline-p))
11293 (call-interactively command))
11294 (or (org-at-table-p) (goto-char p))
11295 (move-marker pos (point))
11296 (select-window win)))
11298 (defun org-table-fedit-scroll (N)
11299 (interactive "p")
11300 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11301 (scroll-other-window N)))
11303 (defun org-table-fedit-scroll-down (N)
11304 (interactive "p")
11305 (org-table-fedit-scroll (- N)))
11307 (defvar org-table-rectangle-overlays nil)
11309 (defun org-table-add-rectangle-overlay (beg end &optional face)
11310 "Add a new overlay."
11311 (let ((ov (org-make-overlay beg end)))
11312 (org-overlay-put ov 'face (or face 'secondary-selection))
11313 (push ov org-table-rectangle-overlays)))
11315 (defun org-table-highlight-rectangle (&optional beg end face)
11316 "Highlight rectangular region in a table."
11317 (setq beg (or beg (point)) end (or end (point)))
11318 (let ((b (min beg end))
11319 (e (max beg end))
11320 l1 c1 l2 c2 tmp)
11321 (and (boundp 'org-show-positions)
11322 (setq org-show-positions (cons b (cons e org-show-positions))))
11323 (goto-char (min beg end))
11324 (setq l1 (org-current-line)
11325 c1 (org-table-current-column))
11326 (goto-char (max beg end))
11327 (setq l2 (org-current-line)
11328 c2 (org-table-current-column))
11329 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11330 (goto-line l1)
11331 (beginning-of-line 1)
11332 (loop for line from l1 to l2 do
11333 (when (looking-at org-table-dataline-regexp)
11334 (org-table-goto-column c1)
11335 (skip-chars-backward "^|\n") (setq beg (point))
11336 (org-table-goto-column c2)
11337 (skip-chars-forward "^|\n") (setq end (point))
11338 (org-table-add-rectangle-overlay beg end face))
11339 (beginning-of-line 2))
11340 (goto-char b))
11341 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11343 (defun org-table-remove-rectangle-highlight (&rest ignore)
11344 "Remove the rectangle overlays."
11345 (unless org-inhibit-highlight-removal
11346 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11347 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11348 (setq org-table-rectangle-overlays nil)))
11350 (defvar org-table-coordinate-overlays nil
11351 "Collects the cooordinate grid overlays, so that they can be removed.")
11352 (make-variable-buffer-local 'org-table-coordinate-overlays)
11354 (defun org-table-overlay-coordinates ()
11355 "Add overlays to the table at point, to show row/column coordinates."
11356 (interactive)
11357 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11358 (setq org-table-coordinate-overlays nil)
11359 (save-excursion
11360 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11361 (goto-char (org-table-begin))
11362 (while (org-at-table-p)
11363 (setq eol (point-at-eol))
11364 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11365 (push ov org-table-coordinate-overlays)
11366 (setq hline (looking-at org-table-hline-regexp))
11367 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11368 (format "%4d" (setq id (1+ id)))))
11369 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11370 (when hline
11371 (setq ic 0)
11372 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11373 (setq beg (1+ (match-beginning 0))
11374 ic (1+ ic)
11375 s1 (concat "$" (int-to-string ic))
11376 s2 (org-number-to-letters ic)
11377 str (if (eq org-table-use-standard-references t) s2 s1))
11378 (setq ov (org-make-overlay beg (+ beg (length str))))
11379 (push ov org-table-coordinate-overlays)
11380 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11381 (beginning-of-line 2)))))
11383 (defun org-table-toggle-coordinate-overlays ()
11384 "Toggle the display of Row/Column numbers in tables."
11385 (interactive)
11386 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11387 (message "Row/Column number display turned %s"
11388 (if org-table-overlay-coordinates "on" "off"))
11389 (if (and (org-at-table-p) org-table-overlay-coordinates)
11390 (org-table-align))
11391 (unless org-table-overlay-coordinates
11392 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11393 (setq org-table-coordinate-overlays nil)))
11395 (defun org-table-toggle-formula-debugger ()
11396 "Toggle the formula debugger in tables."
11397 (interactive)
11398 (setq org-table-formula-debug (not org-table-formula-debug))
11399 (message "Formula debugging has been turned %s"
11400 (if org-table-formula-debug "on" "off")))
11402 ;;; The orgtbl minor mode
11404 ;; Define a minor mode which can be used in other modes in order to
11405 ;; integrate the org-mode table editor.
11407 ;; This is really a hack, because the org-mode table editor uses several
11408 ;; keys which normally belong to the major mode, for example the TAB and
11409 ;; RET keys. Here is how it works: The minor mode defines all the keys
11410 ;; necessary to operate the table editor, but wraps the commands into a
11411 ;; function which tests if the cursor is currently inside a table. If that
11412 ;; is the case, the table editor command is executed. However, when any of
11413 ;; those keys is used outside a table, the function uses `key-binding' to
11414 ;; look up if the key has an associated command in another currently active
11415 ;; keymap (minor modes, major mode, global), and executes that command.
11416 ;; There might be problems if any of the keys used by the table editor is
11417 ;; otherwise used as a prefix key.
11419 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11420 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11421 ;; addresses this by checking explicitly for both bindings.
11423 ;; The optimized version (see variable `orgtbl-optimized') takes over
11424 ;; all keys which are bound to `self-insert-command' in the *global map*.
11425 ;; Some modes bind other commands to simple characters, for example
11426 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11427 ;; active, this binding is ignored inside tables and replaced with a
11428 ;; modified self-insert.
11430 (defvar orgtbl-mode nil
11431 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11432 table editor in arbitrary modes.")
11433 (make-variable-buffer-local 'orgtbl-mode)
11435 (defvar orgtbl-mode-map (make-keymap)
11436 "Keymap for `orgtbl-mode'.")
11438 ;;;###autoload
11439 (defun turn-on-orgtbl ()
11440 "Unconditionally turn on `orgtbl-mode'."
11441 (orgtbl-mode 1))
11443 (defvar org-old-auto-fill-inhibit-regexp nil
11444 "Local variable used by `orgtbl-mode'")
11446 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11447 "Matches a line belonging to an orgtbl.")
11449 (defconst orgtbl-extra-font-lock-keywords
11450 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11451 0 (quote 'org-table) 'prepend))
11452 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11454 ;;;###autoload
11455 (defun orgtbl-mode (&optional arg)
11456 "The `org-mode' table editor as a minor mode for use in other modes."
11457 (interactive)
11458 (if (org-mode-p)
11459 ;; Exit without error, in case some hook functions calls this
11460 ;; by accident in org-mode.
11461 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11462 (setq orgtbl-mode
11463 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11464 (if orgtbl-mode
11465 (progn
11466 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11467 ;; Make sure we are first in minor-mode-map-alist
11468 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11469 (and c (setq minor-mode-map-alist
11470 (cons c (delq c minor-mode-map-alist)))))
11471 (org-set-local (quote org-table-may-need-update) t)
11472 (org-add-hook 'before-change-functions 'org-before-change-function
11473 nil 'local)
11474 (org-set-local 'org-old-auto-fill-inhibit-regexp
11475 auto-fill-inhibit-regexp)
11476 (org-set-local 'auto-fill-inhibit-regexp
11477 (if auto-fill-inhibit-regexp
11478 (concat orgtbl-line-start-regexp "\\|"
11479 auto-fill-inhibit-regexp)
11480 orgtbl-line-start-regexp))
11481 (org-add-to-invisibility-spec '(org-cwidth))
11482 (when (fboundp 'font-lock-add-keywords)
11483 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11484 (org-restart-font-lock))
11485 (easy-menu-add orgtbl-mode-menu)
11486 (run-hooks 'orgtbl-mode-hook))
11487 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11488 (org-cleanup-narrow-column-properties)
11489 (org-remove-from-invisibility-spec '(org-cwidth))
11490 (remove-hook 'before-change-functions 'org-before-change-function t)
11491 (when (fboundp 'font-lock-remove-keywords)
11492 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11493 (org-restart-font-lock))
11494 (easy-menu-remove orgtbl-mode-menu)
11495 (force-mode-line-update 'all))))
11497 (defun org-cleanup-narrow-column-properties ()
11498 "Remove all properties related to narrow-column invisibility."
11499 (let ((s 1))
11500 (while (setq s (text-property-any s (point-max)
11501 'display org-narrow-column-arrow))
11502 (remove-text-properties s (1+ s) '(display t)))
11503 (setq s 1)
11504 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11505 (remove-text-properties s (1+ s) '(org-cwidth t)))
11506 (setq s 1)
11507 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11508 (remove-text-properties s (1+ s) '(invisible t)))))
11510 ;; Install it as a minor mode.
11511 (put 'orgtbl-mode :included t)
11512 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11513 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11515 (defun orgtbl-make-binding (fun n &rest keys)
11516 "Create a function for binding in the table minor mode.
11517 FUN is the command to call inside a table. N is used to create a unique
11518 command name. KEYS are keys that should be checked in for a command
11519 to execute outside of tables."
11520 (eval
11521 (list 'defun
11522 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11523 '(arg)
11524 (concat "In tables, run `" (symbol-name fun) "'.\n"
11525 "Outside of tables, run the binding of `"
11526 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11527 "'.")
11528 '(interactive "p")
11529 (list 'if
11530 '(org-at-table-p)
11531 (list 'call-interactively (list 'quote fun))
11532 (list 'let '(orgtbl-mode)
11533 (list 'call-interactively
11534 (append '(or)
11535 (mapcar (lambda (k)
11536 (list 'key-binding k))
11537 keys)
11538 '('orgtbl-error))))))))
11540 (defun orgtbl-error ()
11541 "Error when there is no default binding for a table key."
11542 (interactive)
11543 (error "This key has no function outside tables"))
11545 (defun orgtbl-setup ()
11546 "Setup orgtbl keymaps."
11547 (let ((nfunc 0)
11548 (bindings
11549 (list
11550 '([(meta shift left)] org-table-delete-column)
11551 '([(meta left)] org-table-move-column-left)
11552 '([(meta right)] org-table-move-column-right)
11553 '([(meta shift right)] org-table-insert-column)
11554 '([(meta shift up)] org-table-kill-row)
11555 '([(meta shift down)] org-table-insert-row)
11556 '([(meta up)] org-table-move-row-up)
11557 '([(meta down)] org-table-move-row-down)
11558 '("\C-c\C-w" org-table-cut-region)
11559 '("\C-c\M-w" org-table-copy-region)
11560 '("\C-c\C-y" org-table-paste-rectangle)
11561 '("\C-c-" org-table-insert-hline)
11562 '("\C-c}" org-table-toggle-coordinate-overlays)
11563 '("\C-c{" org-table-toggle-formula-debugger)
11564 '("\C-m" org-table-next-row)
11565 '([(shift return)] org-table-copy-down)
11566 '("\C-c\C-q" org-table-wrap-region)
11567 '("\C-c?" org-table-field-info)
11568 '("\C-c " org-table-blank-field)
11569 '("\C-c+" org-table-sum)
11570 '("\C-c=" org-table-eval-formula)
11571 '("\C-c'" org-table-edit-formulas)
11572 '("\C-c`" org-table-edit-field)
11573 '("\C-c*" org-table-recalculate)
11574 '("\C-c|" org-table-create-or-convert-from-region)
11575 '("\C-c^" org-table-sort-lines)
11576 '([(control ?#)] org-table-rotate-recalc-marks)))
11577 elt key fun cmd)
11578 (while (setq elt (pop bindings))
11579 (setq nfunc (1+ nfunc))
11580 (setq key (org-key (car elt))
11581 fun (nth 1 elt)
11582 cmd (orgtbl-make-binding fun nfunc key))
11583 (org-defkey orgtbl-mode-map key cmd))
11585 ;; Special treatment needed for TAB and RET
11586 (org-defkey orgtbl-mode-map [(return)]
11587 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11588 (org-defkey orgtbl-mode-map "\C-m"
11589 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11591 (org-defkey orgtbl-mode-map [(tab)]
11592 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11593 (org-defkey orgtbl-mode-map "\C-i"
11594 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11596 (org-defkey orgtbl-mode-map [(shift tab)]
11597 (orgtbl-make-binding 'org-table-previous-field 104
11598 [(shift tab)] [(tab)] "\C-i"))
11600 (org-defkey orgtbl-mode-map "\M-\C-m"
11601 (orgtbl-make-binding 'org-table-wrap-region 105
11602 "\M-\C-m" [(meta return)]))
11603 (org-defkey orgtbl-mode-map [(meta return)]
11604 (orgtbl-make-binding 'org-table-wrap-region 106
11605 [(meta return)] "\M-\C-m"))
11607 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11608 (when orgtbl-optimized
11609 ;; If the user wants maximum table support, we need to hijack
11610 ;; some standard editing functions
11611 (org-remap orgtbl-mode-map
11612 'self-insert-command 'orgtbl-self-insert-command
11613 'delete-char 'org-delete-char
11614 'delete-backward-char 'org-delete-backward-char)
11615 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11616 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11617 '("OrgTbl"
11618 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11619 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11620 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11621 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11622 "--"
11623 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11624 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11625 ["Copy Field from Above"
11626 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11627 "--"
11628 ("Column"
11629 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11630 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11631 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11632 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11633 ("Row"
11634 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11635 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11636 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11637 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11638 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
11639 "--"
11640 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11641 ("Rectangle"
11642 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11643 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11644 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11645 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11646 "--"
11647 ("Radio tables"
11648 ["Insert table template" orgtbl-insert-radio-table
11649 (assq major-mode orgtbl-radio-table-templates)]
11650 ["Comment/uncomment table" orgtbl-toggle-comment t])
11651 "--"
11652 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11653 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11654 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11655 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11656 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11657 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11658 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11659 ["Sum Column/Rectangle" org-table-sum
11660 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11661 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11662 ["Debug Formulas"
11663 org-table-toggle-formula-debugger :active (org-at-table-p)
11664 :keys "C-c {"
11665 :style toggle :selected org-table-formula-debug]
11666 ["Show Col/Row Numbers"
11667 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11668 :keys "C-c }"
11669 :style toggle :selected org-table-overlay-coordinates]
11673 (defun orgtbl-ctrl-c-ctrl-c (arg)
11674 "If the cursor is inside a table, realign the table.
11675 It it is a table to be sent away to a receiver, do it.
11676 With prefix arg, also recompute table."
11677 (interactive "P")
11678 (let ((pos (point)) action)
11679 (save-excursion
11680 (beginning-of-line 1)
11681 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11682 ((looking-at "[ \t]*|") pos)
11683 ((looking-at "#\\+TBLFM:") 'recalc))))
11684 (cond
11685 ((integerp action)
11686 (goto-char action)
11687 (org-table-maybe-eval-formula)
11688 (if arg
11689 (call-interactively 'org-table-recalculate)
11690 (org-table-maybe-recalculate-line))
11691 (call-interactively 'org-table-align)
11692 (orgtbl-send-table 'maybe))
11693 ((eq action 'recalc)
11694 (save-excursion
11695 (beginning-of-line 1)
11696 (skip-chars-backward " \r\n\t")
11697 (if (org-at-table-p)
11698 (org-call-with-arg 'org-table-recalculate t))))
11699 (t (let (orgtbl-mode)
11700 (call-interactively (key-binding "\C-c\C-c")))))))
11702 (defun orgtbl-tab (arg)
11703 "Justification and field motion for `orgtbl-mode'."
11704 (interactive "P")
11705 (if arg (org-table-edit-field t)
11706 (org-table-justify-field-maybe)
11707 (org-table-next-field)))
11709 (defun orgtbl-ret ()
11710 "Justification and field motion for `orgtbl-mode'."
11711 (interactive)
11712 (org-table-justify-field-maybe)
11713 (org-table-next-row))
11715 (defun orgtbl-self-insert-command (N)
11716 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11717 If the cursor is in a table looking at whitespace, the whitespace is
11718 overwritten, and the table is not marked as requiring realignment."
11719 (interactive "p")
11720 (if (and (org-at-table-p)
11722 (and org-table-auto-blank-field
11723 (member last-command
11724 '(orgtbl-hijacker-command-100
11725 orgtbl-hijacker-command-101
11726 orgtbl-hijacker-command-102
11727 orgtbl-hijacker-command-103
11728 orgtbl-hijacker-command-104
11729 orgtbl-hijacker-command-105))
11730 (org-table-blank-field))
11732 (eq N 1)
11733 (looking-at "[^|\n]* +|"))
11734 (let (org-table-may-need-update)
11735 (goto-char (1- (match-end 0)))
11736 (delete-backward-char 1)
11737 (goto-char (match-beginning 0))
11738 (self-insert-command N))
11739 (setq org-table-may-need-update t)
11740 (let (orgtbl-mode)
11741 (call-interactively (key-binding (vector last-input-event))))))
11743 (defun org-force-self-insert (N)
11744 "Needed to enforce self-insert under remapping."
11745 (interactive "p")
11746 (self-insert-command N))
11748 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11749 "Regula expression matching exponentials as produced by calc.")
11751 (defvar org-table-clean-did-remove-column nil)
11753 (defun orgtbl-export (table target)
11754 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11755 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11756 org-table-last-alignment org-table-last-column-widths
11757 maxcol column)
11758 (if (not (fboundp func))
11759 (error "Cannot export orgtbl table to %s" target))
11760 (setq lines (org-table-clean-before-export lines))
11761 (setq table
11762 (mapcar
11763 (lambda (x)
11764 (if (string-match org-table-hline-regexp x)
11765 'hline
11766 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11767 lines))
11768 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11769 table)))
11770 (loop for i from (1- maxcol) downto 0 do
11771 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11772 (setq column (delq nil column))
11773 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11774 (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))
11775 (funcall func table nil)))
11777 (defun orgtbl-send-table (&optional maybe)
11778 "Send a tranformed version of this table to the receiver position.
11779 With argument MAYBE, fail quietly if no transformation is defined for
11780 this table."
11781 (interactive)
11782 (catch 'exit
11783 (unless (org-at-table-p) (error "Not at a table"))
11784 ;; when non-interactive, we assume align has just happened.
11785 (when (interactive-p) (org-table-align))
11786 (save-excursion
11787 (goto-char (org-table-begin))
11788 (beginning-of-line 0)
11789 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11790 (if maybe
11791 (throw 'exit nil)
11792 (error "Don't know how to transform this table."))))
11793 (let* ((name (match-string 1))
11795 (transform (intern (match-string 2)))
11796 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11797 (skip (plist-get params :skip))
11798 (skipcols (plist-get params :skipcols))
11799 (txt (buffer-substring-no-properties
11800 (org-table-begin) (org-table-end)))
11801 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11802 (lines (org-table-clean-before-export lines))
11803 (i0 (if org-table-clean-did-remove-column 2 1))
11804 (table (mapcar
11805 (lambda (x)
11806 (if (string-match org-table-hline-regexp x)
11807 'hline
11808 (org-remove-by-index
11809 (org-split-string (org-trim x) "\\s-*|\\s-*")
11810 skipcols i0)))
11811 lines))
11812 (fun (if (= i0 2) 'cdr 'identity))
11813 (org-table-last-alignment
11814 (org-remove-by-index (funcall fun org-table-last-alignment)
11815 skipcols i0))
11816 (org-table-last-column-widths
11817 (org-remove-by-index (funcall fun org-table-last-column-widths)
11818 skipcols i0)))
11820 (unless (fboundp transform)
11821 (error "No such transformation function %s" transform))
11822 (setq txt (funcall transform table params))
11823 ;; Find the insertion place
11824 (save-excursion
11825 (goto-char (point-min))
11826 (unless (re-search-forward
11827 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11828 (error "Don't know where to insert translated table"))
11829 (goto-char (match-beginning 0))
11830 (beginning-of-line 2)
11831 (setq beg (point))
11832 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11833 (error "Cannot find end of insertion region"))
11834 (beginning-of-line 1)
11835 (delete-region beg (point))
11836 (goto-char beg)
11837 (insert txt "\n"))
11838 (message "Table converted and installed at receiver location"))))
11840 (defun org-remove-by-index (list indices &optional i0)
11841 "Remove the elements in LIST with indices in INDICES.
11842 First element has index 0, or I0 if given."
11843 (if (not indices)
11844 list
11845 (if (integerp indices) (setq indices (list indices)))
11846 (setq i0 (1- (or i0 0)))
11847 (delq :rm (mapcar (lambda (x)
11848 (setq i0 (1+ i0))
11849 (if (memq i0 indices) :rm x))
11850 list))))
11852 (defun orgtbl-toggle-comment ()
11853 "Comment or uncomment the orgtbl at point."
11854 (interactive)
11855 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11856 (re2 (concat "^" orgtbl-line-start-regexp))
11857 (commented (save-excursion (beginning-of-line 1)
11858 (cond ((looking-at re1) t)
11859 ((looking-at re2) nil)
11860 (t (error "Not at an org table")))))
11861 (re (if commented re1 re2))
11862 beg end)
11863 (save-excursion
11864 (beginning-of-line 1)
11865 (while (looking-at re) (beginning-of-line 0))
11866 (beginning-of-line 2)
11867 (setq beg (point))
11868 (while (looking-at re) (beginning-of-line 2))
11869 (setq end (point)))
11870 (comment-region beg end (if commented '(4) nil))))
11872 (defun orgtbl-insert-radio-table ()
11873 "Insert a radio table template appropriate for this major mode."
11874 (interactive)
11875 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11876 (txt (nth 1 e))
11877 name pos)
11878 (unless e (error "No radio table setup defined for %s" major-mode))
11879 (setq name (read-string "Table name: "))
11880 (while (string-match "%n" txt)
11881 (setq txt (replace-match name t t txt)))
11882 (or (bolp) (insert "\n"))
11883 (setq pos (point))
11884 (insert txt)
11885 (goto-char pos)))
11887 (defun org-get-param (params header i sym &optional hsym)
11888 "Get parameter value for symbol SYM.
11889 If this is a header line, actually get the value for the symbol with an
11890 additional \"h\" inserted after the colon.
11891 If the value is a protperty list, get the element for the current column.
11892 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11893 (let ((val (plist-get params sym)))
11894 (and hsym header (setq val (or (plist-get params hsym) val)))
11895 (if (consp val) (plist-get val i) val)))
11897 (defun orgtbl-to-generic (table params)
11898 "Convert the orgtbl-mode TABLE to some other format.
11899 This generic routine can be used for many standard cases.
11900 TABLE is a list, each entry either the symbol `hline' for a horizontal
11901 separator line, or a list of fields for that line.
11902 PARAMS is a property list of parameters that can influence the conversion.
11903 For the generic converter, some parameters are obligatory: You need to
11904 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11905 :splice, you must have :tstart and :tend.
11907 Valid parameters are
11909 :tstart String to start the table. Ignored when :splice is t.
11910 :tend String to end the table. Ignored when :splice is t.
11912 :splice When set to t, return only table body lines, don't wrap
11913 them into :tstart and :tend. Default is nil.
11915 :hline String to be inserted on horizontal separation lines.
11916 May be nil to ignore hlines.
11918 :lstart String to start a new table line.
11919 :lend String to end a table line
11920 :sep Separator between two fields
11921 :lfmt Format for entire line, with enough %s to capture all fields.
11922 If this is present, :lstart, :lend, and :sep are ignored.
11923 :fmt A format to be used to wrap the field, should contain
11924 %s for the original field value. For example, to wrap
11925 everything in dollars, you could use :fmt \"$%s$\".
11926 This may also be a property list with column numbers and
11927 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11929 :hlstart :hlend :hlsep :hlfmt :hfmt
11930 Same as above, specific for the header lines in the table.
11931 All lines before the first hline are treated as header.
11932 If any of these is not present, the data line value is used.
11934 :efmt Use this format to print numbers with exponentials.
11935 The format should have %s twice for inserting mantissa
11936 and exponent, for example \"%s\\\\times10^{%s}\". This
11937 may also be a property list with column numbers and
11938 formats. :fmt will still be applied after :efmt.
11940 In addition to this, the parameters :skip and :skipcols are always handled
11941 directly by `orgtbl-send-table'. See manual."
11942 (interactive)
11943 (let* ((p params)
11944 (splicep (plist-get p :splice))
11945 (hline (plist-get p :hline))
11946 rtn line i fm efm lfmt h)
11948 ;; Do we have a header?
11949 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11950 (setq h t))
11952 ;; Put header
11953 (unless splicep
11954 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11956 ;; Now loop over all lines
11957 (while (setq line (pop table))
11958 (if (eq line 'hline)
11959 ;; A horizontal separator line
11960 (progn (if hline (push hline rtn))
11961 (setq h nil)) ; no longer in header
11962 ;; A normal line. Convert the fields, push line onto the result list
11963 (setq i 0)
11964 (setq line
11965 (mapcar
11966 (lambda (f)
11967 (setq i (1+ i)
11968 fm (org-get-param p h i :fmt :hfmt)
11969 efm (org-get-param p h i :efmt))
11970 (if (and efm (string-match orgtbl-exp-regexp f))
11971 (setq f (format
11972 efm (match-string 1 f) (match-string 2 f))))
11973 (if fm (setq f (format fm f)))
11975 line))
11976 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11977 (push (apply 'format lfmt line) rtn)
11978 (push (concat
11979 (org-get-param p h i :lstart :hlstart)
11980 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11981 (org-get-param p h i :lend :hlend))
11982 rtn))))
11984 (unless splicep
11985 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11987 (mapconcat 'identity (nreverse rtn) "\n")))
11989 (defun orgtbl-to-latex (table params)
11990 "Convert the orgtbl-mode TABLE to LaTeX.
11991 TABLE is a list, each entry either the symbol `hline' for a horizontal
11992 separator line, or a list of fields for that line.
11993 PARAMS is a property list of parameters that can influence the conversion.
11994 Supports all parameters from `orgtbl-to-generic'. Most important for
11995 LaTeX are:
11997 :splice When set to t, return only table body lines, don't wrap
11998 them into a tabular environment. Default is nil.
12000 :fmt A format to be used to wrap the field, should contain %s for the
12001 original field value. For example, to wrap everything in dollars,
12002 use :fmt \"$%s$\". This may also be a property list with column
12003 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
12005 :efmt Format for transforming numbers with exponentials. The format
12006 should have %s twice for inserting mantissa and exponent, for
12007 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
12008 This may also be a property list with column numbers and formats.
12010 The general parameters :skip and :skipcols have already been applied when
12011 this function is called."
12012 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
12013 org-table-last-alignment ""))
12014 (params2
12015 (list
12016 :tstart (concat "\\begin{tabular}{" alignment "}")
12017 :tend "\\end{tabular}"
12018 :lstart "" :lend " \\\\" :sep " & "
12019 :efmt "%s\\,(%s)" :hline "\\hline")))
12020 (orgtbl-to-generic table (org-combine-plists params2 params))))
12022 (defun orgtbl-to-html (table params)
12023 "Convert the orgtbl-mode TABLE to LaTeX.
12024 TABLE is a list, each entry either the symbol `hline' for a horizontal
12025 separator line, or a list of fields for that line.
12026 PARAMS is a property list of parameters that can influence the conversion.
12027 Currently this function recognizes the following parameters:
12029 :splice When set to t, return only table body lines, don't wrap
12030 them into a <table> environment. Default is nil.
12032 The general parameters :skip and :skipcols have already been applied when
12033 this function is called. The function does *not* use `orgtbl-to-generic',
12034 so you cannot specify parameters for it."
12035 (let* ((splicep (plist-get params :splice))
12036 html)
12037 ;; Just call the formatter we already have
12038 ;; We need to make text lines for it, so put the fields back together.
12039 (setq html (org-format-org-table-html
12040 (mapcar
12041 (lambda (x)
12042 (if (eq x 'hline)
12043 "|----+----|"
12044 (concat "| " (mapconcat 'identity x " | ") " |")))
12045 table)
12046 splicep))
12047 (if (string-match "\n+\\'" html)
12048 (setq html (replace-match "" t t html)))
12049 html))
12051 (defun orgtbl-to-texinfo (table params)
12052 "Convert the orgtbl-mode TABLE to TeXInfo.
12053 TABLE is a list, each entry either the symbol `hline' for a horizontal
12054 separator line, or a list of fields for that line.
12055 PARAMS is a property list of parameters that can influence the conversion.
12056 Supports all parameters from `orgtbl-to-generic'. Most important for
12057 TeXInfo are:
12059 :splice nil/t When set to t, return only table body lines, don't wrap
12060 them into a multitable environment. Default is nil.
12062 :fmt fmt A format to be used to wrap the field, should contain
12063 %s for the original field value. For example, to wrap
12064 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
12065 This may also be a property list with column numbers and
12066 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
12068 :cf \"f1 f2..\" The column fractions for the table. By default these
12069 are computed automatically from the width of the columns
12070 under org-mode.
12072 The general parameters :skip and :skipcols have already been applied when
12073 this function is called."
12074 (let* ((total (float (apply '+ org-table-last-column-widths)))
12075 (colfrac (or (plist-get params :cf)
12076 (mapconcat
12077 (lambda (x) (format "%.3f" (/ (float x) total)))
12078 org-table-last-column-widths " ")))
12079 (params2
12080 (list
12081 :tstart (concat "@multitable @columnfractions " colfrac)
12082 :tend "@end multitable"
12083 :lstart "@item " :lend "" :sep " @tab "
12084 :hlstart "@headitem ")))
12085 (orgtbl-to-generic table (org-combine-plists params2 params))))
12087 ;;;; Link Stuff
12089 ;;; Link abbreviations
12091 (defun org-link-expand-abbrev (link)
12092 "Apply replacements as defined in `org-link-abbrev-alist."
12093 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
12094 (let* ((key (match-string 1 link))
12095 (as (or (assoc key org-link-abbrev-alist-local)
12096 (assoc key org-link-abbrev-alist)))
12097 (tag (and (match-end 2) (match-string 3 link)))
12098 rpl)
12099 (if (not as)
12100 link
12101 (setq rpl (cdr as))
12102 (cond
12103 ((symbolp rpl) (funcall rpl tag))
12104 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
12105 (t (concat rpl tag)))))
12106 link))
12108 ;;; Storing and inserting links
12110 (defvar org-insert-link-history nil
12111 "Minibuffer history for links inserted with `org-insert-link'.")
12113 (defvar org-stored-links nil
12114 "Contains the links stored with `org-store-link'.")
12116 (defvar org-store-link-plist nil
12117 "Plist with info about the most recently link created with `org-store-link'.")
12119 (defvar org-link-protocols nil
12120 "Link protocols added to Org-mode using `org-add-link-type'.")
12122 (defvar org-store-link-functions nil
12123 "List of functions that are called to create and store a link.
12124 Each function will be called in turn until one returns a non-nil
12125 value. Each function should check if it is responsible for creating
12126 this link (for example by looking at the major mode).
12127 If not, it must exit and return nil.
12128 If yes, it should return a non-nil value after a calling
12129 `org-store-link-props' with a list of properties and values.
12130 Special properties are:
12132 :type The link prefix. like \"http\". This must be given.
12133 :link The link, like \"http://www.astro.uva.nl/~dominik\".
12134 This is obligatory as well.
12135 :description Optional default description for the second pair
12136 of brackets in an Org-mode link. The user can still change
12137 this when inserting this link into an Org-mode buffer.
12139 In addition to these, any additional properties can be specified
12140 and then used in remember templates.")
12142 (defun org-add-link-type (type &optional follow publish)
12143 "Add TYPE to the list of `org-link-types'.
12144 Re-compute all regular expressions depending on `org-link-types'
12145 FOLLOW and PUBLISH are two functions. Both take the link path as
12146 an argument.
12147 FOLLOW should do whatever is necessary to follow the link, for example
12148 to find a file or display a mail message.
12150 PUBLISH takes the path and retuns the string that should be used when
12151 this document is published. FIMXE: This is actually not yet implemented."
12152 (add-to-list 'org-link-types type t)
12153 (org-make-link-regexps)
12154 (add-to-list 'org-link-protocols
12155 (list type follow publish)))
12157 (defun org-add-agenda-custom-command (entry)
12158 "Replace or add a command in `org-agenda-custom-commands'.
12159 This is mostly for hacking and trying a new command - once the command
12160 works you probably want to add it to `org-agenda-custom-commands' for good."
12161 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12162 (if ass
12163 (setcdr ass (cdr entry))
12164 (push entry org-agenda-custom-commands))))
12166 ;;;###autoload
12167 (defun org-store-link (arg)
12168 "\\<org-mode-map>Store an org-link to the current location.
12169 This link is added to `org-stored-links' and can later be inserted
12170 into an org-buffer with \\[org-insert-link].
12172 For some link types, a prefix arg is interpreted:
12173 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12174 For file links, arg negates `org-context-in-file-links'."
12175 (interactive "P")
12176 (setq org-store-link-plist nil) ; reset
12177 (let (link cpltxt desc description search txt)
12178 (cond
12180 ((run-hook-with-args-until-success 'org-store-link-functions)
12181 (setq link (plist-get org-store-link-plist :link)
12182 desc (or (plist-get org-store-link-plist :description) link)))
12184 ((eq major-mode 'bbdb-mode)
12185 (let ((name (bbdb-record-name (bbdb-current-record)))
12186 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
12187 (setq cpltxt (concat "bbdb:" (or name company))
12188 link (org-make-link cpltxt))
12189 (org-store-link-props :type "bbdb" :name name :company company)))
12191 ((eq major-mode 'Info-mode)
12192 (setq link (org-make-link "info:"
12193 (file-name-nondirectory Info-current-file)
12194 ":" Info-current-node))
12195 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
12196 ":" Info-current-node))
12197 (org-store-link-props :type "info" :file Info-current-file
12198 :node Info-current-node))
12200 ((eq major-mode 'calendar-mode)
12201 (let ((cd (calendar-cursor-to-date)))
12202 (setq link
12203 (format-time-string
12204 (car org-time-stamp-formats)
12205 (apply 'encode-time
12206 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12207 nil nil nil))))
12208 (org-store-link-props :type "calendar" :date cd)))
12210 ((or (eq major-mode 'vm-summary-mode)
12211 (eq major-mode 'vm-presentation-mode))
12212 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
12213 (vm-follow-summary-cursor)
12214 (save-excursion
12215 (vm-select-folder-buffer)
12216 (let* ((message (car vm-message-pointer))
12217 (folder buffer-file-name)
12218 (subject (vm-su-subject message))
12219 (to (vm-get-header-contents message "To"))
12220 (from (vm-get-header-contents message "From"))
12221 (message-id (vm-su-message-id message)))
12222 (org-store-link-props :type "vm" :from from :to to :subject subject
12223 :message-id message-id)
12224 (setq message-id (org-remove-angle-brackets message-id))
12225 (setq folder (abbreviate-file-name folder))
12226 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
12227 folder)
12228 (setq folder (replace-match "" t t folder)))
12229 (setq cpltxt (org-email-link-description))
12230 (setq link (org-make-link "vm:" folder "#" message-id)))))
12232 ((eq major-mode 'wl-summary-mode)
12233 (let* ((msgnum (wl-summary-message-number))
12234 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
12235 msgnum 'message-id))
12236 (wl-message-entity
12237 (if (fboundp 'elmo-message-entity)
12238 (elmo-message-entity
12239 wl-summary-buffer-elmo-folder msgnum)
12240 (elmo-msgdb-overview-get-entity
12241 msgnum (wl-summary-buffer-msgdb))))
12242 (from (wl-summary-line-from))
12243 (to (car (elmo-message-entity-field wl-message-entity 'to)))
12244 (subject (let (wl-thr-indent-string wl-parent-message-entity)
12245 (wl-summary-line-subject))))
12246 (org-store-link-props :type "wl" :from from :to to
12247 :subject subject :message-id message-id)
12248 (setq message-id (org-remove-angle-brackets message-id))
12249 (setq cpltxt (org-email-link-description))
12250 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
12251 "#" message-id))))
12253 ((or (equal major-mode 'mh-folder-mode)
12254 (equal major-mode 'mh-show-mode))
12255 (let ((from (org-mhe-get-header "From:"))
12256 (to (org-mhe-get-header "To:"))
12257 (message-id (org-mhe-get-header "Message-Id:"))
12258 (subject (org-mhe-get-header "Subject:")))
12259 (org-store-link-props :type "mh" :from from :to to
12260 :subject subject :message-id message-id)
12261 (setq cpltxt (org-email-link-description))
12262 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
12263 (org-remove-angle-brackets message-id)))))
12265 ((or (eq major-mode 'rmail-mode)
12266 (eq major-mode 'rmail-summary-mode))
12267 (save-window-excursion
12268 (save-restriction
12269 (when (eq major-mode 'rmail-summary-mode)
12270 (rmail-show-message rmail-current-message))
12271 (rmail-narrow-to-non-pruned-header)
12272 (let ((folder buffer-file-name)
12273 (message-id (mail-fetch-field "message-id"))
12274 (from (mail-fetch-field "from"))
12275 (to (mail-fetch-field "to"))
12276 (subject (mail-fetch-field "subject")))
12277 (org-store-link-props
12278 :type "rmail" :from from :to to
12279 :subject subject :message-id message-id)
12280 (setq message-id (org-remove-angle-brackets message-id))
12281 (setq cpltxt (org-email-link-description))
12282 (setq link (org-make-link "rmail:" folder "#" message-id)))
12283 (rmail-show-message rmail-current-message))))
12285 ((eq major-mode 'gnus-group-mode)
12286 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12287 (gnus-group-group-name)) ; version
12288 ((fboundp 'gnus-group-name)
12289 (gnus-group-name))
12290 (t "???"))))
12291 (unless group (error "Not on a group"))
12292 (org-store-link-props :type "gnus" :group group)
12293 (setq cpltxt (concat
12294 (if (org-xor arg org-usenet-links-prefer-google)
12295 "http://groups.google.com/groups?group="
12296 "gnus:")
12297 group)
12298 link (org-make-link cpltxt))))
12300 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12301 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12302 (let* ((group gnus-newsgroup-name)
12303 (article (gnus-summary-article-number))
12304 (header (gnus-summary-article-header article))
12305 (from (mail-header-from header))
12306 (message-id (mail-header-id header))
12307 (date (mail-header-date header))
12308 (subject (gnus-summary-subject-string)))
12309 (org-store-link-props :type "gnus" :from from :subject subject
12310 :message-id message-id :group group)
12311 (setq cpltxt (org-email-link-description))
12312 (if (org-xor arg org-usenet-links-prefer-google)
12313 (setq link
12314 (concat
12315 cpltxt "\n "
12316 (format "http://groups.google.com/groups?as_umsgid=%s"
12317 (org-fixup-message-id-for-http message-id))))
12318 (setq link (org-make-link "gnus:" group
12319 "#" (number-to-string article))))))
12321 ((eq major-mode 'w3-mode)
12322 (setq cpltxt (url-view-url t)
12323 link (org-make-link cpltxt))
12324 (org-store-link-props :type "w3" :url (url-view-url t)))
12326 ((eq major-mode 'w3m-mode)
12327 (setq cpltxt (or w3m-current-title w3m-current-url)
12328 link (org-make-link w3m-current-url))
12329 (org-store-link-props :type "w3m" :url (url-view-url t)))
12331 ((setq search (run-hook-with-args-until-success
12332 'org-create-file-search-functions))
12333 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12334 "::" search))
12335 (setq cpltxt (or description link)))
12337 ((eq major-mode 'image-mode)
12338 (setq cpltxt (concat "file:"
12339 (abbreviate-file-name buffer-file-name))
12340 link (org-make-link cpltxt))
12341 (org-store-link-props :type "image" :file buffer-file-name))
12343 ((eq major-mode 'dired-mode)
12344 ;; link to the file in the current line
12345 (setq cpltxt (concat "file:"
12346 (abbreviate-file-name
12347 (expand-file-name
12348 (dired-get-filename nil t))))
12349 link (org-make-link cpltxt)))
12351 ((and buffer-file-name (org-mode-p))
12352 ;; Just link to current headline
12353 (setq cpltxt (concat "file:"
12354 (abbreviate-file-name buffer-file-name)))
12355 ;; Add a context search string
12356 (when (org-xor org-context-in-file-links arg)
12357 ;; Check if we are on a target
12358 (if (org-in-regexp "<<\\(.*?\\)>>")
12359 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12360 (setq txt (cond
12361 ((org-on-heading-p) nil)
12362 ((org-region-active-p)
12363 (buffer-substring (region-beginning) (region-end)))
12364 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12365 (when (or (null txt) (string-match "\\S-" txt))
12366 (setq cpltxt
12367 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12368 desc "NONE"))))
12369 (if (string-match "::\\'" cpltxt)
12370 (setq cpltxt (substring cpltxt 0 -2)))
12371 (setq link (org-make-link cpltxt)))
12373 ((buffer-file-name (buffer-base-buffer))
12374 ;; Just link to this file here.
12375 (setq cpltxt (concat "file:"
12376 (abbreviate-file-name
12377 (buffer-file-name (buffer-base-buffer)))))
12378 ;; Add a context string
12379 (when (org-xor org-context-in-file-links arg)
12380 (setq txt (if (org-region-active-p)
12381 (buffer-substring (region-beginning) (region-end))
12382 (buffer-substring (point-at-bol) (point-at-eol))))
12383 ;; Only use search option if there is some text.
12384 (when (string-match "\\S-" txt)
12385 (setq cpltxt
12386 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12387 desc "NONE")))
12388 (setq link (org-make-link cpltxt)))
12390 ((interactive-p)
12391 (error "Cannot link to a buffer which is not visiting a file"))
12393 (t (setq link nil)))
12395 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12396 (setq link (or link cpltxt)
12397 desc (or desc cpltxt))
12398 (if (equal desc "NONE") (setq desc nil))
12400 (if (and (interactive-p) link)
12401 (progn
12402 (setq org-stored-links
12403 (cons (list link desc) org-stored-links))
12404 (message "Stored: %s" (or desc link)))
12405 (and link (org-make-link-string link desc)))))
12407 (defun org-store-link-props (&rest plist)
12408 "Store link properties, extract names and addresses."
12409 (let (x adr)
12410 (when (setq x (plist-get plist :from))
12411 (setq adr (mail-extract-address-components x))
12412 (plist-put plist :fromname (car adr))
12413 (plist-put plist :fromaddress (nth 1 adr)))
12414 (when (setq x (plist-get plist :to))
12415 (setq adr (mail-extract-address-components x))
12416 (plist-put plist :toname (car adr))
12417 (plist-put plist :toaddress (nth 1 adr))))
12418 (let ((from (plist-get plist :from))
12419 (to (plist-get plist :to)))
12420 (when (and from to org-from-is-user-regexp)
12421 (plist-put plist :fromto
12422 (if (string-match org-from-is-user-regexp from)
12423 (concat "to %t")
12424 (concat "from %f")))))
12425 (setq org-store-link-plist plist))
12427 (defun org-email-link-description (&optional fmt)
12428 "Return the description part of an email link.
12429 This takes information from `org-store-link-plist' and formats it
12430 according to FMT (default from `org-email-link-description-format')."
12431 (setq fmt (or fmt org-email-link-description-format))
12432 (let* ((p org-store-link-plist)
12433 (to (plist-get p :toaddress))
12434 (from (plist-get p :fromaddress))
12435 (table
12436 (list
12437 (cons "%c" (plist-get p :fromto))
12438 (cons "%F" (plist-get p :from))
12439 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12440 (cons "%T" (plist-get p :to))
12441 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12442 (cons "%s" (plist-get p :subject))
12443 (cons "%m" (plist-get p :message-id)))))
12444 (when (string-match "%c" fmt)
12445 ;; Check if the user wrote this message
12446 (if (and org-from-is-user-regexp from to
12447 (save-match-data (string-match org-from-is-user-regexp from)))
12448 (setq fmt (replace-match "to %t" t t fmt))
12449 (setq fmt (replace-match "from %f" t t fmt))))
12450 (org-replace-escapes fmt table)))
12452 (defun org-make-org-heading-search-string (&optional string heading)
12453 "Make search string for STRING or current headline."
12454 (interactive)
12455 (let ((s (or string (org-get-heading))))
12456 (unless (and string (not heading))
12457 ;; We are using a headline, clean up garbage in there.
12458 (if (string-match org-todo-regexp s)
12459 (setq s (replace-match "" t t s)))
12460 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12461 (setq s (replace-match "" t t s)))
12462 (setq s (org-trim s))
12463 (if (string-match (concat "^\\(" org-quote-string "\\|"
12464 org-comment-string "\\)") s)
12465 (setq s (replace-match "" t t s)))
12466 (while (string-match org-ts-regexp s)
12467 (setq s (replace-match "" t t s))))
12468 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12469 (setq s (replace-match " " t t s)))
12470 (or string (setq s (concat "*" s))) ; Add * for headlines
12471 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12473 (defun org-make-link (&rest strings)
12474 "Concatenate STRINGS."
12475 (apply 'concat strings))
12477 (defun org-make-link-string (link &optional description)
12478 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12479 (unless (string-match "\\S-" link)
12480 (error "Empty link"))
12481 (when (stringp description)
12482 ;; Remove brackets from the description, they are fatal.
12483 (while (string-match "\\[" description)
12484 (setq description (replace-match "{" t t description)))
12485 (while (string-match "\\]" description)
12486 (setq description (replace-match "}" t t description))))
12487 (when (equal (org-link-escape link) description)
12488 ;; No description needed, it is identical
12489 (setq description nil))
12490 (when (and (not description)
12491 (not (equal link (org-link-escape link))))
12492 (setq description link))
12493 (concat "[[" (org-link-escape link) "]"
12494 (if description (concat "[" description "]") "")
12495 "]"))
12497 (defconst org-link-escape-chars
12498 '((?\ . "%20")
12499 (?\[ . "%5B")
12500 (?\] . "%5D")
12501 (?\340 . "%E0") ; `a
12502 (?\342 . "%E2") ; ^a
12503 (?\347 . "%E7") ; ,c
12504 (?\350 . "%E8") ; `e
12505 (?\351 . "%E9") ; 'e
12506 (?\352 . "%EA") ; ^e
12507 (?\356 . "%EE") ; ^i
12508 (?\364 . "%F4") ; ^o
12509 (?\371 . "%F9") ; `u
12510 (?\373 . "%FB") ; ^u
12511 (?\; . "%3B")
12512 (?? . "%3F")
12513 (?= . "%3D")
12514 (?+ . "%2B")
12516 "Association list of escapes for some characters problematic in links.
12517 This is the list that is used for internal purposes.")
12519 (defconst org-link-escape-chars-browser
12520 '((?\ . "%20")) ; 32 for the SPC char
12521 "Association list of escapes for some characters problematic in links.
12522 This is the list that is used before handing over to the browser.")
12524 (defun org-link-escape (text &optional table)
12525 "Escape charaters in TEXT that are problematic for links."
12526 (setq table (or table org-link-escape-chars))
12527 (when text
12528 (let ((re (mapconcat (lambda (x) (regexp-quote
12529 (char-to-string (car x))))
12530 table "\\|")))
12531 (while (string-match re text)
12532 (setq text
12533 (replace-match
12534 (cdr (assoc (string-to-char (match-string 0 text))
12535 table))
12536 t t text)))
12537 text)))
12539 (defun org-link-unescape (text &optional table)
12540 "Reverse the action of `org-link-escape'."
12541 (setq table (or table org-link-escape-chars))
12542 (when text
12543 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12544 table "\\|")))
12545 (while (string-match re text)
12546 (setq text
12547 (replace-match
12548 (char-to-string (car (rassoc (match-string 0 text) table)))
12549 t t text)))
12550 text)))
12552 (defun org-xor (a b)
12553 "Exclusive or."
12554 (if a (not b) b))
12556 (defun org-get-header (header)
12557 "Find a header field in the current buffer."
12558 (save-excursion
12559 (goto-char (point-min))
12560 (let ((case-fold-search t) s)
12561 (cond
12562 ((eq header 'from)
12563 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12564 (setq s (match-string 1)))
12565 (while (string-match "\"" s)
12566 (setq s (replace-match "" t t s)))
12567 (if (string-match "[<(].*" s)
12568 (setq s (replace-match "" t t s))))
12569 ((eq header 'message-id)
12570 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12571 (setq s (match-string 1))))
12572 ((eq header 'subject)
12573 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12574 (setq s (match-string 1)))))
12575 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12576 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12577 s)))
12580 (defun org-fixup-message-id-for-http (s)
12581 "Replace special characters in a message id, so it can be used in an http query."
12582 (while (string-match "<" s)
12583 (setq s (replace-match "%3C" t t s)))
12584 (while (string-match ">" s)
12585 (setq s (replace-match "%3E" t t s)))
12586 (while (string-match "@" s)
12587 (setq s (replace-match "%40" t t s)))
12590 ;;;###autoload
12591 (defun org-insert-link-global ()
12592 "Insert a link like Org-mode does.
12593 This command can be called in any mode to insert a link in Org-mode syntax."
12594 (interactive)
12595 (org-run-like-in-org-mode 'org-insert-link))
12597 (defun org-insert-link (&optional complete-file)
12598 "Insert a link. At the prompt, enter the link.
12600 Completion can be used to select a link previously stored with
12601 `org-store-link'. When the empty string is entered (i.e. if you just
12602 press RET at the prompt), the link defaults to the most recently
12603 stored link. As SPC triggers completion in the minibuffer, you need to
12604 use M-SPC or C-q SPC to force the insertion of a space character.
12606 You will also be prompted for a description, and if one is given, it will
12607 be displayed in the buffer instead of the link.
12609 If there is already a link at point, this command will allow you to edit link
12610 and description parts.
12612 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12613 selected using completion. The path to the file will be relative to
12614 the current directory if the file is in the current directory or a
12615 subdirectory. Otherwise, the link will be the absolute path as
12616 completed in the minibuffer (i.e. normally ~/path/to/file).
12618 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12619 is in the current directory or below.
12620 With three \\[universal-argument] prefixes, negate the meaning of
12621 `org-keep-stored-link-after-insertion'."
12622 (interactive "P")
12623 (let* ((wcf (current-window-configuration))
12624 (region (if (org-region-active-p)
12625 (buffer-substring (region-beginning) (region-end))))
12626 (remove (and region (list (region-beginning) (region-end))))
12627 (desc region)
12628 tmphist ; byte-compile incorrectly complains about this
12629 link entry file)
12630 (cond
12631 ((org-in-regexp org-bracket-link-regexp 1)
12632 ;; We do have a link at point, and we are going to edit it.
12633 (setq remove (list (match-beginning 0) (match-end 0)))
12634 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12635 (setq link (read-string "Link: "
12636 (org-link-unescape
12637 (org-match-string-no-properties 1)))))
12638 ((or (org-in-regexp org-angle-link-re)
12639 (org-in-regexp org-plain-link-re))
12640 ;; Convert to bracket link
12641 (setq remove (list (match-beginning 0) (match-end 0))
12642 link (read-string "Link: "
12643 (org-remove-angle-brackets (match-string 0)))))
12644 ((equal complete-file '(4))
12645 ;; Completing read for file names.
12646 (setq file (read-file-name "File: "))
12647 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12648 (pwd1 (file-name-as-directory (abbreviate-file-name
12649 (expand-file-name ".")))))
12650 (cond
12651 ((equal complete-file '(16))
12652 (setq link (org-make-link
12653 "file:"
12654 (abbreviate-file-name (expand-file-name file)))))
12655 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12656 (setq link (org-make-link "file:" (match-string 1 file))))
12657 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12658 (expand-file-name file))
12659 (setq link (org-make-link
12660 "file:" (match-string 1 (expand-file-name file)))))
12661 (t (setq link (org-make-link "file:" file))))))
12663 ;; Read link, with completion for stored links.
12664 (with-output-to-temp-buffer "*Org Links*"
12665 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12666 (when org-stored-links
12667 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12668 (princ (mapconcat
12669 (lambda (x)
12670 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12671 (reverse org-stored-links) "\n"))))
12672 (let ((cw (selected-window)))
12673 (select-window (get-buffer-window "*Org Links*"))
12674 (shrink-window-if-larger-than-buffer)
12675 (setq truncate-lines t)
12676 (select-window cw))
12677 ;; Fake a link history, containing the stored links.
12678 (setq tmphist (append (mapcar 'car org-stored-links)
12679 org-insert-link-history))
12680 (unwind-protect
12681 (setq link (org-completing-read
12682 "Link: "
12683 (append
12684 (mapcar (lambda (x) (list (concat (car x) ":")))
12685 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12686 (mapcar (lambda (x) (list (concat x ":")))
12687 org-link-types))
12688 nil nil nil
12689 'tmphist
12690 (or (car (car org-stored-links)))))
12691 (set-window-configuration wcf)
12692 (kill-buffer "*Org Links*"))
12693 (setq entry (assoc link org-stored-links))
12694 (or entry (push link org-insert-link-history))
12695 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12696 (not org-keep-stored-link-after-insertion))
12697 (setq org-stored-links (delq (assoc link org-stored-links)
12698 org-stored-links)))
12699 (setq desc (or desc (nth 1 entry)))))
12701 (if (string-match org-plain-link-re link)
12702 ;; URL-like link, normalize the use of angular brackets.
12703 (setq link (org-make-link (org-remove-angle-brackets link))))
12705 ;; Check if we are linking to the current file with a search option
12706 ;; If yes, simplify the link by using only the search option.
12707 (when (and buffer-file-name
12708 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12709 (let* ((path (match-string 1 link))
12710 (case-fold-search nil)
12711 (search (match-string 2 link)))
12712 (save-match-data
12713 (if (equal (file-truename buffer-file-name) (file-truename path))
12714 ;; We are linking to this same file, with a search option
12715 (setq link search)))))
12717 ;; Check if we can/should use a relative path. If yes, simplify the link
12718 (when (string-match "\\<file:\\(.*\\)" link)
12719 (let* ((path (match-string 1 link))
12720 (origpath path)
12721 (case-fold-search nil))
12722 (cond
12723 ((eq org-link-file-path-type 'absolute)
12724 (setq path (abbreviate-file-name (expand-file-name path))))
12725 ((eq org-link-file-path-type 'noabbrev)
12726 (setq path (expand-file-name path)))
12727 ((eq org-link-file-path-type 'relative)
12728 (setq path (file-relative-name path)))
12730 (save-match-data
12731 (if (string-match (concat "^" (regexp-quote
12732 (file-name-as-directory
12733 (expand-file-name "."))))
12734 (expand-file-name path))
12735 ;; We are linking a file with relative path name.
12736 (setq path (substring (expand-file-name path)
12737 (match-end 0)))))))
12738 (setq link (concat "file:" path))
12739 (if (equal desc origpath)
12740 (setq desc path))))
12742 (setq desc (read-string "Description: " desc))
12743 (unless (string-match "\\S-" desc) (setq desc nil))
12744 (if remove (apply 'delete-region remove))
12745 (insert (org-make-link-string link desc))))
12747 (defun org-completing-read (&rest args)
12748 (let ((minibuffer-local-completion-map
12749 (copy-keymap minibuffer-local-completion-map)))
12750 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12751 (apply 'completing-read args)))
12753 ;;; Opening/following a link
12754 (defvar org-link-search-failed nil)
12756 (defun org-next-link ()
12757 "Move forward to the next link.
12758 If the link is in hidden text, expose it."
12759 (interactive)
12760 (when (and org-link-search-failed (eq this-command last-command))
12761 (goto-char (point-min))
12762 (message "Link search wrapped back to beginning of buffer"))
12763 (setq org-link-search-failed nil)
12764 (let* ((pos (point))
12765 (ct (org-context))
12766 (a (assoc :link ct)))
12767 (if a (goto-char (nth 2 a)))
12768 (if (re-search-forward org-any-link-re nil t)
12769 (progn
12770 (goto-char (match-beginning 0))
12771 (if (org-invisible-p) (org-show-context)))
12772 (goto-char pos)
12773 (setq org-link-search-failed t)
12774 (error "No further link found"))))
12776 (defun org-previous-link ()
12777 "Move backward to the previous link.
12778 If the link is in hidden text, expose it."
12779 (interactive)
12780 (when (and org-link-search-failed (eq this-command last-command))
12781 (goto-char (point-max))
12782 (message "Link search wrapped back to end of buffer"))
12783 (setq org-link-search-failed nil)
12784 (let* ((pos (point))
12785 (ct (org-context))
12786 (a (assoc :link ct)))
12787 (if a (goto-char (nth 1 a)))
12788 (if (re-search-backward org-any-link-re nil t)
12789 (progn
12790 (goto-char (match-beginning 0))
12791 (if (org-invisible-p) (org-show-context)))
12792 (goto-char pos)
12793 (setq org-link-search-failed t)
12794 (error "No further link found"))))
12796 (defun org-find-file-at-mouse (ev)
12797 "Open file link or URL at mouse."
12798 (interactive "e")
12799 (mouse-set-point ev)
12800 (org-open-at-point 'in-emacs))
12802 (defun org-open-at-mouse (ev)
12803 "Open file link or URL at mouse."
12804 (interactive "e")
12805 (mouse-set-point ev)
12806 (org-open-at-point))
12808 (defvar org-window-config-before-follow-link nil
12809 "The window configuration before following a link.
12810 This is saved in case the need arises to restore it.")
12812 (defvar org-open-link-marker (make-marker)
12813 "Marker pointing to the location where `org-open-at-point; was called.")
12815 ;;;###autoload
12816 (defun org-open-at-point-global ()
12817 "Follow a link like Org-mode does.
12818 This command can be called in any mode to follow a link that has
12819 Org-mode syntax."
12820 (interactive)
12821 (org-run-like-in-org-mode 'org-open-at-point))
12823 (defun org-open-at-point (&optional in-emacs)
12824 "Open link at or after point.
12825 If there is no link at point, this function will search forward up to
12826 the end of the current subtree.
12827 Normally, files will be opened by an appropriate application. If the
12828 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12829 (interactive "P")
12830 (move-marker org-open-link-marker (point))
12831 (setq org-window-config-before-follow-link (current-window-configuration))
12832 (org-remove-occur-highlights nil nil t)
12833 (if (org-at-timestamp-p t)
12834 (org-follow-timestamp-link)
12835 (let (type path link line search (pos (point)))
12836 (catch 'match
12837 (save-excursion
12838 (skip-chars-forward "^]\n\r")
12839 (when (org-in-regexp org-bracket-link-regexp)
12840 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12841 (while (string-match " *\n *" link)
12842 (setq link (replace-match " " t t link)))
12843 (setq link (org-link-expand-abbrev link))
12844 (if (string-match org-link-re-with-space2 link)
12845 (setq type (match-string 1 link) path (match-string 2 link))
12846 (setq type "thisfile" path link))
12847 (throw 'match t)))
12849 (when (get-text-property (point) 'org-linked-text)
12850 (setq type "thisfile"
12851 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12852 (1+ (point)) (point))
12853 path (buffer-substring
12854 (previous-single-property-change pos 'org-linked-text)
12855 (next-single-property-change pos 'org-linked-text)))
12856 (throw 'match t))
12858 (save-excursion
12859 (when (or (org-in-regexp org-angle-link-re)
12860 (org-in-regexp org-plain-link-re))
12861 (setq type (match-string 1) path (match-string 2))
12862 (throw 'match t)))
12863 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12864 (setq type "tree-match"
12865 path (match-string 1))
12866 (throw 'match t))
12867 (save-excursion
12868 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12869 (setq type "tags"
12870 path (match-string 1))
12871 (while (string-match ":" path)
12872 (setq path (replace-match "+" t t path)))
12873 (throw 'match t))))
12874 (unless path
12875 (error "No link found"))
12876 ;; Remove any trailing spaces in path
12877 (if (string-match " +\\'" path)
12878 (setq path (replace-match "" t t path)))
12880 (cond
12882 ((assoc type org-link-protocols)
12883 (funcall (nth 1 (assoc type org-link-protocols)) path))
12885 ((equal type "mailto")
12886 (let ((cmd (car org-link-mailto-program))
12887 (args (cdr org-link-mailto-program)) args1
12888 (address path) (subject "") a)
12889 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12890 (setq address (match-string 1 path)
12891 subject (org-link-escape (match-string 2 path))))
12892 (while args
12893 (cond
12894 ((not (stringp (car args))) (push (pop args) args1))
12895 (t (setq a (pop args))
12896 (if (string-match "%a" a)
12897 (setq a (replace-match address t t a)))
12898 (if (string-match "%s" a)
12899 (setq a (replace-match subject t t a)))
12900 (push a args1))))
12901 (apply cmd (nreverse args1))))
12903 ((member type '("http" "https" "ftp" "news"))
12904 (browse-url (concat type ":" (org-link-escape
12905 path org-link-escape-chars-browser))))
12907 ((member type '("message"))
12908 (browse-url (concat type ":" path)))
12910 ((string= type "tags")
12911 (org-tags-view in-emacs path))
12912 ((string= type "thisfile")
12913 (if in-emacs
12914 (switch-to-buffer-other-window
12915 (org-get-buffer-for-internal-link (current-buffer)))
12916 (org-mark-ring-push))
12917 (let ((cmd `(org-link-search
12918 ,path
12919 ,(cond ((equal in-emacs '(4)) 'occur)
12920 ((equal in-emacs '(16)) 'org-occur)
12921 (t nil))
12922 ,pos)))
12923 (condition-case nil (eval cmd)
12924 (error (progn (widen) (eval cmd))))))
12926 ((string= type "tree-match")
12927 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12929 ((string= type "file")
12930 (if (string-match "::\\([0-9]+\\)\\'" path)
12931 (setq line (string-to-number (match-string 1 path))
12932 path (substring path 0 (match-beginning 0)))
12933 (if (string-match "::\\(.+\\)\\'" path)
12934 (setq search (match-string 1 path)
12935 path (substring path 0 (match-beginning 0)))))
12936 (if (string-match "[*?{]" (file-name-nondirectory path))
12937 (dired path)
12938 (org-open-file path in-emacs line search)))
12940 ((string= type "news")
12941 (org-follow-gnus-link path))
12943 ((string= type "bbdb")
12944 (org-follow-bbdb-link path))
12946 ((string= type "info")
12947 (org-follow-info-link path))
12949 ((string= type "gnus")
12950 (let (group article)
12951 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12952 (error "Error in Gnus link"))
12953 (setq group (match-string 1 path)
12954 article (match-string 3 path))
12955 (org-follow-gnus-link group article)))
12957 ((string= type "vm")
12958 (let (folder article)
12959 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12960 (error "Error in VM link"))
12961 (setq folder (match-string 1 path)
12962 article (match-string 3 path))
12963 ;; in-emacs is the prefix arg, will be interpreted as read-only
12964 (org-follow-vm-link folder article in-emacs)))
12966 ((string= type "wl")
12967 (let (folder article)
12968 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12969 (error "Error in Wanderlust link"))
12970 (setq folder (match-string 1 path)
12971 article (match-string 3 path))
12972 (org-follow-wl-link folder article)))
12974 ((string= type "mhe")
12975 (let (folder article)
12976 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12977 (error "Error in MHE link"))
12978 (setq folder (match-string 1 path)
12979 article (match-string 3 path))
12980 (org-follow-mhe-link folder article)))
12982 ((string= type "rmail")
12983 (let (folder article)
12984 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12985 (error "Error in RMAIL link"))
12986 (setq folder (match-string 1 path)
12987 article (match-string 3 path))
12988 (org-follow-rmail-link folder article)))
12990 ((string= type "shell")
12991 (let ((cmd path))
12992 (if (or (not org-confirm-shell-link-function)
12993 (funcall org-confirm-shell-link-function
12994 (format "Execute \"%s\" in shell? "
12995 (org-add-props cmd nil
12996 'face 'org-warning))))
12997 (progn
12998 (message "Executing %s" cmd)
12999 (shell-command cmd))
13000 (error "Abort"))))
13002 ((string= type "elisp")
13003 (let ((cmd path))
13004 (if (or (not org-confirm-elisp-link-function)
13005 (funcall org-confirm-elisp-link-function
13006 (format "Execute \"%s\" as elisp? "
13007 (org-add-props cmd nil
13008 'face 'org-warning))))
13009 (message "%s => %s" cmd (eval (read cmd)))
13010 (error "Abort"))))
13013 (browse-url-at-point)))))
13014 (move-marker org-open-link-marker nil)
13015 (run-hook-with-args 'org-follow-link-hook))
13017 ;;; File search
13019 (defvar org-create-file-search-functions nil
13020 "List of functions to construct the right search string for a file link.
13021 These functions are called in turn with point at the location to
13022 which the link should point.
13024 A function in the hook should first test if it would like to
13025 handle this file type, for example by checking the major-mode or
13026 the file extension. If it decides not to handle this file, it
13027 should just return nil to give other functions a chance. If it
13028 does handle the file, it must return the search string to be used
13029 when following the link. The search string will be part of the
13030 file link, given after a double colon, and `org-open-at-point'
13031 will automatically search for it. If special measures must be
13032 taken to make the search successful, another function should be
13033 added to the companion hook `org-execute-file-search-functions',
13034 which see.
13036 A function in this hook may also use `setq' to set the variable
13037 `description' to provide a suggestion for the descriptive text to
13038 be used for this link when it gets inserted into an Org-mode
13039 buffer with \\[org-insert-link].")
13041 (defvar org-execute-file-search-functions nil
13042 "List of functions to execute a file search triggered by a link.
13044 Functions added to this hook must accept a single argument, the
13045 search string that was part of the file link, the part after the
13046 double colon. The function must first check if it would like to
13047 handle this search, for example by checking the major-mode or the
13048 file extension. If it decides not to handle this search, it
13049 should just return nil to give other functions a chance. If it
13050 does handle the search, it must return a non-nil value to keep
13051 other functions from trying.
13053 Each function can access the current prefix argument through the
13054 variable `current-prefix-argument'. Note that a single prefix is
13055 used to force opening a link in Emacs, so it may be good to only
13056 use a numeric or double prefix to guide the search function.
13058 In case this is needed, a function in this hook can also restore
13059 the window configuration before `org-open-at-point' was called using:
13061 (set-window-configuration org-window-config-before-follow-link)")
13063 (defun org-link-search (s &optional type avoid-pos)
13064 "Search for a link search option.
13065 If S is surrounded by forward slashes, it is interpreted as a
13066 regular expression. In org-mode files, this will create an `org-occur'
13067 sparse tree. In ordinary files, `occur' will be used to list matches.
13068 If the current buffer is in `dired-mode', grep will be used to search
13069 in all files. If AVOID-POS is given, ignore matches near that position."
13070 (let ((case-fold-search t)
13071 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
13072 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
13073 (append '(("") (" ") ("\t") ("\n"))
13074 org-emphasis-alist)
13075 "\\|") "\\)"))
13076 (pos (point))
13077 (pre "") (post "")
13078 words re0 re1 re2 re3 re4 re5 re2a reall)
13079 (cond
13080 ;; First check if there are any special
13081 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
13082 ;; Now try the builtin stuff
13083 ((save-excursion
13084 (goto-char (point-min))
13085 (and
13086 (re-search-forward
13087 (concat "<<" (regexp-quote s0) ">>") nil t)
13088 (setq pos (match-beginning 0))))
13089 ;; There is an exact target for this
13090 (goto-char pos))
13091 ((string-match "^/\\(.*\\)/$" s)
13092 ;; A regular expression
13093 (cond
13094 ((org-mode-p)
13095 (org-occur (match-string 1 s)))
13096 ;;((eq major-mode 'dired-mode)
13097 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
13098 (t (org-do-occur (match-string 1 s)))))
13100 ;; A normal search strings
13101 (when (equal (string-to-char s) ?*)
13102 ;; Anchor on headlines, post may include tags.
13103 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
13104 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
13105 s (substring s 1)))
13106 (remove-text-properties
13107 0 (length s)
13108 '(face nil mouse-face nil keymap nil fontified nil) s)
13109 ;; Make a series of regular expressions to find a match
13110 (setq words (org-split-string s "[ \n\r\t]+")
13111 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
13112 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
13113 "\\)" markers)
13114 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
13115 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
13116 re1 (concat pre re2 post)
13117 re3 (concat pre re4 post)
13118 re5 (concat pre ".*" re4)
13119 re2 (concat pre re2)
13120 re2a (concat pre re2a)
13121 re4 (concat pre re4)
13122 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
13123 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
13124 re5 "\\)"
13126 (cond
13127 ((eq type 'org-occur) (org-occur reall))
13128 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
13129 (t (goto-char (point-min))
13130 (if (or (org-search-not-self 1 re0 nil t)
13131 (org-search-not-self 1 re1 nil t)
13132 (org-search-not-self 1 re2 nil t)
13133 (org-search-not-self 1 re2a nil t)
13134 (org-search-not-self 1 re3 nil t)
13135 (org-search-not-self 1 re4 nil t)
13136 (org-search-not-self 1 re5 nil t)
13138 (goto-char (match-beginning 1))
13139 (goto-char pos)
13140 (error "No match")))))
13142 ;; Normal string-search
13143 (goto-char (point-min))
13144 (if (search-forward s nil t)
13145 (goto-char (match-beginning 0))
13146 (error "No match"))))
13147 (and (org-mode-p) (org-show-context 'link-search))))
13149 (defun org-search-not-self (group &rest args)
13150 "Execute `re-search-forward', but only accept matches that do not
13151 enclose the position of `org-open-link-marker'."
13152 (let ((m org-open-link-marker))
13153 (catch 'exit
13154 (while (apply 're-search-forward args)
13155 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
13156 (goto-char (match-end group))
13157 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
13158 (> (match-beginning 0) (marker-position m))
13159 (< (match-end 0) (marker-position m)))
13160 (save-match-data
13161 (or (not (org-in-regexp
13162 org-bracket-link-analytic-regexp 1))
13163 (not (match-end 4)) ; no description
13164 (and (<= (match-beginning 4) (point))
13165 (>= (match-end 4) (point))))))
13166 (throw 'exit (point))))))))
13168 (defun org-get-buffer-for-internal-link (buffer)
13169 "Return a buffer to be used for displaying the link target of internal links."
13170 (cond
13171 ((not org-display-internal-link-with-indirect-buffer)
13172 buffer)
13173 ((string-match "(Clone)$" (buffer-name buffer))
13174 (message "Buffer is already a clone, not making another one")
13175 ;; we also do not modify visibility in this case
13176 buffer)
13177 (t ; make a new indirect buffer for displaying the link
13178 (let* ((bn (buffer-name buffer))
13179 (ibn (concat bn "(Clone)"))
13180 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13181 (with-current-buffer ib (org-overview))
13182 ib))))
13184 (defun org-do-occur (regexp &optional cleanup)
13185 "Call the Emacs command `occur'.
13186 If CLEANUP is non-nil, remove the printout of the regular expression
13187 in the *Occur* buffer. This is useful if the regex is long and not useful
13188 to read."
13189 (occur regexp)
13190 (when cleanup
13191 (let ((cwin (selected-window)) win beg end)
13192 (when (setq win (get-buffer-window "*Occur*"))
13193 (select-window win))
13194 (goto-char (point-min))
13195 (when (re-search-forward "match[a-z]+" nil t)
13196 (setq beg (match-end 0))
13197 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13198 (setq end (1- (match-beginning 0)))))
13199 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13200 (goto-char (point-min))
13201 (select-window cwin))))
13203 ;;; The mark ring for links jumps
13205 (defvar org-mark-ring nil
13206 "Mark ring for positions before jumps in Org-mode.")
13207 (defvar org-mark-ring-last-goto nil
13208 "Last position in the mark ring used to go back.")
13209 ;; Fill and close the ring
13210 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13211 (loop for i from 1 to org-mark-ring-length do
13212 (push (make-marker) org-mark-ring))
13213 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13214 org-mark-ring)
13216 (defun org-mark-ring-push (&optional pos buffer)
13217 "Put the current position or POS into the mark ring and rotate it."
13218 (interactive)
13219 (setq pos (or pos (point)))
13220 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13221 (move-marker (car org-mark-ring)
13222 (or pos (point))
13223 (or buffer (current-buffer)))
13224 (message "%s"
13225 (substitute-command-keys
13226 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13228 (defun org-mark-ring-goto (&optional n)
13229 "Jump to the previous position in the mark ring.
13230 With prefix arg N, jump back that many stored positions. When
13231 called several times in succession, walk through the entire ring.
13232 Org-mode commands jumping to a different position in the current file,
13233 or to another Org-mode file, automatically push the old position
13234 onto the ring."
13235 (interactive "p")
13236 (let (p m)
13237 (if (eq last-command this-command)
13238 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13239 (setq p org-mark-ring))
13240 (setq org-mark-ring-last-goto p)
13241 (setq m (car p))
13242 (switch-to-buffer (marker-buffer m))
13243 (goto-char m)
13244 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13246 (defun org-remove-angle-brackets (s)
13247 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13248 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13250 (defun org-add-angle-brackets (s)
13251 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13252 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13255 ;;; Following specific links
13257 (defun org-follow-timestamp-link ()
13258 (cond
13259 ((org-at-date-range-p t)
13260 (let ((org-agenda-start-on-weekday)
13261 (t1 (match-string 1))
13262 (t2 (match-string 2)))
13263 (setq t1 (time-to-days (org-time-string-to-time t1))
13264 t2 (time-to-days (org-time-string-to-time t2)))
13265 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13266 ((org-at-timestamp-p t)
13267 (org-agenda-list nil (time-to-days (org-time-string-to-time
13268 (substring (match-string 1) 0 10)))
13270 (t (error "This should not happen"))))
13273 (defun org-follow-bbdb-link (name)
13274 "Follow a BBDB link to NAME."
13275 (require 'bbdb)
13276 (let ((inhibit-redisplay (not debug-on-error))
13277 (bbdb-electric-p nil))
13278 (catch 'exit
13279 ;; Exact match on name
13280 (bbdb-name (concat "\\`" name "\\'") nil)
13281 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13282 ;; Exact match on name
13283 (bbdb-company (concat "\\`" name "\\'") nil)
13284 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13285 ;; Partial match on name
13286 (bbdb-name name nil)
13287 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13288 ;; Partial match on company
13289 (bbdb-company name nil)
13290 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13291 ;; General match including network address and notes
13292 (bbdb name nil)
13293 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13294 (delete-window (get-buffer-window "*BBDB*"))
13295 (error "No matching BBDB record")))))
13297 (defun org-follow-info-link (name)
13298 "Follow an info file & node link to NAME."
13299 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13300 (string-match "\\(.*\\)" name))
13301 (progn
13302 (require 'info)
13303 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13304 (Info-find-node (match-string 1 name) (match-string 2 name))
13305 (Info-find-node (match-string 1 name) "Top")))
13306 (message "Could not open: %s" name)))
13308 (defun org-follow-gnus-link (&optional group article)
13309 "Follow a Gnus link to GROUP and ARTICLE."
13310 (require 'gnus)
13311 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13312 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13313 (cond ((and group article)
13314 (gnus-group-read-group 1 nil group)
13315 (gnus-summary-goto-article (string-to-number article) nil t))
13316 (group (gnus-group-jump-to-group group))))
13318 (defun org-follow-vm-link (&optional folder article readonly)
13319 "Follow a VM link to FOLDER and ARTICLE."
13320 (require 'vm)
13321 (setq article (org-add-angle-brackets article))
13322 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13323 ;; ange-ftp or efs or tramp access
13324 (let ((user (or (match-string 1 folder) (user-login-name)))
13325 (host (match-string 2 folder))
13326 (file (match-string 3 folder)))
13327 (cond
13328 ((featurep 'tramp)
13329 ;; use tramp to access the file
13330 (if (featurep 'xemacs)
13331 (setq folder (format "[%s@%s]%s" user host file))
13332 (setq folder (format "/%s@%s:%s" user host file))))
13334 ;; use ange-ftp or efs
13335 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13336 (setq folder (format "/%s@%s:%s" user host file))))))
13337 (when folder
13338 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13339 (sit-for 0.1)
13340 (when article
13341 (vm-select-folder-buffer)
13342 (widen)
13343 (let ((case-fold-search t))
13344 (goto-char (point-min))
13345 (if (not (re-search-forward
13346 (concat "^" "message-id: *" (regexp-quote article))))
13347 (error "Could not find the specified message in this folder"))
13348 (vm-isearch-update)
13349 (vm-isearch-narrow)
13350 (vm-beginning-of-message)
13351 (vm-summarize)))))
13353 (defun org-follow-wl-link (folder article)
13354 "Follow a Wanderlust link to FOLDER and ARTICLE."
13355 (if (and (string= folder "%")
13356 article
13357 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13358 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13359 ;; Thus, we recompose folder and article ids.
13360 (setq folder (format "%s#%s" folder (match-string 1 article))
13361 article (match-string 3 article)))
13362 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13363 (error "No such folder: %s" folder))
13364 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13365 (and article
13366 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13367 (wl-summary-redisplay)))
13369 (defun org-follow-rmail-link (folder article)
13370 "Follow an RMAIL link to FOLDER and ARTICLE."
13371 (setq article (org-add-angle-brackets article))
13372 (let (message-number)
13373 (save-excursion
13374 (save-window-excursion
13375 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13376 (setq message-number
13377 (save-restriction
13378 (widen)
13379 (goto-char (point-max))
13380 (if (re-search-backward
13381 (concat "^Message-ID:\\s-+" (regexp-quote
13382 (or article "")))
13383 nil t)
13384 (rmail-what-message))))))
13385 (if message-number
13386 (progn
13387 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13388 (rmail-show-message message-number)
13389 message-number)
13390 (error "Message not found"))))
13392 ;;; mh-e integration based on planner-mode
13393 (defun org-mhe-get-message-real-folder ()
13394 "Return the name of the current message real folder, so if you use
13395 sequences, it will now work."
13396 (save-excursion
13397 (let* ((folder
13398 (if (equal major-mode 'mh-folder-mode)
13399 mh-current-folder
13400 ;; Refer to the show buffer
13401 mh-show-folder-buffer))
13402 (end-index
13403 (if (boundp 'mh-index-folder)
13404 (min (length mh-index-folder) (length folder))))
13406 ;; a simple test on mh-index-data does not work, because
13407 ;; mh-index-data is always nil in a show buffer.
13408 (if (and (boundp 'mh-index-folder)
13409 (string= mh-index-folder (substring folder 0 end-index)))
13410 (if (equal major-mode 'mh-show-mode)
13411 (save-window-excursion
13412 (let (pop-up-frames)
13413 (when (buffer-live-p (get-buffer folder))
13414 (progn
13415 (pop-to-buffer folder)
13416 (org-mhe-get-message-folder-from-index)
13419 (org-mhe-get-message-folder-from-index)
13421 folder
13425 (defun org-mhe-get-message-folder-from-index ()
13426 "Returns the name of the message folder in a index folder buffer."
13427 (save-excursion
13428 (mh-index-previous-folder)
13429 (re-search-forward "^\\(+.*\\)$" nil t)
13430 (message "%s" (match-string 1))))
13432 (defun org-mhe-get-message-folder ()
13433 "Return the name of the current message folder. Be careful if you
13434 use sequences."
13435 (save-excursion
13436 (if (equal major-mode 'mh-folder-mode)
13437 mh-current-folder
13438 ;; Refer to the show buffer
13439 mh-show-folder-buffer)))
13441 (defun org-mhe-get-message-num ()
13442 "Return the number of the current message. Be careful if you
13443 use sequences."
13444 (save-excursion
13445 (if (equal major-mode 'mh-folder-mode)
13446 (mh-get-msg-num nil)
13447 ;; Refer to the show buffer
13448 (mh-show-buffer-message-number))))
13450 (defun org-mhe-get-header (header)
13451 "Return a header of the message in folder mode. This will create a
13452 show buffer for the corresponding message. If you have a more clever
13453 idea..."
13454 (let* ((folder (org-mhe-get-message-folder))
13455 (num (org-mhe-get-message-num))
13456 (buffer (get-buffer-create (concat "show-" folder)))
13457 (header-field))
13458 (with-current-buffer buffer
13459 (mh-display-msg num folder)
13460 (if (equal major-mode 'mh-folder-mode)
13461 (mh-header-display)
13462 (mh-show-header-display))
13463 (set-buffer buffer)
13464 (setq header-field (mh-get-header-field header))
13465 (if (equal major-mode 'mh-folder-mode)
13466 (mh-show)
13467 (mh-show-show))
13468 header-field)))
13470 (defun org-follow-mhe-link (folder article)
13471 "Follow an MHE link to FOLDER and ARTICLE.
13472 If ARTICLE is nil FOLDER is shown. If the configuration variable
13473 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13474 ARTICLE is searched in all folders. Indexed searches (swish++,
13475 namazu, and others supported by MH-E) will always search in all
13476 folders."
13477 (require 'mh-e)
13478 (require 'mh-search)
13479 (require 'mh-utils)
13480 (mh-find-path)
13481 (if (not article)
13482 (mh-visit-folder (mh-normalize-folder-name folder))
13483 (setq article (org-add-angle-brackets article))
13484 (mh-search-choose)
13485 (if (equal mh-searcher 'pick)
13486 (progn
13487 (mh-search folder (list "--message-id" article))
13488 (when (and org-mhe-search-all-folders
13489 (not (org-mhe-get-message-real-folder)))
13490 (kill-this-buffer)
13491 (mh-search "+" (list "--message-id" article))))
13492 (mh-search "+" article))
13493 (if (org-mhe-get-message-real-folder)
13494 (mh-show-msg 1)
13495 (kill-this-buffer)
13496 (error "Message not found"))))
13498 ;;; BibTeX links
13500 ;; Use the custom search meachnism to construct and use search strings for
13501 ;; file links to BibTeX database entries.
13503 (defun org-create-file-search-in-bibtex ()
13504 "Create the search string and description for a BibTeX database entry."
13505 (when (eq major-mode 'bibtex-mode)
13506 ;; yes, we want to construct this search string.
13507 ;; Make a good description for this entry, using names, year and the title
13508 ;; Put it into the `description' variable which is dynamically scoped.
13509 (let ((bibtex-autokey-names 1)
13510 (bibtex-autokey-names-stretch 1)
13511 (bibtex-autokey-name-case-convert-function 'identity)
13512 (bibtex-autokey-name-separator " & ")
13513 (bibtex-autokey-additional-names " et al.")
13514 (bibtex-autokey-year-length 4)
13515 (bibtex-autokey-name-year-separator " ")
13516 (bibtex-autokey-titlewords 3)
13517 (bibtex-autokey-titleword-separator " ")
13518 (bibtex-autokey-titleword-case-convert-function 'identity)
13519 (bibtex-autokey-titleword-length 'infty)
13520 (bibtex-autokey-year-title-separator ": "))
13521 (setq description (bibtex-generate-autokey)))
13522 ;; Now parse the entry, get the key and return it.
13523 (save-excursion
13524 (bibtex-beginning-of-entry)
13525 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13527 (defun org-execute-file-search-in-bibtex (s)
13528 "Find the link search string S as a key for a database entry."
13529 (when (eq major-mode 'bibtex-mode)
13530 ;; Yes, we want to do the search in this file.
13531 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13532 (goto-char (point-min))
13533 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13534 (regexp-quote s) "[ \t\n]*,") nil t)
13535 (goto-char (match-beginning 0)))
13536 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13537 ;; Use double prefix to indicate that any web link should be browsed
13538 (let ((b (current-buffer)) (p (point)))
13539 ;; Restore the window configuration because we just use the web link
13540 (set-window-configuration org-window-config-before-follow-link)
13541 (save-excursion (set-buffer b) (goto-char p)
13542 (bibtex-url)))
13543 (recenter 0)) ; Move entry start to beginning of window
13544 ;; return t to indicate that the search is done.
13547 ;; Finally add the functions to the right hooks.
13548 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13549 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13551 ;; end of Bibtex link setup
13553 ;;; Following file links
13555 (defun org-open-file (path &optional in-emacs line search)
13556 "Open the file at PATH.
13557 First, this expands any special file name abbreviations. Then the
13558 configuration variable `org-file-apps' is checked if it contains an
13559 entry for this file type, and if yes, the corresponding command is launched.
13560 If no application is found, Emacs simply visits the file.
13561 With optional argument IN-EMACS, Emacs will visit the file.
13562 Optional LINE specifies a line to go to, optional SEARCH a string to
13563 search for. If LINE or SEARCH is given, the file will always be
13564 opened in Emacs.
13565 If the file does not exist, an error is thrown."
13566 (setq in-emacs (or in-emacs line search))
13567 (let* ((file (if (equal path "")
13568 buffer-file-name
13569 (substitute-in-file-name (expand-file-name path))))
13570 (apps (append org-file-apps (org-default-apps)))
13571 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13572 (dirp (if remp nil (file-directory-p file)))
13573 (dfile (downcase file))
13574 (old-buffer (current-buffer))
13575 (old-pos (point))
13576 (old-mode major-mode)
13577 ext cmd)
13578 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13579 (setq ext (match-string 1 dfile))
13580 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13581 (setq ext (match-string 1 dfile))))
13582 (if in-emacs
13583 (setq cmd 'emacs)
13584 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13585 (and dirp (cdr (assoc 'directory apps)))
13586 (cdr (assoc ext apps))
13587 (cdr (assoc t apps)))))
13588 (when (eq cmd 'mailcap)
13589 (require 'mailcap)
13590 (mailcap-parse-mailcaps)
13591 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13592 (command (mailcap-mime-info mime-type)))
13593 (if (stringp command)
13594 (setq cmd command)
13595 (setq cmd 'emacs))))
13596 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13597 (not (file-exists-p file))
13598 (not org-open-non-existing-files))
13599 (error "No such file: %s" file))
13600 (cond
13601 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13602 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13603 (while (string-match "['\"]%s['\"]" cmd)
13604 (setq cmd (replace-match "%s" t t cmd)))
13605 (while (string-match "%s" cmd)
13606 (setq cmd (replace-match
13607 (save-match-data (shell-quote-argument file))
13608 t t cmd)))
13609 (save-window-excursion
13610 (start-process-shell-command cmd nil cmd)))
13611 ((or (stringp cmd)
13612 (eq cmd 'emacs))
13613 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13614 (widen)
13615 (if line (goto-line line)
13616 (if search (org-link-search search))))
13617 ((consp cmd)
13618 (eval cmd))
13619 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13620 (and (org-mode-p) (eq old-mode 'org-mode)
13621 (or (not (equal old-buffer (current-buffer)))
13622 (not (equal old-pos (point))))
13623 (org-mark-ring-push old-pos old-buffer))))
13625 (defun org-default-apps ()
13626 "Return the default applications for this operating system."
13627 (cond
13628 ((eq system-type 'darwin)
13629 org-file-apps-defaults-macosx)
13630 ((eq system-type 'windows-nt)
13631 org-file-apps-defaults-windowsnt)
13632 (t org-file-apps-defaults-gnu)))
13634 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13635 (defun org-file-remote-p (file)
13636 "Test whether FILE specifies a location on a remote system.
13637 Return non-nil if the location is indeed remote.
13639 For example, the filename \"/user@host:/foo\" specifies a location
13640 on the system \"/user@host:\"."
13641 (cond ((fboundp 'file-remote-p)
13642 (file-remote-p file))
13643 ((fboundp 'tramp-handle-file-remote-p)
13644 (tramp-handle-file-remote-p file))
13645 ((and (boundp 'ange-ftp-name-format)
13646 (string-match (car ange-ftp-name-format) file))
13648 (t nil)))
13651 ;;;; Hooks for remember.el, and refiling
13653 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13654 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13656 ;;;###autoload
13657 (defun org-remember-insinuate ()
13658 "Setup remember.el for use wiht Org-mode."
13659 (require 'remember)
13660 (setq remember-annotation-functions '(org-remember-annotation))
13661 (setq remember-handler-functions '(org-remember-handler))
13662 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13664 ;;;###autoload
13665 (defun org-remember-annotation ()
13666 "Return a link to the current location as an annotation for remember.el.
13667 If you are using Org-mode files as target for data storage with
13668 remember.el, then the annotations should include a link compatible with the
13669 conventions in Org-mode. This function returns such a link."
13670 (org-store-link nil))
13672 (defconst org-remember-help
13673 "Select a destination location for the note.
13674 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13675 RET on headline -> Store as sublevel entry to current headline
13676 RET at beg-of-buf -> Append to file as level 2 headline
13677 <left>/<right> -> before/after current headline, same headings level")
13679 (defvar org-remember-previous-location nil)
13680 (defvar org-force-remember-template-char) ;; dynamically scoped
13682 ;; Save the major mode of the buffer we called remember from
13683 (defvar org-select-template-temp-major-mode nil)
13685 ;; Temporary store the buffer where remember was called from
13686 (defvar org-select-template-original-buffer nil)
13688 (defun org-select-remember-template (&optional use-char)
13689 (when org-remember-templates
13690 (let* ((pre-selected-templates
13691 (mapcar
13692 (lambda (tpl)
13693 (let ((ctxt (nth 5 tpl))
13694 (mode org-select-template-temp-major-mode)
13695 (buf org-select-template-original-buffer))
13696 (and (or (not ctxt) (eq ctxt t)
13697 (and (listp ctxt) (memq mode ctxt))
13698 (and (functionp ctxt)
13699 (if (with-current-buffer buf
13700 ;; Protect the user-defined function from error
13701 (condition-case nil (funcall ctxt) (error nil))))))
13702 tpl)))
13703 org-remember-templates))
13704 ;; If no template at this point, add the default templates:
13705 (pre-selected-templates1
13706 (if (not (delq nil pre-selected-templates))
13707 (mapcar (lambda(x) (if (not (nth 5 x)) x))
13708 org-remember-templates)
13709 pre-selected-templates))
13710 ;; Then unconditionnally add template for any contexts
13711 (pre-selected-templates2
13712 (append (mapcar (lambda(x) (if (eq (nth 5 x) t) x))
13713 org-remember-templates)
13714 (delq nil pre-selected-templates1)))
13715 (templates (mapcar (lambda (x)
13716 (if (stringp (car x))
13717 (append (list (nth 1 x) (car x)) (cddr x))
13718 (append (list (car x) "") (cdr x))))
13719 (delq nil pre-selected-templates2)))
13720 (char (or use-char
13721 (cond
13722 ((= (length templates) 1)
13723 (caar templates))
13724 ((and (boundp 'org-force-remember-template-char)
13725 org-force-remember-template-char)
13726 (if (stringp org-force-remember-template-char)
13727 (string-to-char org-force-remember-template-char)
13728 org-force-remember-template-char))
13730 (message "Select template: %s"
13731 (mapconcat
13732 (lambda (x)
13733 (cond
13734 ((not (string-match "\\S-" (nth 1 x)))
13735 (format "[%c]" (car x)))
13736 ((equal (downcase (car x))
13737 (downcase (aref (nth 1 x) 0)))
13738 (format "[%c]%s" (car x)
13739 (substring (nth 1 x) 1)))
13740 (t (format "[%c]%s" (car x) (nth 1 x)))))
13741 templates " "))
13742 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13743 (when (equal char0 ?\C-g)
13744 (jump-to-register remember-register)
13745 (kill-buffer remember-buffer))
13746 char0))))))
13747 (cddr (assoc char templates)))))
13749 (defvar x-last-selected-text)
13750 (defvar x-last-selected-text-primary)
13752 ;;;###autoload
13753 (defun org-remember-apply-template (&optional use-char skip-interactive)
13754 "Initialize *remember* buffer with template, invoke `org-mode'.
13755 This function should be placed into `remember-mode-hook' and in fact requires
13756 to be run from that hook to function properly."
13757 (if org-remember-templates
13758 (let* ((entry (org-select-remember-template use-char))
13759 (tpl (car entry))
13760 (plist-p (if org-store-link-plist t nil))
13761 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13762 (string-match "\\S-" (nth 1 entry)))
13763 (nth 1 entry)
13764 org-default-notes-file))
13765 (headline (nth 2 entry))
13766 (v-c (or (and (eq window-system 'x)
13767 (fboundp 'x-cut-buffer-or-selection-value)
13768 (x-cut-buffer-or-selection-value))
13769 (org-bound-and-true-p x-last-selected-text)
13770 (org-bound-and-true-p x-last-selected-text-primary)
13771 (and (> (length kill-ring) 0) (current-kill 0))))
13772 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13773 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13774 (v-u (concat "[" (substring v-t 1 -1) "]"))
13775 (v-U (concat "[" (substring v-T 1 -1) "]"))
13776 ;; `initial' and `annotation' are bound in `remember'
13777 (v-i (if (boundp 'initial) initial))
13778 (v-a (if (and (boundp 'annotation) annotation)
13779 (if (equal annotation "[[]]") "" annotation)
13780 ""))
13781 (v-A (if (and v-a
13782 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13783 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13784 v-a))
13785 (v-n user-full-name)
13786 (org-startup-folded nil)
13787 org-time-was-given org-end-time-was-given x
13788 prompt completions char time pos default histvar)
13789 (setq org-store-link-plist
13790 (append (list :annotation v-a :initial v-i)
13791 org-store-link-plist))
13792 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13793 (erase-buffer)
13794 (insert (substitute-command-keys
13795 (format
13796 "## Filing location: Select interactively, default, or last used:
13797 ## %s to select file and header location interactively.
13798 ## %s \"%s\" -> \"* %s\"
13799 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13800 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13801 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13802 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13803 (abbreviate-file-name (or file org-default-notes-file))
13804 (or headline "")
13805 (or (car org-remember-previous-location) "???")
13806 (or (cdr org-remember-previous-location) "???"))))
13807 (insert tpl) (goto-char (point-min))
13808 ;; Simple %-escapes
13809 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13810 (when (and initial (equal (match-string 0) "%i"))
13811 (save-match-data
13812 (let* ((lead (buffer-substring
13813 (point-at-bol) (match-beginning 0))))
13814 (setq v-i (mapconcat 'identity
13815 (org-split-string initial "\n")
13816 (concat "\n" lead))))))
13817 (replace-match
13818 (or (eval (intern (concat "v-" (match-string 1)))) "")
13819 t t))
13821 ;; %[] Insert contents of a file.
13822 (goto-char (point-min))
13823 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13824 (let ((start (match-beginning 0))
13825 (end (match-end 0))
13826 (filename (expand-file-name (match-string 1))))
13827 (goto-char start)
13828 (delete-region start end)
13829 (condition-case error
13830 (insert-file-contents filename)
13831 (error (insert (format "%%![Couldn't insert %s: %s]"
13832 filename error))))))
13833 ;; %() embedded elisp
13834 (goto-char (point-min))
13835 (while (re-search-forward "%\\((.+)\\)" nil t)
13836 (goto-char (match-beginning 0))
13837 (let ((template-start (point)))
13838 (forward-char 1)
13839 (let ((result
13840 (condition-case error
13841 (eval (read (current-buffer)))
13842 (error (format "%%![Error: %s]" error)))))
13843 (delete-region template-start (point))
13844 (insert result))))
13846 ;; From the property list
13847 (when plist-p
13848 (goto-char (point-min))
13849 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13850 (and (setq x (or (plist-get org-store-link-plist
13851 (intern (match-string 1))) ""))
13852 (replace-match x t t))))
13854 ;; Turn on org-mode in the remember buffer, set local variables
13855 (org-mode)
13856 (org-set-local 'org-finish-function 'org-remember-finalize)
13857 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13858 (org-set-local 'org-default-notes-file file))
13859 (if (and headline (stringp headline) (string-match "\\S-" headline))
13860 (org-set-local 'org-remember-default-headline headline))
13861 ;; Interactive template entries
13862 (goto-char (point-min))
13863 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13864 (setq char (if (match-end 3) (match-string 3))
13865 prompt (if (match-end 2) (match-string 2)))
13866 (goto-char (match-beginning 0))
13867 (replace-match "")
13868 (setq completions nil default nil)
13869 (when prompt
13870 (setq completions (org-split-string prompt "|")
13871 prompt (pop completions)
13872 default (car completions)
13873 histvar (intern (concat
13874 "org-remember-template-prompt-history::"
13875 (or prompt "")))
13876 completions (mapcar 'list completions)))
13877 (cond
13878 ((member char '("G" "g"))
13879 (let* ((org-last-tags-completion-table
13880 (org-global-tags-completion-table
13881 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13882 (org-add-colon-after-tag-completion t)
13883 (ins (completing-read
13884 (if prompt (concat prompt ": ") "Tags: ")
13885 'org-tags-completion-function nil nil nil
13886 'org-tags-history)))
13887 (setq ins (mapconcat 'identity
13888 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13889 ":"))
13890 (when (string-match "\\S-" ins)
13891 (or (equal (char-before) ?:) (insert ":"))
13892 (insert ins)
13893 (or (equal (char-after) ?:) (insert ":")))))
13894 (char
13895 (setq org-time-was-given (equal (upcase char) char))
13896 (setq time (org-read-date (equal (upcase char) "U") t nil
13897 prompt))
13898 (org-insert-time-stamp time org-time-was-given
13899 (member char '("u" "U"))
13900 nil nil (list org-end-time-was-given)))
13902 (insert (org-completing-read
13903 (concat (if prompt prompt "Enter string")
13904 (if default (concat " [" default "]"))
13905 ": ")
13906 completions nil nil nil histvar default)))))
13907 (goto-char (point-min))
13908 (if (re-search-forward "%\\?" nil t)
13909 (replace-match "")
13910 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13911 (org-mode)
13912 (org-set-local 'org-finish-function 'org-remember-finalize))
13913 (when (save-excursion
13914 (goto-char (point-min))
13915 (re-search-forward "%!" nil t))
13916 (replace-match "")
13917 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13919 (defun org-remember-finish-immediately ()
13920 "File remember note immediately.
13921 This should be run in `post-command-hook' and will remove itself
13922 from that hook."
13923 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13924 (when org-finish-function
13925 (funcall org-finish-function)))
13927 (defvar org-clock-marker) ; Defined below
13928 (defun org-remember-finalize ()
13929 "Finalize the remember process."
13930 (unless (fboundp 'remember-finalize)
13931 (defalias 'remember-finalize 'remember-buffer))
13932 (when (and org-clock-marker
13933 (equal (marker-buffer org-clock-marker) (current-buffer)))
13934 ;; FIXME: test this, this is w/o notetaking!
13935 (let (org-log-note-clock-out) (org-clock-out)))
13936 (when buffer-file-name
13937 (save-buffer)
13938 (setq buffer-file-name nil))
13939 (remember-finalize))
13941 ;;;###autoload
13942 (defun org-remember (&optional goto org-force-remember-template-char)
13943 "Call `remember'. If this is already a remember buffer, re-apply template.
13944 If there is an active region, make sure remember uses it as initial content
13945 of the remember buffer.
13947 When called interactively with a `C-u' prefix argument GOTO, don't remember
13948 anything, just go to the file/headline where the selected template usually
13949 stores its notes. With a double prefix arg `C-u C-u', go to the last
13950 note stored by remember.
13952 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13953 associated with a template in `org-remember-templates'."
13954 (interactive "P")
13955 (cond
13956 ((equal goto '(4)) (org-go-to-remember-target))
13957 ((equal goto '(16)) (org-remember-goto-last-stored))
13959 ;; set temporary variables that will be needed in
13960 ;; `org-select-remember-template'
13961 (setq org-select-template-temp-major-mode major-mode)
13962 (setq org-select-template-original-buffer (current-buffer))
13963 (if (memq org-finish-function '(remember-buffer remember-finalize))
13964 (progn
13965 (when (< (length org-remember-templates) 2)
13966 (error "No other template available"))
13967 (erase-buffer)
13968 (let ((annotation (plist-get org-store-link-plist :annotation))
13969 (initial (plist-get org-store-link-plist :initial)))
13970 (org-remember-apply-template))
13971 (message "Press C-c C-c to remember data"))
13972 (if (org-region-active-p)
13973 (remember (buffer-substring (point) (mark)))
13974 (call-interactively 'remember))))))
13976 (defun org-remember-goto-last-stored ()
13977 "Go to the location where the last remember note was stored."
13978 (interactive)
13979 (bookmark-jump "org-remember-last-stored")
13980 (message "This is the last note stored by remember"))
13982 (defun org-go-to-remember-target (&optional template-key)
13983 "Go to the target location of a remember template.
13984 The user is queried for the template."
13985 (interactive)
13986 (let* (org-select-template-temp-major-mode
13987 (entry (org-select-remember-template template-key))
13988 (file (nth 1 entry))
13989 (heading (nth 2 entry))
13990 visiting)
13991 (unless (and file (stringp file) (string-match "\\S-" file))
13992 (setq file org-default-notes-file))
13993 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13994 (setq heading org-remember-default-headline))
13995 (setq visiting (org-find-base-buffer-visiting file))
13996 (if (not visiting) (find-file-noselect file))
13997 (switch-to-buffer (or visiting (get-file-buffer file)))
13998 (widen)
13999 (goto-char (point-min))
14000 (if (re-search-forward
14001 (concat "^\\*+[ \t]+" (regexp-quote heading)
14002 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
14003 nil t)
14004 (goto-char (match-beginning 0))
14005 (error "Target headline not found: %s" heading))))
14007 (defvar org-note-abort nil) ; dynamically scoped
14009 ;;;###autoload
14010 (defun org-remember-handler ()
14011 "Store stuff from remember.el into an org file.
14012 First prompts for an org file. If the user just presses return, the value
14013 of `org-default-notes-file' is used.
14014 Then the command offers the headings tree of the selected file in order to
14015 file the text at a specific location.
14016 You can either immediately press RET to get the note appended to the
14017 file, or you can use vertical cursor motion and visibility cycling (TAB) to
14018 find a better place. Then press RET or <left> or <right> in insert the note.
14020 Key Cursor position Note gets inserted
14021 -----------------------------------------------------------------------------
14022 RET buffer-start as level 1 heading at end of file
14023 RET on headline as sublevel of the heading at cursor
14024 RET no heading at cursor position, level taken from context.
14025 Or use prefix arg to specify level manually.
14026 <left> on headline as same level, before current heading
14027 <right> on headline as same level, after current heading
14029 So the fastest way to store the note is to press RET RET to append it to
14030 the default file. This way your current train of thought is not
14031 interrupted, in accordance with the principles of remember.el.
14032 You can also get the fast execution without prompting by using
14033 C-u C-c C-c to exit the remember buffer. See also the variable
14034 `org-remember-store-without-prompt'.
14036 Before being stored away, the function ensures that the text has a
14037 headline, i.e. a first line that starts with a \"*\". If not, a headline
14038 is constructed from the current date and some additional data.
14040 If the variable `org-adapt-indentation' is non-nil, the entire text is
14041 also indented so that it starts in the same column as the headline
14042 \(i.e. after the stars).
14044 See also the variable `org-reverse-note-order'."
14045 (goto-char (point-min))
14046 (while (looking-at "^[ \t]*\n\\|^##.*\n")
14047 (replace-match ""))
14048 (goto-char (point-max))
14049 (beginning-of-line 1)
14050 (while (looking-at "[ \t]*$\\|##.*")
14051 (delete-region (1- (point)) (point-max))
14052 (beginning-of-line 1))
14053 (catch 'quit
14054 (if org-note-abort (throw 'quit nil))
14055 (let* ((txt (buffer-substring (point-min) (point-max)))
14056 (fastp (org-xor (equal current-prefix-arg '(4))
14057 org-remember-store-without-prompt))
14058 (file (cond
14059 (fastp org-default-notes-file)
14060 ((and (eq org-remember-interactive-interface 'refile)
14061 org-refile-targets)
14062 org-default-notes-file)
14063 ((not (and (equal current-prefix-arg '(16))
14064 org-remember-previous-location))
14065 (org-get-org-file))))
14066 (heading org-remember-default-headline)
14067 (visiting (and file (org-find-base-buffer-visiting file)))
14068 (org-startup-folded nil)
14069 (org-startup-align-all-tables nil)
14070 (org-goto-start-pos 1)
14071 spos exitcmd level indent reversed)
14072 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
14073 (setq file (car org-remember-previous-location)
14074 heading (cdr org-remember-previous-location)
14075 fastp t))
14076 (setq current-prefix-arg nil)
14077 (if (string-match "[ \t\n]+\\'" txt)
14078 (setq txt (replace-match "" t t txt)))
14079 ;; Modify text so that it becomes a nice subtree which can be inserted
14080 ;; into an org tree.
14081 (let* ((lines (split-string txt "\n"))
14082 first)
14083 (setq first (car lines) lines (cdr lines))
14084 (if (string-match "^\\*+ " first)
14085 ;; Is already a headline
14086 (setq indent nil)
14087 ;; We need to add a headline: Use time and first buffer line
14088 (setq lines (cons first lines)
14089 first (concat "* " (current-time-string)
14090 " (" (remember-buffer-desc) ")")
14091 indent " "))
14092 (if (and org-adapt-indentation indent)
14093 (setq lines (mapcar
14094 (lambda (x)
14095 (if (string-match "\\S-" x)
14096 (concat indent x) x))
14097 lines)))
14098 (setq txt (concat first "\n"
14099 (mapconcat 'identity lines "\n"))))
14100 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
14101 (setq txt (replace-match "\n\n" t t txt))
14102 (if (string-match "[ \t\n]*\\'" txt)
14103 (setq txt (replace-match "\n" t t txt))))
14104 ;; Put the modified text back into the remember buffer, for refile.
14105 (erase-buffer)
14106 (insert txt)
14107 (goto-char (point-min))
14108 (when (and (eq org-remember-interactive-interface 'refile)
14109 (not fastp))
14110 (org-refile nil (or visiting (find-file-noselect file)))
14111 (throw 'quit t))
14112 ;; Find the file
14113 (if (not visiting) (find-file-noselect file))
14114 (with-current-buffer (or visiting (get-file-buffer file))
14115 (unless (org-mode-p)
14116 (error "Target files for remember notes must be in Org-mode"))
14117 (save-excursion
14118 (save-restriction
14119 (widen)
14120 (and (goto-char (point-min))
14121 (not (re-search-forward "^\\* " nil t))
14122 (insert "\n* " (or heading "Notes") "\n"))
14123 (setq reversed (org-notes-order-reversed-p))
14125 ;; Find the default location
14126 (when (and heading (stringp heading) (string-match "\\S-" heading))
14127 (goto-char (point-min))
14128 (if (re-search-forward
14129 (concat "^\\*+[ \t]+" (regexp-quote heading)
14130 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
14131 nil t)
14132 (setq org-goto-start-pos (match-beginning 0))
14133 (when fastp
14134 (goto-char (point-max))
14135 (unless (bolp) (newline))
14136 (insert "* " heading "\n")
14137 (setq org-goto-start-pos (point-at-bol 0)))))
14139 ;; Ask the User for a location, using the appropriate interface
14140 (cond
14141 (fastp (setq spos org-goto-start-pos
14142 exitcmd 'return))
14143 ((eq org-remember-interactive-interface 'outline)
14144 (setq spos (org-get-location (current-buffer)
14145 org-remember-help)
14146 exitcmd (cdr spos)
14147 spos (car spos)))
14148 ((eq org-remember-interactive-interface 'outline-path-completion)
14149 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
14150 (org-refile-use-outline-path t))
14151 (setq spos (org-refile-get-location "Heading: ")
14152 exitcmd 'return
14153 spos (nth 3 spos))))
14154 (t (error "this should not hapen")))
14155 (if (not spos) (throw 'quit nil)) ; return nil to show we did
14156 ; not handle this note
14157 (goto-char spos)
14158 (cond ((org-on-heading-p t)
14159 (org-back-to-heading t)
14160 (setq level (funcall outline-level))
14161 (cond
14162 ((eq exitcmd 'return)
14163 ;; sublevel of current
14164 (setq org-remember-previous-location
14165 (cons (abbreviate-file-name file)
14166 (org-get-heading 'notags)))
14167 (if reversed
14168 (outline-next-heading)
14169 (org-end-of-subtree t)
14170 (if (not (bolp))
14171 (if (looking-at "[ \t]*\n")
14172 (beginning-of-line 2)
14173 (end-of-line 1)
14174 (insert "\n"))))
14175 (bookmark-set "org-remember-last-stored")
14176 (org-paste-subtree (org-get-valid-level level 1) txt))
14177 ((eq exitcmd 'left)
14178 ;; before current
14179 (bookmark-set "org-remember-last-stored")
14180 (org-paste-subtree level txt))
14181 ((eq exitcmd 'right)
14182 ;; after current
14183 (org-end-of-subtree t)
14184 (bookmark-set "org-remember-last-stored")
14185 (org-paste-subtree level txt))
14186 (t (error "This should not happen"))))
14188 ((and (bobp) (not reversed))
14189 ;; Put it at the end, one level below level 1
14190 (save-restriction
14191 (widen)
14192 (goto-char (point-max))
14193 (if (not (bolp)) (newline))
14194 (bookmark-set "org-remember-last-stored")
14195 (org-paste-subtree (org-get-valid-level 1 1) txt)))
14197 ((and (bobp) reversed)
14198 ;; Put it at the start, as level 1
14199 (save-restriction
14200 (widen)
14201 (goto-char (point-min))
14202 (re-search-forward "^\\*+ " nil t)
14203 (beginning-of-line 1)
14204 (bookmark-set "org-remember-last-stored")
14205 (org-paste-subtree 1 txt)))
14207 ;; Put it right there, with automatic level determined by
14208 ;; org-paste-subtree or from prefix arg
14209 (bookmark-set "org-remember-last-stored")
14210 (org-paste-subtree
14211 (if (numberp current-prefix-arg) current-prefix-arg)
14212 txt)))
14213 (when remember-save-after-remembering
14214 (save-buffer)
14215 (if (not visiting) (kill-buffer (current-buffer)))))))))
14217 t) ;; return t to indicate that we took care of this note.
14219 (defun org-get-org-file ()
14220 "Read a filename, with default directory `org-directory'."
14221 (let ((default (or org-default-notes-file remember-data-file)))
14222 (read-file-name (format "File name [%s]: " default)
14223 (file-name-as-directory org-directory)
14224 default)))
14226 (defun org-notes-order-reversed-p ()
14227 "Check if the current file should receive notes in reversed order."
14228 (cond
14229 ((not org-reverse-note-order) nil)
14230 ((eq t org-reverse-note-order) t)
14231 ((not (listp org-reverse-note-order)) nil)
14232 (t (catch 'exit
14233 (let ((all org-reverse-note-order)
14234 entry)
14235 (while (setq entry (pop all))
14236 (if (string-match (car entry) buffer-file-name)
14237 (throw 'exit (cdr entry))))
14238 nil)))))
14240 ;;; Refiling
14242 (defvar org-refile-target-table nil
14243 "The list of refile targets, created by `org-refile'.")
14245 (defvar org-agenda-new-buffers nil
14246 "Buffers created to visit agenda files.")
14248 (defun org-get-refile-targets (&optional default-buffer)
14249 "Produce a table with refile targets."
14250 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
14251 targets txt re files f desc descre)
14252 (with-current-buffer (or default-buffer (current-buffer))
14253 (while (setq entry (pop entries))
14254 (setq files (car entry) desc (cdr entry))
14255 (cond
14256 ((null files) (setq files (list (current-buffer))))
14257 ((eq files 'org-agenda-files)
14258 (setq files (org-agenda-files 'unrestricted)))
14259 ((and (symbolp files) (fboundp files))
14260 (setq files (funcall files)))
14261 ((and (symbolp files) (boundp files))
14262 (setq files (symbol-value files))))
14263 (if (stringp files) (setq files (list files)))
14264 (cond
14265 ((eq (car desc) :tag)
14266 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
14267 ((eq (car desc) :todo)
14268 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
14269 ((eq (car desc) :regexp)
14270 (setq descre (cdr desc)))
14271 ((eq (car desc) :level)
14272 (setq descre (concat "^\\*\\{" (number-to-string
14273 (if org-odd-levels-only
14274 (1- (* 2 (cdr desc)))
14275 (cdr desc)))
14276 "\\}[ \t]")))
14277 ((eq (car desc) :maxlevel)
14278 (setq descre (concat "^\\*\\{1," (number-to-string
14279 (if org-odd-levels-only
14280 (1- (* 2 (cdr desc)))
14281 (cdr desc)))
14282 "\\}[ \t]")))
14283 (t (error "Bad refiling target description %s" desc)))
14284 (while (setq f (pop files))
14285 (save-excursion
14286 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
14287 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
14288 (save-excursion
14289 (save-restriction
14290 (widen)
14291 (goto-char (point-min))
14292 (while (re-search-forward descre nil t)
14293 (goto-char (point-at-bol))
14294 (when (looking-at org-complex-heading-regexp)
14295 (setq txt (match-string 4)
14296 re (concat "^" (regexp-quote
14297 (buffer-substring (match-beginning 1)
14298 (match-end 4)))))
14299 (if (match-end 5) (setq re (concat re "[ \t]+"
14300 (regexp-quote
14301 (match-string 5)))))
14302 (setq re (concat re "[ \t]*$"))
14303 (when org-refile-use-outline-path
14304 (setq txt (mapconcat 'identity
14305 (append
14306 (if (eq org-refile-use-outline-path 'file)
14307 (list (file-name-nondirectory
14308 (buffer-file-name (buffer-base-buffer))))
14309 (if (eq org-refile-use-outline-path 'full-file-path)
14310 (list (buffer-file-name (buffer-base-buffer)))))
14311 (org-get-outline-path)
14312 (list txt))
14313 "/")))
14314 (push (list txt f re (point)) targets))
14315 (goto-char (point-at-eol))))))))
14316 (nreverse targets))))
14318 (defun org-get-outline-path ()
14319 "Return the outline path to the current entry, as a list."
14320 (let (rtn)
14321 (save-excursion
14322 (while (org-up-heading-safe)
14323 (when (looking-at org-complex-heading-regexp)
14324 (push (org-match-string-no-properties 4) rtn)))
14325 rtn)))
14327 (defvar org-refile-history nil
14328 "History for refiling operations.")
14330 (defun org-refile (&optional goto default-buffer)
14331 "Move the entry at point to another heading.
14332 The list of target headings is compiled using the information in
14333 `org-refile-targets', which see. This list is created upon first use, and
14334 you can update it by calling this command with a double prefix (`C-u C-u').
14335 FIXME: Can we find a better way of updating?
14337 At the target location, the entry is filed as a subitem of the target heading.
14338 Depending on `org-reverse-note-order', the new subitem will either be the
14339 first of the last subitem.
14341 With prefix arg GOTO, the command will only visit the target location,
14342 not actually move anything.
14343 With a double prefix `C-c C-c', go to the location where the last refiling
14344 operation has put the subtree.
14346 With a double prefix argument, the command can be used to jump to any
14347 heading in the current buffer."
14348 (interactive "P")
14349 (let* ((cbuf (current-buffer))
14350 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14351 pos it nbuf file re level reversed)
14352 (if (equal goto '(16))
14353 (org-refile-goto-last-stored)
14354 (when (setq it (org-refile-get-location
14355 (if goto "Goto: " "Refile to: ") default-buffer))
14356 (setq file (nth 1 it)
14357 re (nth 2 it)
14358 pos (nth 3 it))
14359 (setq nbuf (or (find-buffer-visiting file)
14360 (find-file-noselect file)))
14361 (if goto
14362 (progn
14363 (switch-to-buffer nbuf)
14364 (goto-char pos)
14365 (org-show-context 'org-goto))
14366 (org-copy-special)
14367 (save-excursion
14368 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14369 (find-file-noselect file))))
14370 (setq reversed (org-notes-order-reversed-p))
14371 (save-excursion
14372 (save-restriction
14373 (widen)
14374 (goto-char pos)
14375 (looking-at outline-regexp)
14376 (setq level (org-get-valid-level (funcall outline-level) 1))
14377 (goto-char
14378 (if reversed
14379 (outline-next-heading)
14380 (or (save-excursion (outline-get-next-sibling))
14381 (org-end-of-subtree t t)
14382 (point-max))))
14383 (bookmark-set "org-refile-last-stored")
14384 (org-paste-subtree level))))
14385 (org-cut-special)
14386 (message "Entry refiled to \"%s\"" (car it)))))))
14388 (defun org-refile-goto-last-stored ()
14389 "Go to the location where the last refile was stored."
14390 (interactive)
14391 (bookmark-jump "org-refile-last-stored")
14392 (message "This is the location of the last refile"))
14394 (defun org-refile-get-location (&optional prompt default-buffer)
14395 "Prompt the user for a refile location, using PROMPT."
14396 (let ((org-refile-targets org-refile-targets)
14397 (org-refile-use-outline-path org-refile-use-outline-path))
14398 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14399 (unless org-refile-target-table
14400 (error "No refile targets"))
14401 (let* ((cbuf (current-buffer))
14402 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14403 (fname (and filename (file-truename filename)))
14404 (tbl (mapcar
14405 (lambda (x)
14406 (if (not (equal fname (file-truename (nth 1 x))))
14407 (cons (concat (car x) " (" (file-name-nondirectory
14408 (nth 1 x)) ")")
14409 (cdr x))
14411 org-refile-target-table))
14412 (completion-ignore-case t))
14413 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14414 tbl)))
14416 ;;;; Dynamic blocks
14418 (defun org-find-dblock (name)
14419 "Find the first dynamic block with name NAME in the buffer.
14420 If not found, stay at current position and return nil."
14421 (let (pos)
14422 (save-excursion
14423 (goto-char (point-min))
14424 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14425 nil t)
14426 (match-beginning 0))))
14427 (if pos (goto-char pos))
14428 pos))
14430 (defconst org-dblock-start-re
14431 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14432 "Matches the startline of a dynamic block, with parameters.")
14434 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14435 "Matches the end of a dyhamic block.")
14437 (defun org-create-dblock (plist)
14438 "Create a dynamic block section, with parameters taken from PLIST.
14439 PLIST must containe a :name entry which is used as name of the block."
14440 (unless (bolp) (newline))
14441 (let ((name (plist-get plist :name)))
14442 (insert "#+BEGIN: " name)
14443 (while plist
14444 (if (eq (car plist) :name)
14445 (setq plist (cddr plist))
14446 (insert " " (prin1-to-string (pop plist)))))
14447 (insert "\n\n#+END:\n")
14448 (beginning-of-line -2)))
14450 (defun org-prepare-dblock ()
14451 "Prepare dynamic block for refresh.
14452 This empties the block, puts the cursor at the insert position and returns
14453 the property list including an extra property :name with the block name."
14454 (unless (looking-at org-dblock-start-re)
14455 (error "Not at a dynamic block"))
14456 (let* ((begdel (1+ (match-end 0)))
14457 (name (org-no-properties (match-string 1)))
14458 (params (append (list :name name)
14459 (read (concat "(" (match-string 3) ")")))))
14460 (unless (re-search-forward org-dblock-end-re nil t)
14461 (error "Dynamic block not terminated"))
14462 (setq params
14463 (append params
14464 (list :content (buffer-substring
14465 begdel (match-beginning 0)))))
14466 (delete-region begdel (match-beginning 0))
14467 (goto-char begdel)
14468 (open-line 1)
14469 params))
14471 (defun org-map-dblocks (&optional command)
14472 "Apply COMMAND to all dynamic blocks in the current buffer.
14473 If COMMAND is not given, use `org-update-dblock'."
14474 (let ((cmd (or command 'org-update-dblock))
14475 pos)
14476 (save-excursion
14477 (goto-char (point-min))
14478 (while (re-search-forward org-dblock-start-re nil t)
14479 (goto-char (setq pos (match-beginning 0)))
14480 (condition-case nil
14481 (funcall cmd)
14482 (error (message "Error during update of dynamic block")))
14483 (goto-char pos)
14484 (unless (re-search-forward org-dblock-end-re nil t)
14485 (error "Dynamic block not terminated"))))))
14487 (defun org-dblock-update (&optional arg)
14488 "User command for updating dynamic blocks.
14489 Update the dynamic block at point. With prefix ARG, update all dynamic
14490 blocks in the buffer."
14491 (interactive "P")
14492 (if arg
14493 (org-update-all-dblocks)
14494 (or (looking-at org-dblock-start-re)
14495 (org-beginning-of-dblock))
14496 (org-update-dblock)))
14498 (defun org-update-dblock ()
14499 "Update the dynamic block at point
14500 This means to empty the block, parse for parameters and then call
14501 the correct writing function."
14502 (save-window-excursion
14503 (let* ((pos (point))
14504 (line (org-current-line))
14505 (params (org-prepare-dblock))
14506 (name (plist-get params :name))
14507 (cmd (intern (concat "org-dblock-write:" name))))
14508 (message "Updating dynamic block `%s' at line %d..." name line)
14509 (funcall cmd params)
14510 (message "Updating dynamic block `%s' at line %d...done" name line)
14511 (goto-char pos))))
14513 (defun org-beginning-of-dblock ()
14514 "Find the beginning of the dynamic block at point.
14515 Error if there is no scuh block at point."
14516 (let ((pos (point))
14517 beg)
14518 (end-of-line 1)
14519 (if (and (re-search-backward org-dblock-start-re nil t)
14520 (setq beg (match-beginning 0))
14521 (re-search-forward org-dblock-end-re nil t)
14522 (> (match-end 0) pos))
14523 (goto-char beg)
14524 (goto-char pos)
14525 (error "Not in a dynamic block"))))
14527 (defun org-update-all-dblocks ()
14528 "Update all dynamic blocks in the buffer.
14529 This function can be used in a hook."
14530 (when (org-mode-p)
14531 (org-map-dblocks 'org-update-dblock)))
14534 ;;;; Completion
14536 (defconst org-additional-option-like-keywords
14537 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14538 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14539 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14541 (defun org-complete (&optional arg)
14542 "Perform completion on word at point.
14543 At the beginning of a headline, this completes TODO keywords as given in
14544 `org-todo-keywords'.
14545 If the current word is preceded by a backslash, completes the TeX symbols
14546 that are supported for HTML support.
14547 If the current word is preceded by \"#+\", completes special words for
14548 setting file options.
14549 In the line after \"#+STARTUP:, complete valid keywords.\"
14550 At all other locations, this simply calls the value of
14551 `org-completion-fallback-command'."
14552 (interactive "P")
14553 (org-without-partial-completion
14554 (catch 'exit
14555 (let* ((end (point))
14556 (beg1 (save-excursion
14557 (skip-chars-backward (org-re "[:alnum:]_@"))
14558 (point)))
14559 (beg (save-excursion
14560 (skip-chars-backward "a-zA-Z0-9_:$")
14561 (point)))
14562 (confirm (lambda (x) (stringp (car x))))
14563 (searchhead (equal (char-before beg) ?*))
14564 (tag (and (equal (char-before beg1) ?:)
14565 (equal (char-after (point-at-bol)) ?*)))
14566 (prop (and (equal (char-before beg1) ?:)
14567 (not (equal (char-after (point-at-bol)) ?*))))
14568 (texp (equal (char-before beg) ?\\))
14569 (link (equal (char-before beg) ?\[))
14570 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14571 beg)
14572 "#+"))
14573 (startup (string-match "^#\\+STARTUP:.*"
14574 (buffer-substring (point-at-bol) (point))))
14575 (completion-ignore-case opt)
14576 (type nil)
14577 (tbl nil)
14578 (table (cond
14579 (opt
14580 (setq type :opt)
14581 (append
14582 (mapcar
14583 (lambda (x)
14584 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14585 (cons (match-string 2 x) (match-string 1 x)))
14586 (org-split-string (org-get-current-options) "\n"))
14587 (mapcar 'list org-additional-option-like-keywords)))
14588 (startup
14589 (setq type :startup)
14590 org-startup-options)
14591 (link (append org-link-abbrev-alist-local
14592 org-link-abbrev-alist))
14593 (texp
14594 (setq type :tex)
14595 org-html-entities)
14596 ((string-match "\\`\\*+[ \t]+\\'"
14597 (buffer-substring (point-at-bol) beg))
14598 (setq type :todo)
14599 (mapcar 'list org-todo-keywords-1))
14600 (searchhead
14601 (setq type :searchhead)
14602 (save-excursion
14603 (goto-char (point-min))
14604 (while (re-search-forward org-todo-line-regexp nil t)
14605 (push (list
14606 (org-make-org-heading-search-string
14607 (match-string 3) t))
14608 tbl)))
14609 tbl)
14610 (tag (setq type :tag beg beg1)
14611 (or org-tag-alist (org-get-buffer-tags)))
14612 (prop (setq type :prop beg beg1)
14613 (mapcar 'list (org-buffer-property-keys nil t t)))
14614 (t (progn
14615 (call-interactively org-completion-fallback-command)
14616 (throw 'exit nil)))))
14617 (pattern (buffer-substring-no-properties beg end))
14618 (completion (try-completion pattern table confirm)))
14619 (cond ((eq completion t)
14620 (if (not (assoc (upcase pattern) table))
14621 (message "Already complete")
14622 (if (equal type :opt)
14623 (insert (substring (cdr (assoc (upcase pattern) table))
14624 (length pattern)))
14625 (if (memq type '(:tag :prop)) (insert ":")))))
14626 ((null completion)
14627 (message "Can't find completion for \"%s\"" pattern)
14628 (ding))
14629 ((not (string= pattern completion))
14630 (delete-region beg end)
14631 (if (string-match " +$" completion)
14632 (setq completion (replace-match "" t t completion)))
14633 (insert completion)
14634 (if (get-buffer-window "*Completions*")
14635 (delete-window (get-buffer-window "*Completions*")))
14636 (if (assoc completion table)
14637 (if (eq type :todo) (insert " ")
14638 (if (memq type '(:tag :prop)) (insert ":"))))
14639 (if (and (equal type :opt) (assoc completion table))
14640 (message "%s" (substitute-command-keys
14641 "Press \\[org-complete] again to insert example settings"))))
14643 (message "Making completion list...")
14644 (let ((list (sort (all-completions pattern table confirm)
14645 'string<)))
14646 (with-output-to-temp-buffer "*Completions*"
14647 (condition-case nil
14648 ;; Protection needed for XEmacs and emacs 21
14649 (display-completion-list list pattern)
14650 (error (display-completion-list list)))))
14651 (message "Making completion list...%s" "done")))))))
14653 ;;;; TODO, DEADLINE, Comments
14655 (defun org-toggle-comment ()
14656 "Change the COMMENT state of an entry."
14657 (interactive)
14658 (save-excursion
14659 (org-back-to-heading)
14660 (let (case-fold-search)
14661 (if (looking-at (concat outline-regexp
14662 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14663 (replace-match "" t t nil 1)
14664 (if (looking-at outline-regexp)
14665 (progn
14666 (goto-char (match-end 0))
14667 (insert org-comment-string " ")))))))
14669 (defvar org-last-todo-state-is-todo nil
14670 "This is non-nil when the last TODO state change led to a TODO state.
14671 If the last change removed the TODO tag or switched to DONE, then
14672 this is nil.")
14674 (defvar org-setting-tags nil) ; dynamically skiped
14676 ;; FIXME: better place
14677 (defun org-property-or-variable-value (var &optional inherit)
14678 "Check if there is a property fixing the value of VAR.
14679 If yes, return this value. If not, return the current value of the variable."
14680 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14681 (if (and prop (stringp prop) (string-match "\\S-" prop))
14682 (read prop)
14683 (symbol-value var))))
14685 (defun org-parse-local-options (string var)
14686 "Parse STRING for startup setting relevant for variable VAR."
14687 (let ((rtn (symbol-value var))
14688 e opts)
14689 (save-match-data
14690 (if (or (not string) (not (string-match "\\S-" string)))
14692 (setq opts (delq nil (mapcar (lambda (x)
14693 (setq e (assoc x org-startup-options))
14694 (if (eq (nth 1 e) var) e nil))
14695 (org-split-string string "[ \t]+"))))
14696 (if (not opts)
14698 (setq rtn nil)
14699 (while (setq e (pop opts))
14700 (if (not (nth 3 e))
14701 (setq rtn (nth 2 e))
14702 (if (not (listp rtn)) (setq rtn nil))
14703 (push (nth 2 e) rtn)))
14704 rtn)))))
14706 (defvar org-blocker-hook nil
14707 "Hook for functions that are allowed to block a state change.
14709 Each function gets as its single argument a property list, see
14710 `org-trigger-hook' for more information about this list.
14712 If any of the functions in this hook returns nil, the state change
14713 is blocked.")
14715 (defvar org-trigger-hook nil
14716 "Hook for functions that are triggered by a state change.
14718 Each function gets as its single argument a property list with at least
14719 the following elements:
14721 (:type type-of-change :position pos-at-entry-start
14722 :from old-state :to new-state)
14724 Depending on the type, more properties may be present.
14726 This mechanism is currently implemented for:
14728 TODO state changes
14729 ------------------
14730 :type todo-state-change
14731 :from previous state (keyword as a string), or nil
14732 :to new state (keyword as a string), or nil")
14735 (defun org-todo (&optional arg)
14736 "Change the TODO state of an item.
14737 The state of an item is given by a keyword at the start of the heading,
14738 like
14739 *** TODO Write paper
14740 *** DONE Call mom
14742 The different keywords are specified in the variable `org-todo-keywords'.
14743 By default the available states are \"TODO\" and \"DONE\".
14744 So for this example: when the item starts with TODO, it is changed to DONE.
14745 When it starts with DONE, the DONE is removed. And when neither TODO nor
14746 DONE are present, add TODO at the beginning of the heading.
14748 With C-u prefix arg, use completion to determine the new state.
14749 With numeric prefix arg, switch to that state.
14751 For calling through lisp, arg is also interpreted in the following way:
14752 'none -> empty state
14753 \"\"(empty string) -> switch to empty state
14754 'done -> switch to DONE
14755 'nextset -> switch to the next set of keywords
14756 'previousset -> switch to the previous set of keywords
14757 \"WAITING\" -> switch to the specified keyword, but only if it
14758 really is a member of `org-todo-keywords'."
14759 (interactive "P")
14760 (save-excursion
14761 (catch 'exit
14762 (org-back-to-heading)
14763 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14764 (or (looking-at (concat " +" org-todo-regexp " *"))
14765 (looking-at " *"))
14766 (let* ((match-data (match-data))
14767 (startpos (point-at-bol))
14768 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14769 (org-log-done org-log-done)
14770 (org-log-repeat org-log-repeat)
14771 (org-todo-log-states org-todo-log-states)
14772 (this (match-string 1))
14773 (hl-pos (match-beginning 0))
14774 (head (org-get-todo-sequence-head this))
14775 (ass (assoc head org-todo-kwd-alist))
14776 (interpret (nth 1 ass))
14777 (done-word (nth 3 ass))
14778 (final-done-word (nth 4 ass))
14779 (last-state (or this ""))
14780 (completion-ignore-case t)
14781 (member (member this org-todo-keywords-1))
14782 (tail (cdr member))
14783 (state (cond
14784 ((and org-todo-key-trigger
14785 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14786 (and (not arg) org-use-fast-todo-selection
14787 (not (eq org-use-fast-todo-selection 'prefix)))))
14788 ;; Use fast selection
14789 (org-fast-todo-selection))
14790 ((and (equal arg '(4))
14791 (or (not org-use-fast-todo-selection)
14792 (not org-todo-key-trigger)))
14793 ;; Read a state with completion
14794 (completing-read "State: " (mapcar (lambda(x) (list x))
14795 org-todo-keywords-1)
14796 nil t))
14797 ((eq arg 'right)
14798 (if this
14799 (if tail (car tail) nil)
14800 (car org-todo-keywords-1)))
14801 ((eq arg 'left)
14802 (if (equal member org-todo-keywords-1)
14804 (if this
14805 (nth (- (length org-todo-keywords-1) (length tail) 2)
14806 org-todo-keywords-1)
14807 (org-last org-todo-keywords-1))))
14808 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14809 (setq arg nil))) ; hack to fall back to cycling
14810 (arg
14811 ;; user or caller requests a specific state
14812 (cond
14813 ((equal arg "") nil)
14814 ((eq arg 'none) nil)
14815 ((eq arg 'done) (or done-word (car org-done-keywords)))
14816 ((eq arg 'nextset)
14817 (or (car (cdr (member head org-todo-heads)))
14818 (car org-todo-heads)))
14819 ((eq arg 'previousset)
14820 (let ((org-todo-heads (reverse org-todo-heads)))
14821 (or (car (cdr (member head org-todo-heads)))
14822 (car org-todo-heads))))
14823 ((car (member arg org-todo-keywords-1)))
14824 ((nth (1- (prefix-numeric-value arg))
14825 org-todo-keywords-1))))
14826 ((null member) (or head (car org-todo-keywords-1)))
14827 ((equal this final-done-word) nil) ;; -> make empty
14828 ((null tail) nil) ;; -> first entry
14829 ((eq interpret 'sequence)
14830 (car tail))
14831 ((memq interpret '(type priority))
14832 (if (eq this-command last-command)
14833 (car tail)
14834 (if (> (length tail) 0)
14835 (or done-word (car org-done-keywords))
14836 nil)))
14837 (t nil)))
14838 (next (if state (concat " " state " ") " "))
14839 (change-plist (list :type 'todo-state-change :from this :to state
14840 :position startpos))
14841 dolog now-done-p)
14842 (when org-blocker-hook
14843 (unless (save-excursion
14844 (save-match-data
14845 (run-hook-with-args-until-failure
14846 'org-blocker-hook change-plist)))
14847 (if (interactive-p)
14848 (error "TODO state change from %s to %s blocked" this state)
14849 ;; fail silently
14850 (message "TODO state change from %s to %s blocked" this state)
14851 (throw 'exit nil))))
14852 (store-match-data match-data)
14853 (replace-match next t t)
14854 (unless (pos-visible-in-window-p hl-pos)
14855 (message "TODO state changed to %s" (org-trim next)))
14856 (unless head
14857 (setq head (org-get-todo-sequence-head state)
14858 ass (assoc head org-todo-kwd-alist)
14859 interpret (nth 1 ass)
14860 done-word (nth 3 ass)
14861 final-done-word (nth 4 ass)))
14862 (when (memq arg '(nextset previousset))
14863 (message "Keyword-Set %d/%d: %s"
14864 (- (length org-todo-sets) -1
14865 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14866 (length org-todo-sets)
14867 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14868 (setq org-last-todo-state-is-todo
14869 (not (member state org-done-keywords)))
14870 (setq now-done-p (and (member state org-done-keywords)
14871 (not (member this org-done-keywords))))
14872 (and logging (org-local-logging logging))
14873 (when (and (or org-todo-log-states org-log-done)
14874 (not (memq arg '(nextset previousset))))
14875 ;; we need to look at recording a time and note
14876 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14877 (nth 2 (assoc this org-todo-log-states))))
14878 (when (and state
14879 (member state org-not-done-keywords)
14880 (not (member this org-not-done-keywords)))
14881 ;; This is now a todo state and was not one before
14882 ;; If there was a CLOSED time stamp, get rid of it.
14883 (org-add-planning-info nil nil 'closed))
14884 (when (and now-done-p org-log-done)
14885 ;; It is now done, and it was not done before
14886 (org-add-planning-info 'closed (org-current-time))
14887 (if (and (not dolog) (eq 'note org-log-done))
14888 (org-add-log-maybe 'done state 'findpos 'note)))
14889 (when (and state dolog)
14890 ;; This is a non-nil state, and we need to log it
14891 (org-add-log-maybe 'state state 'findpos dolog)))
14892 ;; Fixup tag positioning
14893 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14894 (run-hooks 'org-after-todo-state-change-hook)
14895 (if (and arg (not (member state org-done-keywords)))
14896 (setq head (org-get-todo-sequence-head state)))
14897 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14898 ;; Do we need to trigger a repeat?
14899 (when now-done-p (org-auto-repeat-maybe state))
14900 ;; Fixup cursor location if close to the keyword
14901 (if (and (outline-on-heading-p)
14902 (not (bolp))
14903 (save-excursion (beginning-of-line 1)
14904 (looking-at org-todo-line-regexp))
14905 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14906 (progn
14907 (goto-char (or (match-end 2) (match-end 1)))
14908 (just-one-space)))
14909 (when org-trigger-hook
14910 (save-excursion
14911 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14913 (defun org-local-logging (value)
14914 "Get logging settings from a property VALUE."
14915 (let* (words w a)
14916 ;; directly set the variables, they are already local.
14917 (setq org-log-done nil
14918 org-log-repeat nil
14919 org-todo-log-states nil)
14920 (setq words (org-split-string value))
14921 (while (setq w (pop words))
14922 (cond
14923 ((setq a (assoc w org-startup-options))
14924 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14925 (set (nth 1 a) (nth 2 a))))
14926 ((setq a (org-extract-log-state-settings w))
14927 (and (member (car a) org-todo-keywords-1)
14928 (push a org-todo-log-states)))))))
14930 (defun org-get-todo-sequence-head (kwd)
14931 "Return the head of the TODO sequence to which KWD belongs.
14932 If KWD is not set, check if there is a text property remembering the
14933 right sequence."
14934 (let (p)
14935 (cond
14936 ((not kwd)
14937 (or (get-text-property (point-at-bol) 'org-todo-head)
14938 (progn
14939 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14940 nil (point-at-eol)))
14941 (get-text-property p 'org-todo-head))))
14942 ((not (member kwd org-todo-keywords-1))
14943 (car org-todo-keywords-1))
14944 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14946 (defun org-fast-todo-selection ()
14947 "Fast TODO keyword selection with single keys.
14948 Returns the new TODO keyword, or nil if no state change should occur."
14949 (let* ((fulltable org-todo-key-alist)
14950 (done-keywords org-done-keywords) ;; needed for the faces.
14951 (maxlen (apply 'max (mapcar
14952 (lambda (x)
14953 (if (stringp (car x)) (string-width (car x)) 0))
14954 fulltable)))
14955 (expert nil)
14956 (fwidth (+ maxlen 3 1 3))
14957 (ncol (/ (- (window-width) 4) fwidth))
14958 tg cnt e c tbl
14959 groups ingroup)
14960 (save-window-excursion
14961 (if expert
14962 (set-buffer (get-buffer-create " *Org todo*"))
14963 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14964 (erase-buffer)
14965 (org-set-local 'org-done-keywords done-keywords)
14966 (setq tbl fulltable cnt 0)
14967 (while (setq e (pop tbl))
14968 (cond
14969 ((equal e '(:startgroup))
14970 (push '() groups) (setq ingroup t)
14971 (when (not (= cnt 0))
14972 (setq cnt 0)
14973 (insert "\n"))
14974 (insert "{ "))
14975 ((equal e '(:endgroup))
14976 (setq ingroup nil cnt 0)
14977 (insert "}\n"))
14979 (setq tg (car e) c (cdr e))
14980 (if ingroup (push tg (car groups)))
14981 (setq tg (org-add-props tg nil 'face
14982 (org-get-todo-face tg)))
14983 (if (and (= cnt 0) (not ingroup)) (insert " "))
14984 (insert "[" c "] " tg (make-string
14985 (- fwidth 4 (length tg)) ?\ ))
14986 (when (= (setq cnt (1+ cnt)) ncol)
14987 (insert "\n")
14988 (if ingroup (insert " "))
14989 (setq cnt 0)))))
14990 (insert "\n")
14991 (goto-char (point-min))
14992 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14993 (fit-window-to-buffer))
14994 (message "[a-z..]:Set [SPC]:clear")
14995 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14996 (cond
14997 ((or (= c ?\C-g)
14998 (and (= c ?q) (not (rassoc c fulltable))))
14999 (setq quit-flag t))
15000 ((= c ?\ ) nil)
15001 ((setq e (rassoc c fulltable) tg (car e))
15003 (t (setq quit-flag t))))))
15005 (defun org-get-repeat ()
15006 "Check if tere is a deadline/schedule with repeater in this entry."
15007 (save-match-data
15008 (save-excursion
15009 (org-back-to-heading t)
15010 (if (re-search-forward
15011 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
15012 (match-string 1)))))
15014 (defvar org-last-changed-timestamp)
15015 (defvar org-log-post-message)
15016 (defvar org-log-note-purpose)
15017 (defun org-auto-repeat-maybe (done-word)
15018 "Check if the current headline contains a repeated deadline/schedule.
15019 If yes, set TODO state back to what it was and change the base date
15020 of repeating deadline/scheduled time stamps to new date.
15021 This function is run automatically after each state change to a DONE state."
15022 ;; last-state is dynamically scoped into this function
15023 (let* ((repeat (org-get-repeat))
15024 (aa (assoc last-state org-todo-kwd-alist))
15025 (interpret (nth 1 aa))
15026 (head (nth 2 aa))
15027 (whata '(("d" . day) ("m" . month) ("y" . year)))
15028 (msg "Entry repeats: ")
15029 (org-log-done nil)
15030 (org-todo-log-states nil)
15031 (nshiftmax 10) (nshift 0)
15032 re type n what ts mb0 time)
15033 (when repeat
15034 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
15035 (org-todo (if (eq interpret 'type) last-state head))
15036 (when (and org-log-repeat
15037 (or (not (memq 'org-add-log-note
15038 (default-value 'post-command-hook)))
15039 (eq org-log-note-purpose 'done)))
15040 ;; Make sure a note is taken;
15041 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
15042 'findpos org-log-repeat))
15043 (org-back-to-heading t)
15044 (org-add-planning-info nil nil 'closed)
15045 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
15046 org-deadline-time-regexp "\\)\\|\\("
15047 org-ts-regexp "\\)"))
15048 (while (re-search-forward
15049 re (save-excursion (outline-next-heading) (point)) t)
15050 (setq type (if (match-end 1) org-scheduled-string
15051 (if (match-end 3) org-deadline-string "Plain:"))
15052 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
15053 mb0 (match-beginning 0))
15054 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
15055 (setq n (string-to-number (match-string 2 ts))
15056 what (match-string 3 ts))
15057 (if (equal what "w") (setq n (* n 7) what "d"))
15058 ;; Preparation, see if we need to modify the start date for the change
15059 (when (match-end 1)
15060 (setq time (save-match-data (org-time-string-to-time ts)))
15061 (cond
15062 ((equal (match-string 1 ts) ".")
15063 ;; Shift starting date to today
15064 (org-timestamp-change
15065 (- (time-to-days (current-time)) (time-to-days time))
15066 'day))
15067 ((equal (match-string 1 ts) "+")
15068 (while (< (time-to-days time) (time-to-days (current-time)))
15069 (when (= (incf nshift) nshiftmax)
15070 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
15071 (error "Abort")))
15072 (org-timestamp-change n (cdr (assoc what whata)))
15073 (sit-for .0001) ;; so we can watch the date shifting
15074 (org-at-timestamp-p t)
15075 (setq ts (match-string 1))
15076 (setq time (save-match-data (org-time-string-to-time ts))))
15077 (org-timestamp-change (- n) (cdr (assoc what whata)))
15078 ;; rematch, so that we have everything in place for the real shift
15079 (org-at-timestamp-p t)
15080 (setq ts (match-string 1))
15081 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
15082 (org-timestamp-change n (cdr (assoc what whata)))
15083 (setq msg (concat msg type org-last-changed-timestamp " "))))
15084 (setq org-log-post-message msg)
15085 (message "%s" msg))))
15087 (defun org-show-todo-tree (arg)
15088 "Make a compact tree which shows all headlines marked with TODO.
15089 The tree will show the lines where the regexp matches, and all higher
15090 headlines above the match.
15091 With a \\[universal-argument] prefix, also show the DONE entries.
15092 With a numeric prefix N, construct a sparse tree for the Nth element
15093 of `org-todo-keywords-1'."
15094 (interactive "P")
15095 (let ((case-fold-search nil)
15096 (kwd-re
15097 (cond ((null arg) org-not-done-regexp)
15098 ((equal arg '(4))
15099 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
15100 (mapcar 'list org-todo-keywords-1))))
15101 (concat "\\("
15102 (mapconcat 'identity (org-split-string kwd "|") "\\|")
15103 "\\)\\>")))
15104 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
15105 (regexp-quote (nth (1- (prefix-numeric-value arg))
15106 org-todo-keywords-1)))
15107 (t (error "Invalid prefix argument: %s" arg)))))
15108 (message "%d TODO entries found"
15109 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
15111 (defun org-deadline (&optional remove)
15112 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
15113 With argument REMOVE, remove any deadline from the item."
15114 (interactive "P")
15115 (if remove
15116 (progn
15117 (org-remove-timestamp-with-keyword org-deadline-string)
15118 (message "Item no longer has a deadline."))
15119 (org-add-planning-info 'deadline nil 'closed)))
15121 (defun org-schedule (&optional remove)
15122 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
15123 With argument REMOVE, remove any scheduling date from the item."
15124 (interactive "P")
15125 (if remove
15126 (progn
15127 (org-remove-timestamp-with-keyword org-scheduled-string)
15128 (message "Item is no longer scheduled."))
15129 (org-add-planning-info 'scheduled nil 'closed)))
15131 (defun org-remove-timestamp-with-keyword (keyword)
15132 "Remove all time stamps with KEYWORD in the current entry."
15133 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
15134 beg)
15135 (save-excursion
15136 (org-back-to-heading t)
15137 (setq beg (point))
15138 (org-end-of-subtree t t)
15139 (while (re-search-backward re beg t)
15140 (replace-match "")
15141 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
15142 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
15144 (defun org-add-planning-info (what &optional time &rest remove)
15145 "Insert new timestamp with keyword in the line directly after the headline.
15146 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
15147 If non is given, the user is prompted for a date.
15148 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
15149 be removed."
15150 (interactive)
15151 (let (org-time-was-given org-end-time-was-given)
15152 (when what (setq time (or time (org-read-date nil 'to-time))))
15153 (when (and org-insert-labeled-timestamps-at-point
15154 (member what '(scheduled deadline)))
15155 (insert
15156 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
15157 (org-insert-time-stamp time org-time-was-given
15158 nil nil nil (list org-end-time-was-given))
15159 (setq what nil))
15160 (save-excursion
15161 (save-restriction
15162 (let (col list elt ts buffer-invisibility-spec)
15163 (org-back-to-heading t)
15164 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
15165 (goto-char (match-end 1))
15166 (setq col (current-column))
15167 (goto-char (match-end 0))
15168 (if (eobp) (insert "\n") (forward-char 1))
15169 (if (and (not (looking-at outline-regexp))
15170 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
15171 "[^\r\n]*"))
15172 (not (equal (match-string 1) org-clock-string)))
15173 (narrow-to-region (match-beginning 0) (match-end 0))
15174 (insert-before-markers "\n")
15175 (backward-char 1)
15176 (narrow-to-region (point) (point))
15177 (indent-to-column col))
15178 ;; Check if we have to remove something.
15179 (setq list (cons what remove))
15180 (while list
15181 (setq elt (pop list))
15182 (goto-char (point-min))
15183 (when (or (and (eq elt 'scheduled)
15184 (re-search-forward org-scheduled-time-regexp nil t))
15185 (and (eq elt 'deadline)
15186 (re-search-forward org-deadline-time-regexp nil t))
15187 (and (eq elt 'closed)
15188 (re-search-forward org-closed-time-regexp nil t)))
15189 (replace-match "")
15190 (if (looking-at "--+<[^>]+>") (replace-match ""))
15191 (if (looking-at " +") (replace-match ""))))
15192 (goto-char (point-max))
15193 (when what
15194 (insert
15195 (if (not (equal (char-before) ?\ )) " " "")
15196 (cond ((eq what 'scheduled) org-scheduled-string)
15197 ((eq what 'deadline) org-deadline-string)
15198 ((eq what 'closed) org-closed-string))
15199 " ")
15200 (setq ts (org-insert-time-stamp
15201 time
15202 (or org-time-was-given
15203 (and (eq what 'closed) org-log-done-with-time))
15204 (eq what 'closed)
15205 nil nil (list org-end-time-was-given)))
15206 (end-of-line 1))
15207 (goto-char (point-min))
15208 (widen)
15209 (if (looking-at "[ \t]+\r?\n")
15210 (replace-match ""))
15211 ts)))))
15213 (defvar org-log-note-marker (make-marker))
15214 (defvar org-log-note-purpose nil)
15215 (defvar org-log-note-state nil)
15216 (defvar org-log-note-how nil)
15217 (defvar org-log-note-window-configuration nil)
15218 (defvar org-log-note-return-to (make-marker))
15219 (defvar org-log-post-message nil
15220 "Message to be displayed after a log note has been stored.
15221 The auto-repeater uses this.")
15223 (defun org-add-log-maybe (&optional purpose state findpos how)
15224 "Set up the post command hook to take a note.
15225 If this is about to TODO state change, the new state is expected in STATE.
15226 When FINDPOS is non-nil, find the correct position for the note in
15227 the current entry. If not, assume that it can be inserted at point."
15228 (save-excursion
15229 (when findpos
15230 (org-back-to-heading t)
15231 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
15232 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
15233 "[^\r\n]*\\)?"))
15234 (goto-char (match-end 0))
15235 (unless org-log-states-order-reversed
15236 (and (= (char-after) ?\n) (forward-char 1))
15237 (org-skip-over-state-notes)
15238 (skip-chars-backward " \t\n\r")))
15239 (move-marker org-log-note-marker (point))
15240 (setq org-log-note-purpose purpose
15241 org-log-note-state state
15242 org-log-note-how how)
15243 (add-hook 'post-command-hook 'org-add-log-note 'append)))
15245 (defun org-skip-over-state-notes ()
15246 "Skip past the list of State notes in an entry."
15247 (if (looking-at "\n[ \t]*- State") (forward-char 1))
15248 (while (looking-at "[ \t]*- State")
15249 (condition-case nil
15250 (org-next-item)
15251 (error (org-end-of-item)))))
15253 (defun org-add-log-note (&optional purpose)
15254 "Pop up a window for taking a note, and add this note later at point."
15255 (remove-hook 'post-command-hook 'org-add-log-note)
15256 (setq org-log-note-window-configuration (current-window-configuration))
15257 (delete-other-windows)
15258 (move-marker org-log-note-return-to (point))
15259 (switch-to-buffer (marker-buffer org-log-note-marker))
15260 (goto-char org-log-note-marker)
15261 (org-switch-to-buffer-other-window "*Org Note*")
15262 (erase-buffer)
15263 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
15264 (org-store-log-note)
15265 (let ((org-inhibit-startup t)) (org-mode))
15266 (insert (format "# Insert note for %s.
15267 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
15268 (cond
15269 ((eq org-log-note-purpose 'clock-out) "stopped clock")
15270 ((eq org-log-note-purpose 'done) "closed todo item")
15271 ((eq org-log-note-purpose 'state)
15272 (format "state change to \"%s\"" org-log-note-state))
15273 (t (error "This should not happen")))))
15274 (org-set-local 'org-finish-function 'org-store-log-note)))
15276 (defun org-store-log-note ()
15277 "Finish taking a log note, and insert it to where it belongs."
15278 (let ((txt (buffer-string))
15279 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
15280 lines ind)
15281 (kill-buffer (current-buffer))
15282 (while (string-match "\\`#.*\n[ \t\n]*" txt)
15283 (setq txt (replace-match "" t t txt)))
15284 (if (string-match "\\s-+\\'" txt)
15285 (setq txt (replace-match "" t t txt)))
15286 (setq lines (org-split-string txt "\n"))
15287 (when (and note (string-match "\\S-" note))
15288 (setq note
15289 (org-replace-escapes
15290 note
15291 (list (cons "%u" (user-login-name))
15292 (cons "%U" user-full-name)
15293 (cons "%t" (format-time-string
15294 (org-time-stamp-format 'long 'inactive)
15295 (current-time)))
15296 (cons "%s" (if org-log-note-state
15297 (concat "\"" org-log-note-state "\"")
15298 "")))))
15299 (if lines (setq note (concat note " \\\\")))
15300 (push note lines))
15301 (when (or current-prefix-arg org-note-abort) (setq lines nil))
15302 (when lines
15303 (save-excursion
15304 (set-buffer (marker-buffer org-log-note-marker))
15305 (save-excursion
15306 (goto-char org-log-note-marker)
15307 (move-marker org-log-note-marker nil)
15308 (end-of-line 1)
15309 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
15310 (indent-relative nil)
15311 (insert "- " (pop lines))
15312 (org-indent-line-function)
15313 (beginning-of-line 1)
15314 (looking-at "[ \t]*")
15315 (setq ind (concat (match-string 0) " "))
15316 (end-of-line 1)
15317 (while lines (insert "\n" ind (pop lines)))))))
15318 (set-window-configuration org-log-note-window-configuration)
15319 (with-current-buffer (marker-buffer org-log-note-return-to)
15320 (goto-char org-log-note-return-to))
15321 (move-marker org-log-note-return-to nil)
15322 (and org-log-post-message (message "%s" org-log-post-message)))
15324 ;; FIXME: what else would be useful?
15325 ;; - priority
15326 ;; - date
15328 (defun org-sparse-tree (&optional arg)
15329 "Create a sparse tree, prompt for the details.
15330 This command can create sparse trees. You first need to select the type
15331 of match used to create the tree:
15333 t Show entries with a specific TODO keyword.
15334 T Show entries selected by a tags match.
15335 p Enter a property name and its value (both with completion on existing
15336 names/values) and show entries with that property.
15337 r Show entries matching a regular expression
15338 d Show deadlines due within `org-deadline-warning-days'."
15339 (interactive "P")
15340 (let (ans kwd value)
15341 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15342 (setq ans (read-char-exclusive))
15343 (cond
15344 ((equal ans ?d)
15345 (call-interactively 'org-check-deadlines))
15346 ((equal ans ?b)
15347 (call-interactively 'org-check-before-date))
15348 ((equal ans ?t)
15349 (org-show-todo-tree '(4)))
15350 ((equal ans ?T)
15351 (call-interactively 'org-tags-sparse-tree))
15352 ((member ans '(?p ?P))
15353 (setq kwd (completing-read "Property: "
15354 (mapcar 'list (org-buffer-property-keys))))
15355 (setq value (completing-read "Value: "
15356 (mapcar 'list (org-property-values kwd))))
15357 (unless (string-match "\\`{.*}\\'" value)
15358 (setq value (concat "\"" value "\"")))
15359 (org-tags-sparse-tree arg (concat kwd "=" value)))
15360 ((member ans '(?r ?R ?/))
15361 (call-interactively 'org-occur))
15362 (t (error "No such sparse tree command \"%c\"" ans)))))
15364 (defvar org-occur-highlights nil
15365 "List of overlays used for occur matches.")
15366 (make-variable-buffer-local 'org-occur-highlights)
15367 (defvar org-occur-parameters nil
15368 "Parameters of the active org-occur calls.
15369 This is a list, each call to org-occur pushes as cons cell,
15370 containing the regular expression and the callback, onto the list.
15371 The list can contain several entries if `org-occur' has been called
15372 several time with the KEEP-PREVIOUS argument. Otherwise, this list
15373 will only contain one set of parameters. When the highlights are
15374 removed (for example with `C-c C-c', or with the next edit (depending
15375 on `org-remove-highlights-with-change'), this variable is emptied
15376 as well.")
15377 (make-variable-buffer-local 'org-occur-parameters)
15379 (defun org-occur (regexp &optional keep-previous callback)
15380 "Make a compact tree which shows all matches of REGEXP.
15381 The tree will show the lines where the regexp matches, and all higher
15382 headlines above the match. It will also show the heading after the match,
15383 to make sure editing the matching entry is easy.
15384 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15385 call to `org-occur' will be kept, to allow stacking of calls to this
15386 command.
15387 If CALLBACK is non-nil, it is a function which is called to confirm
15388 that the match should indeed be shown."
15389 (interactive "sRegexp: \nP")
15390 (unless keep-previous
15391 (org-remove-occur-highlights nil nil t))
15392 (push (cons regexp callback) org-occur-parameters)
15393 (let ((cnt 0))
15394 (save-excursion
15395 (goto-char (point-min))
15396 (if (or (not keep-previous) ; do not want to keep
15397 (not org-occur-highlights)) ; no previous matches
15398 ;; hide everything
15399 (org-overview))
15400 (while (re-search-forward regexp nil t)
15401 (when (or (not callback)
15402 (save-match-data (funcall callback)))
15403 (setq cnt (1+ cnt))
15404 (when org-highlight-sparse-tree-matches
15405 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15406 (org-show-context 'occur-tree))))
15407 (when org-remove-highlights-with-change
15408 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15409 nil 'local))
15410 (unless org-sparse-tree-open-archived-trees
15411 (org-hide-archived-subtrees (point-min) (point-max)))
15412 (run-hooks 'org-occur-hook)
15413 (if (interactive-p)
15414 (message "%d match(es) for regexp %s" cnt regexp))
15415 cnt))
15417 (defun org-show-context (&optional key)
15418 "Make sure point and context and visible.
15419 How much context is shown depends upon the variables
15420 `org-show-hierarchy-above', `org-show-following-heading'. and
15421 `org-show-siblings'."
15422 (let ((heading-p (org-on-heading-p t))
15423 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15424 (following-p (org-get-alist-option org-show-following-heading key))
15425 (entry-p (org-get-alist-option org-show-entry-below key))
15426 (siblings-p (org-get-alist-option org-show-siblings key)))
15427 (catch 'exit
15428 ;; Show heading or entry text
15429 (if (and heading-p (not entry-p))
15430 (org-flag-heading nil) ; only show the heading
15431 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15432 (org-show-hidden-entry))) ; show entire entry
15433 (when following-p
15434 ;; Show next sibling, or heading below text
15435 (save-excursion
15436 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15437 (org-flag-heading nil))))
15438 (when siblings-p (org-show-siblings))
15439 (when hierarchy-p
15440 ;; show all higher headings, possibly with siblings
15441 (save-excursion
15442 (while (and (condition-case nil
15443 (progn (org-up-heading-all 1) t)
15444 (error nil))
15445 (not (bobp)))
15446 (org-flag-heading nil)
15447 (when siblings-p (org-show-siblings))))))))
15449 (defun org-reveal (&optional siblings)
15450 "Show current entry, hierarchy above it, and the following headline.
15451 This can be used to show a consistent set of context around locations
15452 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15453 not t for the search context.
15455 With optional argument SIBLINGS, on each level of the hierarchy all
15456 siblings are shown. This repairs the tree structure to what it would
15457 look like when opened with hierarchical calls to `org-cycle'."
15458 (interactive "P")
15459 (let ((org-show-hierarchy-above t)
15460 (org-show-following-heading t)
15461 (org-show-siblings (if siblings t org-show-siblings)))
15462 (org-show-context nil)))
15464 (defun org-highlight-new-match (beg end)
15465 "Highlight from BEG to END and mark the highlight is an occur headline."
15466 (let ((ov (org-make-overlay beg end)))
15467 (org-overlay-put ov 'face 'secondary-selection)
15468 (push ov org-occur-highlights)))
15470 (defun org-remove-occur-highlights (&optional beg end noremove)
15471 "Remove the occur highlights from the buffer.
15472 BEG and END are ignored. If NOREMOVE is nil, remove this function
15473 from the `before-change-functions' in the current buffer."
15474 (interactive)
15475 (unless org-inhibit-highlight-removal
15476 (mapc 'org-delete-overlay org-occur-highlights)
15477 (setq org-occur-highlights nil)
15478 (setq org-occur-parameters nil)
15479 (unless noremove
15480 (remove-hook 'before-change-functions
15481 'org-remove-occur-highlights 'local))))
15483 ;;;; Priorities
15485 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15486 "Regular expression matching the priority indicator.")
15488 (defvar org-remove-priority-next-time nil)
15490 (defun org-priority-up ()
15491 "Increase the priority of the current item."
15492 (interactive)
15493 (org-priority 'up))
15495 (defun org-priority-down ()
15496 "Decrease the priority of the current item."
15497 (interactive)
15498 (org-priority 'down))
15500 (defun org-priority (&optional action)
15501 "Change the priority of an item by ARG.
15502 ACTION can be `set', `up', `down', or a character."
15503 (interactive)
15504 (setq action (or action 'set))
15505 (let (current new news have remove)
15506 (save-excursion
15507 (org-back-to-heading)
15508 (if (looking-at org-priority-regexp)
15509 (setq current (string-to-char (match-string 2))
15510 have t)
15511 (setq current org-default-priority))
15512 (cond
15513 ((or (eq action 'set) (integerp action))
15514 (if (integerp action)
15515 (setq new action)
15516 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15517 (setq new (read-char-exclusive)))
15518 (if (and (= (upcase org-highest-priority) org-highest-priority)
15519 (= (upcase org-lowest-priority) org-lowest-priority))
15520 (setq new (upcase new)))
15521 (cond ((equal new ?\ ) (setq remove t))
15522 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15523 (error "Priority must be between `%c' and `%c'"
15524 org-highest-priority org-lowest-priority))))
15525 ((eq action 'up)
15526 (if (and (not have) (eq last-command this-command))
15527 (setq new org-lowest-priority)
15528 (setq new (if (and org-priority-start-cycle-with-default (not have))
15529 org-default-priority (1- current)))))
15530 ((eq action 'down)
15531 (if (and (not have) (eq last-command this-command))
15532 (setq new org-highest-priority)
15533 (setq new (if (and org-priority-start-cycle-with-default (not have))
15534 org-default-priority (1+ current)))))
15535 (t (error "Invalid action")))
15536 (if (or (< (upcase new) org-highest-priority)
15537 (> (upcase new) org-lowest-priority))
15538 (setq remove t))
15539 (setq news (format "%c" new))
15540 (if have
15541 (if remove
15542 (replace-match "" t t nil 1)
15543 (replace-match news t t nil 2))
15544 (if remove
15545 (error "No priority cookie found in line")
15546 (looking-at org-todo-line-regexp)
15547 (if (match-end 2)
15548 (progn
15549 (goto-char (match-end 2))
15550 (insert " [#" news "]"))
15551 (goto-char (match-beginning 3))
15552 (insert "[#" news "] ")))))
15553 (org-preserve-lc (org-set-tags nil 'align))
15554 (if remove
15555 (message "Priority removed")
15556 (message "Priority of current item set to %s" news))))
15559 (defun org-get-priority (s)
15560 "Find priority cookie and return priority."
15561 (save-match-data
15562 (if (not (string-match org-priority-regexp s))
15563 (* 1000 (- org-lowest-priority org-default-priority))
15564 (* 1000 (- org-lowest-priority
15565 (string-to-char (match-string 2 s)))))))
15567 ;;;; Tags
15569 (defun org-scan-tags (action matcher &optional todo-only)
15570 "Scan headline tags with inheritance and produce output ACTION.
15571 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15572 evaluated, testing if a given set of tags qualifies a headline for
15573 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15574 are included in the output."
15575 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15576 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15577 (org-re
15578 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15579 (props (list 'face nil
15580 'done-face 'org-done
15581 'undone-face nil
15582 'mouse-face 'highlight
15583 'org-not-done-regexp org-not-done-regexp
15584 'org-todo-regexp org-todo-regexp
15585 'keymap org-agenda-keymap
15586 'help-echo
15587 (format "mouse-2 or RET jump to org file %s"
15588 (abbreviate-file-name
15589 (or (buffer-file-name (buffer-base-buffer))
15590 (buffer-name (buffer-base-buffer)))))))
15591 (case-fold-search nil)
15592 lspos
15593 tags tags-list tags-alist (llast 0) rtn level category i txt
15594 todo marker entry priority)
15595 (save-excursion
15596 (goto-char (point-min))
15597 (when (eq action 'sparse-tree)
15598 (org-overview)
15599 (org-remove-occur-highlights))
15600 (while (re-search-forward re nil t)
15601 (catch :skip
15602 (setq todo (if (match-end 1) (match-string 2))
15603 tags (if (match-end 4) (match-string 4)))
15604 (goto-char (setq lspos (1+ (match-beginning 0))))
15605 (setq level (org-reduced-level (funcall outline-level))
15606 category (org-get-category))
15607 (setq i llast llast level)
15608 ;; remove tag lists from same and sublevels
15609 (while (>= i level)
15610 (when (setq entry (assoc i tags-alist))
15611 (setq tags-alist (delete entry tags-alist)))
15612 (setq i (1- i)))
15613 ;; add the nex tags
15614 (when tags
15615 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15616 tags-alist
15617 (cons (cons level tags) tags-alist)))
15618 ;; compile tags for current headline
15619 (setq tags-list
15620 (if org-use-tag-inheritance
15621 (apply 'append (mapcar 'cdr tags-alist))
15622 tags))
15623 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15624 (eval matcher)
15625 (or (not org-agenda-skip-archived-trees)
15626 (not (member org-archive-tag tags-list))))
15627 (and (eq action 'agenda) (org-agenda-skip))
15628 ;; list this headline
15630 (if (eq action 'sparse-tree)
15631 (progn
15632 (and org-highlight-sparse-tree-matches
15633 (org-get-heading) (match-end 0)
15634 (org-highlight-new-match
15635 (match-beginning 0) (match-beginning 1)))
15636 (org-show-context 'tags-tree))
15637 (setq txt (org-format-agenda-item
15639 (concat
15640 (if org-tags-match-list-sublevels
15641 (make-string (1- level) ?.) "")
15642 (org-get-heading))
15643 category tags-list)
15644 priority (org-get-priority txt))
15645 (goto-char lspos)
15646 (setq marker (org-agenda-new-marker))
15647 (org-add-props txt props
15648 'org-marker marker 'org-hd-marker marker 'org-category category
15649 'priority priority 'type "tagsmatch")
15650 (push txt rtn))
15651 ;; if we are to skip sublevels, jump to end of subtree
15652 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15653 (when (and (eq action 'sparse-tree)
15654 (not org-sparse-tree-open-archived-trees))
15655 (org-hide-archived-subtrees (point-min) (point-max)))
15656 (nreverse rtn)))
15658 (defvar todo-only) ;; dynamically scoped
15660 (defun org-tags-sparse-tree (&optional todo-only match)
15661 "Create a sparse tree according to tags string MATCH.
15662 MATCH can contain positive and negative selection of tags, like
15663 \"+WORK+URGENT-WITHBOSS\".
15664 If optional argument TODO_ONLY is non-nil, only select lines that are
15665 also TODO lines."
15666 (interactive "P")
15667 (org-prepare-agenda-buffers (list (current-buffer)))
15668 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15670 (defvar org-cached-props nil)
15671 (defun org-cached-entry-get (pom property)
15672 (if (or (eq t org-use-property-inheritance)
15673 (member property org-use-property-inheritance))
15674 ;; Caching is not possible, check it directly
15675 (org-entry-get pom property 'inherit)
15676 ;; Get all properties, so that we can do complicated checks easily
15677 (cdr (assoc property (or org-cached-props
15678 (setq org-cached-props
15679 (org-entry-properties pom)))))))
15681 (defun org-global-tags-completion-table (&optional files)
15682 "Return the list of all tags in all agenda buffer/files."
15683 (save-excursion
15684 (org-uniquify
15685 (delq nil
15686 (apply 'append
15687 (mapcar
15688 (lambda (file)
15689 (set-buffer (find-file-noselect file))
15690 (append (org-get-buffer-tags)
15691 (mapcar (lambda (x) (if (stringp (car-safe x))
15692 (list (car-safe x)) nil))
15693 org-tag-alist)))
15694 (if (and files (car files))
15695 files
15696 (org-agenda-files))))))))
15698 (defun org-make-tags-matcher (match)
15699 "Create the TAGS//TODO matcher form for the selection string MATCH."
15700 ;; todo-only is scoped dynamically into this function, and the function
15701 ;; may change it it the matcher asksk for it.
15702 (unless match
15703 ;; Get a new match request, with completion
15704 (let ((org-last-tags-completion-table
15705 (org-global-tags-completion-table)))
15706 (setq match (completing-read
15707 "Match: " 'org-tags-completion-function nil nil nil
15708 'org-tags-history))))
15710 ;; Parse the string and create a lisp form
15711 (let ((match0 match)
15712 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15713 minus tag mm
15714 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15715 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15716 (if (string-match "/+" match)
15717 ;; match contains also a todo-matching request
15718 (progn
15719 (setq tagsmatch (substring match 0 (match-beginning 0))
15720 todomatch (substring match (match-end 0)))
15721 (if (string-match "^!" todomatch)
15722 (setq todo-only t todomatch (substring todomatch 1)))
15723 (if (string-match "^\\s-*$" todomatch)
15724 (setq todomatch nil)))
15725 ;; only matching tags
15726 (setq tagsmatch match todomatch nil))
15728 ;; Make the tags matcher
15729 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15730 (setq tagsmatcher t)
15731 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15732 (while (setq term (pop orterms))
15733 (while (and (equal (substring term -1) "\\") orterms)
15734 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15735 (while (string-match re term)
15736 (setq minus (and (match-end 1)
15737 (equal (match-string 1 term) "-"))
15738 tag (match-string 2 term)
15739 re-p (equal (string-to-char tag) ?{)
15740 level-p (match-end 3)
15741 prop-p (match-end 4)
15742 mm (cond
15743 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15744 (level-p `(= level ,(string-to-number
15745 (match-string 3 term))))
15746 (prop-p
15747 (setq pn (match-string 4 term)
15748 pv (match-string 5 term)
15749 cat-p (equal pn "CATEGORY")
15750 re-p (equal (string-to-char pv) ?{)
15751 pv (substring pv 1 -1))
15752 (if (equal pn "CATEGORY")
15753 (setq gv '(get-text-property (point) 'org-category))
15754 (setq gv `(org-cached-entry-get nil ,pn)))
15755 (if re-p
15756 `(string-match ,pv (or ,gv ""))
15757 `(equal ,pv (or ,gv ""))))
15758 (t `(member ,(downcase tag) tags-list)))
15759 mm (if minus (list 'not mm) mm)
15760 term (substring term (match-end 0)))
15761 (push mm tagsmatcher))
15762 (push (if (> (length tagsmatcher) 1)
15763 (cons 'and tagsmatcher)
15764 (car tagsmatcher))
15765 orlist)
15766 (setq tagsmatcher nil))
15767 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15768 (setq tagsmatcher
15769 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15771 ;; Make the todo matcher
15772 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15773 (setq todomatcher t)
15774 (setq orterms (org-split-string todomatch "|") orlist nil)
15775 (while (setq term (pop orterms))
15776 (while (string-match re term)
15777 (setq minus (and (match-end 1)
15778 (equal (match-string 1 term) "-"))
15779 kwd (match-string 2 term)
15780 re-p (equal (string-to-char kwd) ?{)
15781 term (substring term (match-end 0))
15782 mm (if re-p
15783 `(string-match ,(substring kwd 1 -1) todo)
15784 (list 'equal 'todo kwd))
15785 mm (if minus (list 'not mm) mm))
15786 (push mm todomatcher))
15787 (push (if (> (length todomatcher) 1)
15788 (cons 'and todomatcher)
15789 (car todomatcher))
15790 orlist)
15791 (setq todomatcher nil))
15792 (setq todomatcher (if (> (length orlist) 1)
15793 (cons 'or orlist) (car orlist))))
15795 ;; Return the string and lisp forms of the matcher
15796 (setq matcher (if todomatcher
15797 (list 'and tagsmatcher todomatcher)
15798 tagsmatcher))
15799 (cons match0 matcher)))
15801 (defun org-match-any-p (re list)
15802 "Does re match any element of list?"
15803 (setq list (mapcar (lambda (x) (string-match re x)) list))
15804 (delq nil list))
15806 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15807 (defvar org-tags-overlay (org-make-overlay 1 1))
15808 (org-detach-overlay org-tags-overlay)
15810 (defun org-align-tags-here (to-col)
15811 ;; Assumes that this is a headline
15812 (let ((pos (point)) (col (current-column)) tags)
15813 (beginning-of-line 1)
15814 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15815 (< pos (match-beginning 2)))
15816 (progn
15817 (setq tags (match-string 2))
15818 (goto-char (match-beginning 1))
15819 (insert " ")
15820 (delete-region (point) (1+ (match-end 0)))
15821 (backward-char 1)
15822 (move-to-column
15823 (max (1+ (current-column))
15824 (1+ col)
15825 (if (> to-col 0)
15826 to-col
15827 (- (abs to-col) (length tags))))
15829 (insert tags)
15830 (move-to-column (min (current-column) col) t))
15831 (goto-char pos))))
15833 (defun org-set-tags (&optional arg just-align)
15834 "Set the tags for the current headline.
15835 With prefix ARG, realign all tags in headings in the current buffer."
15836 (interactive "P")
15837 (let* ((re (concat "^" outline-regexp))
15838 (current (org-get-tags-string))
15839 (col (current-column))
15840 (org-setting-tags t)
15841 table current-tags inherited-tags ; computed below when needed
15842 tags p0 c0 c1 rpl)
15843 (if arg
15844 (save-excursion
15845 (goto-char (point-min))
15846 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15847 (while (re-search-forward re nil t)
15848 (org-set-tags nil t)
15849 (end-of-line 1)))
15850 (message "All tags realigned to column %d" org-tags-column))
15851 (if just-align
15852 (setq tags current)
15853 ;; Get a new set of tags from the user
15854 (save-excursion
15855 (setq table (or org-tag-alist (org-get-buffer-tags))
15856 org-last-tags-completion-table table
15857 current-tags (org-split-string current ":")
15858 inherited-tags (nreverse
15859 (nthcdr (length current-tags)
15860 (nreverse (org-get-tags-at))))
15861 tags
15862 (if (or (eq t org-use-fast-tag-selection)
15863 (and org-use-fast-tag-selection
15864 (delq nil (mapcar 'cdr table))))
15865 (org-fast-tag-selection
15866 current-tags inherited-tags table
15867 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15868 (let ((org-add-colon-after-tag-completion t))
15869 (org-trim
15870 (org-without-partial-completion
15871 (completing-read "Tags: " 'org-tags-completion-function
15872 nil nil current 'org-tags-history)))))))
15873 (while (string-match "[-+&]+" tags)
15874 ;; No boolean logic, just a list
15875 (setq tags (replace-match ":" t t tags))))
15877 (if (string-match "\\`[\t ]*\\'" tags)
15878 (setq tags "")
15879 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15880 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15882 ;; Insert new tags at the correct column
15883 (beginning-of-line 1)
15884 (cond
15885 ((and (equal current "") (equal tags "")))
15886 ((re-search-forward
15887 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15888 (point-at-eol) t)
15889 (if (equal tags "")
15890 (setq rpl "")
15891 (goto-char (match-beginning 0))
15892 (setq c0 (current-column) p0 (point)
15893 c1 (max (1+ c0) (if (> org-tags-column 0)
15894 org-tags-column
15895 (- (- org-tags-column) (length tags))))
15896 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15897 (replace-match rpl t t)
15898 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15899 tags)
15900 (t (error "Tags alignment failed")))
15901 (move-to-column col)
15902 (unless just-align
15903 (run-hooks 'org-after-tags-change-hook)))))
15905 (defun org-change-tag-in-region (beg end tag off)
15906 "Add or remove TAG for each entry in the region.
15907 This works in the agenda, and also in an org-mode buffer."
15908 (interactive
15909 (list (region-beginning) (region-end)
15910 (let ((org-last-tags-completion-table
15911 (if (org-mode-p)
15912 (org-get-buffer-tags)
15913 (org-global-tags-completion-table))))
15914 (completing-read
15915 "Tag: " 'org-tags-completion-function nil nil nil
15916 'org-tags-history))
15917 (progn
15918 (message "[s]et or [r]emove? ")
15919 (equal (read-char-exclusive) ?r))))
15920 (if (fboundp 'deactivate-mark) (deactivate-mark))
15921 (let ((agendap (equal major-mode 'org-agenda-mode))
15922 l1 l2 m buf pos newhead (cnt 0))
15923 (goto-char end)
15924 (setq l2 (1- (org-current-line)))
15925 (goto-char beg)
15926 (setq l1 (org-current-line))
15927 (loop for l from l1 to l2 do
15928 (goto-line l)
15929 (setq m (get-text-property (point) 'org-hd-marker))
15930 (when (or (and (org-mode-p) (org-on-heading-p))
15931 (and agendap m))
15932 (setq buf (if agendap (marker-buffer m) (current-buffer))
15933 pos (if agendap m (point)))
15934 (with-current-buffer buf
15935 (save-excursion
15936 (save-restriction
15937 (goto-char pos)
15938 (setq cnt (1+ cnt))
15939 (org-toggle-tag tag (if off 'off 'on))
15940 (setq newhead (org-get-heading)))))
15941 (and agendap (org-agenda-change-all-lines newhead m))))
15942 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15944 (defun org-tags-completion-function (string predicate &optional flag)
15945 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15946 (confirm (lambda (x) (stringp (car x)))))
15947 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15948 (setq s1 (match-string 1 string)
15949 s2 (match-string 2 string))
15950 (setq s1 "" s2 string))
15951 (cond
15952 ((eq flag nil)
15953 ;; try completion
15954 (setq rtn (try-completion s2 ctable confirm))
15955 (if (stringp rtn)
15956 (setq rtn
15957 (concat s1 s2 (substring rtn (length s2))
15958 (if (and org-add-colon-after-tag-completion
15959 (assoc rtn ctable))
15960 ":" ""))))
15961 rtn)
15962 ((eq flag t)
15963 ;; all-completions
15964 (all-completions s2 ctable confirm)
15966 ((eq flag 'lambda)
15967 ;; exact match?
15968 (assoc s2 ctable)))
15971 (defun org-fast-tag-insert (kwd tags face &optional end)
15972 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15973 (insert (format "%-12s" (concat kwd ":"))
15974 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15975 (or end "")))
15977 (defun org-fast-tag-show-exit (flag)
15978 (save-excursion
15979 (goto-line 3)
15980 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15981 (replace-match ""))
15982 (when flag
15983 (end-of-line 1)
15984 (move-to-column (- (window-width) 19) t)
15985 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15987 (defun org-set-current-tags-overlay (current prefix)
15988 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15989 (if (featurep 'xemacs)
15990 (org-overlay-display org-tags-overlay (concat prefix s)
15991 'secondary-selection)
15992 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15993 (org-overlay-display org-tags-overlay (concat prefix s)))))
15995 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15996 "Fast tag selection with single keys.
15997 CURRENT is the current list of tags in the headline, INHERITED is the
15998 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15999 possibly with grouping information. TODO-TABLE is a similar table with
16000 TODO keywords, should these have keys assigned to them.
16001 If the keys are nil, a-z are automatically assigned.
16002 Returns the new tags string, or nil to not change the current settings."
16003 (let* ((fulltable (append table todo-table))
16004 (maxlen (apply 'max (mapcar
16005 (lambda (x)
16006 (if (stringp (car x)) (string-width (car x)) 0))
16007 fulltable)))
16008 (buf (current-buffer))
16009 (expert (eq org-fast-tag-selection-single-key 'expert))
16010 (buffer-tags nil)
16011 (fwidth (+ maxlen 3 1 3))
16012 (ncol (/ (- (window-width) 4) fwidth))
16013 (i-face 'org-done)
16014 (c-face 'org-todo)
16015 tg cnt e c char c1 c2 ntable tbl rtn
16016 ov-start ov-end ov-prefix
16017 (exit-after-next org-fast-tag-selection-single-key)
16018 (done-keywords org-done-keywords)
16019 groups ingroup)
16020 (save-excursion
16021 (beginning-of-line 1)
16022 (if (looking-at
16023 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16024 (setq ov-start (match-beginning 1)
16025 ov-end (match-end 1)
16026 ov-prefix "")
16027 (setq ov-start (1- (point-at-eol))
16028 ov-end (1+ ov-start))
16029 (skip-chars-forward "^\n\r")
16030 (setq ov-prefix
16031 (concat
16032 (buffer-substring (1- (point)) (point))
16033 (if (> (current-column) org-tags-column)
16035 (make-string (- org-tags-column (current-column)) ?\ ))))))
16036 (org-move-overlay org-tags-overlay ov-start ov-end)
16037 (save-window-excursion
16038 (if expert
16039 (set-buffer (get-buffer-create " *Org tags*"))
16040 (delete-other-windows)
16041 (split-window-vertically)
16042 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
16043 (erase-buffer)
16044 (org-set-local 'org-done-keywords done-keywords)
16045 (org-fast-tag-insert "Inherited" inherited i-face "\n")
16046 (org-fast-tag-insert "Current" current c-face "\n\n")
16047 (org-fast-tag-show-exit exit-after-next)
16048 (org-set-current-tags-overlay current ov-prefix)
16049 (setq tbl fulltable char ?a cnt 0)
16050 (while (setq e (pop tbl))
16051 (cond
16052 ((equal e '(:startgroup))
16053 (push '() groups) (setq ingroup t)
16054 (when (not (= cnt 0))
16055 (setq cnt 0)
16056 (insert "\n"))
16057 (insert "{ "))
16058 ((equal e '(:endgroup))
16059 (setq ingroup nil cnt 0)
16060 (insert "}\n"))
16062 (setq tg (car e) c2 nil)
16063 (if (cdr e)
16064 (setq c (cdr e))
16065 ;; automatically assign a character.
16066 (setq c1 (string-to-char
16067 (downcase (substring
16068 tg (if (= (string-to-char tg) ?@) 1 0)))))
16069 (if (or (rassoc c1 ntable) (rassoc c1 table))
16070 (while (or (rassoc char ntable) (rassoc char table))
16071 (setq char (1+ char)))
16072 (setq c2 c1))
16073 (setq c (or c2 char)))
16074 (if ingroup (push tg (car groups)))
16075 (setq tg (org-add-props tg nil 'face
16076 (cond
16077 ((not (assoc tg table))
16078 (org-get-todo-face tg))
16079 ((member tg current) c-face)
16080 ((member tg inherited) i-face)
16081 (t nil))))
16082 (if (and (= cnt 0) (not ingroup)) (insert " "))
16083 (insert "[" c "] " tg (make-string
16084 (- fwidth 4 (length tg)) ?\ ))
16085 (push (cons tg c) ntable)
16086 (when (= (setq cnt (1+ cnt)) ncol)
16087 (insert "\n")
16088 (if ingroup (insert " "))
16089 (setq cnt 0)))))
16090 (setq ntable (nreverse ntable))
16091 (insert "\n")
16092 (goto-char (point-min))
16093 (if (and (not expert) (fboundp 'fit-window-to-buffer))
16094 (fit-window-to-buffer))
16095 (setq rtn
16096 (catch 'exit
16097 (while t
16098 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
16099 (if groups " [!] no groups" " [!]groups")
16100 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
16101 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
16102 (cond
16103 ((= c ?\r) (throw 'exit t))
16104 ((= c ?!)
16105 (setq groups (not groups))
16106 (goto-char (point-min))
16107 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
16108 ((= c ?\C-c)
16109 (if (not expert)
16110 (org-fast-tag-show-exit
16111 (setq exit-after-next (not exit-after-next)))
16112 (setq expert nil)
16113 (delete-other-windows)
16114 (split-window-vertically)
16115 (org-switch-to-buffer-other-window " *Org tags*")
16116 (and (fboundp 'fit-window-to-buffer)
16117 (fit-window-to-buffer))))
16118 ((or (= c ?\C-g)
16119 (and (= c ?q) (not (rassoc c ntable))))
16120 (org-detach-overlay org-tags-overlay)
16121 (setq quit-flag t))
16122 ((= c ?\ )
16123 (setq current nil)
16124 (if exit-after-next (setq exit-after-next 'now)))
16125 ((= c ?\t)
16126 (condition-case nil
16127 (setq tg (completing-read
16128 "Tag: "
16129 (or buffer-tags
16130 (with-current-buffer buf
16131 (org-get-buffer-tags)))))
16132 (quit (setq tg "")))
16133 (when (string-match "\\S-" tg)
16134 (add-to-list 'buffer-tags (list tg))
16135 (if (member tg current)
16136 (setq current (delete tg current))
16137 (push tg current)))
16138 (if exit-after-next (setq exit-after-next 'now)))
16139 ((setq e (rassoc c todo-table) tg (car e))
16140 (with-current-buffer buf
16141 (save-excursion (org-todo tg)))
16142 (if exit-after-next (setq exit-after-next 'now)))
16143 ((setq e (rassoc c ntable) tg (car e))
16144 (if (member tg current)
16145 (setq current (delete tg current))
16146 (loop for g in groups do
16147 (if (member tg g)
16148 (mapc (lambda (x)
16149 (setq current (delete x current)))
16150 g)))
16151 (push tg current))
16152 (if exit-after-next (setq exit-after-next 'now))))
16154 ;; Create a sorted list
16155 (setq current
16156 (sort current
16157 (lambda (a b)
16158 (assoc b (cdr (memq (assoc a ntable) ntable))))))
16159 (if (eq exit-after-next 'now) (throw 'exit t))
16160 (goto-char (point-min))
16161 (beginning-of-line 2)
16162 (delete-region (point) (point-at-eol))
16163 (org-fast-tag-insert "Current" current c-face)
16164 (org-set-current-tags-overlay current ov-prefix)
16165 (while (re-search-forward
16166 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
16167 (setq tg (match-string 1))
16168 (add-text-properties
16169 (match-beginning 1) (match-end 1)
16170 (list 'face
16171 (cond
16172 ((member tg current) c-face)
16173 ((member tg inherited) i-face)
16174 (t (get-text-property (match-beginning 1) 'face))))))
16175 (goto-char (point-min)))))
16176 (org-detach-overlay org-tags-overlay)
16177 (if rtn
16178 (mapconcat 'identity current ":")
16179 nil))))
16181 (defun org-get-tags-string ()
16182 "Get the TAGS string in the current headline."
16183 (unless (org-on-heading-p t)
16184 (error "Not on a heading"))
16185 (save-excursion
16186 (beginning-of-line 1)
16187 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16188 (org-match-string-no-properties 1)
16189 "")))
16191 (defun org-get-tags ()
16192 "Get the list of tags specified in the current headline."
16193 (org-split-string (org-get-tags-string) ":"))
16195 (defun org-get-buffer-tags ()
16196 "Get a table of all tags used in the buffer, for completion."
16197 (let (tags)
16198 (save-excursion
16199 (goto-char (point-min))
16200 (while (re-search-forward
16201 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
16202 (when (equal (char-after (point-at-bol 0)) ?*)
16203 (mapc (lambda (x) (add-to-list 'tags x))
16204 (org-split-string (org-match-string-no-properties 1) ":")))))
16205 (mapcar 'list tags)))
16208 ;;;; Properties
16210 ;;; Setting and retrieving properties
16212 (defconst org-special-properties
16213 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
16214 "TIMESTAMP" "TIMESTAMP_IA")
16215 "The special properties valid in Org-mode.
16217 These are properties that are not defined in the property drawer,
16218 but in some other way.")
16220 (defconst org-default-properties
16221 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
16222 "LOCATION" "LOGGING" "COLUMNS")
16223 "Some properties that are used by Org-mode for various purposes.
16224 Being in this list makes sure that they are offered for completion.")
16226 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
16227 "Regular expression matching the first line of a property drawer.")
16229 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
16230 "Regular expression matching the first line of a property drawer.")
16232 (defun org-property-action ()
16233 "Do an action on properties."
16234 (interactive)
16235 (let (c)
16236 (org-at-property-p)
16237 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
16238 (setq c (read-char-exclusive))
16239 (cond
16240 ((equal c ?s)
16241 (call-interactively 'org-set-property))
16242 ((equal c ?d)
16243 (call-interactively 'org-delete-property))
16244 ((equal c ?D)
16245 (call-interactively 'org-delete-property-globally))
16246 ((equal c ?c)
16247 (call-interactively 'org-compute-property-at-point))
16248 (t (error "No such property action %c" c)))))
16250 (defun org-at-property-p ()
16251 "Is the cursor in a property line?"
16252 ;; FIXME: Does not check if we are actually in the drawer.
16253 ;; FIXME: also returns true on any drawers.....
16254 ;; This is used by C-c C-c for property action.
16255 (save-excursion
16256 (beginning-of-line 1)
16257 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
16259 (defmacro org-with-point-at (pom &rest body)
16260 "Move to buffer and point of point-or-marker POM for the duration of BODY."
16261 (declare (indent 1) (debug t))
16262 `(save-excursion
16263 (if (markerp pom) (set-buffer (marker-buffer pom)))
16264 (save-excursion
16265 (goto-char (or pom (point)))
16266 ,@body)))
16268 (defun org-get-property-block (&optional beg end force)
16269 "Return the (beg . end) range of the body of the property drawer.
16270 BEG and END can be beginning and end of subtree, if not given
16271 they will be found.
16272 If the drawer does not exist and FORCE is non-nil, create the drawer."
16273 (catch 'exit
16274 (save-excursion
16275 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
16276 (end (or end (progn (outline-next-heading) (point)))))
16277 (goto-char beg)
16278 (if (re-search-forward org-property-start-re end t)
16279 (setq beg (1+ (match-end 0)))
16280 (if force
16281 (save-excursion
16282 (org-insert-property-drawer)
16283 (setq end (progn (outline-next-heading) (point))))
16284 (throw 'exit nil))
16285 (goto-char beg)
16286 (if (re-search-forward org-property-start-re end t)
16287 (setq beg (1+ (match-end 0)))))
16288 (if (re-search-forward org-property-end-re end t)
16289 (setq end (match-beginning 0))
16290 (or force (throw 'exit nil))
16291 (goto-char beg)
16292 (setq end beg)
16293 (org-indent-line-function)
16294 (insert ":END:\n"))
16295 (cons beg end)))))
16297 (defun org-entry-properties (&optional pom which)
16298 "Get all properties of the entry at point-or-marker POM.
16299 This includes the TODO keyword, the tags, time strings for deadline,
16300 scheduled, and clocking, and any additional properties defined in the
16301 entry. The return value is an alist, keys may occur multiple times
16302 if the property key was used several times.
16303 POM may also be nil, in which case the current entry is used.
16304 If WHICH is nil or `all', get all properties. If WHICH is
16305 `special' or `standard', only get that subclass."
16306 (setq which (or which 'all))
16307 (org-with-point-at pom
16308 (let ((clockstr (substring org-clock-string 0 -1))
16309 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
16310 beg end range props sum-props key value string clocksum)
16311 (save-excursion
16312 (when (condition-case nil (org-back-to-heading t) (error nil))
16313 (setq beg (point))
16314 (setq sum-props (get-text-property (point) 'org-summaries))
16315 (setq clocksum (get-text-property (point) :org-clock-minutes))
16316 (outline-next-heading)
16317 (setq end (point))
16318 (when (memq which '(all special))
16319 ;; Get the special properties, like TODO and tags
16320 (goto-char beg)
16321 (when (and (looking-at org-todo-line-regexp) (match-end 2))
16322 (push (cons "TODO" (org-match-string-no-properties 2)) props))
16323 (when (looking-at org-priority-regexp)
16324 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16325 (when (and (setq value (org-get-tags-string))
16326 (string-match "\\S-" value))
16327 (push (cons "TAGS" value) props))
16328 (when (setq value (org-get-tags-at))
16329 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16330 props))
16331 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16332 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16333 string (if (equal key clockstr)
16334 (org-no-properties
16335 (org-trim
16336 (buffer-substring
16337 (match-beginning 3) (goto-char (point-at-eol)))))
16338 (substring (org-match-string-no-properties 3) 1 -1)))
16339 (unless key
16340 (if (= (char-after (match-beginning 3)) ?\[)
16341 (setq key "TIMESTAMP_IA")
16342 (setq key "TIMESTAMP")))
16343 (when (or (equal key clockstr) (not (assoc key props)))
16344 (push (cons key string) props)))
16348 (when (memq which '(all standard))
16349 ;; Get the standard properties, like :PORP: ...
16350 (setq range (org-get-property-block beg end))
16351 (when range
16352 (goto-char (car range))
16353 (while (re-search-forward
16354 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16355 (cdr range) t)
16356 (setq key (org-match-string-no-properties 1)
16357 value (org-trim (or (org-match-string-no-properties 2) "")))
16358 (unless (member key excluded)
16359 (push (cons key (or value "")) props)))))
16360 (if clocksum
16361 (push (cons "CLOCKSUM"
16362 (org-column-number-to-string (/ (float clocksum) 60.)
16363 'add_times))
16364 props))
16365 (append sum-props (nreverse props)))))))
16367 (defun org-entry-get (pom property &optional inherit)
16368 "Get value of PROPERTY for entry at point-or-marker POM.
16369 If INHERIT is non-nil and the entry does not have the property,
16370 then also check higher levels of the hierarchy.
16371 If the property is present but empty, the return value is the empty string.
16372 If the property is not present at all, nil is returned."
16373 (org-with-point-at pom
16374 (if inherit
16375 (org-entry-get-with-inheritance property)
16376 (if (member property org-special-properties)
16377 ;; We need a special property. Use brute force, get all properties.
16378 (cdr (assoc property (org-entry-properties nil 'special)))
16379 (let ((range (org-get-property-block)))
16380 (if (and range
16381 (goto-char (car range))
16382 (re-search-forward
16383 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16384 (cdr range) t))
16385 ;; Found the property, return it.
16386 (if (match-end 1)
16387 (org-match-string-no-properties 1)
16388 "")))))))
16390 (defun org-entry-delete (pom property)
16391 "Delete the property PROPERTY from entry at point-or-marker POM."
16392 (org-with-point-at pom
16393 (if (member property org-special-properties)
16394 nil ; cannot delete these properties.
16395 (let ((range (org-get-property-block)))
16396 (if (and range
16397 (goto-char (car range))
16398 (re-search-forward
16399 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16400 (cdr range) t))
16401 (progn
16402 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16404 nil)))))
16406 ;; Multi-values properties are properties that contain multiple values
16407 ;; These values are assumed to be single words, separated by whitespace.
16408 (defun org-entry-add-to-multivalued-property (pom property value)
16409 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16410 (let* ((old (org-entry-get pom property))
16411 (values (and old (org-split-string old "[ \t]"))))
16412 (unless (member value values)
16413 (setq values (cons value values))
16414 (org-entry-put pom property
16415 (mapconcat 'identity values " ")))))
16417 (defun org-entry-remove-from-multivalued-property (pom property value)
16418 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16419 (let* ((old (org-entry-get pom property))
16420 (values (and old (org-split-string old "[ \t]"))))
16421 (when (member value values)
16422 (setq values (delete value values))
16423 (org-entry-put pom property
16424 (mapconcat 'identity values " ")))))
16426 (defun org-entry-member-in-multivalued-property (pom property value)
16427 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16428 (let* ((old (org-entry-get pom property))
16429 (values (and old (org-split-string old "[ \t]"))))
16430 (member value values)))
16432 (defvar org-entry-property-inherited-from (make-marker))
16434 (defun org-entry-get-with-inheritance (property)
16435 "Get entry property, and search higher levels if not present."
16436 (let (tmp)
16437 (save-excursion
16438 (save-restriction
16439 (widen)
16440 (catch 'ex
16441 (while t
16442 (when (setq tmp (org-entry-get nil property))
16443 (org-back-to-heading t)
16444 (move-marker org-entry-property-inherited-from (point))
16445 (throw 'ex tmp))
16446 (or (org-up-heading-safe) (throw 'ex nil)))))
16447 (or tmp (cdr (assoc property org-local-properties))
16448 (cdr (assoc property org-global-properties))))))
16450 (defun org-entry-put (pom property value)
16451 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16452 (org-with-point-at pom
16453 (org-back-to-heading t)
16454 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16455 range)
16456 (cond
16457 ((equal property "TODO")
16458 (when (and (stringp value) (string-match "\\S-" value)
16459 (not (member value org-todo-keywords-1)))
16460 (error "\"%s\" is not a valid TODO state" value))
16461 (if (or (not value)
16462 (not (string-match "\\S-" value)))
16463 (setq value 'none))
16464 (org-todo value)
16465 (org-set-tags nil 'align))
16466 ((equal property "PRIORITY")
16467 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16468 (string-to-char value) ?\ ))
16469 (org-set-tags nil 'align))
16470 ((equal property "SCHEDULED")
16471 (if (re-search-forward org-scheduled-time-regexp end t)
16472 (cond
16473 ((eq value 'earlier) (org-timestamp-change -1 'day))
16474 ((eq value 'later) (org-timestamp-change 1 'day))
16475 (t (call-interactively 'org-schedule)))
16476 (call-interactively 'org-schedule)))
16477 ((equal property "DEADLINE")
16478 (if (re-search-forward org-deadline-time-regexp end t)
16479 (cond
16480 ((eq value 'earlier) (org-timestamp-change -1 'day))
16481 ((eq value 'later) (org-timestamp-change 1 'day))
16482 (t (call-interactively 'org-deadline)))
16483 (call-interactively 'org-deadline)))
16484 ((member property org-special-properties)
16485 (error "The %s property can not yet be set with `org-entry-put'"
16486 property))
16487 (t ; a non-special property
16488 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16489 (setq range (org-get-property-block beg end 'force))
16490 (goto-char (car range))
16491 (if (re-search-forward
16492 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16493 (progn
16494 (delete-region (match-beginning 1) (match-end 1))
16495 (goto-char (match-beginning 1)))
16496 (goto-char (cdr range))
16497 (insert "\n")
16498 (backward-char 1)
16499 (org-indent-line-function)
16500 (insert ":" property ":"))
16501 (and value (insert " " value))
16502 (org-indent-line-function)))))))
16504 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16505 "Get all property keys in the current buffer.
16506 With INCLUDE-SPECIALS, also list the special properties that relect things
16507 like tags and TODO state.
16508 With INCLUDE-DEFAULTS, also include properties that has special meaning
16509 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16510 With INCLUDE-COLUMNS, also include property names given in COLUMN
16511 formats in the current buffer."
16512 (let (rtn range cfmt cols s p)
16513 (save-excursion
16514 (save-restriction
16515 (widen)
16516 (goto-char (point-min))
16517 (while (re-search-forward org-property-start-re nil t)
16518 (setq range (org-get-property-block))
16519 (goto-char (car range))
16520 (while (re-search-forward
16521 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16522 (cdr range) t)
16523 (add-to-list 'rtn (org-match-string-no-properties 1)))
16524 (outline-next-heading))))
16526 (when include-specials
16527 (setq rtn (append org-special-properties rtn)))
16529 (when include-defaults
16530 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16532 (when include-columns
16533 (save-excursion
16534 (save-restriction
16535 (widen)
16536 (goto-char (point-min))
16537 (while (re-search-forward
16538 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16539 nil t)
16540 (setq cfmt (match-string 2) s 0)
16541 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16542 cfmt s)
16543 (setq s (match-end 0)
16544 p (match-string 1 cfmt))
16545 (unless (or (equal p "ITEM")
16546 (member p org-special-properties))
16547 (add-to-list 'rtn (match-string 1 cfmt))))))))
16549 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16551 (defun org-property-values (key)
16552 "Return a list of all values of property KEY."
16553 (save-excursion
16554 (save-restriction
16555 (widen)
16556 (goto-char (point-min))
16557 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16558 values)
16559 (while (re-search-forward re nil t)
16560 (add-to-list 'values (org-trim (match-string 1))))
16561 (delete "" values)))))
16563 (defun org-insert-property-drawer ()
16564 "Insert a property drawer into the current entry."
16565 (interactive)
16566 (org-back-to-heading t)
16567 (looking-at outline-regexp)
16568 (let ((indent (- (match-end 0)(match-beginning 0)))
16569 (beg (point))
16570 (re (concat "^[ \t]*" org-keyword-time-regexp))
16571 end hiddenp)
16572 (outline-next-heading)
16573 (setq end (point))
16574 (goto-char beg)
16575 (while (re-search-forward re end t))
16576 (setq hiddenp (org-invisible-p))
16577 (end-of-line 1)
16578 (and (equal (char-after) ?\n) (forward-char 1))
16579 (org-skip-over-state-notes)
16580 (skip-chars-backward " \t\n\r")
16581 (if (eq (char-before) ?*) (forward-char 1))
16582 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16583 (beginning-of-line 0)
16584 (indent-to-column indent)
16585 (beginning-of-line 2)
16586 (indent-to-column indent)
16587 (beginning-of-line 0)
16588 (if hiddenp
16589 (save-excursion
16590 (org-back-to-heading t)
16591 (hide-entry))
16592 (org-flag-drawer t))))
16594 (defun org-set-property (property value)
16595 "In the current entry, set PROPERTY to VALUE.
16596 When called interactively, this will prompt for a property name, offering
16597 completion on existing and default properties. And then it will prompt
16598 for a value, offering competion either on allowed values (via an inherited
16599 xxx_ALL property) or on existing values in other instances of this property
16600 in the current file."
16601 (interactive
16602 (let* ((prop (completing-read
16603 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16604 (cur (org-entry-get nil prop))
16605 (allowed (org-property-get-allowed-values nil prop 'table))
16606 (existing (mapcar 'list (org-property-values prop)))
16607 (val (if allowed
16608 (completing-read "Value: " allowed nil 'req-match)
16609 (completing-read
16610 (concat "Value" (if (and cur (string-match "\\S-" cur))
16611 (concat "[" cur "]") "")
16612 ": ")
16613 existing nil nil "" nil cur))))
16614 (list prop (if (equal val "") cur val))))
16615 (unless (equal (org-entry-get nil property) value)
16616 (org-entry-put nil property value)))
16618 (defun org-delete-property (property)
16619 "In the current entry, delete PROPERTY."
16620 (interactive
16621 (let* ((prop (completing-read
16622 "Property: " (org-entry-properties nil 'standard))))
16623 (list prop)))
16624 (message "Property %s %s" property
16625 (if (org-entry-delete nil property)
16626 "deleted"
16627 "was not present in the entry")))
16629 (defun org-delete-property-globally (property)
16630 "Remove PROPERTY globally, from all entries."
16631 (interactive
16632 (let* ((prop (completing-read
16633 "Globally remove property: "
16634 (mapcar 'list (org-buffer-property-keys)))))
16635 (list prop)))
16636 (save-excursion
16637 (save-restriction
16638 (widen)
16639 (goto-char (point-min))
16640 (let ((cnt 0))
16641 (while (re-search-forward
16642 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16643 nil t)
16644 (setq cnt (1+ cnt))
16645 (replace-match ""))
16646 (message "Property \"%s\" removed from %d entries" property cnt)))))
16648 (defvar org-columns-current-fmt-compiled) ; defined below
16650 (defun org-compute-property-at-point ()
16651 "Compute the property at point.
16652 This looks for an enclosing column format, extracts the operator and
16653 then applies it to the proerty in the column format's scope."
16654 (interactive)
16655 (unless (org-at-property-p)
16656 (error "Not at a property"))
16657 (let ((prop (org-match-string-no-properties 2)))
16658 (org-columns-get-format-and-top-level)
16659 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16660 (error "No operator defined for property %s" prop))
16661 (org-columns-compute prop)))
16663 (defun org-property-get-allowed-values (pom property &optional table)
16664 "Get allowed values for the property PROPERTY.
16665 When TABLE is non-nil, return an alist that can directly be used for
16666 completion."
16667 (let (vals)
16668 (cond
16669 ((equal property "TODO")
16670 (setq vals (org-with-point-at pom
16671 (append org-todo-keywords-1 '("")))))
16672 ((equal property "PRIORITY")
16673 (let ((n org-lowest-priority))
16674 (while (>= n org-highest-priority)
16675 (push (char-to-string n) vals)
16676 (setq n (1- n)))))
16677 ((member property org-special-properties))
16679 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16681 (when (and vals (string-match "\\S-" vals))
16682 (setq vals (car (read-from-string (concat "(" vals ")"))))
16683 (setq vals (mapcar (lambda (x)
16684 (cond ((stringp x) x)
16685 ((numberp x) (number-to-string x))
16686 ((symbolp x) (symbol-name x))
16687 (t "???")))
16688 vals)))))
16689 (if table (mapcar 'list vals) vals)))
16691 (defun org-property-previous-allowed-value (&optional previous)
16692 "Switch to the next allowed value for this property."
16693 (interactive)
16694 (org-property-next-allowed-value t))
16696 (defun org-property-next-allowed-value (&optional previous)
16697 "Switch to the next allowed value for this property."
16698 (interactive)
16699 (unless (org-at-property-p)
16700 (error "Not at a property"))
16701 (let* ((key (match-string 2))
16702 (value (match-string 3))
16703 (allowed (or (org-property-get-allowed-values (point) key)
16704 (and (member value '("[ ]" "[-]" "[X]"))
16705 '("[ ]" "[X]"))))
16706 nval)
16707 (unless allowed
16708 (error "Allowed values for this property have not been defined"))
16709 (if previous (setq allowed (reverse allowed)))
16710 (if (member value allowed)
16711 (setq nval (car (cdr (member value allowed)))))
16712 (setq nval (or nval (car allowed)))
16713 (if (equal nval value)
16714 (error "Only one allowed value for this property"))
16715 (org-at-property-p)
16716 (replace-match (concat " :" key ": " nval) t t)
16717 (org-indent-line-function)
16718 (beginning-of-line 1)
16719 (skip-chars-forward " \t")))
16721 (defun org-find-entry-with-id (ident)
16722 "Locate the entry that contains the ID property with exact value IDENT.
16723 IDENT can be a string, a symbol or a number, this function will search for
16724 the string representation of it.
16725 Return the position where this entry starts, or nil if there is no such entry."
16726 (let ((id (cond
16727 ((stringp ident) ident)
16728 ((symbol-name ident) (symbol-name ident))
16729 ((numberp ident) (number-to-string ident))
16730 (t (error "IDENT %s must be a string, symbol or number" ident))))
16731 (case-fold-search nil))
16732 (save-excursion
16733 (save-restriction
16734 (widen)
16735 (goto-char (point-min))
16736 (when (re-search-forward
16737 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16738 nil t)
16739 (org-back-to-heading)
16740 (point))))))
16742 ;;; Column View
16744 (defvar org-columns-overlays nil
16745 "Holds the list of current column overlays.")
16747 (defvar org-columns-current-fmt nil
16748 "Local variable, holds the currently active column format.")
16749 (defvar org-columns-current-fmt-compiled nil
16750 "Local variable, holds the currently active column format.
16751 This is the compiled version of the format.")
16752 (defvar org-columns-current-widths nil
16753 "Loval variable, holds the currently widths of fields.")
16754 (defvar org-columns-current-maxwidths nil
16755 "Loval variable, holds the currently active maximum column widths.")
16756 (defvar org-columns-begin-marker (make-marker)
16757 "Points to the position where last a column creation command was called.")
16758 (defvar org-columns-top-level-marker (make-marker)
16759 "Points to the position where current columns region starts.")
16761 (defvar org-columns-map (make-sparse-keymap)
16762 "The keymap valid in column display.")
16764 (defun org-columns-content ()
16765 "Switch to contents view while in columns view."
16766 (interactive)
16767 (org-overview)
16768 (org-content))
16770 (org-defkey org-columns-map "c" 'org-columns-content)
16771 (org-defkey org-columns-map "o" 'org-overview)
16772 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16773 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16774 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16775 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16776 (org-defkey org-columns-map "v" 'org-columns-show-value)
16777 (org-defkey org-columns-map "q" 'org-columns-quit)
16778 (org-defkey org-columns-map "r" 'org-columns-redo)
16779 (org-defkey org-columns-map "g" 'org-columns-redo)
16780 (org-defkey org-columns-map [left] 'backward-char)
16781 (org-defkey org-columns-map "\M-b" 'backward-char)
16782 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16783 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16784 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16785 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16786 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16787 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16788 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16789 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16790 (org-defkey org-columns-map "<" 'org-columns-narrow)
16791 (org-defkey org-columns-map ">" 'org-columns-widen)
16792 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16793 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16794 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16795 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16797 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16798 '("Column"
16799 ["Edit property" org-columns-edit-value t]
16800 ["Next allowed value" org-columns-next-allowed-value t]
16801 ["Previous allowed value" org-columns-previous-allowed-value t]
16802 ["Show full value" org-columns-show-value t]
16803 ["Edit allowed values" org-columns-edit-allowed t]
16804 "--"
16805 ["Edit column attributes" org-columns-edit-attributes t]
16806 ["Increase column width" org-columns-widen t]
16807 ["Decrease column width" org-columns-narrow t]
16808 "--"
16809 ["Move column right" org-columns-move-right t]
16810 ["Move column left" org-columns-move-left t]
16811 ["Add column" org-columns-new t]
16812 ["Delete column" org-columns-delete t]
16813 "--"
16814 ["CONTENTS" org-columns-content t]
16815 ["OVERVIEW" org-overview t]
16816 ["Refresh columns display" org-columns-redo t]
16817 "--"
16818 ["Open link" org-columns-open-link t]
16819 "--"
16820 ["Quit" org-columns-quit t]))
16822 (defun org-columns-new-overlay (beg end &optional string face)
16823 "Create a new column overlay and add it to the list."
16824 (let ((ov (org-make-overlay beg end)))
16825 (org-overlay-put ov 'face (or face 'secondary-selection))
16826 (org-overlay-display ov string face)
16827 (push ov org-columns-overlays)
16828 ov))
16830 (defun org-columns-display-here (&optional props)
16831 "Overlay the current line with column display."
16832 (interactive)
16833 (let* ((fmt org-columns-current-fmt-compiled)
16834 (beg (point-at-bol))
16835 (level-face (save-excursion
16836 (beginning-of-line 1)
16837 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16838 (org-get-level-face 2))))
16839 (color (list :foreground
16840 (face-attribute (or level-face 'default) :foreground)))
16841 props pom property ass width f string ov column val modval)
16842 ;; Check if the entry is in another buffer.
16843 (unless props
16844 (if (eq major-mode 'org-agenda-mode)
16845 (setq pom (or (get-text-property (point) 'org-hd-marker)
16846 (get-text-property (point) 'org-marker))
16847 props (if pom (org-entry-properties pom) nil))
16848 (setq props (org-entry-properties nil))))
16849 ;; Walk the format
16850 (while (setq column (pop fmt))
16851 (setq property (car column)
16852 ass (if (equal property "ITEM")
16853 (cons "ITEM"
16854 (save-match-data
16855 (org-no-properties
16856 (org-remove-tabs
16857 (buffer-substring-no-properties
16858 (point-at-bol) (point-at-eol))))))
16859 (assoc property props))
16860 width (or (cdr (assoc property org-columns-current-maxwidths))
16861 (nth 2 column)
16862 (length property))
16863 f (format "%%-%d.%ds | " width width)
16864 val (or (cdr ass) "")
16865 modval (if (equal property "ITEM")
16866 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16867 string (format f (or modval val)))
16868 ;; Create the overlay
16869 (org-unmodified
16870 (setq ov (org-columns-new-overlay
16871 beg (setq beg (1+ beg)) string
16872 (list color 'org-column)))
16873 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16874 (org-overlay-put ov 'keymap org-columns-map)
16875 (org-overlay-put ov 'org-columns-key property)
16876 (org-overlay-put ov 'org-columns-value (cdr ass))
16877 (org-overlay-put ov 'org-columns-value-modified modval)
16878 (org-overlay-put ov 'org-columns-pom pom)
16879 (org-overlay-put ov 'org-columns-format f))
16880 (if (or (not (char-after beg))
16881 (equal (char-after beg) ?\n))
16882 (let ((inhibit-read-only t))
16883 (save-excursion
16884 (goto-char beg)
16885 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16886 ;; Make the rest of the line disappear.
16887 (org-unmodified
16888 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16889 (org-overlay-put ov 'invisible t)
16890 (org-overlay-put ov 'keymap org-columns-map)
16891 (org-overlay-put ov 'intangible t)
16892 (push ov org-columns-overlays)
16893 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16894 (org-overlay-put ov 'keymap org-columns-map)
16895 (push ov org-columns-overlays)
16896 (let ((inhibit-read-only t))
16897 (put-text-property (max (point-min) (1- (point-at-bol)))
16898 (min (point-max) (1+ (point-at-eol)))
16899 'read-only "Type `e' to edit property")))))
16901 (defvar org-previous-header-line-format nil
16902 "The header line format before column view was turned on.")
16903 (defvar org-columns-inhibit-recalculation nil
16904 "Inhibit recomputing of columns on column view startup.")
16907 (defvar header-line-format)
16908 (defun org-columns-display-here-title ()
16909 "Overlay the newline before the current line with the table title."
16910 (interactive)
16911 (let ((fmt org-columns-current-fmt-compiled)
16912 string (title "")
16913 property width f column str widths)
16914 (while (setq column (pop fmt))
16915 (setq property (car column)
16916 str (or (nth 1 column) property)
16917 width (or (cdr (assoc property org-columns-current-maxwidths))
16918 (nth 2 column)
16919 (length str))
16920 widths (push width widths)
16921 f (format "%%-%d.%ds | " width width)
16922 string (format f str)
16923 title (concat title string)))
16924 (setq title (concat
16925 (org-add-props " " nil 'display '(space :align-to 0))
16926 (org-add-props title nil 'face '(:weight bold :underline t))))
16927 (org-set-local 'org-previous-header-line-format header-line-format)
16928 (org-set-local 'org-columns-current-widths (nreverse widths))
16929 (setq header-line-format title)))
16931 (defun org-columns-remove-overlays ()
16932 "Remove all currently active column overlays."
16933 (interactive)
16934 (when (marker-buffer org-columns-begin-marker)
16935 (with-current-buffer (marker-buffer org-columns-begin-marker)
16936 (when (local-variable-p 'org-previous-header-line-format)
16937 (setq header-line-format org-previous-header-line-format)
16938 (kill-local-variable 'org-previous-header-line-format))
16939 (move-marker org-columns-begin-marker nil)
16940 (move-marker org-columns-top-level-marker nil)
16941 (org-unmodified
16942 (mapc 'org-delete-overlay org-columns-overlays)
16943 (setq org-columns-overlays nil)
16944 (let ((inhibit-read-only t))
16945 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16947 (defun org-columns-cleanup-item (item fmt)
16948 "Remove from ITEM what is a column in the format FMT."
16949 (if (not org-complex-heading-regexp)
16950 item
16951 (when (string-match org-complex-heading-regexp item)
16952 (concat
16953 (org-add-props (concat (match-string 1 item) " ") nil
16954 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16955 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16956 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16957 " " (match-string 4 item)
16958 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16960 (defun org-columns-show-value ()
16961 "Show the full value of the property."
16962 (interactive)
16963 (let ((value (get-char-property (point) 'org-columns-value)))
16964 (message "Value is: %s" (or value ""))))
16966 (defun org-columns-quit ()
16967 "Remove the column overlays and in this way exit column editing."
16968 (interactive)
16969 (org-unmodified
16970 (org-columns-remove-overlays)
16971 (let ((inhibit-read-only t))
16972 (remove-text-properties (point-min) (point-max) '(read-only t))))
16973 (when (eq major-mode 'org-agenda-mode)
16974 (message
16975 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16977 (defun org-columns-check-computed ()
16978 "Check if this column value is computed.
16979 If yes, throw an error indicating that changing it does not make sense."
16980 (let ((val (get-char-property (point) 'org-columns-value)))
16981 (when (and (stringp val)
16982 (get-char-property 0 'org-computed val))
16983 (error "This value is computed from the entry's children"))))
16985 (defun org-columns-todo (&optional arg)
16986 "Change the TODO state during column view."
16987 (interactive "P")
16988 (org-columns-edit-value "TODO"))
16990 (defun org-columns-set-tags-or-toggle (&optional arg)
16991 "Toggle checkbox at point, or set tags for current headline."
16992 (interactive "P")
16993 (if (string-match "\\`\\[[ xX-]\\]\\'"
16994 (get-char-property (point) 'org-columns-value))
16995 (org-columns-next-allowed-value)
16996 (org-columns-edit-value "TAGS")))
16998 (defun org-columns-edit-value (&optional key)
16999 "Edit the value of the property at point in column view.
17000 Where possible, use the standard interface for changing this line."
17001 (interactive)
17002 (org-columns-check-computed)
17003 (let* ((external-key key)
17004 (col (current-column))
17005 (key (or key (get-char-property (point) 'org-columns-key)))
17006 (value (get-char-property (point) 'org-columns-value))
17007 (bol (point-at-bol)) (eol (point-at-eol))
17008 (pom (or (get-text-property bol 'org-hd-marker)
17009 (point))) ; keep despite of compiler waring
17010 (line-overlays
17011 (delq nil (mapcar (lambda (x)
17012 (and (eq (overlay-buffer x) (current-buffer))
17013 (>= (overlay-start x) bol)
17014 (<= (overlay-start x) eol)
17016 org-columns-overlays)))
17017 nval eval allowed)
17018 (cond
17019 ((equal key "CLOCKSUM")
17020 (error "This special column cannot be edited"))
17021 ((equal key "ITEM")
17022 (setq eval '(org-with-point-at pom
17023 (org-edit-headline))))
17024 ((equal key "TODO")
17025 (setq eval '(org-with-point-at pom
17026 (let ((current-prefix-arg
17027 (if external-key current-prefix-arg '(4))))
17028 (call-interactively 'org-todo)))))
17029 ((equal key "PRIORITY")
17030 (setq eval '(org-with-point-at pom
17031 (call-interactively 'org-priority))))
17032 ((equal key "TAGS")
17033 (setq eval '(org-with-point-at pom
17034 (let ((org-fast-tag-selection-single-key
17035 (if (eq org-fast-tag-selection-single-key 'expert)
17036 t org-fast-tag-selection-single-key)))
17037 (call-interactively 'org-set-tags)))))
17038 ((equal key "DEADLINE")
17039 (setq eval '(org-with-point-at pom
17040 (call-interactively 'org-deadline))))
17041 ((equal key "SCHEDULED")
17042 (setq eval '(org-with-point-at pom
17043 (call-interactively 'org-schedule))))
17045 (setq allowed (org-property-get-allowed-values pom key 'table))
17046 (if allowed
17047 (setq nval (completing-read "Value: " allowed nil t))
17048 (setq nval (read-string "Edit: " value)))
17049 (setq nval (org-trim nval))
17050 (when (not (equal nval value))
17051 (setq eval '(org-entry-put pom key nval)))))
17052 (when eval
17053 (let ((inhibit-read-only t))
17054 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
17055 (unwind-protect
17056 (progn
17057 (setq org-columns-overlays
17058 (org-delete-all line-overlays org-columns-overlays))
17059 (mapc 'org-delete-overlay line-overlays)
17060 (org-columns-eval eval))
17061 (org-columns-display-here))))
17062 (move-to-column col)
17063 (if (and (org-mode-p)
17064 (nth 3 (assoc key org-columns-current-fmt-compiled)))
17065 (org-columns-update key))))
17067 (defun org-edit-headline () ; FIXME: this is not columns specific
17068 "Edit the current headline, the part without TODO keyword, TAGS."
17069 (org-back-to-heading)
17070 (when (looking-at org-todo-line-regexp)
17071 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
17072 (txt (match-string 3))
17073 (post "")
17074 txt2)
17075 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
17076 (setq post (match-string 0 txt)
17077 txt (substring txt 0 (match-beginning 0))))
17078 (setq txt2 (read-string "Edit: " txt))
17079 (when (not (equal txt txt2))
17080 (beginning-of-line 1)
17081 (insert pre txt2 post)
17082 (delete-region (point) (point-at-eol))
17083 (org-set-tags nil t)))))
17085 (defun org-columns-edit-allowed ()
17086 "Edit the list of allowed values for the current property."
17087 (interactive)
17088 (let* ((key (get-char-property (point) 'org-columns-key))
17089 (key1 (concat key "_ALL"))
17090 (allowed (org-entry-get (point) key1 t))
17091 nval)
17092 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
17093 (setq nval (read-string "Allowed: " allowed))
17094 (org-entry-put
17095 (cond ((marker-position org-entry-property-inherited-from)
17096 org-entry-property-inherited-from)
17097 ((marker-position org-columns-top-level-marker)
17098 org-columns-top-level-marker))
17099 key1 nval)))
17101 (defmacro org-no-warnings (&rest body)
17102 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
17104 (defun org-columns-eval (form)
17105 (let (hidep)
17106 (save-excursion
17107 (beginning-of-line 1)
17108 ;; `next-line' is needed here, because it skips invisible line.
17109 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
17110 (setq hidep (org-on-heading-p 1)))
17111 (eval form)
17112 (and hidep (hide-entry))))
17114 (defun org-columns-previous-allowed-value ()
17115 "Switch to the previous allowed value for this column."
17116 (interactive)
17117 (org-columns-next-allowed-value t))
17119 (defun org-columns-next-allowed-value (&optional previous)
17120 "Switch to the next allowed value for this column."
17121 (interactive)
17122 (org-columns-check-computed)
17123 (let* ((col (current-column))
17124 (key (get-char-property (point) 'org-columns-key))
17125 (value (get-char-property (point) 'org-columns-value))
17126 (bol (point-at-bol)) (eol (point-at-eol))
17127 (pom (or (get-text-property bol 'org-hd-marker)
17128 (point))) ; keep despite of compiler waring
17129 (line-overlays
17130 (delq nil (mapcar (lambda (x)
17131 (and (eq (overlay-buffer x) (current-buffer))
17132 (>= (overlay-start x) bol)
17133 (<= (overlay-start x) eol)
17135 org-columns-overlays)))
17136 (allowed (or (org-property-get-allowed-values pom key)
17137 (and (memq
17138 (nth 4 (assoc key org-columns-current-fmt-compiled))
17139 '(checkbox checkbox-n-of-m checkbox-percent))
17140 '("[ ]" "[X]"))))
17141 nval)
17142 (when (equal key "ITEM")
17143 (error "Cannot edit item headline from here"))
17144 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
17145 (error "Allowed values for this property have not been defined"))
17146 (if (member key '("SCHEDULED" "DEADLINE"))
17147 (setq nval (if previous 'earlier 'later))
17148 (if previous (setq allowed (reverse allowed)))
17149 (if (member value allowed)
17150 (setq nval (car (cdr (member value allowed)))))
17151 (setq nval (or nval (car allowed)))
17152 (if (equal nval value)
17153 (error "Only one allowed value for this property")))
17154 (let ((inhibit-read-only t))
17155 (remove-text-properties (1- bol) eol '(read-only t))
17156 (unwind-protect
17157 (progn
17158 (setq org-columns-overlays
17159 (org-delete-all line-overlays org-columns-overlays))
17160 (mapc 'org-delete-overlay line-overlays)
17161 (org-columns-eval '(org-entry-put pom key nval)))
17162 (org-columns-display-here)))
17163 (move-to-column col)
17164 (if (and (org-mode-p)
17165 (nth 3 (assoc key org-columns-current-fmt-compiled)))
17166 (org-columns-update key))))
17168 (defun org-verify-version (task)
17169 (cond
17170 ((eq task 'columns)
17171 (if (or (featurep 'xemacs)
17172 (< emacs-major-version 22))
17173 (error "Emacs 22 is required for the columns feature")))))
17175 (defun org-columns-open-link (&optional arg)
17176 (interactive "P")
17177 (let ((value (get-char-property (point) 'org-columns-value)))
17178 (org-open-link-from-string value arg)))
17180 (defun org-open-link-from-string (s &optional arg)
17181 "Open a link in the string S, as if it was in Org-mode."
17182 (interactive)
17183 (with-temp-buffer
17184 (let ((org-inhibit-startup t))
17185 (org-mode)
17186 (insert s)
17187 (goto-char (point-min))
17188 (org-open-at-point arg))))
17190 (defun org-columns-get-format-and-top-level ()
17191 (let (fmt)
17192 (when (condition-case nil (org-back-to-heading) (error nil))
17193 (move-marker org-entry-property-inherited-from nil)
17194 (setq fmt (org-entry-get nil "COLUMNS" t)))
17195 (setq fmt (or fmt org-columns-default-format))
17196 (org-set-local 'org-columns-current-fmt fmt)
17197 (org-columns-compile-format fmt)
17198 (if (marker-position org-entry-property-inherited-from)
17199 (move-marker org-columns-top-level-marker
17200 org-entry-property-inherited-from)
17201 (move-marker org-columns-top-level-marker (point)))
17202 fmt))
17204 (defun org-columns ()
17205 "Turn on column view on an org-mode file."
17206 (interactive)
17207 (org-verify-version 'columns)
17208 (org-columns-remove-overlays)
17209 (move-marker org-columns-begin-marker (point))
17210 (let (beg end fmt cache maxwidths)
17211 (setq fmt (org-columns-get-format-and-top-level))
17212 (save-excursion
17213 (goto-char org-columns-top-level-marker)
17214 (setq beg (point))
17215 (unless org-columns-inhibit-recalculation
17216 (org-columns-compute-all))
17217 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
17218 (point-max)))
17219 ;; Get and cache the properties
17220 (goto-char beg)
17221 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
17222 (save-excursion
17223 (save-restriction
17224 (narrow-to-region beg end)
17225 (org-clock-sum))))
17226 (while (re-search-forward (concat "^" outline-regexp) end t)
17227 (push (cons (org-current-line) (org-entry-properties)) cache))
17228 (when cache
17229 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17230 (org-set-local 'org-columns-current-maxwidths maxwidths)
17231 (org-columns-display-here-title)
17232 (mapc (lambda (x)
17233 (goto-line (car x))
17234 (org-columns-display-here (cdr x)))
17235 cache)))))
17237 (defun org-columns-new (&optional prop title width op fmt &rest rest)
17238 "Insert a new column, to the leeft o the current column."
17239 (interactive)
17240 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
17241 cell)
17242 (setq prop (completing-read
17243 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
17244 nil nil prop))
17245 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
17246 (setq width (read-string "Column width: " (if width (number-to-string width))))
17247 (if (string-match "\\S-" width)
17248 (setq width (string-to-number width))
17249 (setq width nil))
17250 (setq fmt (completing-read "Summary [none]: "
17251 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
17252 nil t))
17253 (if (string-match "\\S-" fmt)
17254 (setq fmt (intern fmt))
17255 (setq fmt nil))
17256 (if (eq fmt 'none) (setq fmt nil))
17257 (if editp
17258 (progn
17259 (setcar editp prop)
17260 (setcdr editp (list title width nil fmt)))
17261 (setq cell (nthcdr (1- (current-column))
17262 org-columns-current-fmt-compiled))
17263 (setcdr cell (cons (list prop title width nil fmt)
17264 (cdr cell))))
17265 (org-columns-store-format)
17266 (org-columns-redo)))
17268 (defun org-columns-delete ()
17269 "Delete the column at point from columns view."
17270 (interactive)
17271 (let* ((n (current-column))
17272 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
17273 (when (y-or-n-p
17274 (format "Are you sure you want to remove column \"%s\"? " title))
17275 (setq org-columns-current-fmt-compiled
17276 (delq (nth n org-columns-current-fmt-compiled)
17277 org-columns-current-fmt-compiled))
17278 (org-columns-store-format)
17279 (org-columns-redo)
17280 (if (>= (current-column) (length org-columns-current-fmt-compiled))
17281 (backward-char 1)))))
17283 (defun org-columns-edit-attributes ()
17284 "Edit the attributes of the current column."
17285 (interactive)
17286 (let* ((n (current-column))
17287 (info (nth n org-columns-current-fmt-compiled)))
17288 (apply 'org-columns-new info)))
17290 (defun org-columns-widen (arg)
17291 "Make the column wider by ARG characters."
17292 (interactive "p")
17293 (let* ((n (current-column))
17294 (entry (nth n org-columns-current-fmt-compiled))
17295 (width (or (nth 2 entry)
17296 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
17297 (setq width (max 1 (+ width arg)))
17298 (setcar (nthcdr 2 entry) width)
17299 (org-columns-store-format)
17300 (org-columns-redo)))
17302 (defun org-columns-narrow (arg)
17303 "Make the column nrrower by ARG characters."
17304 (interactive "p")
17305 (org-columns-widen (- arg)))
17307 (defun org-columns-move-right ()
17308 "Swap this column with the one to the right."
17309 (interactive)
17310 (let* ((n (current-column))
17311 (cell (nthcdr n org-columns-current-fmt-compiled))
17313 (when (>= n (1- (length org-columns-current-fmt-compiled)))
17314 (error "Cannot shift this column further to the right"))
17315 (setq e (car cell))
17316 (setcar cell (car (cdr cell)))
17317 (setcdr cell (cons e (cdr (cdr cell))))
17318 (org-columns-store-format)
17319 (org-columns-redo)
17320 (forward-char 1)))
17322 (defun org-columns-move-left ()
17323 "Swap this column with the one to the left."
17324 (interactive)
17325 (let* ((n (current-column)))
17326 (when (= n 0)
17327 (error "Cannot shift this column further to the left"))
17328 (backward-char 1)
17329 (org-columns-move-right)
17330 (backward-char 1)))
17332 (defun org-columns-store-format ()
17333 "Store the text version of the current columns format in appropriate place.
17334 This is either in the COLUMNS property of the node starting the current column
17335 display, or in the #+COLUMNS line of the current buffer."
17336 (let (fmt (cnt 0))
17337 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17338 (org-set-local 'org-columns-current-fmt fmt)
17339 (if (marker-position org-columns-top-level-marker)
17340 (save-excursion
17341 (goto-char org-columns-top-level-marker)
17342 (if (and (org-at-heading-p)
17343 (org-entry-get nil "COLUMNS"))
17344 (org-entry-put nil "COLUMNS" fmt)
17345 (goto-char (point-min))
17346 ;; Overwrite all #+COLUMNS lines....
17347 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17348 (setq cnt (1+ cnt))
17349 (replace-match (concat "#+COLUMNS: " fmt) t t))
17350 (unless (> cnt 0)
17351 (goto-char (point-min))
17352 (or (org-on-heading-p t) (outline-next-heading))
17353 (let ((inhibit-read-only t))
17354 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17355 (org-set-local 'org-columns-default-format fmt))))))
17357 (defvar org-overriding-columns-format nil
17358 "When set, overrides any other definition.")
17359 (defvar org-agenda-view-columns-initially nil
17360 "When set, switch to columns view immediately after creating the agenda.")
17362 (defun org-agenda-columns ()
17363 "Turn on column view in the agenda."
17364 (interactive)
17365 (org-verify-version 'columns)
17366 (org-columns-remove-overlays)
17367 (move-marker org-columns-begin-marker (point))
17368 (let (fmt cache maxwidths m)
17369 (cond
17370 ((and (local-variable-p 'org-overriding-columns-format)
17371 org-overriding-columns-format)
17372 (setq fmt org-overriding-columns-format))
17373 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17374 (setq fmt (org-entry-get m "COLUMNS" t)))
17375 ((and (boundp 'org-columns-current-fmt)
17376 (local-variable-p 'org-columns-current-fmt)
17377 org-columns-current-fmt)
17378 (setq fmt org-columns-current-fmt))
17379 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17380 (setq m (get-text-property m 'org-hd-marker))
17381 (setq fmt (org-entry-get m "COLUMNS" t))))
17382 (setq fmt (or fmt org-columns-default-format))
17383 (org-set-local 'org-columns-current-fmt fmt)
17384 (org-columns-compile-format fmt)
17385 (save-excursion
17386 ;; Get and cache the properties
17387 (goto-char (point-min))
17388 (while (not (eobp))
17389 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17390 (get-text-property (point) 'org-marker)))
17391 (push (cons (org-current-line) (org-entry-properties m)) cache))
17392 (beginning-of-line 2))
17393 (when cache
17394 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17395 (org-set-local 'org-columns-current-maxwidths maxwidths)
17396 (org-columns-display-here-title)
17397 (mapc (lambda (x)
17398 (goto-line (car x))
17399 (org-columns-display-here (cdr x)))
17400 cache)))))
17402 (defun org-columns-get-autowidth-alist (s cache)
17403 "Derive the maximum column widths from the format and the cache."
17404 (let ((start 0) rtn)
17405 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17406 (push (cons (match-string 1 s) 1) rtn)
17407 (setq start (match-end 0)))
17408 (mapc (lambda (x)
17409 (setcdr x (apply 'max
17410 (mapcar
17411 (lambda (y)
17412 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17413 cache))))
17414 rtn)
17415 rtn))
17417 (defun org-columns-compute-all ()
17418 "Compute all columns that have operators defined."
17419 (org-unmodified
17420 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17421 (let ((columns org-columns-current-fmt-compiled) col)
17422 (while (setq col (pop columns))
17423 (when (nth 3 col)
17424 (save-excursion
17425 (org-columns-compute (car col)))))))
17427 (defun org-columns-update (property)
17428 "Recompute PROPERTY, and update the columns display for it."
17429 (org-columns-compute property)
17430 (let (fmt val pos)
17431 (save-excursion
17432 (mapc (lambda (ov)
17433 (when (equal (org-overlay-get ov 'org-columns-key) property)
17434 (setq pos (org-overlay-start ov))
17435 (goto-char pos)
17436 (when (setq val (cdr (assoc property
17437 (get-text-property
17438 (point-at-bol) 'org-summaries))))
17439 (setq fmt (org-overlay-get ov 'org-columns-format))
17440 (org-overlay-put ov 'org-columns-value val)
17441 (org-overlay-put ov 'display (format fmt val)))))
17442 org-columns-overlays))))
17444 (defun org-columns-compute (property)
17445 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17446 (interactive)
17447 (let* ((re (concat "^" outline-regexp))
17448 (lmax 30) ; Does anyone use deeper levels???
17449 (lsum (make-vector lmax 0))
17450 (lflag (make-vector lmax nil))
17451 (level 0)
17452 (ass (assoc property org-columns-current-fmt-compiled))
17453 (format (nth 4 ass))
17454 (printf (nth 5 ass))
17455 (beg org-columns-top-level-marker)
17456 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17457 (save-excursion
17458 ;; Find the region to compute
17459 (goto-char beg)
17460 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17461 (goto-char end)
17462 ;; Walk the tree from the back and do the computations
17463 (while (re-search-backward re beg t)
17464 (setq sumpos (match-beginning 0)
17465 last-level level
17466 level (org-outline-level)
17467 val (org-entry-get nil property)
17468 valflag (and val (string-match "\\S-" val)))
17469 (cond
17470 ((< level last-level)
17471 ;; put the sum of lower levels here as a property
17472 (setq sum (aref lsum last-level) ; current sum
17473 flag (aref lflag last-level) ; any valid entries from children?
17474 str (org-column-number-to-string sum format printf)
17475 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17476 useval (if flag str1 (if valflag val ""))
17477 sum-alist (get-text-property sumpos 'org-summaries))
17478 (if (assoc property sum-alist)
17479 (setcdr (assoc property sum-alist) useval)
17480 (push (cons property useval) sum-alist)
17481 (org-unmodified
17482 (add-text-properties sumpos (1+ sumpos)
17483 (list 'org-summaries sum-alist))))
17484 (when val
17485 (org-entry-put nil property (if flag str val)))
17486 ;; add current to current level accumulator
17487 (when (or flag valflag)
17488 (aset lsum level (+ (aref lsum level)
17489 (if flag sum (org-column-string-to-number
17490 (if flag str val) format))))
17491 (aset lflag level t))
17492 ;; clear accumulators for deeper levels
17493 (loop for l from (1+ level) to (1- lmax) do
17494 (aset lsum l 0)
17495 (aset lflag l nil)))
17496 ((>= level last-level)
17497 ;; add what we have here to the accumulator for this level
17498 (aset lsum level (+ (aref lsum level)
17499 (org-column-string-to-number (or val "0") format)))
17500 (and valflag (aset lflag level t)))
17501 (t (error "This should not happen")))))))
17503 (defun org-columns-redo ()
17504 "Construct the column display again."
17505 (interactive)
17506 (message "Recomputing columns...")
17507 (save-excursion
17508 (if (marker-position org-columns-begin-marker)
17509 (goto-char org-columns-begin-marker))
17510 (org-columns-remove-overlays)
17511 (if (org-mode-p)
17512 (call-interactively 'org-columns)
17513 (call-interactively 'org-agenda-columns)))
17514 (message "Recomputing columns...done"))
17516 (defun org-columns-not-in-agenda ()
17517 (if (eq major-mode 'org-agenda-mode)
17518 (error "This command is only allowed in Org-mode buffers")))
17521 (defun org-string-to-number (s)
17522 "Convert string to number, and interpret hh:mm:ss."
17523 (if (not (string-match ":" s))
17524 (string-to-number s)
17525 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17526 (while l
17527 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17528 sum)))
17530 (defun org-column-number-to-string (n fmt &optional printf)
17531 "Convert a computed column number to a string value, according to FMT."
17532 (cond
17533 ((eq fmt 'add_times)
17534 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17535 (format "%d:%02d" h m)))
17536 ((eq fmt 'checkbox)
17537 (cond ((= n (floor n)) "[X]")
17538 ((> n 1.) "[-]")
17539 (t "[ ]")))
17540 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17541 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17542 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17543 (printf (format printf n))
17544 ((eq fmt 'currency)
17545 (format "%.2f" n))
17546 (t (number-to-string n))))
17548 (defun org-nofm-to-completion (n m &optional percent)
17549 (if (not percent)
17550 (format "[%d/%d]" n m)
17551 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17553 (defun org-column-string-to-number (s fmt)
17554 "Convert a column value to a number that can be used for column computing."
17555 (cond
17556 ((string-match ":" s)
17557 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17558 (while l
17559 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17560 sum))
17561 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17562 (if (equal s "[X]") 1. 0.000001))
17563 (t (string-to-number s))))
17565 (defun org-columns-uncompile-format (cfmt)
17566 "Turn the compiled columns format back into a string representation."
17567 (let ((rtn "") e s prop title op width fmt printf)
17568 (while (setq e (pop cfmt))
17569 (setq prop (car e)
17570 title (nth 1 e)
17571 width (nth 2 e)
17572 op (nth 3 e)
17573 fmt (nth 4 e)
17574 printf (nth 5 e))
17575 (cond
17576 ((eq fmt 'add_times) (setq op ":"))
17577 ((eq fmt 'checkbox) (setq op "X"))
17578 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17579 ((eq fmt 'checkbox-percent) (setq op "X%"))
17580 ((eq fmt 'add_numbers) (setq op "+"))
17581 ((eq fmt 'currency) (setq op "$")))
17582 (if (and op printf) (setq op (concat op ";" printf)))
17583 (if (equal title prop) (setq title nil))
17584 (setq s (concat "%" (if width (number-to-string width))
17585 prop
17586 (if title (concat "(" title ")"))
17587 (if op (concat "{" op "}"))))
17588 (setq rtn (concat rtn " " s)))
17589 (org-trim rtn)))
17591 (defun org-columns-compile-format (fmt)
17592 "Turn a column format string into an alist of specifications.
17593 The alist has one entry for each column in the format. The elements of
17594 that list are:
17595 property the property
17596 title the title field for the columns
17597 width the column width in characters, can be nil for automatic
17598 operator the operator if any
17599 format the output format for computed results, derived from operator
17600 printf a printf format for computed values"
17601 (let ((start 0) width prop title op f printf)
17602 (setq org-columns-current-fmt-compiled nil)
17603 (while (string-match
17604 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17605 fmt start)
17606 (setq start (match-end 0)
17607 width (match-string 1 fmt)
17608 prop (match-string 2 fmt)
17609 title (or (match-string 3 fmt) prop)
17610 op (match-string 4 fmt)
17611 f nil
17612 printf nil)
17613 (if width (setq width (string-to-number width)))
17614 (when (and op (string-match ";" op))
17615 (setq printf (substring op (match-end 0))
17616 op (substring op 0 (match-beginning 0))))
17617 (cond
17618 ((equal op "+") (setq f 'add_numbers))
17619 ((equal op "$") (setq f 'currency))
17620 ((equal op ":") (setq f 'add_times))
17621 ((equal op "X") (setq f 'checkbox))
17622 ((equal op "X/") (setq f 'checkbox-n-of-m))
17623 ((equal op "X%") (setq f 'checkbox-percent))
17625 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17626 (setq org-columns-current-fmt-compiled
17627 (nreverse org-columns-current-fmt-compiled))))
17630 ;;; Dynamic block for Column view
17632 (defun org-columns-capture-view (&optional maxlevel skip-empty-rows)
17633 "Get the column view of the current buffer or subtree.
17634 The first optional argument MAXLEVEL sets the level limit. A
17635 second optional argument SKIP-EMPTY-ROWS tells whether to skip
17636 empty rows, an empty row being one where all the column view
17637 specifiers except ITEM are empty. This function returns a list
17638 containing the title row and all other rows. Each row is a list
17639 of fields."
17640 (save-excursion
17641 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17642 (n (length title)) row tbl)
17643 (goto-char (point-min))
17644 (while (and (re-search-forward "^\\(\\*+\\) " nil t)
17645 (or (null maxlevel)
17646 (>= maxlevel
17647 (if org-odd-levels-only
17648 (/ (1+ (length (match-string 1))) 2)
17649 (length (match-string 1))))))
17650 (when (get-char-property (match-beginning 0) 'org-columns-key)
17651 (setq row nil)
17652 (loop for i from 0 to (1- n) do
17653 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17654 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17656 row))
17657 (setq row (nreverse row))
17658 (unless (and skip-empty-rows
17659 (eq 1 (length (delete "" (delete-dups row)))))
17660 (push row tbl))))
17661 (append (list title 'hline) (nreverse tbl)))))
17663 (defun org-dblock-write:columnview (params)
17664 "Write the column view table.
17665 PARAMS is a property list of parameters:
17667 :width enforce same column widths with <N> specifiers.
17668 :id the :ID: property of the entry where the columns view
17669 should be built, as a string. When `local', call locally.
17670 When `global' call column view with the cursor at the beginning
17671 of the buffer (usually this means that the whole buffer switches
17672 to column view).
17673 :hlines When t, insert a hline before each item. When a number, insert
17674 a hline before each level <= that number.
17675 :vlines When t, make each column a colgroup to enforce vertical lines.
17676 :maxlevel When set to a number, don't capture headlines below this level.
17677 :skip-empty-rows
17678 When t, skip rows where all specifiers other than ITEM are empty."
17679 (let ((pos (move-marker (make-marker) (point)))
17680 (hlines (plist-get params :hlines))
17681 (vlines (plist-get params :vlines))
17682 (maxlevel (plist-get params :maxlevel))
17683 (skip-empty-rows (plist-get params :skip-empty-rows))
17684 tbl id idpos nfields tmp)
17685 (save-excursion
17686 (save-restriction
17687 (when (setq id (plist-get params :id))
17688 (cond ((not id) nil)
17689 ((eq id 'global) (goto-char (point-min)))
17690 ((eq id 'local) nil)
17691 ((setq idpos (org-find-entry-with-id id))
17692 (goto-char idpos))
17693 (t (error "Cannot find entry with :ID: %s" id))))
17694 (org-columns)
17695 (setq tbl (org-columns-capture-view maxlevel skip-empty-rows))
17696 (setq nfields (length (car tbl)))
17697 (org-columns-quit)))
17698 (goto-char pos)
17699 (move-marker pos nil)
17700 (when tbl
17701 (when (plist-get params :hlines)
17702 (setq tmp nil)
17703 (while tbl
17704 (if (eq (car tbl) 'hline)
17705 (push (pop tbl) tmp)
17706 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17707 (if (and (not (eq (car tmp) 'hline))
17708 (or (eq hlines t)
17709 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17710 (push 'hline tmp)))
17711 (push (pop tbl) tmp)))
17712 (setq tbl (nreverse tmp)))
17713 (when vlines
17714 (setq tbl (mapcar (lambda (x)
17715 (if (eq 'hline x) x (cons "" x)))
17716 tbl))
17717 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17718 (setq pos (point))
17719 (insert (org-listtable-to-string tbl))
17720 (when (plist-get params :width)
17721 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17722 org-columns-current-widths "|")))
17723 (goto-char pos)
17724 (org-table-align))))
17726 (defun org-listtable-to-string (tbl)
17727 "Convert a listtable TBL to a string that contains the Org-mode table.
17728 The table still need to be alligned. The resulting string has no leading
17729 and tailing newline characters."
17730 (mapconcat
17731 (lambda (x)
17732 (cond
17733 ((listp x)
17734 (concat "|" (mapconcat 'identity x "|") "|"))
17735 ((eq x 'hline) "|-|")
17736 (t (error "Garbage in listtable: %s" x))))
17737 tbl "\n"))
17739 (defun org-insert-columns-dblock ()
17740 "Create a dynamic block capturing a column view table."
17741 (interactive)
17742 (let ((defaults '(:name "columnview" :hlines 1))
17743 (id (completing-read
17744 "Capture columns (local, global, entry with :ID: property) [local]: "
17745 (append '(("global") ("local"))
17746 (mapcar 'list (org-property-values "ID"))))))
17747 (if (equal id "") (setq id 'local))
17748 (if (equal id "global") (setq id 'global))
17749 (setq defaults (append defaults (list :id id)))
17750 (org-create-dblock defaults)
17751 (org-update-dblock)))
17753 ;;;; Timestamps
17755 (defvar org-last-changed-timestamp nil)
17756 (defvar org-time-was-given) ; dynamically scoped parameter
17757 (defvar org-end-time-was-given) ; dynamically scoped parameter
17758 (defvar org-ts-what) ; dynamically scoped parameter
17760 (defun org-time-stamp (arg)
17761 "Prompt for a date/time and insert a time stamp.
17762 If the user specifies a time like HH:MM, or if this command is called
17763 with a prefix argument, the time stamp will contain date and time.
17764 Otherwise, only the date will be included. All parts of a date not
17765 specified by the user will be filled in from the current date/time.
17766 So if you press just return without typing anything, the time stamp
17767 will represent the current date/time. If there is already a timestamp
17768 at the cursor, it will be modified."
17769 (interactive "P")
17770 (let* ((ts nil)
17771 (default-time
17772 ;; Default time is either today, or, when entering a range,
17773 ;; the range start.
17774 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17775 (save-excursion
17776 (re-search-backward
17777 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17778 (- (point) 20) t)))
17779 (apply 'encode-time (org-parse-time-string (match-string 1)))
17780 (current-time)))
17781 (default-input (and ts (org-get-compact-tod ts)))
17782 org-time-was-given org-end-time-was-given time)
17783 (cond
17784 ((and (org-at-timestamp-p)
17785 (eq last-command 'org-time-stamp)
17786 (eq this-command 'org-time-stamp))
17787 (insert "--")
17788 (setq time (let ((this-command this-command))
17789 (org-read-date arg 'totime nil nil default-time default-input)))
17790 (org-insert-time-stamp time (or org-time-was-given arg)))
17791 ((org-at-timestamp-p)
17792 (setq time (let ((this-command this-command))
17793 (org-read-date arg 'totime nil nil default-time default-input)))
17794 (when (org-at-timestamp-p) ; just to get the match data
17795 (replace-match "")
17796 (setq org-last-changed-timestamp
17797 (org-insert-time-stamp
17798 time (or org-time-was-given arg)
17799 nil nil nil (list org-end-time-was-given))))
17800 (message "Timestamp updated"))
17802 (setq time (let ((this-command this-command))
17803 (org-read-date arg 'totime nil nil default-time default-input)))
17804 (org-insert-time-stamp time (or org-time-was-given arg)
17805 nil nil nil (list org-end-time-was-given))))))
17807 ;; FIXME: can we use this for something else????
17808 ;; like computing time differences?????
17809 (defun org-get-compact-tod (s)
17810 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17811 (let* ((t1 (match-string 1 s))
17812 (h1 (string-to-number (match-string 2 s)))
17813 (m1 (string-to-number (match-string 3 s)))
17814 (t2 (and (match-end 4) (match-string 5 s)))
17815 (h2 (and t2 (string-to-number (match-string 6 s))))
17816 (m2 (and t2 (string-to-number (match-string 7 s))))
17817 dh dm)
17818 (if (not t2)
17820 (setq dh (- h2 h1) dm (- m2 m1))
17821 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17822 (concat t1 "+" (number-to-string dh)
17823 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17825 (defun org-time-stamp-inactive (&optional arg)
17826 "Insert an inactive time stamp.
17827 An inactive time stamp is enclosed in square brackets instead of angle
17828 brackets. It is inactive in the sense that it does not trigger agenda entries,
17829 does not link to the calendar and cannot be changed with the S-cursor keys.
17830 So these are more for recording a certain time/date."
17831 (interactive "P")
17832 (let (org-time-was-given org-end-time-was-given time)
17833 (setq time (org-read-date arg 'totime))
17834 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17835 nil nil (list org-end-time-was-given))))
17837 (defvar org-date-ovl (org-make-overlay 1 1))
17838 (org-overlay-put org-date-ovl 'face 'org-warning)
17839 (org-detach-overlay org-date-ovl)
17841 (defvar org-ans1) ; dynamically scoped parameter
17842 (defvar org-ans2) ; dynamically scoped parameter
17844 (defvar org-plain-time-of-day-regexp) ; defined below
17846 (defvar org-read-date-overlay nil)
17847 (defvar org-dcst nil) ; dynamically scoped
17849 (defun org-read-date (&optional with-time to-time from-string prompt
17850 default-time default-input)
17851 "Read a date, possibly a time, and make things smooth for the user.
17852 The prompt will suggest to enter an ISO date, but you can also enter anything
17853 which will at least partially be understood by `parse-time-string'.
17854 Unrecognized parts of the date will default to the current day, month, year,
17855 hour and minute. If this command is called to replace a timestamp at point,
17856 of to enter the second timestamp of a range, the default time is taken from the
17857 existing stamp. For example,
17858 3-2-5 --> 2003-02-05
17859 feb 15 --> currentyear-02-15
17860 sep 12 9 --> 2009-09-12
17861 12:45 --> today 12:45
17862 22 sept 0:34 --> currentyear-09-22 0:34
17863 12 --> currentyear-currentmonth-12
17864 Fri --> nearest Friday (today or later)
17865 etc.
17867 Furthermore you can specify a relative date by giving, as the *first* thing
17868 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17869 change in days weeks, months, years.
17870 With a single plus or minus, the date is relative to today. With a double
17871 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17872 +4d --> four days from today
17873 +4 --> same as above
17874 +2w --> two weeks from today
17875 ++5 --> five days from default date
17877 The function understands only English month and weekday abbreviations,
17878 but this can be configured with the variables `parse-time-months' and
17879 `parse-time-weekdays'.
17881 While prompting, a calendar is popped up - you can also select the
17882 date with the mouse (button 1). The calendar shows a period of three
17883 months. To scroll it to other months, use the keys `>' and `<'.
17884 If you don't like the calendar, turn it off with
17885 \(setq org-read-date-popup-calendar nil)
17887 With optional argument TO-TIME, the date will immediately be converted
17888 to an internal time.
17889 With an optional argument WITH-TIME, the prompt will suggest to also
17890 insert a time. Note that when WITH-TIME is not set, you can still
17891 enter a time, and this function will inform the calling routine about
17892 this change. The calling routine may then choose to change the format
17893 used to insert the time stamp into the buffer to include the time.
17894 With optional argument FROM-STRING, read from this string instead from
17895 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17896 the time/date that is used for everything that is not specified by the
17897 user."
17898 (require 'parse-time)
17899 (let* ((org-time-stamp-rounding-minutes
17900 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
17901 (org-dcst org-display-custom-times)
17902 (ct (org-current-time))
17903 (def (or default-time ct))
17904 (defdecode (decode-time def))
17905 (dummy (progn
17906 (when (< (nth 2 defdecode) org-extend-today-until)
17907 (setcar (nthcdr 2 defdecode) -1)
17908 (setcar (nthcdr 1 defdecode) 59)
17909 (setq def (apply 'encode-time defdecode)
17910 defdecode (decode-time def)))))
17911 (calendar-move-hook nil)
17912 (view-diary-entries-initially nil)
17913 (view-calendar-holidays-initially nil)
17914 (timestr (format-time-string
17915 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17916 (prompt (concat (if prompt (concat prompt " ") "")
17917 (format "Date+time [%s]: " timestr)))
17918 ans (org-ans0 "") org-ans1 org-ans2 final)
17920 (cond
17921 (from-string (setq ans from-string))
17922 (org-read-date-popup-calendar
17923 (save-excursion
17924 (save-window-excursion
17925 (calendar)
17926 (calendar-forward-day (- (time-to-days def)
17927 (calendar-absolute-from-gregorian
17928 (calendar-current-date))))
17929 (org-eval-in-calendar nil t)
17930 (let* ((old-map (current-local-map))
17931 (map (copy-keymap calendar-mode-map))
17932 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17933 (org-defkey map (kbd "RET") 'org-calendar-select)
17934 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17935 'org-calendar-select-mouse)
17936 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17937 'org-calendar-select-mouse)
17938 (org-defkey minibuffer-local-map [(meta shift left)]
17939 (lambda () (interactive)
17940 (org-eval-in-calendar '(calendar-backward-month 1))))
17941 (org-defkey minibuffer-local-map [(meta shift right)]
17942 (lambda () (interactive)
17943 (org-eval-in-calendar '(calendar-forward-month 1))))
17944 (org-defkey minibuffer-local-map [(meta shift up)]
17945 (lambda () (interactive)
17946 (org-eval-in-calendar '(calendar-backward-year 1))))
17947 (org-defkey minibuffer-local-map [(meta shift down)]
17948 (lambda () (interactive)
17949 (org-eval-in-calendar '(calendar-forward-year 1))))
17950 (org-defkey minibuffer-local-map [(shift up)]
17951 (lambda () (interactive)
17952 (org-eval-in-calendar '(calendar-backward-week 1))))
17953 (org-defkey minibuffer-local-map [(shift down)]
17954 (lambda () (interactive)
17955 (org-eval-in-calendar '(calendar-forward-week 1))))
17956 (org-defkey minibuffer-local-map [(shift left)]
17957 (lambda () (interactive)
17958 (org-eval-in-calendar '(calendar-backward-day 1))))
17959 (org-defkey minibuffer-local-map [(shift right)]
17960 (lambda () (interactive)
17961 (org-eval-in-calendar '(calendar-forward-day 1))))
17962 (org-defkey minibuffer-local-map ">"
17963 (lambda () (interactive)
17964 (org-eval-in-calendar '(scroll-calendar-left 1))))
17965 (org-defkey minibuffer-local-map "<"
17966 (lambda () (interactive)
17967 (org-eval-in-calendar '(scroll-calendar-right 1))))
17968 (unwind-protect
17969 (progn
17970 (use-local-map map)
17971 (add-hook 'post-command-hook 'org-read-date-display)
17972 (setq org-ans0 (read-string prompt default-input nil nil))
17973 ;; org-ans0: from prompt
17974 ;; org-ans1: from mouse click
17975 ;; org-ans2: from calendar motion
17976 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17977 (remove-hook 'post-command-hook 'org-read-date-display)
17978 (use-local-map old-map)
17979 (when org-read-date-overlay
17980 (org-delete-overlay org-read-date-overlay)
17981 (setq org-read-date-overlay nil)))))))
17983 (t ; Naked prompt only
17984 (unwind-protect
17985 (setq ans (read-string prompt default-input nil timestr))
17986 (when org-read-date-overlay
17987 (org-delete-overlay org-read-date-overlay)
17988 (setq org-read-date-overlay nil)))))
17990 (setq final (org-read-date-analyze ans def defdecode))
17992 (if to-time
17993 (apply 'encode-time final)
17994 (if (and (boundp 'org-time-was-given) org-time-was-given)
17995 (format "%04d-%02d-%02d %02d:%02d"
17996 (nth 5 final) (nth 4 final) (nth 3 final)
17997 (nth 2 final) (nth 1 final))
17998 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17999 (defvar def)
18000 (defvar defdecode)
18001 (defvar with-time)
18002 (defun org-read-date-display ()
18003 "Display the currrent date prompt interpretation in the minibuffer."
18004 (when org-read-date-display-live
18005 (when org-read-date-overlay
18006 (org-delete-overlay org-read-date-overlay))
18007 (let ((p (point)))
18008 (end-of-line 1)
18009 (while (not (equal (buffer-substring
18010 (max (point-min) (- (point) 4)) (point))
18011 " "))
18012 (insert " "))
18013 (goto-char p))
18014 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
18015 " " (or org-ans1 org-ans2)))
18016 (org-end-time-was-given nil)
18017 (f (org-read-date-analyze ans def defdecode))
18018 (fmts (if org-dcst
18019 org-time-stamp-custom-formats
18020 org-time-stamp-formats))
18021 (fmt (if (or with-time
18022 (and (boundp 'org-time-was-given) org-time-was-given))
18023 (cdr fmts)
18024 (car fmts)))
18025 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
18026 (when (and org-end-time-was-given
18027 (string-match org-plain-time-of-day-regexp txt))
18028 (setq txt (concat (substring txt 0 (match-end 0)) "-"
18029 org-end-time-was-given
18030 (substring txt (match-end 0)))))
18031 (setq org-read-date-overlay
18032 (make-overlay (1- (point-at-eol)) (point-at-eol)))
18033 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
18035 (defun org-read-date-analyze (ans def defdecode)
18036 "Analyze the combined answer of the date prompt."
18037 ;; FIXME: cleanup and comment
18038 (let (delta deltan deltaw deltadef year month day
18039 hour minute second wday pm h2 m2 tl wday1)
18041 (when (setq delta (org-read-date-get-relative ans (current-time) def))
18042 (setq ans (replace-match "" t t ans)
18043 deltan (car delta)
18044 deltaw (nth 1 delta)
18045 deltadef (nth 2 delta)))
18047 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
18048 (when (string-match
18049 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
18050 (setq year (if (match-end 2)
18051 (string-to-number (match-string 2 ans))
18052 (string-to-number (format-time-string "%Y")))
18053 month (string-to-number (match-string 3 ans))
18054 day (string-to-number (match-string 4 ans)))
18055 (if (< year 100) (setq year (+ 2000 year)))
18056 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
18057 t nil ans)))
18058 ;; Help matching am/pm times, because `parse-time-string' does not do that.
18059 ;; If there is a time with am/pm, and *no* time without it, we convert
18060 ;; so that matching will be successful.
18061 (loop for i from 1 to 2 do ; twice, for end time as well
18062 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
18063 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
18064 (setq hour (string-to-number (match-string 1 ans))
18065 minute (if (match-end 3)
18066 (string-to-number (match-string 3 ans))
18068 pm (equal ?p
18069 (string-to-char (downcase (match-string 4 ans)))))
18070 (if (and (= hour 12) (not pm))
18071 (setq hour 0)
18072 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
18073 (setq ans (replace-match (format "%02d:%02d" hour minute)
18074 t t ans))))
18076 ;; Check if a time range is given as a duration
18077 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
18078 (setq hour (string-to-number (match-string 1 ans))
18079 h2 (+ hour (string-to-number (match-string 3 ans)))
18080 minute (string-to-number (match-string 2 ans))
18081 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
18082 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
18083 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
18085 ;; Check if there is a time range
18086 (when (boundp 'org-end-time-was-given)
18087 (setq org-time-was-given nil)
18088 (when (and (string-match org-plain-time-of-day-regexp ans)
18089 (match-end 8))
18090 (setq org-end-time-was-given (match-string 8 ans))
18091 (setq ans (concat (substring ans 0 (match-beginning 7))
18092 (substring ans (match-end 7))))))
18094 (setq tl (parse-time-string ans)
18095 day (or (nth 3 tl) (nth 3 defdecode))
18096 month (or (nth 4 tl)
18097 (if (and org-read-date-prefer-future
18098 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
18099 (1+ (nth 4 defdecode))
18100 (nth 4 defdecode)))
18101 year (or (nth 5 tl)
18102 (if (and org-read-date-prefer-future
18103 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
18104 (1+ (nth 5 defdecode))
18105 (nth 5 defdecode)))
18106 hour (or (nth 2 tl) (nth 2 defdecode))
18107 minute (or (nth 1 tl) (nth 1 defdecode))
18108 second (or (nth 0 tl) 0)
18109 wday (nth 6 tl))
18110 (when deltan
18111 (unless deltadef
18112 (let ((now (decode-time (current-time))))
18113 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
18114 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
18115 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
18116 ((equal deltaw "m") (setq month (+ month deltan)))
18117 ((equal deltaw "y") (setq year (+ year deltan)))))
18118 (when (and wday (not (nth 3 tl)))
18119 ;; Weekday was given, but no day, so pick that day in the week
18120 ;; on or after the derived date.
18121 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
18122 (unless (equal wday wday1)
18123 (setq day (+ day (% (- wday wday1 -7) 7)))))
18124 (if (and (boundp 'org-time-was-given)
18125 (nth 2 tl))
18126 (setq org-time-was-given t))
18127 (if (< year 100) (setq year (+ 2000 year)))
18128 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
18129 (list second minute hour day month year)))
18131 (defvar parse-time-weekdays)
18133 (defun org-read-date-get-relative (s today default)
18134 "Check string S for special relative date string.
18135 TODAY and DEFAULT are internal times, for today and for a default.
18136 Return shift list (N what def-flag)
18137 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
18138 N is the number of WHATs to shift.
18139 DEF-FLAG is t when a double ++ or -- indicates shift relative to
18140 the DEFAULT date rather than TODAY."
18141 (when (string-match
18142 (concat
18143 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
18144 "\\([0-9]+\\)?"
18145 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
18146 "\\([ \t]\\|$\\)") s)
18147 (let* ((dir (if (match-end 1)
18148 (string-to-char (substring (match-string 1 s) -1))
18149 ?+))
18150 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
18151 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
18152 (what (if (match-end 3) (match-string 3 s) "d"))
18153 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
18154 (date (if rel default today))
18155 (wday (nth 6 (decode-time date)))
18156 delta)
18157 (if wday1
18158 (progn
18159 (setq delta (mod (+ 7 (- wday1 wday)) 7))
18160 (if (= dir ?-) (setq delta (- delta 7)))
18161 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
18162 (list delta "d" rel))
18163 (list (* n (if (= dir ?-) -1 1)) what rel)))))
18165 (defun org-eval-in-calendar (form &optional keepdate)
18166 "Eval FORM in the calendar window and return to current window.
18167 Also, store the cursor date in variable org-ans2."
18168 (let ((sw (selected-window)))
18169 (select-window (get-buffer-window "*Calendar*"))
18170 (eval form)
18171 (when (and (not keepdate) (calendar-cursor-to-date))
18172 (let* ((date (calendar-cursor-to-date))
18173 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18174 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
18175 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
18176 (select-window sw)))
18178 ; ;; Update the prompt to show new default date
18179 ; (save-excursion
18180 ; (goto-char (point-min))
18181 ; (when (and org-ans2
18182 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
18183 ; (get-text-property (match-end 0) 'field))
18184 ; (let ((inhibit-read-only t))
18185 ; (replace-match (concat "[" org-ans2 "]") t t)
18186 ; (add-text-properties (point-min) (1+ (match-end 0))
18187 ; (text-properties-at (1+ (point-min)))))))))
18189 (defun org-calendar-select ()
18190 "Return to `org-read-date' with the date currently selected.
18191 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18192 (interactive)
18193 (when (calendar-cursor-to-date)
18194 (let* ((date (calendar-cursor-to-date))
18195 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18196 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18197 (if (active-minibuffer-window) (exit-minibuffer))))
18199 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
18200 "Insert a date stamp for the date given by the internal TIME.
18201 WITH-HM means, use the stamp format that includes the time of the day.
18202 INACTIVE means use square brackets instead of angular ones, so that the
18203 stamp will not contribute to the agenda.
18204 PRE and POST are optional strings to be inserted before and after the
18205 stamp.
18206 The command returns the inserted time stamp."
18207 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
18208 stamp)
18209 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
18210 (insert-before-markers (or pre ""))
18211 (insert-before-markers (setq stamp (format-time-string fmt time)))
18212 (when (listp extra)
18213 (setq extra (car extra))
18214 (if (and (stringp extra)
18215 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
18216 (setq extra (format "-%02d:%02d"
18217 (string-to-number (match-string 1 extra))
18218 (string-to-number (match-string 2 extra))))
18219 (setq extra nil)))
18220 (when extra
18221 (backward-char 1)
18222 (insert-before-markers extra)
18223 (forward-char 1))
18224 (insert-before-markers (or post ""))
18225 stamp))
18227 (defun org-toggle-time-stamp-overlays ()
18228 "Toggle the use of custom time stamp formats."
18229 (interactive)
18230 (setq org-display-custom-times (not org-display-custom-times))
18231 (unless org-display-custom-times
18232 (let ((p (point-min)) (bmp (buffer-modified-p)))
18233 (while (setq p (next-single-property-change p 'display))
18234 (if (and (get-text-property p 'display)
18235 (eq (get-text-property p 'face) 'org-date))
18236 (remove-text-properties
18237 p (setq p (next-single-property-change p 'display))
18238 '(display t))))
18239 (set-buffer-modified-p bmp)))
18240 (if (featurep 'xemacs)
18241 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
18242 (org-restart-font-lock)
18243 (setq org-table-may-need-update t)
18244 (if org-display-custom-times
18245 (message "Time stamps are overlayed with custom format")
18246 (message "Time stamp overlays removed")))
18248 (defun org-display-custom-time (beg end)
18249 "Overlay modified time stamp format over timestamp between BED and END."
18250 (let* ((ts (buffer-substring beg end))
18251 t1 w1 with-hm tf time str w2 (off 0))
18252 (save-match-data
18253 (setq t1 (org-parse-time-string ts t))
18254 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
18255 (setq off (- (match-end 0) (match-beginning 0)))))
18256 (setq end (- end off))
18257 (setq w1 (- end beg)
18258 with-hm (and (nth 1 t1) (nth 2 t1))
18259 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
18260 time (org-fix-decoded-time t1)
18261 str (org-add-props
18262 (format-time-string
18263 (substring tf 1 -1) (apply 'encode-time time))
18264 nil 'mouse-face 'highlight)
18265 w2 (length str))
18266 (if (not (= w2 w1))
18267 (add-text-properties (1+ beg) (+ 2 beg)
18268 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
18269 (if (featurep 'xemacs)
18270 (progn
18271 (put-text-property beg end 'invisible t)
18272 (put-text-property beg end 'end-glyph (make-glyph str)))
18273 (put-text-property beg end 'display str))))
18275 (defun org-translate-time (string)
18276 "Translate all timestamps in STRING to custom format.
18277 But do this only if the variable `org-display-custom-times' is set."
18278 (when org-display-custom-times
18279 (save-match-data
18280 (let* ((start 0)
18281 (re org-ts-regexp-both)
18282 t1 with-hm inactive tf time str beg end)
18283 (while (setq start (string-match re string start))
18284 (setq beg (match-beginning 0)
18285 end (match-end 0)
18286 t1 (save-match-data
18287 (org-parse-time-string (substring string beg end) t))
18288 with-hm (and (nth 1 t1) (nth 2 t1))
18289 inactive (equal (substring string beg (1+ beg)) "[")
18290 tf (funcall (if with-hm 'cdr 'car)
18291 org-time-stamp-custom-formats)
18292 time (org-fix-decoded-time t1)
18293 str (format-time-string
18294 (concat
18295 (if inactive "[" "<") (substring tf 1 -1)
18296 (if inactive "]" ">"))
18297 (apply 'encode-time time))
18298 string (replace-match str t t string)
18299 start (+ start (length str)))))))
18300 string)
18302 (defun org-fix-decoded-time (time)
18303 "Set 0 instead of nil for the first 6 elements of time.
18304 Don't touch the rest."
18305 (let ((n 0))
18306 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
18308 (defun org-days-to-time (timestamp-string)
18309 "Difference between TIMESTAMP-STRING and now in days."
18310 (- (time-to-days (org-time-string-to-time timestamp-string))
18311 (time-to-days (current-time))))
18313 (defun org-deadline-close (timestamp-string &optional ndays)
18314 "Is the time in TIMESTAMP-STRING close to the current date?"
18315 (setq ndays (or ndays (org-get-wdays timestamp-string)))
18316 (and (< (org-days-to-time timestamp-string) ndays)
18317 (not (org-entry-is-done-p))))
18319 (defun org-get-wdays (ts)
18320 "Get the deadline lead time appropriate for timestring TS."
18321 (cond
18322 ((<= org-deadline-warning-days 0)
18323 ;; 0 or negative, enforce this value no matter what
18324 (- org-deadline-warning-days))
18325 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
18326 ;; lead time is specified.
18327 (floor (* (string-to-number (match-string 1 ts))
18328 (cdr (assoc (match-string 2 ts)
18329 '(("d" . 1) ("w" . 7)
18330 ("m" . 30.4) ("y" . 365.25)))))))
18331 ;; go for the default.
18332 (t org-deadline-warning-days)))
18334 (defun org-calendar-select-mouse (ev)
18335 "Return to `org-read-date' with the date currently selected.
18336 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18337 (interactive "e")
18338 (mouse-set-point ev)
18339 (when (calendar-cursor-to-date)
18340 (let* ((date (calendar-cursor-to-date))
18341 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18342 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18343 (if (active-minibuffer-window) (exit-minibuffer))))
18345 (defun org-check-deadlines (ndays)
18346 "Check if there are any deadlines due or past due.
18347 A deadline is considered due if it happens within `org-deadline-warning-days'
18348 days from today's date. If the deadline appears in an entry marked DONE,
18349 it is not shown. The prefix arg NDAYS can be used to test that many
18350 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18351 (interactive "P")
18352 (let* ((org-warn-days
18353 (cond
18354 ((equal ndays '(4)) 100000)
18355 (ndays (prefix-numeric-value ndays))
18356 (t (abs org-deadline-warning-days))))
18357 (case-fold-search nil)
18358 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18359 (callback
18360 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18362 (message "%d deadlines past-due or due within %d days"
18363 (org-occur regexp nil callback)
18364 org-warn-days)))
18366 (defun org-check-before-date (date)
18367 "Check if there are deadlines or scheduled entries before DATE."
18368 (interactive (list (org-read-date)))
18369 (let ((case-fold-search nil)
18370 (regexp (concat "\\<\\(" org-deadline-string
18371 "\\|" org-scheduled-string
18372 "\\) *<\\([^>]+\\)>"))
18373 (callback
18374 (lambda () (time-less-p
18375 (org-time-string-to-time (match-string 2))
18376 (org-time-string-to-time date)))))
18377 (message "%d entries before %s"
18378 (org-occur regexp nil callback) date)))
18380 (defun org-evaluate-time-range (&optional to-buffer)
18381 "Evaluate a time range by computing the difference between start and end.
18382 Normally the result is just printed in the echo area, but with prefix arg
18383 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18384 If the time range is actually in a table, the result is inserted into the
18385 next column.
18386 For time difference computation, a year is assumed to be exactly 365
18387 days in order to avoid rounding problems."
18388 (interactive "P")
18390 (org-clock-update-time-maybe)
18391 (save-excursion
18392 (unless (org-at-date-range-p t)
18393 (goto-char (point-at-bol))
18394 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18395 (if (not (org-at-date-range-p t))
18396 (error "Not at a time-stamp range, and none found in current line")))
18397 (let* ((ts1 (match-string 1))
18398 (ts2 (match-string 2))
18399 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18400 (match-end (match-end 0))
18401 (time1 (org-time-string-to-time ts1))
18402 (time2 (org-time-string-to-time ts2))
18403 (t1 (time-to-seconds time1))
18404 (t2 (time-to-seconds time2))
18405 (diff (abs (- t2 t1)))
18406 (negative (< (- t2 t1) 0))
18407 ;; (ys (floor (* 365 24 60 60)))
18408 (ds (* 24 60 60))
18409 (hs (* 60 60))
18410 (fy "%dy %dd %02d:%02d")
18411 (fy1 "%dy %dd")
18412 (fd "%dd %02d:%02d")
18413 (fd1 "%dd")
18414 (fh "%02d:%02d")
18415 y d h m align)
18416 (if havetime
18417 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18419 d (floor (/ diff ds)) diff (mod diff ds)
18420 h (floor (/ diff hs)) diff (mod diff hs)
18421 m (floor (/ diff 60)))
18422 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18424 d (floor (+ (/ diff ds) 0.5))
18425 h 0 m 0))
18426 (if (not to-buffer)
18427 (message "%s" (org-make-tdiff-string y d h m))
18428 (if (org-at-table-p)
18429 (progn
18430 (goto-char match-end)
18431 (setq align t)
18432 (and (looking-at " *|") (goto-char (match-end 0))))
18433 (goto-char match-end))
18434 (if (looking-at
18435 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18436 (replace-match ""))
18437 (if negative (insert " -"))
18438 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18439 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18440 (insert " " (format fh h m))))
18441 (if align (org-table-align))
18442 (message "Time difference inserted")))))
18444 (defun org-make-tdiff-string (y d h m)
18445 (let ((fmt "")
18446 (l nil))
18447 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18448 l (push y l)))
18449 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18450 l (push d l)))
18451 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18452 l (push h l)))
18453 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18454 l (push m l)))
18455 (apply 'format fmt (nreverse l))))
18457 (defun org-time-string-to-time (s)
18458 (apply 'encode-time (org-parse-time-string s)))
18460 (defun org-time-string-to-absolute (s &optional daynr prefer)
18461 "Convert a time stamp to an absolute day number.
18462 If there is a specifyer for a cyclic time stamp, get the closest date to
18463 DAYNR."
18464 (cond
18465 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18466 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18467 daynr
18468 (+ daynr 1000)))
18469 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18470 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18471 (time-to-days (current-time))) (match-string 0 s)
18472 prefer))
18473 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18475 (defun org-time-from-absolute (d)
18476 "Return the time corresponding to date D.
18477 D may be an absolute day number, or a calendar-type list (month day year)."
18478 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18479 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18481 (defun org-calendar-holiday ()
18482 "List of holidays, for Diary display in Org-mode."
18483 (require 'holidays)
18484 (let ((hl (funcall
18485 (if (fboundp 'calendar-check-holidays)
18486 'calendar-check-holidays 'check-calendar-holidays) date)))
18487 (if hl (mapconcat 'identity hl "; "))))
18489 (defun org-diary-sexp-entry (sexp entry date)
18490 "Process a SEXP diary ENTRY for DATE."
18491 (require 'diary-lib)
18492 (let ((result (if calendar-debug-sexp
18493 (let ((stack-trace-on-error t))
18494 (eval (car (read-from-string sexp))))
18495 (condition-case nil
18496 (eval (car (read-from-string sexp)))
18497 (error
18498 (beep)
18499 (message "Bad sexp at line %d in %s: %s"
18500 (org-current-line)
18501 (buffer-file-name) sexp)
18502 (sleep-for 2))))))
18503 (cond ((stringp result) result)
18504 ((and (consp result)
18505 (stringp (cdr result))) (cdr result))
18506 (result entry)
18507 (t nil))))
18509 (defun org-diary-to-ical-string (frombuf)
18510 "Get iCalendar entries from diary entries in buffer FROMBUF.
18511 This uses the icalendar.el library."
18512 (let* ((tmpdir (if (featurep 'xemacs)
18513 (temp-directory)
18514 temporary-file-directory))
18515 (tmpfile (make-temp-name
18516 (expand-file-name "orgics" tmpdir)))
18517 buf rtn b e)
18518 (save-excursion
18519 (set-buffer frombuf)
18520 (icalendar-export-region (point-min) (point-max) tmpfile)
18521 (setq buf (find-buffer-visiting tmpfile))
18522 (set-buffer buf)
18523 (goto-char (point-min))
18524 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18525 (setq b (match-beginning 0)))
18526 (goto-char (point-max))
18527 (if (re-search-backward "^END:VEVENT" nil t)
18528 (setq e (match-end 0)))
18529 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18530 (kill-buffer buf)
18531 (kill-buffer frombuf)
18532 (delete-file tmpfile)
18533 rtn))
18535 (defun org-closest-date (start current change prefer)
18536 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18537 When PREFER is `past' return a date that is either CURRENT or past.
18538 When PREFER is `future', return a date that is either CURRENT or future."
18539 ;; Make the proper lists from the dates
18540 (catch 'exit
18541 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18542 dn dw sday cday n1 n2
18543 d m y y1 y2 date1 date2 nmonths nm ny m2)
18545 (setq start (org-date-to-gregorian start)
18546 current (org-date-to-gregorian
18547 (if org-agenda-repeating-timestamp-show-all
18548 current
18549 (time-to-days (current-time))))
18550 sday (calendar-absolute-from-gregorian start)
18551 cday (calendar-absolute-from-gregorian current))
18553 (if (<= cday sday) (throw 'exit sday))
18555 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18556 (setq dn (string-to-number (match-string 1 change))
18557 dw (cdr (assoc (match-string 2 change) a1)))
18558 (error "Invalid change specifyer: %s" change))
18559 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18560 (cond
18561 ((eq dw 'day)
18562 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18563 n2 (+ n1 dn)))
18564 ((eq dw 'year)
18565 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18566 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18567 (setq date1 (list m d y1)
18568 n1 (calendar-absolute-from-gregorian date1)
18569 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18570 n2 (calendar-absolute-from-gregorian date2)))
18571 ((eq dw 'month)
18572 ;; approx number of month between the tow dates
18573 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18574 ;; How often does dn fit in there?
18575 (setq d (nth 1 start) m (car start) y (nth 2 start)
18576 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18577 m (+ m nm)
18578 ny (floor (/ m 12))
18579 y (+ y ny)
18580 m (- m (* ny 12)))
18581 (while (> m 12) (setq m (- m 12) y (1+ y)))
18582 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18583 (setq m2 (+ m dn) y2 y)
18584 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18585 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18586 (while (< n2 cday)
18587 (setq n1 n2 m m2 y y2)
18588 (setq m2 (+ m dn) y2 y)
18589 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18590 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18592 (if org-agenda-repeating-timestamp-show-all
18593 (cond
18594 ((eq prefer 'past) n1)
18595 ((eq prefer 'future) (if (= cday n1) n1 n2))
18596 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18597 (cond
18598 ((eq prefer 'past) n1)
18599 ((eq prefer 'future) (if (= cday n1) n1 n2))
18600 (t (if (= cday n1) n1 n2)))))))
18602 (defun org-date-to-gregorian (date)
18603 "Turn any specification of DATE into a gregorian date for the calendar."
18604 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18605 ((and (listp date) (= (length date) 3)) date)
18606 ((stringp date)
18607 (setq date (org-parse-time-string date))
18608 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18609 ((listp date)
18610 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18612 (defun org-parse-time-string (s &optional nodefault)
18613 "Parse the standard Org-mode time string.
18614 This should be a lot faster than the normal `parse-time-string'.
18615 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18616 hour and minute fields will be nil if not given."
18617 (if (string-match org-ts-regexp0 s)
18618 (list 0
18619 (if (or (match-beginning 8) (not nodefault))
18620 (string-to-number (or (match-string 8 s) "0")))
18621 (if (or (match-beginning 7) (not nodefault))
18622 (string-to-number (or (match-string 7 s) "0")))
18623 (string-to-number (match-string 4 s))
18624 (string-to-number (match-string 3 s))
18625 (string-to-number (match-string 2 s))
18626 nil nil nil)
18627 (make-list 9 0)))
18629 (defun org-timestamp-up (&optional arg)
18630 "Increase the date item at the cursor by one.
18631 If the cursor is on the year, change the year. If it is on the month or
18632 the day, change that.
18633 With prefix ARG, change by that many units."
18634 (interactive "p")
18635 (org-timestamp-change (prefix-numeric-value arg)))
18637 (defun org-timestamp-down (&optional arg)
18638 "Decrease the date item at the cursor by one.
18639 If the cursor is on the year, change the year. If it is on the month or
18640 the day, change that.
18641 With prefix ARG, change by that many units."
18642 (interactive "p")
18643 (org-timestamp-change (- (prefix-numeric-value arg))))
18645 (defun org-timestamp-up-day (&optional arg)
18646 "Increase the date in the time stamp by one day.
18647 With prefix ARG, change that many days."
18648 (interactive "p")
18649 (if (and (not (org-at-timestamp-p t))
18650 (org-on-heading-p))
18651 (org-todo 'up)
18652 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18654 (defun org-timestamp-down-day (&optional arg)
18655 "Decrease the date in the time stamp by one day.
18656 With prefix ARG, change that many days."
18657 (interactive "p")
18658 (if (and (not (org-at-timestamp-p t))
18659 (org-on-heading-p))
18660 (org-todo 'down)
18661 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18663 (defsubst org-pos-in-match-range (pos n)
18664 (and (match-beginning n)
18665 (<= (match-beginning n) pos)
18666 (>= (match-end n) pos)))
18668 (defun org-at-timestamp-p (&optional inactive-ok)
18669 "Determine if the cursor is in or at a timestamp."
18670 (interactive)
18671 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18672 (pos (point))
18673 (ans (or (looking-at tsr)
18674 (save-excursion
18675 (skip-chars-backward "^[<\n\r\t")
18676 (if (> (point) (point-min)) (backward-char 1))
18677 (and (looking-at tsr)
18678 (> (- (match-end 0) pos) -1))))))
18679 (and ans
18680 (boundp 'org-ts-what)
18681 (setq org-ts-what
18682 (cond
18683 ((= pos (match-beginning 0)) 'bracket)
18684 ((= pos (1- (match-end 0))) 'bracket)
18685 ((org-pos-in-match-range pos 2) 'year)
18686 ((org-pos-in-match-range pos 3) 'month)
18687 ((org-pos-in-match-range pos 7) 'hour)
18688 ((org-pos-in-match-range pos 8) 'minute)
18689 ((or (org-pos-in-match-range pos 4)
18690 (org-pos-in-match-range pos 5)) 'day)
18691 ((and (> pos (or (match-end 8) (match-end 5)))
18692 (< pos (match-end 0)))
18693 (- pos (or (match-end 8) (match-end 5))))
18694 (t 'day))))
18695 ans))
18697 (defun org-toggle-timestamp-type ()
18698 "Toggle the type (<active> or [inactive]) of a time stamp."
18699 (interactive)
18700 (when (org-at-timestamp-p t)
18701 (save-excursion
18702 (goto-char (match-beginning 0))
18703 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18704 (goto-char (1- (match-end 0)))
18705 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18706 (message "Timestamp is now %sactive"
18707 (if (equal (char-before) ?>) "in" ""))))
18709 (defun org-timestamp-change (n &optional what)
18710 "Change the date in the time stamp at point.
18711 The date will be changed by N times WHAT. WHAT can be `day', `month',
18712 `year', `minute', `second'. If WHAT is not given, the cursor position
18713 in the timestamp determines what will be changed."
18714 (let ((pos (point))
18715 with-hm inactive
18716 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18717 org-ts-what
18718 extra rem
18719 ts time time0)
18720 (if (not (org-at-timestamp-p t))
18721 (error "Not at a timestamp"))
18722 (if (and (not what) (eq org-ts-what 'bracket))
18723 (org-toggle-timestamp-type)
18724 (if (and (not what) (not (eq org-ts-what 'day))
18725 org-display-custom-times
18726 (get-text-property (point) 'display)
18727 (not (get-text-property (1- (point)) 'display)))
18728 (setq org-ts-what 'day))
18729 (setq org-ts-what (or what org-ts-what)
18730 inactive (= (char-after (match-beginning 0)) ?\[)
18731 ts (match-string 0))
18732 (replace-match "")
18733 (if (string-match
18734 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
18736 (setq extra (match-string 1 ts)))
18737 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18738 (setq with-hm t))
18739 (setq time0 (org-parse-time-string ts))
18740 (when (and (eq org-ts-what 'minute)
18741 (eq current-prefix-arg nil))
18742 (setq n (* dm (org-no-warnings (signum n))))
18743 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
18744 (setcar (cdr time0) (+ (nth 1 time0)
18745 (if (> n 0) (- rem) (- dm rem))))))
18746 (setq time
18747 (encode-time (or (car time0) 0)
18748 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18749 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18750 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18751 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18752 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18753 (nthcdr 6 time0)))
18754 (when (integerp org-ts-what)
18755 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18756 (if (eq what 'calendar)
18757 (let ((cal-date (org-get-date-from-calendar)))
18758 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18759 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18760 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18761 (setcar time0 (or (car time0) 0))
18762 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18763 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18764 (setq time (apply 'encode-time time0))))
18765 (setq org-last-changed-timestamp
18766 (org-insert-time-stamp time with-hm inactive nil nil extra))
18767 (org-clock-update-time-maybe)
18768 (goto-char pos)
18769 ;; Try to recenter the calendar window, if any
18770 (if (and org-calendar-follow-timestamp-change
18771 (get-buffer-window "*Calendar*" t)
18772 (memq org-ts-what '(day month year)))
18773 (org-recenter-calendar (time-to-days time))))))
18775 ;; FIXME: does not yet work for lead times
18776 (defun org-modify-ts-extra (s pos n dm)
18777 "Change the different parts of the lead-time and repeat fields in timestamp."
18778 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18779 ng h m new rem)
18780 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18781 (cond
18782 ((or (org-pos-in-match-range pos 2)
18783 (org-pos-in-match-range pos 3))
18784 (setq m (string-to-number (match-string 3 s))
18785 h (string-to-number (match-string 2 s)))
18786 (if (org-pos-in-match-range pos 2)
18787 (setq h (+ h n))
18788 (setq n (* dm (org-no-warnings (signum n))))
18789 (when (not (= 0 (setq rem (% m dm))))
18790 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18791 (setq m (+ m n)))
18792 (if (< m 0) (setq m (+ m 60) h (1- h)))
18793 (if (> m 59) (setq m (- m 60) h (1+ h)))
18794 (setq h (min 24 (max 0 h)))
18795 (setq ng 1 new (format "-%02d:%02d" h m)))
18796 ((org-pos-in-match-range pos 6)
18797 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18798 ((org-pos-in-match-range pos 5)
18799 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18801 ((org-pos-in-match-range pos 9)
18802 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18803 ((org-pos-in-match-range pos 8)
18804 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18806 (when ng
18807 (setq s (concat
18808 (substring s 0 (match-beginning ng))
18810 (substring s (match-end ng))))))
18813 (defun org-recenter-calendar (date)
18814 "If the calendar is visible, recenter it to DATE."
18815 (let* ((win (selected-window))
18816 (cwin (get-buffer-window "*Calendar*" t))
18817 (calendar-move-hook nil))
18818 (when cwin
18819 (select-window cwin)
18820 (calendar-goto-date (if (listp date) date
18821 (calendar-gregorian-from-absolute date)))
18822 (select-window win))))
18824 (defun org-goto-calendar (&optional arg)
18825 "Go to the Emacs calendar at the current date.
18826 If there is a time stamp in the current line, go to that date.
18827 A prefix ARG can be used to force the current date."
18828 (interactive "P")
18829 (let ((tsr org-ts-regexp) diff
18830 (calendar-move-hook nil)
18831 (view-calendar-holidays-initially nil)
18832 (view-diary-entries-initially nil))
18833 (if (or (org-at-timestamp-p)
18834 (save-excursion
18835 (beginning-of-line 1)
18836 (looking-at (concat ".*" tsr))))
18837 (let ((d1 (time-to-days (current-time)))
18838 (d2 (time-to-days
18839 (org-time-string-to-time (match-string 1)))))
18840 (setq diff (- d2 d1))))
18841 (calendar)
18842 (calendar-goto-today)
18843 (if (and diff (not arg)) (calendar-forward-day diff))))
18845 (defun org-get-date-from-calendar ()
18846 "Return a list (month day year) of date at point in calendar."
18847 (with-current-buffer "*Calendar*"
18848 (save-match-data
18849 (calendar-cursor-to-date))))
18851 (defun org-date-from-calendar ()
18852 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18853 If there is already a time stamp at the cursor position, update it."
18854 (interactive)
18855 (if (org-at-timestamp-p t)
18856 (org-timestamp-change 0 'calendar)
18857 (let ((cal-date (org-get-date-from-calendar)))
18858 (org-insert-time-stamp
18859 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18861 (defvar appt-time-msg-list)
18863 ;;;###autoload
18864 (defun org-agenda-to-appt (&optional refresh filter)
18865 "Activate appointments found in `org-agenda-files'.
18866 With a \\[universal-argument] prefix, refresh the list of
18867 appointements.
18869 If FILTER is t, interactively prompt the user for a regular
18870 expression, and filter out entries that don't match it.
18872 If FILTER is a string, use this string as a regular expression
18873 for filtering entries out.
18875 FILTER can also be an alist with the car of each cell being
18876 either 'headline or 'category. For example:
18878 '((headline \"IMPORTANT\")
18879 (category \"Work\"))
18881 will only add headlines containing IMPORTANT or headlines
18882 belonging to the \"Work\" category."
18883 (interactive "P")
18884 (require 'calendar)
18885 (if refresh (setq appt-time-msg-list nil))
18886 (if (eq filter t)
18887 (setq filter (read-from-minibuffer "Regexp filter: ")))
18888 (let* ((cnt 0) ; count added events
18889 (org-agenda-new-buffers nil)
18890 (org-deadline-warning-days 0)
18891 (today (org-date-to-gregorian
18892 (time-to-days (current-time))))
18893 (files (org-agenda-files)) entries file)
18894 ;; Get all entries which may contain an appt
18895 (while (setq file (pop files))
18896 (setq entries
18897 (append entries
18898 (org-agenda-get-day-entries
18899 file today :timestamp :scheduled :deadline))))
18900 (setq entries (delq nil entries))
18901 ;; Map thru entries and find if we should filter them out
18902 (mapc
18903 (lambda(x)
18904 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18905 (cat (get-text-property 1 'org-category x))
18906 (tod (get-text-property 1 'time-of-day x))
18907 (ok (or (null filter)
18908 (and (stringp filter) (string-match filter evt))
18909 (and (listp filter)
18910 (or (string-match
18911 (cadr (assoc 'category filter)) cat)
18912 (string-match
18913 (cadr (assoc 'headline filter)) evt))))))
18914 ;; FIXME: Shall we remove text-properties for the appt text?
18915 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18916 (when (and ok tod)
18917 (setq tod (number-to-string tod)
18918 tod (when (string-match
18919 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18920 (concat (match-string 1 tod) ":"
18921 (match-string 2 tod))))
18922 (appt-add tod evt)
18923 (setq cnt (1+ cnt))))) entries)
18924 (org-release-buffers org-agenda-new-buffers)
18925 (if (eq cnt 0)
18926 (message "No event to add")
18927 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18929 ;;; The clock for measuring work time.
18931 (defvar org-mode-line-string "")
18932 (put 'org-mode-line-string 'risky-local-variable t)
18934 (defvar org-mode-line-timer nil)
18935 (defvar org-clock-heading "")
18936 (defvar org-clock-start-time "")
18938 (defun org-update-mode-line ()
18939 (let* ((delta (- (time-to-seconds (current-time))
18940 (time-to-seconds org-clock-start-time)))
18941 (h (floor delta 3600))
18942 (m (floor (- delta (* 3600 h)) 60)))
18943 (setq org-mode-line-string
18944 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18945 'help-echo "Org-mode clock is running"))
18946 (force-mode-line-update)))
18948 (defvar org-clock-marker (make-marker)
18949 "Marker recording the last clock-in.")
18950 (defvar org-clock-mode-line-entry nil
18951 "Information for the modeline about the running clock.")
18953 (defun org-clock-in ()
18954 "Start the clock on the current item.
18955 If necessary, clock-out of the currently active clock."
18956 (interactive)
18957 (org-clock-out t)
18958 (let (ts)
18959 (save-excursion
18960 (org-back-to-heading t)
18961 (when (and org-clock-in-switch-to-state
18962 (not (looking-at (concat outline-regexp "[ \t]*"
18963 org-clock-in-switch-to-state
18964 "\\>"))))
18965 (org-todo org-clock-in-switch-to-state))
18966 (if (and org-clock-heading-function
18967 (functionp org-clock-heading-function))
18968 (setq org-clock-heading (funcall org-clock-heading-function))
18969 (if (looking-at org-complex-heading-regexp)
18970 (setq org-clock-heading (match-string 4))
18971 (setq org-clock-heading "???")))
18972 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18973 (org-clock-find-position)
18975 (insert "\n") (backward-char 1)
18976 (indent-relative)
18977 (insert org-clock-string " ")
18978 (setq org-clock-start-time (current-time))
18979 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18980 (move-marker org-clock-marker (point) (buffer-base-buffer))
18981 (or global-mode-string (setq global-mode-string '("")))
18982 (or (memq 'org-mode-line-string global-mode-string)
18983 (setq global-mode-string
18984 (append global-mode-string '(org-mode-line-string))))
18985 (org-update-mode-line)
18986 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18987 (message "Clock started at %s" ts))))
18989 (defun org-clock-find-position ()
18990 "Find the location where the next clock line should be inserted."
18991 (org-back-to-heading t)
18992 (catch 'exit
18993 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18994 (re (concat "^[ \t]*" org-clock-string))
18995 (cnt 0)
18996 first last)
18997 (goto-char beg)
18998 (when (eobp) (newline) (setq end (max (point) end)))
18999 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
19000 ;; we seem to have a CLOCK drawer, so go there.
19001 (beginning-of-line 2)
19002 (throw 'exit t))
19003 ;; Lets count the CLOCK lines
19004 (goto-char beg)
19005 (while (re-search-forward re end t)
19006 (setq first (or first (match-beginning 0))
19007 last (match-beginning 0)
19008 cnt (1+ cnt)))
19009 (when (and (integerp org-clock-into-drawer)
19010 (>= (1+ cnt) org-clock-into-drawer))
19011 ;; Wrap current entries into a new drawer
19012 (goto-char last)
19013 (beginning-of-line 2)
19014 (if (org-at-item-p) (org-end-of-item))
19015 (insert ":END:\n")
19016 (beginning-of-line 0)
19017 (org-indent-line-function)
19018 (goto-char first)
19019 (insert ":CLOCK:\n")
19020 (beginning-of-line 0)
19021 (org-indent-line-function)
19022 (org-flag-drawer t)
19023 (beginning-of-line 2)
19024 (throw 'exit nil))
19026 (goto-char beg)
19027 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
19028 (not (equal (match-string 1) org-clock-string)))
19029 ;; Planning info, skip to after it
19030 (beginning-of-line 2)
19031 (or (bolp) (newline)))
19032 (when (eq t org-clock-into-drawer)
19033 (insert ":CLOCK:\n:END:\n")
19034 (beginning-of-line -1)
19035 (org-indent-line-function)
19036 (org-flag-drawer t)
19037 (beginning-of-line 2)
19038 (org-indent-line-function)))))
19040 (defun org-clock-out (&optional fail-quietly)
19041 "Stop the currently running clock.
19042 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
19043 (interactive)
19044 (catch 'exit
19045 (if (not (marker-buffer org-clock-marker))
19046 (if fail-quietly (throw 'exit t) (error "No active clock")))
19047 (let (ts te s h m)
19048 (save-excursion
19049 (set-buffer (marker-buffer org-clock-marker))
19050 (goto-char org-clock-marker)
19051 (beginning-of-line 1)
19052 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
19053 (equal (match-string 1) org-clock-string))
19054 (setq ts (match-string 2))
19055 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
19056 (goto-char (match-end 0))
19057 (delete-region (point) (point-at-eol))
19058 (insert "--")
19059 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
19060 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
19061 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
19062 h (floor (/ s 3600))
19063 s (- s (* 3600 h))
19064 m (floor (/ s 60))
19065 s (- s (* 60 s)))
19066 (insert " => " (format "%2d:%02d" h m))
19067 (move-marker org-clock-marker nil)
19068 (when org-log-note-clock-out
19069 (org-add-log-maybe 'clock-out))
19070 (when org-mode-line-timer
19071 (cancel-timer org-mode-line-timer)
19072 (setq org-mode-line-timer nil))
19073 (setq global-mode-string
19074 (delq 'org-mode-line-string global-mode-string))
19075 (force-mode-line-update)
19076 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
19078 (defun org-clock-cancel ()
19079 "Cancel the running clock be removing the start timestamp."
19080 (interactive)
19081 (if (not (marker-buffer org-clock-marker))
19082 (error "No active clock"))
19083 (save-excursion
19084 (set-buffer (marker-buffer org-clock-marker))
19085 (goto-char org-clock-marker)
19086 (delete-region (1- (point-at-bol)) (point-at-eol)))
19087 (setq global-mode-string
19088 (delq 'org-mode-line-string global-mode-string))
19089 (force-mode-line-update)
19090 (message "Clock canceled"))
19092 (defun org-clock-goto (&optional delete-windows)
19093 "Go to the currently clocked-in entry."
19094 (interactive "P")
19095 (if (not (marker-buffer org-clock-marker))
19096 (error "No active clock"))
19097 (switch-to-buffer-other-window
19098 (marker-buffer org-clock-marker))
19099 (if delete-windows (delete-other-windows))
19100 (goto-char org-clock-marker)
19101 (org-show-entry)
19102 (org-back-to-heading)
19103 (recenter))
19105 (defvar org-clock-file-total-minutes nil
19106 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
19107 (make-variable-buffer-local 'org-clock-file-total-minutes)
19109 (defun org-clock-sum (&optional tstart tend)
19110 "Sum the times for each subtree.
19111 Puts the resulting times in minutes as a text property on each headline."
19112 (interactive)
19113 (let* ((bmp (buffer-modified-p))
19114 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
19115 org-clock-string
19116 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
19117 (lmax 30)
19118 (ltimes (make-vector lmax 0))
19119 (t1 0)
19120 (level 0)
19121 ts te dt
19122 time)
19123 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
19124 (save-excursion
19125 (goto-char (point-max))
19126 (while (re-search-backward re nil t)
19127 (cond
19128 ((match-end 2)
19129 ;; Two time stamps
19130 (setq ts (match-string 2)
19131 te (match-string 3)
19132 ts (time-to-seconds
19133 (apply 'encode-time (org-parse-time-string ts)))
19134 te (time-to-seconds
19135 (apply 'encode-time (org-parse-time-string te)))
19136 ts (if tstart (max ts tstart) ts)
19137 te (if tend (min te tend) te)
19138 dt (- te ts)
19139 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
19140 ((match-end 4)
19141 ;; A naket time
19142 (setq t1 (+ t1 (string-to-number (match-string 5))
19143 (* 60 (string-to-number (match-string 4))))))
19144 (t ;; A headline
19145 (setq level (- (match-end 1) (match-beginning 1)))
19146 (when (or (> t1 0) (> (aref ltimes level) 0))
19147 (loop for l from 0 to level do
19148 (aset ltimes l (+ (aref ltimes l) t1)))
19149 (setq t1 0 time (aref ltimes level))
19150 (loop for l from level to (1- lmax) do
19151 (aset ltimes l 0))
19152 (goto-char (match-beginning 0))
19153 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
19154 (setq org-clock-file-total-minutes (aref ltimes 0)))
19155 (set-buffer-modified-p bmp)))
19157 (defun org-clock-display (&optional total-only)
19158 "Show subtree times in the entire buffer.
19159 If TOTAL-ONLY is non-nil, only show the total time for the entire file
19160 in the echo area."
19161 (interactive)
19162 (org-remove-clock-overlays)
19163 (let (time h m p)
19164 (org-clock-sum)
19165 (unless total-only
19166 (save-excursion
19167 (goto-char (point-min))
19168 (while (or (and (equal (setq p (point)) (point-min))
19169 (get-text-property p :org-clock-minutes))
19170 (setq p (next-single-property-change
19171 (point) :org-clock-minutes)))
19172 (goto-char p)
19173 (when (setq time (get-text-property p :org-clock-minutes))
19174 (org-put-clock-overlay time (funcall outline-level))))
19175 (setq h (/ org-clock-file-total-minutes 60)
19176 m (- org-clock-file-total-minutes (* 60 h)))
19177 ;; Arrange to remove the overlays upon next change.
19178 (when org-remove-highlights-with-change
19179 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
19180 nil 'local))))
19181 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
19183 (defvar org-clock-overlays nil)
19184 (make-variable-buffer-local 'org-clock-overlays)
19186 (defun org-put-clock-overlay (time &optional level)
19187 "Put an overlays on the current line, displaying TIME.
19188 If LEVEL is given, prefix time with a corresponding number of stars.
19189 This creates a new overlay and stores it in `org-clock-overlays', so that it
19190 will be easy to remove."
19191 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
19192 (l (if level (org-get-valid-level level 0) 0))
19193 (off 0)
19194 ov tx)
19195 (move-to-column c)
19196 (unless (eolp) (skip-chars-backward "^ \t"))
19197 (skip-chars-backward " \t")
19198 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
19199 tx (concat (buffer-substring (1- (point)) (point))
19200 (make-string (+ off (max 0 (- c (current-column)))) ?.)
19201 (org-add-props (format "%s %2d:%02d%s"
19202 (make-string l ?*) h m
19203 (make-string (- 16 l) ?\ ))
19204 '(face secondary-selection))
19205 ""))
19206 (if (not (featurep 'xemacs))
19207 (org-overlay-put ov 'display tx)
19208 (org-overlay-put ov 'invisible t)
19209 (org-overlay-put ov 'end-glyph (make-glyph tx)))
19210 (push ov org-clock-overlays)))
19212 (defun org-remove-clock-overlays (&optional beg end noremove)
19213 "Remove the occur highlights from the buffer.
19214 BEG and END are ignored. If NOREMOVE is nil, remove this function
19215 from the `before-change-functions' in the current buffer."
19216 (interactive)
19217 (unless org-inhibit-highlight-removal
19218 (mapc 'org-delete-overlay org-clock-overlays)
19219 (setq org-clock-overlays nil)
19220 (unless noremove
19221 (remove-hook 'before-change-functions
19222 'org-remove-clock-overlays 'local))))
19224 (defun org-clock-out-if-current ()
19225 "Clock out if the current entry contains the running clock.
19226 This is used to stop the clock after a TODO entry is marked DONE,
19227 and is only done if the variable `org-clock-out-when-done' is not nil."
19228 (when (and org-clock-out-when-done
19229 (member state org-done-keywords)
19230 (equal (marker-buffer org-clock-marker) (current-buffer))
19231 (< (point) org-clock-marker)
19232 (> (save-excursion (outline-next-heading) (point))
19233 org-clock-marker))
19234 ;; Clock out, but don't accept a logging message for this.
19235 (let ((org-log-note-clock-out nil))
19236 (org-clock-out))))
19238 (add-hook 'org-after-todo-state-change-hook
19239 'org-clock-out-if-current)
19241 (defun org-check-running-clock ()
19242 "Check if the current buffer contains the running clock.
19243 If yes, offer to stop it and to save the buffer with the changes."
19244 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
19245 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
19246 (buffer-name))))
19247 (org-clock-out)
19248 (when (y-or-n-p "Save changed buffer?")
19249 (save-buffer))))
19251 (defun org-clock-report (&optional arg)
19252 "Create a table containing a report about clocked time.
19253 If the cursor is inside an existing clocktable block, then the table
19254 will be updated. If not, a new clocktable will be inserted.
19255 When called with a prefix argument, move to the first clock table in the
19256 buffer and update it."
19257 (interactive "P")
19258 (org-remove-clock-overlays)
19259 (when arg
19260 (org-find-dblock "clocktable")
19261 (org-show-entry))
19262 (if (org-in-clocktable-p)
19263 (goto-char (org-in-clocktable-p))
19264 (org-create-dblock (list :name "clocktable"
19265 :maxlevel 2 :scope 'file)))
19266 (org-update-dblock))
19268 (defun org-in-clocktable-p ()
19269 "Check if the cursor is in a clocktable."
19270 (let ((pos (point)) start)
19271 (save-excursion
19272 (end-of-line 1)
19273 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
19274 (setq start (match-beginning 0))
19275 (re-search-forward "^#\\+END:.*" nil t)
19276 (>= (match-end 0) pos)
19277 start))))
19279 (defun org-clock-update-time-maybe ()
19280 "If this is a CLOCK line, update it and return t.
19281 Otherwise, return nil."
19282 (interactive)
19283 (save-excursion
19284 (beginning-of-line 1)
19285 (skip-chars-forward " \t")
19286 (when (looking-at org-clock-string)
19287 (let ((re (concat "[ \t]*" org-clock-string
19288 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
19289 "\\([ \t]*=>.*\\)?"))
19290 ts te h m s)
19291 (if (not (looking-at re))
19293 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
19294 (end-of-line 1)
19295 (setq ts (match-string 1)
19296 te (match-string 2))
19297 (setq s (- (time-to-seconds
19298 (apply 'encode-time (org-parse-time-string te)))
19299 (time-to-seconds
19300 (apply 'encode-time (org-parse-time-string ts))))
19301 h (floor (/ s 3600))
19302 s (- s (* 3600 h))
19303 m (floor (/ s 60))
19304 s (- s (* 60 s)))
19305 (insert " => " (format "%2d:%02d" h m))
19306 t)))))
19308 (defun org-clock-special-range (key &optional time as-strings)
19309 "Return two times bordering a special time range.
19310 Key is a symbol specifying the range and can be one of `today', `yesterday',
19311 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
19312 A week starts Monday 0:00 and ends Sunday 24:00.
19313 The range is determined relative to TIME. TIME defaults to the current time.
19314 The return value is a cons cell with two internal times like the ones
19315 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
19316 the returned times will be formatted strings."
19317 (let* ((tm (decode-time (or time (current-time))))
19318 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
19319 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
19320 (dow (nth 6 tm))
19321 s1 m1 h1 d1 month1 y1 diff ts te fm)
19322 (cond
19323 ((eq key 'today)
19324 (setq h 0 m 0 h1 24 m1 0))
19325 ((eq key 'yesterday)
19326 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19327 ((eq key 'thisweek)
19328 (setq diff (if (= dow 0) 6 (1- dow))
19329 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19330 ((eq key 'lastweek)
19331 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19332 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19333 ((eq key 'thismonth)
19334 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19335 ((eq key 'lastmonth)
19336 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19337 ((eq key 'thisyear)
19338 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19339 ((eq key 'lastyear)
19340 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19341 (t (error "No such time block %s" key)))
19342 (setq ts (encode-time s m h d month y)
19343 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19344 (or d1 d) (or month1 month) (or y1 y)))
19345 (setq fm (cdr org-time-stamp-formats))
19346 (if as-strings
19347 (cons (format-time-string fm ts) (format-time-string fm te))
19348 (cons ts te))))
19350 (defun org-dblock-write:clocktable (params)
19351 "Write the standard clocktable."
19352 (catch 'exit
19353 (let* ((hlchars '((1 . "*") (2 . "/")))
19354 (ins (make-marker))
19355 (total-time nil)
19356 (scope (plist-get params :scope))
19357 (tostring (plist-get params :tostring))
19358 (multifile (plist-get params :multifile))
19359 (header (plist-get params :header))
19360 (maxlevel (or (plist-get params :maxlevel) 3))
19361 (step (plist-get params :step))
19362 (emph (plist-get params :emphasize))
19363 (ts (plist-get params :tstart))
19364 (te (plist-get params :tend))
19365 (block (plist-get params :block))
19366 (link (plist-get params :link))
19367 ipos time h m p level hlc hdl
19368 cc beg end pos tbl)
19369 (when step
19370 (org-clocktable-steps params)
19371 (throw 'exit nil))
19372 (when block
19373 (setq cc (org-clock-special-range block nil t)
19374 ts (car cc) te (cdr cc)))
19375 (if ts (setq ts (time-to-seconds
19376 (apply 'encode-time (org-parse-time-string ts)))))
19377 (if te (setq te (time-to-seconds
19378 (apply 'encode-time (org-parse-time-string te)))))
19379 (move-marker ins (point))
19380 (setq ipos (point))
19382 ;; Get the right scope
19383 (setq pos (point))
19384 (save-restriction
19385 (cond
19386 ((not scope))
19387 ((eq scope 'file) (widen))
19388 ((eq scope 'subtree) (org-narrow-to-subtree))
19389 ((eq scope 'tree)
19390 (while (org-up-heading-safe))
19391 (org-narrow-to-subtree))
19392 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19393 (symbol-name scope)))
19394 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19395 (catch 'exit
19396 (while (org-up-heading-safe)
19397 (looking-at outline-regexp)
19398 (if (<= (org-reduced-level (funcall outline-level)) level)
19399 (throw 'exit nil))))
19400 (org-narrow-to-subtree))
19401 ((or (listp scope) (eq scope 'agenda))
19402 (let* ((files (if (listp scope) scope (org-agenda-files)))
19403 (scope 'agenda)
19404 (p1 (copy-sequence params))
19405 file)
19406 (plist-put p1 :tostring t)
19407 (plist-put p1 :multifile t)
19408 (plist-put p1 :scope 'file)
19409 (org-prepare-agenda-buffers files)
19410 (while (setq file (pop files))
19411 (with-current-buffer (find-buffer-visiting file)
19412 (push (org-clocktable-add-file
19413 file (org-dblock-write:clocktable p1)) tbl)
19414 (setq total-time (+ (or total-time 0)
19415 org-clock-file-total-minutes)))))))
19416 (goto-char pos)
19418 (unless (eq scope 'agenda)
19419 (org-clock-sum ts te)
19420 (goto-char (point-min))
19421 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19422 (goto-char p)
19423 (when (setq time (get-text-property p :org-clock-minutes))
19424 (save-excursion
19425 (beginning-of-line 1)
19426 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19427 (setq level (org-reduced-level
19428 (- (match-end 1) (match-beginning 1))))
19429 (<= level maxlevel))
19430 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19431 hdl (if (not link)
19432 (match-string 2)
19433 (org-make-link-string
19434 (format "file:%s::%s"
19435 (buffer-file-name)
19436 (save-match-data
19437 (org-make-org-heading-search-string
19438 (match-string 2))))
19439 (match-string 2)))
19440 h (/ time 60)
19441 m (- time (* 60 h)))
19442 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19443 (push (concat
19444 "| " (int-to-string level) "|" hlc hdl hlc " |"
19445 (make-string (1- level) ?|)
19446 hlc (format "%d:%02d" h m) hlc
19447 " |") tbl))))))
19448 (setq tbl (nreverse tbl))
19449 (if tostring
19450 (if tbl (mapconcat 'identity tbl "\n") nil)
19451 (goto-char ins)
19452 (insert-before-markers
19453 (or header
19454 (concat
19455 "Clock summary at ["
19456 (substring
19457 (format-time-string (cdr org-time-stamp-formats))
19458 1 -1)
19459 "]."
19460 (if block
19461 (format " Considered range is /%s/." block)
19463 "\n\n"))
19464 (if (eq scope 'agenda) "|File" "")
19465 "|L|Headline|Time|\n")
19466 (setq total-time (or total-time org-clock-file-total-minutes)
19467 h (/ total-time 60)
19468 m (- total-time (* 60 h)))
19469 (insert-before-markers
19470 "|-\n|"
19471 (if (eq scope 'agenda) "|" "")
19473 "*Total time*| "
19474 (format "*%d:%02d*" h m)
19475 "|\n|-\n")
19476 (setq tbl (delq nil tbl))
19477 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19478 (equal (substring (car tbl) 0 2) "|-"))
19479 (pop tbl))
19480 (insert-before-markers (mapconcat
19481 'identity (delq nil tbl)
19482 (if (eq scope 'agenda) "\n|-\n" "\n")))
19483 (backward-delete-char 1)
19484 (goto-char ipos)
19485 (skip-chars-forward "^|")
19486 (org-table-align))))))
19488 (defun org-clocktable-steps (params)
19489 (let* ((p1 (copy-sequence params))
19490 (ts (plist-get p1 :tstart))
19491 (te (plist-get p1 :tend))
19492 (step0 (plist-get p1 :step))
19493 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19494 (block (plist-get p1 :block))
19496 (when block
19497 (setq cc (org-clock-special-range block nil t)
19498 ts (car cc) te (cdr cc)))
19499 (if ts (setq ts (time-to-seconds
19500 (apply 'encode-time (org-parse-time-string ts)))))
19501 (if te (setq te (time-to-seconds
19502 (apply 'encode-time (org-parse-time-string te)))))
19503 (plist-put p1 :header "")
19504 (plist-put p1 :step nil)
19505 (plist-put p1 :block nil)
19506 (while (< ts te)
19507 (or (bolp) (insert "\n"))
19508 (plist-put p1 :tstart (format-time-string
19509 (car org-time-stamp-formats)
19510 (seconds-to-time ts)))
19511 (plist-put p1 :tend (format-time-string
19512 (car org-time-stamp-formats)
19513 (seconds-to-time (setq ts (+ ts step)))))
19514 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19515 (plist-get p1 :tstart) "\n")
19516 (org-dblock-write:clocktable p1)
19517 (re-search-forward "#\\+END:")
19518 (end-of-line 0))))
19521 (defun org-clocktable-add-file (file table)
19522 (if table
19523 (let ((lines (org-split-string table "\n"))
19524 (ff (file-name-nondirectory file)))
19525 (mapconcat 'identity
19526 (mapcar (lambda (x)
19527 (if (string-match org-table-dataline-regexp x)
19528 (concat "|" ff x)
19530 lines)
19531 "\n"))))
19533 ;; FIXME: I don't think anybody uses this, ask David
19534 (defun org-collect-clock-time-entries ()
19535 "Return an internal list with clocking information.
19536 This list has one entry for each CLOCK interval.
19537 FIXME: describe the elements."
19538 (interactive)
19539 (let ((re (concat "^[ \t]*" org-clock-string
19540 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19541 rtn beg end next cont level title total closedp leafp
19542 clockpos titlepos h m donep)
19543 (save-excursion
19544 (org-clock-sum)
19545 (goto-char (point-min))
19546 (while (re-search-forward re nil t)
19547 (setq clockpos (match-beginning 0)
19548 beg (match-string 1) end (match-string 2)
19549 cont (match-end 0))
19550 (setq beg (apply 'encode-time (org-parse-time-string beg))
19551 end (apply 'encode-time (org-parse-time-string end)))
19552 (org-back-to-heading t)
19553 (setq donep (org-entry-is-done-p))
19554 (setq titlepos (point)
19555 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19556 h (/ total 60) m (- total (* 60 h))
19557 total (cons h m))
19558 (looking-at "\\(\\*+\\) +\\(.*\\)")
19559 (setq level (- (match-end 1) (match-beginning 1))
19560 title (org-match-string-no-properties 2))
19561 (save-excursion (outline-next-heading) (setq next (point)))
19562 (setq closedp (re-search-forward org-closed-time-regexp next t))
19563 (goto-char next)
19564 (setq leafp (and (looking-at "^\\*+ ")
19565 (<= (- (match-end 0) (point)) level)))
19566 (push (list beg end clockpos closedp donep
19567 total title titlepos level leafp)
19568 rtn)
19569 (goto-char cont)))
19570 (nreverse rtn)))
19572 ;;;; Agenda, and Diary Integration
19574 ;;; Define the Org-agenda-mode
19576 (defvar org-agenda-mode-map (make-sparse-keymap)
19577 "Keymap for `org-agenda-mode'.")
19579 (defvar org-agenda-menu) ; defined later in this file.
19580 (defvar org-agenda-follow-mode nil)
19581 (defvar org-agenda-show-log nil)
19582 (defvar org-agenda-redo-command nil)
19583 (defvar org-agenda-query-string nil)
19584 (defvar org-agenda-mode-hook nil)
19585 (defvar org-agenda-type nil)
19586 (defvar org-agenda-force-single-file nil)
19588 (defun org-agenda-mode ()
19589 "Mode for time-sorted view on action items in Org-mode files.
19591 The following commands are available:
19593 \\{org-agenda-mode-map}"
19594 (interactive)
19595 (kill-all-local-variables)
19596 (setq org-agenda-undo-list nil
19597 org-agenda-pending-undo-list nil)
19598 (setq major-mode 'org-agenda-mode)
19599 ;; Keep global-font-lock-mode from turning on font-lock-mode
19600 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19601 (setq mode-name "Org-Agenda")
19602 (use-local-map org-agenda-mode-map)
19603 (easy-menu-add org-agenda-menu)
19604 (if org-startup-truncated (setq truncate-lines t))
19605 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19606 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19607 ;; Make sure properties are removed when copying text
19608 (when (boundp 'buffer-substring-filters)
19609 (org-set-local 'buffer-substring-filters
19610 (cons (lambda (x)
19611 (set-text-properties 0 (length x) nil x) x)
19612 buffer-substring-filters)))
19613 (unless org-agenda-keep-modes
19614 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19615 org-agenda-show-log nil))
19616 (easy-menu-change
19617 '("Agenda") "Agenda Files"
19618 (append
19619 (list
19620 (vector
19621 (if (get 'org-agenda-files 'org-restrict)
19622 "Restricted to single file"
19623 "Edit File List")
19624 '(org-edit-agenda-file-list)
19625 (not (get 'org-agenda-files 'org-restrict)))
19626 "--")
19627 (mapcar 'org-file-menu-entry (org-agenda-files))))
19628 (org-agenda-set-mode-name)
19629 (apply
19630 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19631 (list 'org-agenda-mode-hook)))
19633 (substitute-key-definition 'undo 'org-agenda-undo
19634 org-agenda-mode-map global-map)
19635 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19636 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19637 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19638 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19639 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19640 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19641 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19642 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19643 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19644 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19645 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19646 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19647 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19648 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19649 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19650 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19651 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19652 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19653 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19654 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19655 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19656 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19657 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19658 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19659 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19660 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19661 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19662 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19663 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19665 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19666 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19667 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19668 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19669 (while l (org-defkey org-agenda-mode-map
19670 (int-to-string (pop l)) 'digit-argument)))
19672 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19673 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19674 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19675 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19676 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19677 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19678 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19679 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19680 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19681 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19682 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19683 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19684 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19685 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19686 (org-defkey org-agenda-mode-map "n" 'next-line)
19687 (org-defkey org-agenda-mode-map "p" 'previous-line)
19688 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19689 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19690 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19691 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19692 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19693 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19694 (eval-after-load "calendar"
19695 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19696 'org-calendar-goto-agenda))
19697 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19698 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19699 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19700 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19701 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19702 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19703 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19704 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19705 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19706 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19707 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19708 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19709 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19710 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19711 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19712 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19713 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19714 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19715 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19716 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19717 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19718 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19720 (org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add)
19721 (org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract)
19722 (org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re)
19723 (org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re)
19725 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19726 "Local keymap for agenda entries from Org-mode.")
19728 (org-defkey org-agenda-keymap
19729 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19730 (org-defkey org-agenda-keymap
19731 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19732 (when org-agenda-mouse-1-follows-link
19733 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19734 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19735 '("Agenda"
19736 ("Agenda Files")
19737 "--"
19738 ["Show" org-agenda-show t]
19739 ["Go To (other window)" org-agenda-goto t]
19740 ["Go To (this window)" org-agenda-switch-to t]
19741 ["Follow Mode" org-agenda-follow-mode
19742 :style toggle :selected org-agenda-follow-mode :active t]
19743 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19744 "--"
19745 ["Cycle TODO" org-agenda-todo t]
19746 ["Archive subtree" org-agenda-archive t]
19747 ["Delete subtree" org-agenda-kill t]
19748 "--"
19749 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19750 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19751 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19752 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19753 "--"
19754 ("Tags and Properties"
19755 ["Show all Tags" org-agenda-show-tags t]
19756 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19757 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19758 "--"
19759 ["Column View" org-columns t])
19760 ("Date/Schedule"
19761 ["Schedule" org-agenda-schedule t]
19762 ["Set Deadline" org-agenda-deadline t]
19763 "--"
19764 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19765 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19766 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19767 ("Clock"
19768 ["Clock in" org-agenda-clock-in t]
19769 ["Clock out" org-agenda-clock-out t]
19770 ["Clock cancel" org-agenda-clock-cancel t]
19771 ["Goto running clock" org-clock-goto t])
19772 ("Priority"
19773 ["Set Priority" org-agenda-priority t]
19774 ["Increase Priority" org-agenda-priority-up t]
19775 ["Decrease Priority" org-agenda-priority-down t]
19776 ["Show Priority" org-agenda-show-priority t])
19777 ("Calendar/Diary"
19778 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19779 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19780 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19781 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19782 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19783 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19784 "--"
19785 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19786 "--"
19787 ("View"
19788 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19789 :style radio :selected (equal org-agenda-ndays 1)]
19790 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19791 :style radio :selected (equal org-agenda-ndays 7)]
19792 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19793 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19794 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19795 :style radio :selected (member org-agenda-ndays '(365 366))]
19796 "--"
19797 ["Show Logbook entries" org-agenda-log-mode
19798 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19799 ["Include Diary" org-agenda-toggle-diary
19800 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19801 ["Use Time Grid" org-agenda-toggle-time-grid
19802 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19803 ["Write view to file" org-write-agenda t]
19804 ["Rebuild buffer" org-agenda-redo t]
19805 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19806 "--"
19807 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19808 "--"
19809 ["Quit" org-agenda-quit t]
19810 ["Exit and Release Buffers" org-agenda-exit t]
19813 ;;; Agenda undo
19815 (defvar org-agenda-allow-remote-undo t
19816 "Non-nil means, allow remote undo from the agenda buffer.")
19817 (defvar org-agenda-undo-list nil
19818 "List of undoable operations in the agenda since last refresh.")
19819 (defvar org-agenda-undo-has-started-in nil
19820 "Buffers that have already seen `undo-start' in the current undo sequence.")
19821 (defvar org-agenda-pending-undo-list nil
19822 "In a series of undo commands, this is the list of remaning undo items.")
19824 (defmacro org-if-unprotected (&rest body)
19825 "Execute BODY if there is no `org-protected' text property at point."
19826 (declare (debug t))
19827 `(unless (get-text-property (point) 'org-protected)
19828 ,@body))
19830 (defmacro org-with-remote-undo (_buffer &rest _body)
19831 "Execute BODY while recording undo information in two buffers."
19832 (declare (indent 1) (debug t))
19833 `(let ((_cline (org-current-line))
19834 (_cmd this-command)
19835 (_buf1 (current-buffer))
19836 (_buf2 ,_buffer)
19837 (_undo1 buffer-undo-list)
19838 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19839 _c1 _c2)
19840 ,@_body
19841 (when org-agenda-allow-remote-undo
19842 (setq _c1 (org-verify-change-for-undo
19843 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19844 _c2 (org-verify-change-for-undo
19845 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19846 (when (or _c1 _c2)
19847 ;; make sure there are undo boundaries
19848 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19849 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19850 ;; remember which buffer to undo
19851 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19852 org-agenda-undo-list)))))
19854 (defun org-agenda-undo ()
19855 "Undo a remote editing step in the agenda.
19856 This undoes changes both in the agenda buffer and in the remote buffer
19857 that have been changed along."
19858 (interactive)
19859 (or org-agenda-allow-remote-undo
19860 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19861 (if (not (eq this-command last-command))
19862 (setq org-agenda-undo-has-started-in nil
19863 org-agenda-pending-undo-list org-agenda-undo-list))
19864 (if (not org-agenda-pending-undo-list)
19865 (error "No further undo information"))
19866 (let* ((entry (pop org-agenda-pending-undo-list))
19867 buf line cmd rembuf)
19868 (setq cmd (pop entry) line (pop entry))
19869 (setq rembuf (nth 2 entry))
19870 (org-with-remote-undo rembuf
19871 (while (bufferp (setq buf (pop entry)))
19872 (if (pop entry)
19873 (with-current-buffer buf
19874 (let ((last-undo-buffer buf)
19875 (inhibit-read-only t))
19876 (unless (memq buf org-agenda-undo-has-started-in)
19877 (push buf org-agenda-undo-has-started-in)
19878 (make-local-variable 'pending-undo-list)
19879 (undo-start))
19880 (while (and pending-undo-list
19881 (listp pending-undo-list)
19882 (not (car pending-undo-list)))
19883 (pop pending-undo-list))
19884 (undo-more 1))))))
19885 (goto-line line)
19886 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19888 (defun org-verify-change-for-undo (l1 l2)
19889 "Verify that a real change occurred between the undo lists L1 and L2."
19890 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19891 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19892 (not (eq l1 l2)))
19894 ;;; Agenda dispatch
19896 (defvar org-agenda-restrict nil)
19897 (defvar org-agenda-restrict-begin (make-marker))
19898 (defvar org-agenda-restrict-end (make-marker))
19899 (defvar org-agenda-last-dispatch-buffer nil)
19900 (defvar org-agenda-overriding-restriction nil)
19902 ;;;###autoload
19903 (defun org-agenda (arg &optional keys restriction)
19904 "Dispatch agenda commands to collect entries to the agenda buffer.
19905 Prompts for a command to execute. Any prefix arg will be passed
19906 on to the selected command. The default selections are:
19908 a Call `org-agenda-list' to display the agenda for current day or week.
19909 t Call `org-todo-list' to display the global todo list.
19910 T Call `org-todo-list' to display the global todo list, select only
19911 entries with a specific TODO keyword (the user gets a prompt).
19912 m Call `org-tags-view' to display headlines with tags matching
19913 a condition (the user is prompted for the condition).
19914 M Like `m', but select only TODO entries, no ordinary headlines.
19915 L Create a timeline for the current buffer.
19916 e Export views to associated files.
19918 More commands can be added by configuring the variable
19919 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19920 searches can be pre-defined in this way.
19922 If the current buffer is in Org-mode and visiting a file, you can also
19923 first press `<' once to indicate that the agenda should be temporarily
19924 \(until the next use of \\[org-agenda]) restricted to the current file.
19925 Pressing `<' twice means to restrict to the current subtree or region
19926 \(if active)."
19927 (interactive "P")
19928 (catch 'exit
19929 (let* ((prefix-descriptions nil)
19930 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19931 (org-agenda-custom-commands
19932 ;; normalize different versions
19933 (delq nil
19934 (mapcar
19935 (lambda (x)
19936 (cond ((stringp (cdr x))
19937 (push x prefix-descriptions)
19938 nil)
19939 ((stringp (nth 1 x)) x)
19940 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19941 (t (cons (car x) (cons "" (cdr x))))))
19942 org-agenda-custom-commands)))
19943 (buf (current-buffer))
19944 (bfn (buffer-file-name (buffer-base-buffer)))
19945 entry key type match lprops ans)
19946 ;; Turn off restriction unless there is an overriding one
19947 (unless org-agenda-overriding-restriction
19948 (put 'org-agenda-files 'org-restrict nil)
19949 (setq org-agenda-restrict nil)
19950 (move-marker org-agenda-restrict-begin nil)
19951 (move-marker org-agenda-restrict-end nil))
19952 ;; Delete old local properties
19953 (put 'org-agenda-redo-command 'org-lprops nil)
19954 ;; Remember where this call originated
19955 (setq org-agenda-last-dispatch-buffer (current-buffer))
19956 (unless keys
19957 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19958 keys (car ans)
19959 restriction (cdr ans)))
19960 ;; Estabish the restriction, if any
19961 (when (and (not org-agenda-overriding-restriction) restriction)
19962 (put 'org-agenda-files 'org-restrict (list bfn))
19963 (cond
19964 ((eq restriction 'region)
19965 (setq org-agenda-restrict t)
19966 (move-marker org-agenda-restrict-begin (region-beginning))
19967 (move-marker org-agenda-restrict-end (region-end)))
19968 ((eq restriction 'subtree)
19969 (save-excursion
19970 (setq org-agenda-restrict t)
19971 (org-back-to-heading t)
19972 (move-marker org-agenda-restrict-begin (point))
19973 (move-marker org-agenda-restrict-end
19974 (progn (org-end-of-subtree t)))))))
19976 (require 'calendar) ; FIXME: can we avoid this for some commands?
19977 ;; For example the todo list should not need it (but does...)
19978 (cond
19979 ((setq entry (assoc keys org-agenda-custom-commands))
19980 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19981 (progn
19982 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19983 (put 'org-agenda-redo-command 'org-lprops lprops)
19984 (cond
19985 ((eq type 'agenda)
19986 (org-let lprops '(org-agenda-list current-prefix-arg)))
19987 ((eq type 'alltodo)
19988 (org-let lprops '(org-todo-list current-prefix-arg)))
19989 ((eq type 'search)
19990 (org-let lprops '(org-search-view current-prefix-arg match)))
19991 ((eq type 'stuck)
19992 (org-let lprops '(org-agenda-list-stuck-projects
19993 current-prefix-arg)))
19994 ((eq type 'tags)
19995 (org-let lprops '(org-tags-view current-prefix-arg match)))
19996 ((eq type 'tags-todo)
19997 (org-let lprops '(org-tags-view '(4) match)))
19998 ((eq type 'todo)
19999 (org-let lprops '(org-todo-list match)))
20000 ((eq type 'tags-tree)
20001 (org-check-for-org-mode)
20002 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
20003 ((eq type 'todo-tree)
20004 (org-check-for-org-mode)
20005 (org-let lprops
20006 '(org-occur (concat "^" outline-regexp "[ \t]*"
20007 (regexp-quote match) "\\>"))))
20008 ((eq type 'occur-tree)
20009 (org-check-for-org-mode)
20010 (org-let lprops '(org-occur match)))
20011 ((functionp type)
20012 (org-let lprops '(funcall type match)))
20013 ((fboundp type)
20014 (org-let lprops '(funcall type match)))
20015 (t (error "Invalid custom agenda command type %s" type))))
20016 (org-run-agenda-series (nth 1 entry) (cddr entry))))
20017 ((equal keys "C")
20018 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
20019 (customize-variable 'org-agenda-custom-commands))
20020 ((equal keys "a") (call-interactively 'org-agenda-list))
20021 ((equal keys "s") (call-interactively 'org-search-view))
20022 ((equal keys "t") (call-interactively 'org-todo-list))
20023 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
20024 ((equal keys "m") (call-interactively 'org-tags-view))
20025 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
20026 ((equal keys "e") (call-interactively 'org-store-agenda-views))
20027 ((equal keys "L")
20028 (unless (org-mode-p)
20029 (error "This is not an Org-mode file"))
20030 (unless restriction
20031 (put 'org-agenda-files 'org-restrict (list bfn))
20032 (org-call-with-arg 'org-timeline arg)))
20033 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
20034 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
20035 ((equal keys "!") (customize-variable 'org-stuck-projects))
20036 (t (error "Invalid agenda key"))))))
20038 (defun org-agenda-normalize-custom-commands (cmds)
20039 (delq nil
20040 (mapcar
20041 (lambda (x)
20042 (cond ((stringp (cdr x)) nil)
20043 ((stringp (nth 1 x)) x)
20044 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
20045 (t (cons (car x) (cons "" (cdr x))))))
20046 cmds)))
20048 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
20049 "The user interface for selecting an agenda command."
20050 (catch 'exit
20051 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
20052 (restrict-ok (and bfn (org-mode-p)))
20053 (region-p (org-region-active-p))
20054 (custom org-agenda-custom-commands)
20055 (selstring "")
20056 restriction second-time
20057 c entry key type match prefixes rmheader header-end custom1 desc)
20058 (save-window-excursion
20059 (delete-other-windows)
20060 (org-switch-to-buffer-other-window " *Agenda Commands*")
20061 (erase-buffer)
20062 (insert (eval-when-compile
20063 (let ((header
20065 Press key for an agenda command: < Buffer,subtree/region restriction
20066 -------------------------------- > Remove restriction
20067 a Agenda for current week or day e Export agenda views
20068 t List of all TODO entries T Entries with special TODO kwd
20069 m Match a TAGS query M Like m, but only TODO entries
20070 L Timeline for current buffer # List stuck projects (!=configure)
20071 s Search for keywords C Configure custom agenda commands
20072 / Multi-occur
20074 (start 0))
20075 (while (string-match
20076 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
20077 header start)
20078 (setq start (match-end 0))
20079 (add-text-properties (match-beginning 2) (match-end 2)
20080 '(face bold) header))
20081 header)))
20082 (setq header-end (move-marker (make-marker) (point)))
20083 (while t
20084 (setq custom1 custom)
20085 (when (eq rmheader t)
20086 (goto-line 1)
20087 (re-search-forward ":" nil t)
20088 (delete-region (match-end 0) (point-at-eol))
20089 (forward-char 1)
20090 (looking-at "-+")
20091 (delete-region (match-end 0) (point-at-eol))
20092 (move-marker header-end (match-end 0)))
20093 (goto-char header-end)
20094 (delete-region (point) (point-max))
20095 (while (setq entry (pop custom1))
20096 (setq key (car entry) desc (nth 1 entry)
20097 type (nth 2 entry) match (nth 3 entry))
20098 (if (> (length key) 1)
20099 (add-to-list 'prefixes (string-to-char key))
20100 (insert
20101 (format
20102 "\n%-4s%-14s: %s"
20103 (org-add-props (copy-sequence key)
20104 '(face bold))
20105 (cond
20106 ((string-match "\\S-" desc) desc)
20107 ((eq type 'agenda) "Agenda for current week or day")
20108 ((eq type 'alltodo) "List of all TODO entries")
20109 ((eq type 'search) "Word search")
20110 ((eq type 'stuck) "List of stuck projects")
20111 ((eq type 'todo) "TODO keyword")
20112 ((eq type 'tags) "Tags query")
20113 ((eq type 'tags-todo) "Tags (TODO)")
20114 ((eq type 'tags-tree) "Tags tree")
20115 ((eq type 'todo-tree) "TODO kwd tree")
20116 ((eq type 'occur-tree) "Occur tree")
20117 ((functionp type) (if (symbolp type)
20118 (symbol-name type)
20119 "Lambda expression"))
20120 (t "???"))
20121 (cond
20122 ((stringp match)
20123 (org-add-props match nil 'face 'org-warning))
20124 (match
20125 (format "set of %d commands" (length match)))
20126 (t ""))))))
20127 (when prefixes
20128 (mapc (lambda (x)
20129 (insert
20130 (format "\n%s %s"
20131 (org-add-props (char-to-string x)
20132 nil 'face 'bold)
20133 (or (cdr (assoc (concat selstring (char-to-string x))
20134 prefix-descriptions))
20135 "Prefix key"))))
20136 prefixes))
20137 (goto-char (point-min))
20138 (when (fboundp 'fit-window-to-buffer)
20139 (if second-time
20140 (if (not (pos-visible-in-window-p (point-max)))
20141 (fit-window-to-buffer))
20142 (setq second-time t)
20143 (fit-window-to-buffer)))
20144 (message "Press key for agenda command%s:"
20145 (if (or restrict-ok org-agenda-overriding-restriction)
20146 (if org-agenda-overriding-restriction
20147 " (restriction lock active)"
20148 (if restriction
20149 (format " (restricted to %s)" restriction)
20150 " (unrestricted)"))
20151 ""))
20152 (setq c (read-char-exclusive))
20153 (message "")
20154 (cond
20155 ((assoc (char-to-string c) custom)
20156 (setq selstring (concat selstring (char-to-string c)))
20157 (throw 'exit (cons selstring restriction)))
20158 ((memq c prefixes)
20159 (setq selstring (concat selstring (char-to-string c))
20160 prefixes nil
20161 rmheader (or rmheader t)
20162 custom (delq nil (mapcar
20163 (lambda (x)
20164 (if (or (= (length (car x)) 1)
20165 (/= (string-to-char (car x)) c))
20167 (cons (substring (car x) 1) (cdr x))))
20168 custom))))
20169 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
20170 (message "Restriction is only possible in Org-mode buffers")
20171 (ding) (sit-for 1))
20172 ((eq c ?1)
20173 (org-agenda-remove-restriction-lock 'noupdate)
20174 (setq restriction 'buffer))
20175 ((eq c ?0)
20176 (org-agenda-remove-restriction-lock 'noupdate)
20177 (setq restriction (if region-p 'region 'subtree)))
20178 ((eq c ?<)
20179 (org-agenda-remove-restriction-lock 'noupdate)
20180 (setq restriction
20181 (cond
20182 ((eq restriction 'buffer)
20183 (if region-p 'region 'subtree))
20184 ((memq restriction '(subtree region))
20185 nil)
20186 (t 'buffer))))
20187 ((eq c ?>)
20188 (org-agenda-remove-restriction-lock 'noupdate)
20189 (setq restriction nil))
20190 ((and (equal selstring "") (memq c '(?s ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
20191 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
20192 ((and (> (length selstring) 0) (eq c ?\d))
20193 (delete-window)
20194 (org-agenda-get-restriction-and-command prefix-descriptions))
20196 ((equal c ?q) (error "Abort"))
20197 (t (error "Invalid key %c" c))))))))
20199 (defun org-run-agenda-series (name series)
20200 (org-prepare-agenda name)
20201 (let* ((org-agenda-multi t)
20202 (redo (list 'org-run-agenda-series name (list 'quote series)))
20203 (cmds (car series))
20204 (gprops (nth 1 series))
20205 match ;; The byte compiler incorrectly complains about this. Keep it!
20206 cmd type lprops)
20207 (while (setq cmd (pop cmds))
20208 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
20209 (cond
20210 ((eq type 'agenda)
20211 (org-let2 gprops lprops
20212 '(call-interactively 'org-agenda-list)))
20213 ((eq type 'alltodo)
20214 (org-let2 gprops lprops
20215 '(call-interactively 'org-todo-list)))
20216 ((eq type 'search)
20217 (org-let2 gprops lprops
20218 '(org-search-view current-prefix-arg match)))
20219 ((eq type 'stuck)
20220 (org-let2 gprops lprops
20221 '(call-interactively 'org-agenda-list-stuck-projects)))
20222 ((eq type 'tags)
20223 (org-let2 gprops lprops
20224 '(org-tags-view current-prefix-arg match)))
20225 ((eq type 'tags-todo)
20226 (org-let2 gprops lprops
20227 '(org-tags-view '(4) match)))
20228 ((eq type 'todo)
20229 (org-let2 gprops lprops
20230 '(org-todo-list match)))
20231 ((fboundp type)
20232 (org-let2 gprops lprops
20233 '(funcall type match)))
20234 (t (error "Invalid type in command series"))))
20235 (widen)
20236 (setq org-agenda-redo-command redo)
20237 (goto-char (point-min)))
20238 (org-finalize-agenda))
20240 ;;;###autoload
20241 (defmacro org-batch-agenda (cmd-key &rest parameters)
20242 "Run an agenda command in batch mode and send the result to STDOUT.
20243 If CMD-KEY is a string of length 1, it is used as a key in
20244 `org-agenda-custom-commands' and triggers this command. If it is a
20245 longer string it is used as a tags/todo match string.
20246 Paramters are alternating variable names and values that will be bound
20247 before running the agenda command."
20248 (let (pars)
20249 (while parameters
20250 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20251 (if (> (length cmd-key) 2)
20252 (eval (list 'let (nreverse pars)
20253 (list 'org-tags-view nil cmd-key)))
20254 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20255 (set-buffer org-agenda-buffer-name)
20256 (princ (org-encode-for-stdout (buffer-string)))))
20258 (defun org-encode-for-stdout (string)
20259 (if (fboundp 'encode-coding-string)
20260 (encode-coding-string string buffer-file-coding-system)
20261 string))
20263 (defvar org-agenda-info nil)
20265 ;;;###autoload
20266 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
20267 "Run an agenda command in batch mode and send the result to STDOUT.
20268 If CMD-KEY is a string of length 1, it is used as a key in
20269 `org-agenda-custom-commands' and triggers this command. If it is a
20270 longer string it is used as a tags/todo match string.
20271 Paramters are alternating variable names and values that will be bound
20272 before running the agenda command.
20274 The output gives a line for each selected agenda item. Each
20275 item is a list of comma-separated values, like this:
20277 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
20279 category The category of the item
20280 head The headline, without TODO kwd, TAGS and PRIORITY
20281 type The type of the agenda entry, can be
20282 todo selected in TODO match
20283 tagsmatch selected in tags match
20284 diary imported from diary
20285 deadline a deadline on given date
20286 scheduled scheduled on given date
20287 timestamp entry has timestamp on given date
20288 closed entry was closed on given date
20289 upcoming-deadline warning about deadline
20290 past-scheduled forwarded scheduled item
20291 block entry has date block including g. date
20292 todo The todo keyword, if any
20293 tags All tags including inherited ones, separated by colons
20294 date The relevant date, like 2007-2-14
20295 time The time, like 15:00-16:50
20296 extra Sting with extra planning info
20297 priority-l The priority letter if any was given
20298 priority-n The computed numerical priority
20299 agenda-day The day in the agenda where this is listed"
20301 (let (pars)
20302 (while parameters
20303 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20304 (push (list 'org-agenda-remove-tags t) pars)
20305 (if (> (length cmd-key) 2)
20306 (eval (list 'let (nreverse pars)
20307 (list 'org-tags-view nil cmd-key)))
20308 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20309 (set-buffer org-agenda-buffer-name)
20310 (let* ((lines (org-split-string (buffer-string) "\n"))
20311 line)
20312 (while (setq line (pop lines))
20313 (catch 'next
20314 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
20315 (setq org-agenda-info
20316 (org-fix-agenda-info (text-properties-at 0 line)))
20317 (princ
20318 (org-encode-for-stdout
20319 (mapconcat 'org-agenda-export-csv-mapper
20320 '(org-category txt type todo tags date time-of-day extra
20321 priority-letter priority agenda-day)
20322 ",")))
20323 (princ "\n"))))))
20325 (defun org-fix-agenda-info (props)
20326 "Make sure all properties on an agenda item have a canonical form,
20327 so the export commands can easily use it."
20328 (let (tmp re)
20329 (when (setq tmp (plist-get props 'tags))
20330 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20331 (when (setq tmp (plist-get props 'date))
20332 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20333 (let ((calendar-date-display-form '(year "-" month "-" day)))
20334 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20336 (setq tmp (calendar-date-string tmp)))
20337 (setq props (plist-put props 'date tmp)))
20338 (when (setq tmp (plist-get props 'day))
20339 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20340 (let ((calendar-date-display-form '(year "-" month "-" day)))
20341 (setq tmp (calendar-date-string tmp)))
20342 (setq props (plist-put props 'day tmp))
20343 (setq props (plist-put props 'agenda-day tmp)))
20344 (when (setq tmp (plist-get props 'txt))
20345 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20346 (plist-put props 'priority-letter (match-string 1 tmp))
20347 (setq tmp (replace-match "" t t tmp)))
20348 (when (and (setq re (plist-get props 'org-todo-regexp))
20349 (setq re (concat "\\`\\.*" re " ?"))
20350 (string-match re tmp))
20351 (plist-put props 'todo (match-string 1 tmp))
20352 (setq tmp (replace-match "" t t tmp)))
20353 (plist-put props 'txt tmp)))
20354 props)
20356 (defun org-agenda-export-csv-mapper (prop)
20357 (let ((res (plist-get org-agenda-info prop)))
20358 (setq res
20359 (cond
20360 ((not res) "")
20361 ((stringp res) res)
20362 (t (prin1-to-string res))))
20363 (while (string-match "," res)
20364 (setq res (replace-match ";" t t res)))
20365 (org-trim res)))
20368 ;;;###autoload
20369 (defun org-store-agenda-views (&rest parameters)
20370 (interactive)
20371 (eval (list 'org-batch-store-agenda-views)))
20373 ;; FIXME, why is this a macro?????
20374 ;;;###autoload
20375 (defmacro org-batch-store-agenda-views (&rest parameters)
20376 "Run all custom agenda commands that have a file argument."
20377 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20378 (pop-up-frames nil)
20379 (dir default-directory)
20380 pars cmd thiscmdkey files opts)
20381 (while parameters
20382 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20383 (setq pars (reverse pars))
20384 (save-window-excursion
20385 (while cmds
20386 (setq cmd (pop cmds)
20387 thiscmdkey (car cmd)
20388 opts (nth 4 cmd)
20389 files (nth 5 cmd))
20390 (if (stringp files) (setq files (list files)))
20391 (when files
20392 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20393 (list 'org-agenda nil thiscmdkey)))
20394 (set-buffer org-agenda-buffer-name)
20395 (while files
20396 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20397 (list 'org-write-agenda
20398 (expand-file-name (pop files) dir) t))))
20399 (and (get-buffer org-agenda-buffer-name)
20400 (kill-buffer org-agenda-buffer-name)))))))
20402 (defun org-write-agenda (file &optional nosettings)
20403 "Write the current buffer (an agenda view) as a file.
20404 Depending on the extension of the file name, plain text (.txt),
20405 HTML (.html or .htm) or Postscript (.ps) is produced.
20406 If the extension is .ics, run icalendar export over all files used
20407 to construct the agenda and limit the export to entries listed in the
20408 agenda now.
20409 If NOSETTINGS is given, do not scope the settings of
20410 `org-agenda-exporter-settings' into the export commands. This is used when
20411 the settings have already been scoped and we do not wish to overrule other,
20412 higher priority settings."
20413 (interactive "FWrite agenda to file: ")
20414 (if (not (file-writable-p file))
20415 (error "Cannot write agenda to file %s" file))
20416 (cond
20417 ((string-match "\\.html?\\'" file) (require 'htmlize))
20418 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20419 (org-let (if nosettings nil org-agenda-exporter-settings)
20420 '(save-excursion
20421 (save-window-excursion
20422 (cond
20423 ((string-match "\\.html?\\'" file)
20424 (set-buffer (htmlize-buffer (current-buffer)))
20426 (when (and org-agenda-export-html-style
20427 (string-match "<style>" org-agenda-export-html-style))
20428 ;; replace <style> section with org-agenda-export-html-style
20429 (goto-char (point-min))
20430 (kill-region (- (search-forward "<style") 6)
20431 (search-forward "</style>"))
20432 (insert org-agenda-export-html-style))
20433 (write-file file)
20434 (kill-buffer (current-buffer))
20435 (message "HTML written to %s" file))
20436 ((string-match "\\.ps\\'" file)
20437 (ps-print-buffer-with-faces file)
20438 (message "Postscript written to %s" file))
20439 ((string-match "\\.ics\\'" file)
20440 (let ((org-agenda-marker-table
20441 (org-create-marker-find-array
20442 (org-agenda-collect-markers)))
20443 (org-icalendar-verify-function 'org-check-agenda-marker-table)
20444 (org-combined-agenda-icalendar-file file))
20445 (apply 'org-export-icalendar 'combine (org-agenda-files))))
20447 (let ((bs (buffer-string)))
20448 (find-file file)
20449 (insert bs)
20450 (save-buffer 0)
20451 (kill-buffer (current-buffer))
20452 (message "Plain text written to %s" file))))))
20453 (set-buffer org-agenda-buffer-name)))
20455 (defun org-agenda-collect-markers ()
20456 "Collect the markers pointing to entries in the agenda buffer."
20457 (let (m markers)
20458 (save-excursion
20459 (goto-char (point-min))
20460 (while (not (eobp))
20461 (when (setq m (or (get-text-property (point) 'org-hd-marker)
20462 (get-text-property (point) 'org-marker)))
20463 (push m markers))
20464 (beginning-of-line 2)))
20465 (nreverse markers)))
20467 (defun org-create-marker-find-array (marker-list)
20468 "Create a alist of files names with all marker positions in that file."
20469 (let (f tbl m a p)
20470 (while (setq m (pop marker-list))
20471 (setq p (marker-position m)
20472 f (buffer-file-name (or (buffer-base-buffer
20473 (marker-buffer m))
20474 (marker-buffer m))))
20475 (if (setq a (assoc f tbl))
20476 (push (marker-position m) (cdr a))
20477 (push (list f p) tbl)))
20478 (mapcar (lambda (x) (setcdr x (sort (copy-sequence (cdr x)) '<)) x)
20479 tbl)))
20481 (defvar org-agenda-marker-table nil) ; dyamically scoped parameter
20482 (defun org-check-agenda-marker-table ()
20483 "Check of the current entry is on the marker list."
20484 (let ((file (buffer-file-name (or (buffer-base-buffer) (current-buffer))))
20486 (and (setq a (assoc file org-agenda-marker-table))
20487 (save-match-data
20488 (save-excursion
20489 (org-back-to-heading t)
20490 (member (point) (cdr a)))))))
20492 (defmacro org-no-read-only (&rest body)
20493 "Inhibit read-only for BODY."
20494 `(let ((inhibit-read-only t)) ,@body))
20496 (defun org-check-for-org-mode ()
20497 "Make sure current buffer is in org-mode. Error if not."
20498 (or (org-mode-p)
20499 (error "Cannot execute org-mode agenda command on buffer in %s."
20500 major-mode)))
20502 (defun org-fit-agenda-window ()
20503 "Fit the window to the buffer size."
20504 (and (memq org-agenda-window-setup '(reorganize-frame))
20505 (fboundp 'fit-window-to-buffer)
20506 (fit-window-to-buffer
20508 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20509 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20511 ;;; Agenda file list
20513 (defun org-agenda-files (&optional unrestricted)
20514 "Get the list of agenda files.
20515 Optional UNRESTRICTED means return the full list even if a restriction
20516 is currently in place."
20517 (let ((files
20518 (cond
20519 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20520 ((stringp org-agenda-files) (org-read-agenda-file-list))
20521 ((listp org-agenda-files) org-agenda-files)
20522 (t (error "Invalid value of `org-agenda-files'")))))
20523 (setq files (apply 'append
20524 (mapcar (lambda (f)
20525 (if (file-directory-p f)
20526 (directory-files f t
20527 org-agenda-file-regexp)
20528 (list f)))
20529 files)))
20530 (if org-agenda-skip-unavailable-files
20531 (delq nil
20532 (mapcar (function
20533 (lambda (file)
20534 (and (file-readable-p file) file)))
20535 files))
20536 files))) ; `org-check-agenda-file' will remove them from the list
20538 (defun org-edit-agenda-file-list ()
20539 "Edit the list of agenda files.
20540 Depending on setup, this either uses customize to edit the variable
20541 `org-agenda-files', or it visits the file that is holding the list. In the
20542 latter case, the buffer is set up in a way that saving it automatically kills
20543 the buffer and restores the previous window configuration."
20544 (interactive)
20545 (if (stringp org-agenda-files)
20546 (let ((cw (current-window-configuration)))
20547 (find-file org-agenda-files)
20548 (org-set-local 'org-window-configuration cw)
20549 (org-add-hook 'after-save-hook
20550 (lambda ()
20551 (set-window-configuration
20552 (prog1 org-window-configuration
20553 (kill-buffer (current-buffer))))
20554 (org-install-agenda-files-menu)
20555 (message "New agenda file list installed"))
20556 nil 'local)
20557 (message "%s" (substitute-command-keys
20558 "Edit list and finish with \\[save-buffer]")))
20559 (customize-variable 'org-agenda-files)))
20561 (defun org-store-new-agenda-file-list (list)
20562 "Set new value for the agenda file list and save it correcly."
20563 (if (stringp org-agenda-files)
20564 (let ((f org-agenda-files) b)
20565 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20566 (with-temp-file f
20567 (insert (mapconcat 'identity list "\n") "\n")))
20568 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20569 (setq org-agenda-files list)
20570 (customize-save-variable 'org-agenda-files org-agenda-files))))
20572 (defun org-read-agenda-file-list ()
20573 "Read the list of agenda files from a file."
20574 (when (stringp org-agenda-files)
20575 (with-temp-buffer
20576 (insert-file-contents org-agenda-files)
20577 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20580 ;;;###autoload
20581 (defun org-cycle-agenda-files ()
20582 "Cycle through the files in `org-agenda-files'.
20583 If the current buffer visits an agenda file, find the next one in the list.
20584 If the current buffer does not, find the first agenda file."
20585 (interactive)
20586 (let* ((fs (org-agenda-files t))
20587 (files (append fs (list (car fs))))
20588 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20589 file)
20590 (unless files (error "No agenda files"))
20591 (catch 'exit
20592 (while (setq file (pop files))
20593 (if (equal (file-truename file) tcf)
20594 (when (car files)
20595 (find-file (car files))
20596 (throw 'exit t))))
20597 (find-file (car fs)))
20598 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20600 (defun org-agenda-file-to-front (&optional to-end)
20601 "Move/add the current file to the top of the agenda file list.
20602 If the file is not present in the list, it is added to the front. If it is
20603 present, it is moved there. With optional argument TO-END, add/move to the
20604 end of the list."
20605 (interactive "P")
20606 (let ((org-agenda-skip-unavailable-files nil)
20607 (file-alist (mapcar (lambda (x)
20608 (cons (file-truename x) x))
20609 (org-agenda-files t)))
20610 (ctf (file-truename buffer-file-name))
20611 x had)
20612 (setq x (assoc ctf file-alist) had x)
20614 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20615 (if to-end
20616 (setq file-alist (append (delq x file-alist) (list x)))
20617 (setq file-alist (cons x (delq x file-alist))))
20618 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20619 (org-install-agenda-files-menu)
20620 (message "File %s to %s of agenda file list"
20621 (if had "moved" "added") (if to-end "end" "front"))))
20623 (defun org-remove-file (&optional file)
20624 "Remove current file from the list of files in variable `org-agenda-files'.
20625 These are the files which are being checked for agenda entries.
20626 Optional argument FILE means, use this file instead of the current."
20627 (interactive)
20628 (let* ((org-agenda-skip-unavailable-files nil)
20629 (file (or file buffer-file-name))
20630 (true-file (file-truename file))
20631 (afile (abbreviate-file-name file))
20632 (files (delq nil (mapcar
20633 (lambda (x)
20634 (if (equal true-file
20635 (file-truename x))
20636 nil x))
20637 (org-agenda-files t)))))
20638 (if (not (= (length files) (length (org-agenda-files t))))
20639 (progn
20640 (org-store-new-agenda-file-list files)
20641 (org-install-agenda-files-menu)
20642 (message "Removed file: %s" afile))
20643 (message "File was not in list: %s (not removed)" afile))))
20645 (defun org-file-menu-entry (file)
20646 (vector file (list 'find-file file) t))
20648 (defun org-check-agenda-file (file)
20649 "Make sure FILE exists. If not, ask user what to do."
20650 (when (not (file-exists-p file))
20651 (message "non-existent file %s. [R]emove from list or [A]bort?"
20652 (abbreviate-file-name file))
20653 (let ((r (downcase (read-char-exclusive))))
20654 (cond
20655 ((equal r ?r)
20656 (org-remove-file file)
20657 (throw 'nextfile t))
20658 (t (error "Abort"))))))
20660 ;;; Agenda prepare and finalize
20662 (defvar org-agenda-multi nil) ; dynammically scoped
20663 (defvar org-agenda-buffer-name "*Org Agenda*")
20664 (defvar org-pre-agenda-window-conf nil)
20665 (defvar org-agenda-name nil)
20666 (defun org-prepare-agenda (&optional name)
20667 (setq org-todo-keywords-for-agenda nil)
20668 (setq org-done-keywords-for-agenda nil)
20669 (if org-agenda-multi
20670 (progn
20671 (setq buffer-read-only nil)
20672 (goto-char (point-max))
20673 (unless (or (bobp) org-agenda-compact-blocks)
20674 (insert "\n" (make-string (window-width) ?=) "\n"))
20675 (narrow-to-region (point) (point-max)))
20676 (org-agenda-reset-markers)
20677 (org-prepare-agenda-buffers (org-agenda-files))
20678 (setq org-todo-keywords-for-agenda
20679 (org-uniquify org-todo-keywords-for-agenda))
20680 (setq org-done-keywords-for-agenda
20681 (org-uniquify org-done-keywords-for-agenda))
20682 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20683 (awin (get-buffer-window abuf)))
20684 (cond
20685 ((equal (current-buffer) abuf) nil)
20686 (awin (select-window awin))
20687 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20688 ((equal org-agenda-window-setup 'current-window)
20689 (switch-to-buffer abuf))
20690 ((equal org-agenda-window-setup 'other-window)
20691 (org-switch-to-buffer-other-window abuf))
20692 ((equal org-agenda-window-setup 'other-frame)
20693 (switch-to-buffer-other-frame abuf))
20694 ((equal org-agenda-window-setup 'reorganize-frame)
20695 (delete-other-windows)
20696 (org-switch-to-buffer-other-window abuf))))
20697 (setq buffer-read-only nil)
20698 (erase-buffer)
20699 (org-agenda-mode)
20700 (and name (not org-agenda-name)
20701 (org-set-local 'org-agenda-name name)))
20702 (setq buffer-read-only nil))
20704 (defun org-finalize-agenda ()
20705 "Finishing touch for the agenda buffer, called just before displaying it."
20706 (unless org-agenda-multi
20707 (save-excursion
20708 (let ((inhibit-read-only t))
20709 (goto-char (point-min))
20710 (while (org-activate-bracket-links (point-max))
20711 (add-text-properties (match-beginning 0) (match-end 0)
20712 '(face org-link)))
20713 (org-agenda-align-tags)
20714 (unless org-agenda-with-colors
20715 (remove-text-properties (point-min) (point-max) '(face nil))))
20716 (if (and (boundp 'org-overriding-columns-format)
20717 org-overriding-columns-format)
20718 (org-set-local 'org-overriding-columns-format
20719 org-overriding-columns-format))
20720 (if (and (boundp 'org-agenda-view-columns-initially)
20721 org-agenda-view-columns-initially)
20722 (org-agenda-columns))
20723 (when org-agenda-fontify-priorities
20724 (org-fontify-priorities))
20725 (run-hooks 'org-finalize-agenda-hook)
20726 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20729 (defun org-fontify-priorities ()
20730 "Make highest priority lines bold, and lowest italic."
20731 (interactive)
20732 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20733 (org-delete-overlay o)))
20734 (org-overlays-in (point-min) (point-max)))
20735 (save-excursion
20736 (let ((inhibit-read-only t)
20737 b e p ov h l)
20738 (goto-char (point-min))
20739 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20740 (setq h (or (get-char-property (point) 'org-highest-priority)
20741 org-highest-priority)
20742 l (or (get-char-property (point) 'org-lowest-priority)
20743 org-lowest-priority)
20744 p (string-to-char (match-string 1))
20745 b (match-beginning 0) e (point-at-eol)
20746 ov (org-make-overlay b e))
20747 (org-overlay-put
20748 ov 'face
20749 (cond ((listp org-agenda-fontify-priorities)
20750 (cdr (assoc p org-agenda-fontify-priorities)))
20751 ((equal p l) 'italic)
20752 ((equal p h) 'bold)))
20753 (org-overlay-put ov 'org-type 'org-priority)))))
20755 (defun org-prepare-agenda-buffers (files)
20756 "Create buffers for all agenda files, protect archived trees and comments."
20757 (interactive)
20758 (let ((pa '(:org-archived t))
20759 (pc '(:org-comment t))
20760 (pall '(:org-archived t :org-comment t))
20761 (inhibit-read-only t)
20762 (rea (concat ":" org-archive-tag ":"))
20763 bmp file re)
20764 (save-excursion
20765 (save-restriction
20766 (while (setq file (pop files))
20767 (if (bufferp file)
20768 (set-buffer file)
20769 (org-check-agenda-file file)
20770 (set-buffer (org-get-agenda-file-buffer file)))
20771 (widen)
20772 (setq bmp (buffer-modified-p))
20773 (org-refresh-category-properties)
20774 (setq org-todo-keywords-for-agenda
20775 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20776 (setq org-done-keywords-for-agenda
20777 (append org-done-keywords-for-agenda org-done-keywords))
20778 (save-excursion
20779 (remove-text-properties (point-min) (point-max) pall)
20780 (when org-agenda-skip-archived-trees
20781 (goto-char (point-min))
20782 (while (re-search-forward rea nil t)
20783 (if (org-on-heading-p t)
20784 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20785 (goto-char (point-min))
20786 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20787 (while (re-search-forward re nil t)
20788 (add-text-properties
20789 (match-beginning 0) (org-end-of-subtree t) pc)))
20790 (set-buffer-modified-p bmp))))))
20792 (defvar org-agenda-skip-function nil
20793 "Function to be called at each match during agenda construction.
20794 If this function returns nil, the current match should not be skipped.
20795 Otherwise, the function must return a position from where the search
20796 should be continued.
20797 This may also be a Lisp form, it will be evaluated.
20798 Never set this variable using `setq' or so, because then it will apply
20799 to all future agenda commands. Instead, bind it with `let' to scope
20800 it dynamically into the agenda-constructing command. A good way to set
20801 it is through options in org-agenda-custom-commands.")
20803 (defun org-agenda-skip ()
20804 "Throw to `:skip' in places that should be skipped.
20805 Also moves point to the end of the skipped region, so that search can
20806 continue from there."
20807 (let ((p (point-at-bol)) to fp)
20808 (and org-agenda-skip-archived-trees
20809 (get-text-property p :org-archived)
20810 (org-end-of-subtree t)
20811 (throw :skip t))
20812 (and (get-text-property p :org-comment)
20813 (org-end-of-subtree t)
20814 (throw :skip t))
20815 (if (equal (char-after p) ?#) (throw :skip t))
20816 (when (and (or (setq fp (functionp org-agenda-skip-function))
20817 (consp org-agenda-skip-function))
20818 (setq to (save-excursion
20819 (save-match-data
20820 (if fp
20821 (funcall org-agenda-skip-function)
20822 (eval org-agenda-skip-function))))))
20823 (goto-char to)
20824 (throw :skip t))))
20826 (defvar org-agenda-markers nil
20827 "List of all currently active markers created by `org-agenda'.")
20828 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20829 "Creation time of the last agenda marker.")
20831 (defun org-agenda-new-marker (&optional pos)
20832 "Return a new agenda marker.
20833 Org-mode keeps a list of these markers and resets them when they are
20834 no longer in use."
20835 (let ((m (copy-marker (or pos (point)))))
20836 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20837 (push m org-agenda-markers)
20840 (defun org-agenda-reset-markers ()
20841 "Reset markers created by `org-agenda'."
20842 (while org-agenda-markers
20843 (move-marker (pop org-agenda-markers) nil)))
20845 (defun org-get-agenda-file-buffer (file)
20846 "Get a buffer visiting FILE. If the buffer needs to be created, add
20847 it to the list of buffers which might be released later."
20848 (let ((buf (org-find-base-buffer-visiting file)))
20849 (if buf
20850 buf ; just return it
20851 ;; Make a new buffer and remember it
20852 (setq buf (find-file-noselect file))
20853 (if buf (push buf org-agenda-new-buffers))
20854 buf)))
20856 (defun org-release-buffers (blist)
20857 "Release all buffers in list, asking the user for confirmation when needed.
20858 When a buffer is unmodified, it is just killed. When modified, it is saved
20859 \(if the user agrees) and then killed."
20860 (let (buf file)
20861 (while (setq buf (pop blist))
20862 (setq file (buffer-file-name buf))
20863 (when (and (buffer-modified-p buf)
20864 file
20865 (y-or-n-p (format "Save file %s? " file)))
20866 (with-current-buffer buf (save-buffer)))
20867 (kill-buffer buf))))
20869 (defun org-get-category (&optional pos)
20870 "Get the category applying to position POS."
20871 (get-text-property (or pos (point)) 'org-category))
20873 ;;; Agenda timeline
20875 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20877 (defun org-timeline (&optional include-all)
20878 "Show a time-sorted view of the entries in the current org file.
20879 Only entries with a time stamp of today or later will be listed. With
20880 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20881 under the current date.
20882 If the buffer contains an active region, only check the region for
20883 dates."
20884 (interactive "P")
20885 (require 'calendar)
20886 (org-compile-prefix-format 'timeline)
20887 (org-set-sorting-strategy 'timeline)
20888 (let* ((dopast t)
20889 (dotodo include-all)
20890 (doclosed org-agenda-show-log)
20891 (entry buffer-file-name)
20892 (date (calendar-current-date))
20893 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20894 (end (if (org-region-active-p) (region-end) (point-max)))
20895 (day-numbers (org-get-all-dates beg end 'no-ranges
20896 t doclosed ; always include today
20897 org-timeline-show-empty-dates))
20898 (org-deadline-warning-days 0)
20899 (org-agenda-only-exact-dates t)
20900 (today (time-to-days (current-time)))
20901 (past t)
20902 args
20903 s e rtn d emptyp)
20904 (setq org-agenda-redo-command
20905 (list 'progn
20906 (list 'org-switch-to-buffer-other-window (current-buffer))
20907 (list 'org-timeline (list 'quote include-all))))
20908 (if (not dopast)
20909 ;; Remove past dates from the list of dates.
20910 (setq day-numbers (delq nil (mapcar (lambda(x)
20911 (if (>= x today) x nil))
20912 day-numbers))))
20913 (org-prepare-agenda (concat "Timeline "
20914 (file-name-nondirectory buffer-file-name)))
20915 (if doclosed (push :closed args))
20916 (push :timestamp args)
20917 (push :deadline args)
20918 (push :scheduled args)
20919 (push :sexp args)
20920 (if dotodo (push :todo args))
20921 (while (setq d (pop day-numbers))
20922 (if (and (listp d) (eq (car d) :omitted))
20923 (progn
20924 (setq s (point))
20925 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20926 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20927 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20928 (if (and (>= d today)
20929 dopast
20930 past)
20931 (progn
20932 (setq past nil)
20933 (insert (make-string 79 ?-) "\n")))
20934 (setq date (calendar-gregorian-from-absolute d))
20935 (setq s (point))
20936 (setq rtn (and (not emptyp)
20937 (apply 'org-agenda-get-day-entries entry
20938 date args)))
20939 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20940 (progn
20941 (insert
20942 (if (stringp org-agenda-format-date)
20943 (format-time-string org-agenda-format-date
20944 (org-time-from-absolute date))
20945 (funcall org-agenda-format-date date))
20946 "\n")
20947 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20948 (put-text-property s (1- (point)) 'org-date-line t)
20949 (if (equal d today)
20950 (put-text-property s (1- (point)) 'org-today t))
20951 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20952 (put-text-property s (1- (point)) 'day d)))))
20953 (goto-char (point-min))
20954 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20955 (point-min)))
20956 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20957 (org-finalize-agenda)
20958 (setq buffer-read-only t)))
20960 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20961 "Return a list of all relevant day numbers from BEG to END buffer positions.
20962 If NO-RANGES is non-nil, include only the start and end dates of a range,
20963 not every single day in the range. If FORCE-TODAY is non-nil, make
20964 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20965 inactive time stamps (those in square brackets) are included.
20966 When EMPTY is non-nil, also include days without any entries."
20967 (let ((re (concat
20968 (if pre-re pre-re "")
20969 (if inactive org-ts-regexp-both org-ts-regexp)))
20970 dates dates1 date day day1 day2 ts1 ts2)
20971 (if force-today
20972 (setq dates (list (time-to-days (current-time)))))
20973 (save-excursion
20974 (goto-char beg)
20975 (while (re-search-forward re end t)
20976 (setq day (time-to-days (org-time-string-to-time
20977 (substring (match-string 1) 0 10))))
20978 (or (memq day dates) (push day dates)))
20979 (unless no-ranges
20980 (goto-char beg)
20981 (while (re-search-forward org-tr-regexp end t)
20982 (setq ts1 (substring (match-string 1) 0 10)
20983 ts2 (substring (match-string 2) 0 10)
20984 day1 (time-to-days (org-time-string-to-time ts1))
20985 day2 (time-to-days (org-time-string-to-time ts2)))
20986 (while (< (setq day1 (1+ day1)) day2)
20987 (or (memq day1 dates) (push day1 dates)))))
20988 (setq dates (sort dates '<))
20989 (when empty
20990 (while (setq day (pop dates))
20991 (setq day2 (car dates))
20992 (push day dates1)
20993 (when (and day2 empty)
20994 (if (or (eq empty t)
20995 (and (numberp empty) (<= (- day2 day) empty)))
20996 (while (< (setq day (1+ day)) day2)
20997 (push (list day) dates1))
20998 (push (cons :omitted (- day2 day)) dates1))))
20999 (setq dates (nreverse dates1)))
21000 dates)))
21002 ;;; Agenda Daily/Weekly
21004 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
21005 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
21006 (defvar org-agenda-last-arguments nil
21007 "The arguments of the previous call to org-agenda")
21008 (defvar org-starting-day nil) ; local variable in the agenda buffer
21009 (defvar org-agenda-span nil) ; local variable in the agenda buffer
21010 (defvar org-include-all-loc nil) ; local variable
21011 (defvar org-agenda-remove-date nil) ; dynamically scoped FIXME: not used???
21013 ;;;###autoload
21014 (defun org-agenda-list (&optional include-all start-day ndays)
21015 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
21016 The view will be for the current day or week, but from the overview buffer
21017 you will be able to go to other days/weeks.
21019 With one \\[universal-argument] prefix argument INCLUDE-ALL,
21020 all unfinished TODO items will also be shown, before the agenda.
21021 This feature is considered obsolete, please use the TODO list or a block
21022 agenda instead.
21024 With a numeric prefix argument in an interactive call, the agenda will
21025 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
21026 the number of days. NDAYS defaults to `org-agenda-ndays'.
21028 START-DAY defaults to TODAY, or to the most recent match for the weekday
21029 given in `org-agenda-start-on-weekday'."
21030 (interactive "P")
21031 (if (and (integerp include-all) (> include-all 0))
21032 (setq ndays include-all include-all nil))
21033 (setq ndays (or ndays org-agenda-ndays)
21034 start-day (or start-day org-agenda-start-day))
21035 (if org-agenda-overriding-arguments
21036 (setq include-all (car org-agenda-overriding-arguments)
21037 start-day (nth 1 org-agenda-overriding-arguments)
21038 ndays (nth 2 org-agenda-overriding-arguments)))
21039 (if (stringp start-day)
21040 ;; Convert to an absolute day number
21041 (setq start-day (time-to-days (org-read-date nil t start-day))))
21042 (setq org-agenda-last-arguments (list include-all start-day ndays))
21043 (org-compile-prefix-format 'agenda)
21044 (org-set-sorting-strategy 'agenda)
21045 (require 'calendar)
21046 (let* ((org-agenda-start-on-weekday
21047 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
21048 org-agenda-start-on-weekday nil))
21049 (thefiles (org-agenda-files))
21050 (files thefiles)
21051 (today (time-to-days
21052 (time-subtract (current-time)
21053 (list 0 (* 3600 org-extend-today-until) 0))))
21054 (sd (or start-day today))
21055 (start (if (or (null org-agenda-start-on-weekday)
21056 (< org-agenda-ndays 7))
21058 (let* ((nt (calendar-day-of-week
21059 (calendar-gregorian-from-absolute sd)))
21060 (n1 org-agenda-start-on-weekday)
21061 (d (- nt n1)))
21062 (- sd (+ (if (< d 0) 7 0) d)))))
21063 (day-numbers (list start))
21064 (day-cnt 0)
21065 (inhibit-redisplay (not debug-on-error))
21066 s e rtn rtnall file date d start-pos end-pos todayp nd)
21067 (setq org-agenda-redo-command
21068 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
21069 ;; Make the list of days
21070 (setq ndays (or ndays org-agenda-ndays)
21071 nd ndays)
21072 (while (> ndays 1)
21073 (push (1+ (car day-numbers)) day-numbers)
21074 (setq ndays (1- ndays)))
21075 (setq day-numbers (nreverse day-numbers))
21076 (org-prepare-agenda "Day/Week")
21077 (org-set-local 'org-starting-day (car day-numbers))
21078 (org-set-local 'org-include-all-loc include-all)
21079 (org-set-local 'org-agenda-span
21080 (org-agenda-ndays-to-span nd))
21081 (when (and (or include-all org-agenda-include-all-todo)
21082 (member today day-numbers))
21083 (setq files thefiles
21084 rtnall nil)
21085 (while (setq file (pop files))
21086 (catch 'nextfile
21087 (org-check-agenda-file file)
21088 (setq date (calendar-gregorian-from-absolute today)
21089 rtn (org-agenda-get-day-entries
21090 file date :todo))
21091 (setq rtnall (append rtnall rtn))))
21092 (when rtnall
21093 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
21094 (add-text-properties (point-min) (1- (point))
21095 (list 'face 'org-agenda-structure))
21096 (insert (org-finalize-agenda-entries rtnall) "\n")))
21097 (unless org-agenda-compact-blocks
21098 (setq s (point))
21099 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
21100 "-agenda:\n")
21101 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
21102 'org-date-line t)))
21103 (while (setq d (pop day-numbers))
21104 (setq date (calendar-gregorian-from-absolute d)
21105 s (point))
21106 (if (or (setq todayp (= d today))
21107 (and (not start-pos) (= d sd)))
21108 (setq start-pos (point))
21109 (if (and start-pos (not end-pos))
21110 (setq end-pos (point))))
21111 (setq files thefiles
21112 rtnall nil)
21113 (while (setq file (pop files))
21114 (catch 'nextfile
21115 (org-check-agenda-file file)
21116 (if org-agenda-show-log
21117 (setq rtn (org-agenda-get-day-entries
21118 file date
21119 :deadline :scheduled :timestamp :sexp :closed))
21120 (setq rtn (org-agenda-get-day-entries
21121 file date
21122 :deadline :scheduled :sexp :timestamp)))
21123 (setq rtnall (append rtnall rtn))))
21124 (if org-agenda-include-diary
21125 (progn
21126 (require 'diary-lib)
21127 (setq rtn (org-get-entries-from-diary date))
21128 (setq rtnall (append rtnall rtn))))
21129 (if (or rtnall org-agenda-show-all-dates)
21130 (progn
21131 (setq day-cnt (1+ day-cnt))
21132 (insert
21133 (if (stringp org-agenda-format-date)
21134 (format-time-string org-agenda-format-date
21135 (org-time-from-absolute date))
21136 (funcall org-agenda-format-date date))
21137 "\n")
21138 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
21139 (put-text-property s (1- (point)) 'org-date-line t)
21140 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
21141 (if todayp (put-text-property s (1- (point)) 'org-today t))
21142 (if rtnall (insert
21143 (org-finalize-agenda-entries
21144 (org-agenda-add-time-grid-maybe
21145 rtnall nd todayp))
21146 "\n"))
21147 (put-text-property s (1- (point)) 'day d)
21148 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
21149 (goto-char (point-min))
21150 (org-fit-agenda-window)
21151 (unless (and (pos-visible-in-window-p (point-min))
21152 (pos-visible-in-window-p (point-max)))
21153 (goto-char (1- (point-max)))
21154 (recenter -1)
21155 (if (not (pos-visible-in-window-p (or start-pos 1)))
21156 (progn
21157 (goto-char (or start-pos 1))
21158 (recenter 1))))
21159 (goto-char (or start-pos 1))
21160 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
21161 (org-finalize-agenda)
21162 (setq buffer-read-only t)
21163 (message "")))
21165 (defun org-agenda-ndays-to-span (n)
21166 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
21168 ;;; Agenda word search
21170 (defvar org-agenda-search-history nil)
21172 ;;;###autoload
21173 (defun org-search-view (&optional arg string)
21174 "Show all entries that contain words or regular expressions.
21175 If the first character of the search string is an asterisks,
21176 search only the headlines.
21178 The search string is broken into \"words\" by splitting at whitespace.
21179 The individual words are then interpreted as a boolean expression with
21180 logical AND. Words prefixed with a minus must not occur in the entry.
21181 Words without a prefix or prefixed with a plus must occur in the entry.
21182 Matching is case-insensitive and the words are enclosed by word delimiters.
21184 Words enclosed by curly braces are interpreted as regular expressions
21185 that must or must not match in the entry.
21187 This command searches the agenda files, and in addition the files listed
21188 in `org-agenda-text-search-extra-files'."
21189 (interactive "P")
21190 (org-compile-prefix-format 'search)
21191 (org-set-sorting-strategy 'search)
21192 (org-prepare-agenda "SEARCH")
21193 (let* ((props (list 'face nil
21194 'done-face 'org-done
21195 'org-not-done-regexp org-not-done-regexp
21196 'org-todo-regexp org-todo-regexp
21197 'mouse-face 'highlight
21198 'keymap org-agenda-keymap
21199 'help-echo (format "mouse-2 or RET jump to location")))
21200 regexp rtn rtnall files file pos
21201 marker priority category tags c neg re
21202 ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
21203 (unless (and (not arg)
21204 (stringp string)
21205 (string-match "\\S-" string))
21206 (setq string (read-string "[+-]Word/{Regexp} ...: "
21207 (cond
21208 ((integerp arg) (cons string arg))
21209 (arg string))
21210 'org-agenda-search-history)))
21211 (setq org-agenda-redo-command
21212 (list 'org-search-view 'current-prefix-arg string))
21213 (setq org-agenda-query-string string)
21215 (if (equal (string-to-char string) ?*)
21216 (setq hdl-only t
21217 words (substring string 1))
21218 (setq words string))
21219 (setq words (org-split-string words))
21220 (mapc (lambda (w)
21221 (setq c (string-to-char w))
21222 (if (equal c ?-)
21223 (setq neg t w (substring w 1))
21224 (if (equal c ?+)
21225 (setq neg nil w (substring w 1))
21226 (setq neg nil)))
21227 (if (string-match "\\`{.*}\\'" w)
21228 (setq re (substring w 1 -1))
21229 (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>")))
21230 (if neg (push re regexps-) (push re regexps+)))
21231 words)
21232 (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b)))))
21233 (if (not regexps+)
21234 (setq regexp (concat "^" org-outline-regexp))
21235 (setq regexp (pop regexps+))
21236 (if hdl-only (setq regexp (concat "^" org-outline-regexp ".*?"
21237 regexp))))
21238 (setq files (append (org-agenda-files) org-agenda-text-search-extra-files)
21239 rtnall nil)
21240 (while (setq file (pop files))
21241 (setq ee nil)
21242 (catch 'nextfile
21243 (org-check-agenda-file file)
21244 (setq buffer (if (file-exists-p file)
21245 (org-get-agenda-file-buffer file)
21246 (error "No such file %s" file)))
21247 (if (not buffer)
21248 ;; If file does not exist, make sure an error message is sent
21249 (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s"
21250 file))))
21251 (with-current-buffer buffer
21252 (unless (org-mode-p)
21253 (error "Agenda file %s is not in `org-mode'" file))
21254 (let ((case-fold-search t))
21255 (save-excursion
21256 (save-restriction
21257 (if org-agenda-restrict
21258 (narrow-to-region org-agenda-restrict-begin
21259 org-agenda-restrict-end)
21260 (widen))
21261 (goto-char (point-min))
21262 (unless (or (org-on-heading-p)
21263 (outline-next-heading))
21264 (throw 'nextfile t))
21265 (goto-char (max (point-min) (1- (point))))
21266 (while (re-search-forward regexp nil t)
21267 (org-back-to-heading t)
21268 (skip-chars-forward "* ")
21269 (setq beg (point-at-bol)
21270 beg1 (point)
21271 end (progn (outline-next-heading) (point)))
21272 (catch :skip
21273 (goto-char beg)
21274 (org-agenda-skip)
21275 (setq str (buffer-substring-no-properties
21276 (point-at-bol)
21277 (if hdl-only (point-at-eol) end)))
21278 (mapc (lambda (wr) (when (string-match wr str)
21279 (goto-char (1- end))
21280 (throw :skip t)))
21281 regexps-)
21282 (mapc (lambda (wr) (unless (string-match wr str)
21283 (goto-char (1- end))
21284 (throw :skip t)))
21285 regexps+)
21286 (goto-char beg)
21287 (setq marker (org-agenda-new-marker (point))
21288 category (org-get-category)
21289 tags (org-get-tags-at (point))
21290 txt (org-format-agenda-item
21292 (buffer-substring-no-properties
21293 beg1 (point-at-eol))
21294 category tags))
21295 (org-add-props txt props
21296 'org-marker marker 'org-hd-marker marker
21297 'priority 1000 'org-category category
21298 'type "search")
21299 (push txt ee)
21300 (goto-char (1- end)))))))))
21301 (setq rtn (nreverse ee))
21302 (setq rtnall (append rtnall rtn)))
21303 (if org-agenda-overriding-header
21304 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21305 nil 'face 'org-agenda-structure) "\n")
21306 (insert "Search words: ")
21307 (add-text-properties (point-min) (1- (point))
21308 (list 'face 'org-agenda-structure))
21309 (setq pos (point))
21310 (insert string "\n")
21311 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21312 (setq pos (point))
21313 (unless org-agenda-multi
21314 (insert "Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit\n")
21315 (add-text-properties pos (1- (point))
21316 (list 'face 'org-agenda-structure))))
21317 (when rtnall
21318 (insert (org-finalize-agenda-entries rtnall) "\n"))
21319 (goto-char (point-min))
21320 (org-fit-agenda-window)
21321 (add-text-properties (point-min) (point-max) '(org-agenda-type search))
21322 (org-finalize-agenda)
21323 (setq buffer-read-only t)))
21325 ;;; Agenda TODO list
21327 (defvar org-select-this-todo-keyword nil)
21328 (defvar org-last-arg nil)
21330 ;;;###autoload
21331 (defun org-todo-list (arg)
21332 "Show all TODO entries from all agenda file in a single list.
21333 The prefix arg can be used to select a specific TODO keyword and limit
21334 the list to these. When using \\[universal-argument], you will be prompted
21335 for a keyword. A numeric prefix directly selects the Nth keyword in
21336 `org-todo-keywords-1'."
21337 (interactive "P")
21338 (require 'calendar)
21339 (org-compile-prefix-format 'todo)
21340 (org-set-sorting-strategy 'todo)
21341 (org-prepare-agenda "TODO")
21342 (let* ((today (time-to-days (current-time)))
21343 (date (calendar-gregorian-from-absolute today))
21344 (kwds org-todo-keywords-for-agenda)
21345 (completion-ignore-case t)
21346 (org-select-this-todo-keyword
21347 (if (stringp arg) arg
21348 (and arg (integerp arg) (> arg 0)
21349 (nth (1- arg) kwds))))
21350 rtn rtnall files file pos)
21351 (when (equal arg '(4))
21352 (setq org-select-this-todo-keyword
21353 (completing-read "Keyword (or KWD1|K2D2|...): "
21354 (mapcar 'list kwds) nil nil)))
21355 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
21356 (org-set-local 'org-last-arg arg)
21357 (setq org-agenda-redo-command
21358 '(org-todo-list (or current-prefix-arg org-last-arg)))
21359 (setq files (org-agenda-files)
21360 rtnall nil)
21361 (while (setq file (pop files))
21362 (catch 'nextfile
21363 (org-check-agenda-file file)
21364 (setq rtn (org-agenda-get-day-entries file date :todo))
21365 (setq rtnall (append rtnall rtn))))
21366 (if org-agenda-overriding-header
21367 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21368 nil 'face 'org-agenda-structure) "\n")
21369 (insert "Global list of TODO items of type: ")
21370 (add-text-properties (point-min) (1- (point))
21371 (list 'face 'org-agenda-structure))
21372 (setq pos (point))
21373 (insert (or org-select-this-todo-keyword "ALL") "\n")
21374 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21375 (setq pos (point))
21376 (unless org-agenda-multi
21377 (insert "Available with `N r': (0)ALL")
21378 (let ((n 0) s)
21379 (mapc (lambda (x)
21380 (setq s (format "(%d)%s" (setq n (1+ n)) x))
21381 (if (> (+ (current-column) (string-width s) 1) (frame-width))
21382 (insert "\n "))
21383 (insert " " s))
21384 kwds))
21385 (insert "\n"))
21386 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21387 (when rtnall
21388 (insert (org-finalize-agenda-entries rtnall) "\n"))
21389 (goto-char (point-min))
21390 (org-fit-agenda-window)
21391 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
21392 (org-finalize-agenda)
21393 (setq buffer-read-only t)))
21395 ;;; Agenda tags match
21397 ;;;###autoload
21398 (defun org-tags-view (&optional todo-only match)
21399 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
21400 The prefix arg TODO-ONLY limits the search to TODO entries."
21401 (interactive "P")
21402 (org-compile-prefix-format 'tags)
21403 (org-set-sorting-strategy 'tags)
21404 (let* ((org-tags-match-list-sublevels
21405 (if todo-only t org-tags-match-list-sublevels))
21406 (completion-ignore-case t)
21407 rtn rtnall files file pos matcher
21408 buffer)
21409 (setq matcher (org-make-tags-matcher match)
21410 match (car matcher) matcher (cdr matcher))
21411 (org-prepare-agenda (concat "TAGS " match))
21412 (setq org-agenda-query-string match)
21413 (setq org-agenda-redo-command
21414 (list 'org-tags-view (list 'quote todo-only)
21415 (list 'if 'current-prefix-arg nil 'org-agenda-query-string)))
21416 (setq files (org-agenda-files)
21417 rtnall nil)
21418 (while (setq file (pop files))
21419 (catch 'nextfile
21420 (org-check-agenda-file file)
21421 (setq buffer (if (file-exists-p file)
21422 (org-get-agenda-file-buffer file)
21423 (error "No such file %s" file)))
21424 (if (not buffer)
21425 ;; If file does not exist, merror message to agenda
21426 (setq rtn (list
21427 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21428 rtnall (append rtnall rtn))
21429 (with-current-buffer buffer
21430 (unless (org-mode-p)
21431 (error "Agenda file %s is not in `org-mode'" file))
21432 (save-excursion
21433 (save-restriction
21434 (if org-agenda-restrict
21435 (narrow-to-region org-agenda-restrict-begin
21436 org-agenda-restrict-end)
21437 (widen))
21438 (setq rtn (org-scan-tags 'agenda matcher todo-only))
21439 (setq rtnall (append rtnall rtn))))))))
21440 (if org-agenda-overriding-header
21441 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21442 nil 'face 'org-agenda-structure) "\n")
21443 (insert "Headlines with TAGS match: ")
21444 (add-text-properties (point-min) (1- (point))
21445 (list 'face 'org-agenda-structure))
21446 (setq pos (point))
21447 (insert match "\n")
21448 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21449 (setq pos (point))
21450 (unless org-agenda-multi
21451 (insert "Press `C-u r' to search again with new search string\n"))
21452 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21453 (when rtnall
21454 (insert (org-finalize-agenda-entries rtnall) "\n"))
21455 (goto-char (point-min))
21456 (org-fit-agenda-window)
21457 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
21458 (org-finalize-agenda)
21459 (setq buffer-read-only t)))
21461 ;;; Agenda Finding stuck projects
21463 (defvar org-agenda-skip-regexp nil
21464 "Regular expression used in skipping subtrees for the agenda.
21465 This is basically a temporary global variable that can be set and then
21466 used by user-defined selections using `org-agenda-skip-function'.")
21468 (defvar org-agenda-overriding-header nil
21469 "When this is set during todo and tags searches, will replace header.")
21471 (defun org-agenda-skip-subtree-when-regexp-matches ()
21472 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
21473 If yes, it returns the end position of this tree, causing agenda commands
21474 to skip this subtree. This is a function that can be put into
21475 `org-agenda-skip-function' for the duration of a command."
21476 (let ((end (save-excursion (org-end-of-subtree t)))
21477 skip)
21478 (save-excursion
21479 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
21480 (and skip end)))
21482 (defun org-agenda-skip-entry-if (&rest conditions)
21483 "Skip entry if any of CONDITIONS is true.
21484 See `org-agenda-skip-if' for details."
21485 (org-agenda-skip-if nil conditions))
21487 (defun org-agenda-skip-subtree-if (&rest conditions)
21488 "Skip entry if any of CONDITIONS is true.
21489 See `org-agenda-skip-if' for details."
21490 (org-agenda-skip-if t conditions))
21492 (defun org-agenda-skip-if (subtree conditions)
21493 "Checks current entity for CONDITIONS.
21494 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21495 the entry, i.e. the text before the next heading is checked.
21497 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21498 from different tests. Valid conditions are:
21500 scheduled Check if there is a scheduled cookie
21501 notscheduled Check if there is no scheduled cookie
21502 deadline Check if there is a deadline
21503 notdeadline Check if there is no deadline
21504 regexp Check if regexp matches
21505 notregexp Check if regexp does not match.
21507 The regexp is taken from the conditions list, it must come right after
21508 the `regexp' or `notregexp' element.
21510 If any of these conditions is met, this function returns the end point of
21511 the entity, causing the search to continue from there. This is a function
21512 that can be put into `org-agenda-skip-function' for the duration of a command."
21513 (let (beg end m)
21514 (org-back-to-heading t)
21515 (setq beg (point)
21516 end (if subtree
21517 (progn (org-end-of-subtree t) (point))
21518 (progn (outline-next-heading) (1- (point)))))
21519 (goto-char beg)
21520 (and
21522 (and (memq 'scheduled conditions)
21523 (re-search-forward org-scheduled-time-regexp end t))
21524 (and (memq 'notscheduled conditions)
21525 (not (re-search-forward org-scheduled-time-regexp end t)))
21526 (and (memq 'deadline conditions)
21527 (re-search-forward org-deadline-time-regexp end t))
21528 (and (memq 'notdeadline conditions)
21529 (not (re-search-forward org-deadline-time-regexp end t)))
21530 (and (setq m (memq 'regexp conditions))
21531 (stringp (nth 1 m))
21532 (re-search-forward (nth 1 m) end t))
21533 (and (setq m (memq 'notregexp conditions))
21534 (stringp (nth 1 m))
21535 (not (re-search-forward (nth 1 m) end t))))
21536 end)))
21538 ;;;###autoload
21539 (defun org-agenda-list-stuck-projects (&rest ignore)
21540 "Create agenda view for projects that are stuck.
21541 Stuck projects are project that have no next actions. For the definitions
21542 of what a project is and how to check if it stuck, customize the variable
21543 `org-stuck-projects'.
21544 MATCH is being ignored."
21545 (interactive)
21546 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21547 ;; FIXME: we could have used org-agenda-skip-if here.
21548 (org-agenda-overriding-header "List of stuck projects: ")
21549 (matcher (nth 0 org-stuck-projects))
21550 (todo (nth 1 org-stuck-projects))
21551 (todo-wds (if (member "*" todo)
21552 (progn
21553 (org-prepare-agenda-buffers (org-agenda-files))
21554 (org-delete-all
21555 org-done-keywords-for-agenda
21556 (copy-sequence org-todo-keywords-for-agenda)))
21557 todo))
21558 (todo-re (concat "^\\*+[ \t]+\\("
21559 (mapconcat 'identity todo-wds "\\|")
21560 "\\)\\>"))
21561 (tags (nth 2 org-stuck-projects))
21562 (tags-re (if (member "*" tags)
21563 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21564 (concat "^\\*+ .*:\\("
21565 (mapconcat 'identity tags "\\|")
21566 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21567 (gen-re (nth 3 org-stuck-projects))
21568 (re-list
21569 (delq nil
21570 (list
21571 (if todo todo-re)
21572 (if tags tags-re)
21573 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21574 gen-re)))))
21575 (setq org-agenda-skip-regexp
21576 (if re-list
21577 (mapconcat 'identity re-list "\\|")
21578 (error "No information how to identify unstuck projects")))
21579 (org-tags-view nil matcher)
21580 (with-current-buffer org-agenda-buffer-name
21581 (setq org-agenda-redo-command
21582 '(org-agenda-list-stuck-projects
21583 (or current-prefix-arg org-last-arg))))))
21585 ;;; Diary integration
21587 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21588 (defvar list-diary-entries-hook)
21590 (defun org-get-entries-from-diary (date)
21591 "Get the (Emacs Calendar) diary entries for DATE."
21592 (require 'diary-lib)
21593 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21594 (diary-display-hook '(fancy-diary-display))
21595 (pop-up-frames nil)
21596 (list-diary-entries-hook
21597 (cons 'org-diary-default-entry list-diary-entries-hook))
21598 (diary-file-name-prefix-function nil) ; turn this feature off
21599 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21600 entries
21601 (org-disable-agenda-to-diary t))
21602 (save-excursion
21603 (save-window-excursion
21604 (funcall (if (fboundp 'diary-list-entries)
21605 'diary-list-entries 'list-diary-entries)
21606 date 1)))
21607 (if (not (get-buffer fancy-diary-buffer))
21608 (setq entries nil)
21609 (with-current-buffer fancy-diary-buffer
21610 (setq buffer-read-only nil)
21611 (if (zerop (buffer-size))
21612 ;; No entries
21613 (setq entries nil)
21614 ;; Omit the date and other unnecessary stuff
21615 (org-agenda-cleanup-fancy-diary)
21616 ;; Add prefix to each line and extend the text properties
21617 (if (zerop (buffer-size))
21618 (setq entries nil)
21619 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21620 (set-buffer-modified-p nil)
21621 (kill-buffer fancy-diary-buffer)))
21622 (when entries
21623 (setq entries (org-split-string entries "\n"))
21624 (setq entries
21625 (mapcar
21626 (lambda (x)
21627 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21628 ;; Extend the text properties to the beginning of the line
21629 (org-add-props x (text-properties-at (1- (length x)) x)
21630 'type "diary" 'date date))
21631 entries)))))
21633 (defun org-agenda-cleanup-fancy-diary ()
21634 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21635 This gets rid of the date, the underline under the date, and
21636 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21637 date. It also removes lines that contain only whitespace."
21638 (goto-char (point-min))
21639 (if (looking-at ".*?:[ \t]*")
21640 (progn
21641 (replace-match "")
21642 (re-search-forward "\n=+$" nil t)
21643 (replace-match "")
21644 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21645 (re-search-forward "\n=+$" nil t)
21646 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21647 (goto-char (point-min))
21648 (while (re-search-forward "^ +\n" nil t)
21649 (replace-match ""))
21650 (goto-char (point-min))
21651 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21652 (replace-match "")))
21654 ;; Make sure entries from the diary have the right text properties.
21655 (eval-after-load "diary-lib"
21656 '(if (boundp 'diary-modify-entry-list-string-function)
21657 ;; We can rely on the hook, nothing to do
21659 ;; Hook not avaiable, must use advice to make this work
21660 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21661 "Make the position visible."
21662 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21663 (stringp string)
21664 buffer-file-name)
21665 (setq string (org-modify-diary-entry-string string))))))
21667 (defun org-modify-diary-entry-string (string)
21668 "Add text properties to string, allowing org-mode to act on it."
21669 (org-add-props string nil
21670 'mouse-face 'highlight
21671 'keymap org-agenda-keymap
21672 'help-echo (if buffer-file-name
21673 (format "mouse-2 or RET jump to diary file %s"
21674 (abbreviate-file-name buffer-file-name))
21676 'org-agenda-diary-link t
21677 'org-marker (org-agenda-new-marker (point-at-bol))))
21679 (defun org-diary-default-entry ()
21680 "Add a dummy entry to the diary.
21681 Needed to avoid empty dates which mess up holiday display."
21682 ;; Catch the error if dealing with the new add-to-diary-alist
21683 (when org-disable-agenda-to-diary
21684 (condition-case nil
21685 (add-to-diary-list original-date "Org-mode dummy" "")
21686 (error
21687 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21689 ;;;###autoload
21690 (defun org-diary (&rest args)
21691 "Return diary information from org-files.
21692 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21693 It accesses org files and extracts information from those files to be
21694 listed in the diary. The function accepts arguments specifying what
21695 items should be listed. The following arguments are allowed:
21697 :timestamp List the headlines of items containing a date stamp or
21698 date range matching the selected date. Deadlines will
21699 also be listed, on the expiration day.
21701 :sexp List entries resulting from diary-like sexps.
21703 :deadline List any deadlines past due, or due within
21704 `org-deadline-warning-days'. The listing occurs only
21705 in the diary for *today*, not at any other date. If
21706 an entry is marked DONE, it is no longer listed.
21708 :scheduled List all items which are scheduled for the given date.
21709 The diary for *today* also contains items which were
21710 scheduled earlier and are not yet marked DONE.
21712 :todo List all TODO items from the org-file. This may be a
21713 long list - so this is not turned on by default.
21714 Like deadlines, these entries only show up in the
21715 diary for *today*, not at any other date.
21717 The call in the diary file should look like this:
21719 &%%(org-diary) ~/path/to/some/orgfile.org
21721 Use a separate line for each org file to check. Or, if you omit the file name,
21722 all files listed in `org-agenda-files' will be checked automatically:
21724 &%%(org-diary)
21726 If you don't give any arguments (as in the example above), the default
21727 arguments (:deadline :scheduled :timestamp :sexp) are used.
21728 So the example above may also be written as
21730 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21732 The function expects the lisp variables `entry' and `date' to be provided
21733 by the caller, because this is how the calendar works. Don't use this
21734 function from a program - use `org-agenda-get-day-entries' instead."
21735 (when (> (- (time-to-seconds (current-time))
21736 org-agenda-last-marker-time)
21738 (org-agenda-reset-markers))
21739 (org-compile-prefix-format 'agenda)
21740 (org-set-sorting-strategy 'agenda)
21741 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21742 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21743 (list entry)
21744 (org-agenda-files t)))
21745 file rtn results)
21746 (org-prepare-agenda-buffers files)
21747 ;; If this is called during org-agenda, don't return any entries to
21748 ;; the calendar. Org Agenda will list these entries itself.
21749 (if org-disable-agenda-to-diary (setq files nil))
21750 (while (setq file (pop files))
21751 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21752 (setq results (append results rtn)))
21753 (if results
21754 (concat (org-finalize-agenda-entries results) "\n"))))
21756 ;;; Agenda entry finders
21758 (defun org-agenda-get-day-entries (file date &rest args)
21759 "Does the work for `org-diary' and `org-agenda'.
21760 FILE is the path to a file to be checked for entries. DATE is date like
21761 the one returned by `calendar-current-date'. ARGS are symbols indicating
21762 which kind of entries should be extracted. For details about these, see
21763 the documentation of `org-diary'."
21764 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21765 (let* ((org-startup-folded nil)
21766 (org-startup-align-all-tables nil)
21767 (buffer (if (file-exists-p file)
21768 (org-get-agenda-file-buffer file)
21769 (error "No such file %s" file)))
21770 arg results rtn)
21771 (if (not buffer)
21772 ;; If file does not exist, make sure an error message ends up in diary
21773 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21774 (with-current-buffer buffer
21775 (unless (org-mode-p)
21776 (error "Agenda file %s is not in `org-mode'" file))
21777 (let ((case-fold-search nil))
21778 (save-excursion
21779 (save-restriction
21780 (if org-agenda-restrict
21781 (narrow-to-region org-agenda-restrict-begin
21782 org-agenda-restrict-end)
21783 (widen))
21784 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21785 (while (setq arg (pop args))
21786 (cond
21787 ((and (eq arg :todo)
21788 (equal date (calendar-current-date)))
21789 (setq rtn (org-agenda-get-todos))
21790 (setq results (append results rtn)))
21791 ((eq arg :timestamp)
21792 (setq rtn (org-agenda-get-blocks))
21793 (setq results (append results rtn))
21794 (setq rtn (org-agenda-get-timestamps))
21795 (setq results (append results rtn)))
21796 ((eq arg :sexp)
21797 (setq rtn (org-agenda-get-sexps))
21798 (setq results (append results rtn)))
21799 ((eq arg :scheduled)
21800 (setq rtn (org-agenda-get-scheduled))
21801 (setq results (append results rtn)))
21802 ((eq arg :closed)
21803 (setq rtn (org-agenda-get-closed))
21804 (setq results (append results rtn)))
21805 ((eq arg :deadline)
21806 (setq rtn (org-agenda-get-deadlines))
21807 (setq results (append results rtn))))))))
21808 results))))
21810 (defun org-entry-is-todo-p ()
21811 (member (org-get-todo-state) org-not-done-keywords))
21813 (defun org-entry-is-done-p ()
21814 (member (org-get-todo-state) org-done-keywords))
21816 (defun org-get-todo-state ()
21817 (save-excursion
21818 (org-back-to-heading t)
21819 (and (looking-at org-todo-line-regexp)
21820 (match-end 2)
21821 (match-string 2))))
21823 (defun org-at-date-range-p (&optional inactive-ok)
21824 "Is the cursor inside a date range?"
21825 (interactive)
21826 (save-excursion
21827 (catch 'exit
21828 (let ((pos (point)))
21829 (skip-chars-backward "^[<\r\n")
21830 (skip-chars-backward "<[")
21831 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21832 (>= (match-end 0) pos)
21833 (throw 'exit t))
21834 (skip-chars-backward "^<[\r\n")
21835 (skip-chars-backward "<[")
21836 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21837 (>= (match-end 0) pos)
21838 (throw 'exit t)))
21839 nil)))
21841 (defun org-agenda-get-todos ()
21842 "Return the TODO information for agenda display."
21843 (let* ((props (list 'face nil
21844 'done-face 'org-done
21845 'org-not-done-regexp org-not-done-regexp
21846 'org-todo-regexp org-todo-regexp
21847 'mouse-face 'highlight
21848 'keymap org-agenda-keymap
21849 'help-echo
21850 (format "mouse-2 or RET jump to org file %s"
21851 (abbreviate-file-name buffer-file-name))))
21852 ;; FIXME: get rid of the \n at some point but watch out
21853 (regexp (concat "^\\*+[ \t]+\\("
21854 (if org-select-this-todo-keyword
21855 (if (equal org-select-this-todo-keyword "*")
21856 org-todo-regexp
21857 (concat "\\<\\("
21858 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21859 "\\)\\>"))
21860 org-not-done-regexp)
21861 "[^\n\r]*\\)"))
21862 marker priority category tags
21863 ee txt beg end)
21864 (goto-char (point-min))
21865 (while (re-search-forward regexp nil t)
21866 (catch :skip
21867 (save-match-data
21868 (beginning-of-line)
21869 (setq beg (point) end (progn (outline-next-heading) (point)))
21870 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21871 (re-search-forward org-ts-regexp end t))
21872 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21873 (re-search-forward org-scheduled-time-regexp end t))
21874 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21875 (re-search-forward org-deadline-time-regexp end t)
21876 (org-deadline-close (match-string 1))))
21877 (goto-char (1+ beg))
21878 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21879 (throw :skip nil)))
21880 (goto-char beg)
21881 (org-agenda-skip)
21882 (goto-char (match-beginning 1))
21883 (setq marker (org-agenda-new-marker (match-beginning 0))
21884 category (org-get-category)
21885 tags (org-get-tags-at (point))
21886 txt (org-format-agenda-item "" (match-string 1) category tags)
21887 priority (1+ (org-get-priority txt)))
21888 (org-add-props txt props
21889 'org-marker marker 'org-hd-marker marker
21890 'priority priority 'org-category category
21891 'type "todo")
21892 (push txt ee)
21893 (if org-agenda-todo-list-sublevels
21894 (goto-char (match-end 1))
21895 (org-end-of-subtree 'invisible))))
21896 (nreverse ee)))
21898 (defconst org-agenda-no-heading-message
21899 "No heading for this item in buffer or region.")
21901 (defun org-agenda-get-timestamps ()
21902 "Return the date stamp information for agenda display."
21903 (let* ((props (list 'face nil
21904 'org-not-done-regexp org-not-done-regexp
21905 'org-todo-regexp org-todo-regexp
21906 'mouse-face 'highlight
21907 'keymap org-agenda-keymap
21908 'help-echo
21909 (format "mouse-2 or RET jump to org file %s"
21910 (abbreviate-file-name buffer-file-name))))
21911 (d1 (calendar-absolute-from-gregorian date))
21912 (remove-re
21913 (concat
21914 (regexp-quote
21915 (format-time-string
21916 "<%Y-%m-%d"
21917 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21918 ".*?>"))
21919 (regexp
21920 (concat
21921 (regexp-quote
21922 (substring
21923 (format-time-string
21924 (car org-time-stamp-formats)
21925 (apply 'encode-time ; DATE bound by calendar
21926 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21927 0 11))
21928 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21929 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21930 marker hdmarker deadlinep scheduledp donep tmp priority category
21931 ee txt timestr tags b0 b3 e3 head)
21932 (goto-char (point-min))
21933 (while (re-search-forward regexp nil t)
21934 (setq b0 (match-beginning 0)
21935 b3 (match-beginning 3) e3 (match-end 3))
21936 (catch :skip
21937 (and (org-at-date-range-p) (throw :skip nil))
21938 (org-agenda-skip)
21939 (if (and (match-end 1)
21940 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21941 (throw :skip nil))
21942 (if (and e3
21943 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21944 (throw :skip nil))
21945 (setq marker (org-agenda-new-marker b0)
21946 category (org-get-category b0)
21947 tmp (buffer-substring (max (point-min)
21948 (- b0 org-ds-keyword-length))
21950 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21951 deadlinep (string-match org-deadline-regexp tmp)
21952 scheduledp (string-match org-scheduled-regexp tmp)
21953 donep (org-entry-is-done-p))
21954 (if (or scheduledp deadlinep) (throw :skip t))
21955 (if (string-match ">" timestr)
21956 ;; substring should only run to end of time stamp
21957 (setq timestr (substring timestr 0 (match-end 0))))
21958 (save-excursion
21959 (if (re-search-backward "^\\*+ " nil t)
21960 (progn
21961 (goto-char (match-beginning 0))
21962 (setq hdmarker (org-agenda-new-marker)
21963 tags (org-get-tags-at))
21964 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21965 (setq head (match-string 1))
21966 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21967 (setq txt (org-format-agenda-item
21968 nil head category tags timestr nil
21969 remove-re)))
21970 (setq txt org-agenda-no-heading-message))
21971 (setq priority (org-get-priority txt))
21972 (org-add-props txt props
21973 'org-marker marker 'org-hd-marker hdmarker)
21974 (org-add-props txt nil 'priority priority
21975 'org-category category 'date date
21976 'type "timestamp")
21977 (push txt ee))
21978 (outline-next-heading)))
21979 (nreverse ee)))
21981 (defun org-agenda-get-sexps ()
21982 "Return the sexp information for agenda display."
21983 (require 'diary-lib)
21984 (let* ((props (list 'face nil
21985 'mouse-face 'highlight
21986 'keymap org-agenda-keymap
21987 'help-echo
21988 (format "mouse-2 or RET jump to org file %s"
21989 (abbreviate-file-name buffer-file-name))))
21990 (regexp "^&?%%(")
21991 marker category ee txt tags entry result beg b sexp sexp-entry)
21992 (goto-char (point-min))
21993 (while (re-search-forward regexp nil t)
21994 (catch :skip
21995 (org-agenda-skip)
21996 (setq beg (match-beginning 0))
21997 (goto-char (1- (match-end 0)))
21998 (setq b (point))
21999 (forward-sexp 1)
22000 (setq sexp (buffer-substring b (point)))
22001 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
22002 (org-trim (match-string 1))
22003 ""))
22004 (setq result (org-diary-sexp-entry sexp sexp-entry date))
22005 (when result
22006 (setq marker (org-agenda-new-marker beg)
22007 category (org-get-category beg))
22009 (if (string-match "\\S-" result)
22010 (setq txt result)
22011 (setq txt "SEXP entry returned empty string"))
22013 (setq txt (org-format-agenda-item
22014 "" txt category tags 'time))
22015 (org-add-props txt props 'org-marker marker)
22016 (org-add-props txt nil
22017 'org-category category 'date date
22018 'type "sexp")
22019 (push txt ee))))
22020 (nreverse ee)))
22022 (defun org-agenda-get-closed ()
22023 "Return the logged TODO entries for agenda display."
22024 (let* ((props (list 'mouse-face 'highlight
22025 'org-not-done-regexp org-not-done-regexp
22026 'org-todo-regexp org-todo-regexp
22027 'keymap org-agenda-keymap
22028 'help-echo
22029 (format "mouse-2 or RET jump to org file %s"
22030 (abbreviate-file-name buffer-file-name))))
22031 (regexp (concat
22032 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
22033 (regexp-quote
22034 (substring
22035 (format-time-string
22036 (car org-time-stamp-formats)
22037 (apply 'encode-time ; DATE bound by calendar
22038 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
22039 1 11))))
22040 marker hdmarker priority category tags closedp
22041 ee txt timestr)
22042 (goto-char (point-min))
22043 (while (re-search-forward regexp nil t)
22044 (catch :skip
22045 (org-agenda-skip)
22046 (setq marker (org-agenda-new-marker (match-beginning 0))
22047 closedp (equal (match-string 1) org-closed-string)
22048 category (org-get-category (match-beginning 0))
22049 timestr (buffer-substring (match-beginning 0) (point-at-eol))
22050 ;; donep (org-entry-is-done-p)
22052 (if (string-match "\\]" timestr)
22053 ;; substring should only run to end of time stamp
22054 (setq timestr (substring timestr 0 (match-end 0))))
22055 (save-excursion
22056 (if (re-search-backward "^\\*+ " nil t)
22057 (progn
22058 (goto-char (match-beginning 0))
22059 (setq hdmarker (org-agenda-new-marker)
22060 tags (org-get-tags-at))
22061 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
22062 (setq txt (org-format-agenda-item
22063 (if closedp "Closed: " "Clocked: ")
22064 (match-string 1) category tags timestr)))
22065 (setq txt org-agenda-no-heading-message))
22066 (setq priority 100000)
22067 (org-add-props txt props
22068 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
22069 'priority priority 'org-category category
22070 'type "closed" 'date date
22071 'undone-face 'org-warning 'done-face 'org-done)
22072 (push txt ee))
22073 (goto-char (point-at-eol))))
22074 (nreverse ee)))
22076 (defun org-agenda-get-deadlines ()
22077 "Return the deadline information for agenda display."
22078 (let* ((props (list 'mouse-face 'highlight
22079 'org-not-done-regexp org-not-done-regexp
22080 'org-todo-regexp org-todo-regexp
22081 'keymap org-agenda-keymap
22082 'help-echo
22083 (format "mouse-2 or RET jump to org file %s"
22084 (abbreviate-file-name buffer-file-name))))
22085 (regexp org-deadline-time-regexp)
22086 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
22087 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
22088 d2 diff dfrac wdays pos pos1 category tags
22089 ee txt head face s upcomingp donep timestr)
22090 (goto-char (point-min))
22091 (while (re-search-forward regexp nil t)
22092 (catch :skip
22093 (org-agenda-skip)
22094 (setq s (match-string 1)
22095 pos (1- (match-beginning 1))
22096 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
22097 diff (- d2 d1)
22098 wdays (org-get-wdays s)
22099 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
22100 upcomingp (and todayp (> diff 0)))
22101 ;; When to show a deadline in the calendar:
22102 ;; If the expiration is within wdays warning time.
22103 ;; Past-due deadlines are only shown on the current date
22104 (if (or (and (<= diff wdays)
22105 (and todayp (not org-agenda-only-exact-dates)))
22106 (= diff 0))
22107 (save-excursion
22108 (setq category (org-get-category))
22109 (if (re-search-backward "^\\*+[ \t]+" nil t)
22110 (progn
22111 (goto-char (match-end 0))
22112 (setq pos1 (match-beginning 0))
22113 (setq tags (org-get-tags-at pos1))
22114 (setq head (buffer-substring-no-properties
22115 (point)
22116 (progn (skip-chars-forward "^\r\n")
22117 (point))))
22118 (setq donep (string-match org-looking-at-done-regexp head))
22119 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
22120 (setq timestr
22121 (concat (substring s (match-beginning 1)) " "))
22122 (setq timestr 'time))
22123 (if (and donep
22124 (or org-agenda-skip-deadline-if-done
22125 (not (= diff 0))))
22126 (setq txt nil)
22127 (setq txt (org-format-agenda-item
22128 (if (= diff 0)
22129 (car org-agenda-deadline-leaders)
22130 (format (nth 1 org-agenda-deadline-leaders)
22131 diff))
22132 head category tags timestr))))
22133 (setq txt org-agenda-no-heading-message))
22134 (when txt
22135 (setq face (org-agenda-deadline-face dfrac wdays))
22136 (org-add-props txt props
22137 'org-marker (org-agenda-new-marker pos)
22138 'org-hd-marker (org-agenda-new-marker pos1)
22139 'priority (+ (- diff)
22140 (org-get-priority txt))
22141 'org-category category
22142 'type (if upcomingp "upcoming-deadline" "deadline")
22143 'date (if upcomingp date d2)
22144 'face (if donep 'org-done face)
22145 'undone-face face 'done-face 'org-done)
22146 (push txt ee))))))
22147 (nreverse ee)))
22149 (defun org-agenda-deadline-face (fraction &optional wdays)
22150 "Return the face to displaying a deadline item.
22151 FRACTION is what fraction of the head-warning time has passed."
22152 (if (equal wdays 0) (setq fraction 1.))
22153 (let ((faces org-agenda-deadline-faces) f)
22154 (catch 'exit
22155 (while (setq f (pop faces))
22156 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
22158 (defun org-agenda-get-scheduled ()
22159 "Return the scheduled information for agenda display."
22160 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
22161 'org-todo-regexp org-todo-regexp
22162 'done-face 'org-done
22163 'mouse-face 'highlight
22164 'keymap org-agenda-keymap
22165 'help-echo
22166 (format "mouse-2 or RET jump to org file %s"
22167 (abbreviate-file-name buffer-file-name))))
22168 (regexp org-scheduled-time-regexp)
22169 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
22170 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
22171 d2 diff pos pos1 category tags
22172 ee txt head pastschedp donep face timestr s)
22173 (goto-char (point-min))
22174 (while (re-search-forward regexp nil t)
22175 (catch :skip
22176 (org-agenda-skip)
22177 (setq s (match-string 1)
22178 pos (1- (match-beginning 1))
22179 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
22180 ;;; is this right?
22181 ;;; do we need to do this for deadleine too????
22182 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
22183 diff (- d2 d1))
22184 (setq pastschedp (and todayp (< diff 0)))
22185 ;; When to show a scheduled item in the calendar:
22186 ;; If it is on or past the date.
22187 (if (or (and (< diff 0)
22188 (and todayp (not org-agenda-only-exact-dates)))
22189 (= diff 0))
22190 (save-excursion
22191 (setq category (org-get-category))
22192 (if (re-search-backward "^\\*+[ \t]+" nil t)
22193 (progn
22194 (goto-char (match-end 0))
22195 (setq pos1 (match-beginning 0))
22196 (setq tags (org-get-tags-at))
22197 (setq head (buffer-substring-no-properties
22198 (point)
22199 (progn (skip-chars-forward "^\r\n") (point))))
22200 (setq donep (string-match org-looking-at-done-regexp head))
22201 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
22202 (setq timestr
22203 (concat (substring s (match-beginning 1)) " "))
22204 (setq timestr 'time))
22205 (if (and donep
22206 (or org-agenda-skip-scheduled-if-done
22207 (not (= diff 0))))
22208 (setq txt nil)
22209 (setq txt (org-format-agenda-item
22210 (if (= diff 0)
22211 (car org-agenda-scheduled-leaders)
22212 (format (nth 1 org-agenda-scheduled-leaders)
22213 (- 1 diff)))
22214 head category tags timestr))))
22215 (setq txt org-agenda-no-heading-message))
22216 (when txt
22217 (setq face (if pastschedp
22218 'org-scheduled-previously
22219 'org-scheduled-today))
22220 (org-add-props txt props
22221 'undone-face face
22222 'face (if donep 'org-done face)
22223 'org-marker (org-agenda-new-marker pos)
22224 'org-hd-marker (org-agenda-new-marker pos1)
22225 'type (if pastschedp "past-scheduled" "scheduled")
22226 'date (if pastschedp d2 date)
22227 'priority (+ 94 (- 5 diff) (org-get-priority txt))
22228 'org-category category)
22229 (push txt ee))))))
22230 (nreverse ee)))
22232 (defun org-agenda-get-blocks ()
22233 "Return the date-range information for agenda display."
22234 (let* ((props (list 'face nil
22235 'org-not-done-regexp org-not-done-regexp
22236 'org-todo-regexp org-todo-regexp
22237 'mouse-face 'highlight
22238 'keymap org-agenda-keymap
22239 'help-echo
22240 (format "mouse-2 or RET jump to org file %s"
22241 (abbreviate-file-name buffer-file-name))))
22242 (regexp org-tr-regexp)
22243 (d0 (calendar-absolute-from-gregorian date))
22244 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
22245 donep head)
22246 (goto-char (point-min))
22247 (while (re-search-forward regexp nil t)
22248 (catch :skip
22249 (org-agenda-skip)
22250 (setq pos (point))
22251 (setq timestr (match-string 0)
22252 s1 (match-string 1)
22253 s2 (match-string 2)
22254 d1 (time-to-days (org-time-string-to-time s1))
22255 d2 (time-to-days (org-time-string-to-time s2)))
22256 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
22257 ;; Only allow days between the limits, because the normal
22258 ;; date stamps will catch the limits.
22259 (save-excursion
22260 (setq marker (org-agenda-new-marker (point)))
22261 (setq category (org-get-category))
22262 (if (re-search-backward "^\\*+ " nil t)
22263 (progn
22264 (goto-char (match-beginning 0))
22265 (setq hdmarker (org-agenda-new-marker (point)))
22266 (setq tags (org-get-tags-at))
22267 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
22268 (setq head (match-string 1))
22269 (and org-agenda-skip-timestamp-if-done
22270 (org-entry-is-done-p)
22271 (throw :skip t))
22272 (setq txt (org-format-agenda-item
22273 (format (if (= d1 d2) "" "(%d/%d): ")
22274 (1+ (- d0 d1)) (1+ (- d2 d1)))
22275 head category tags
22276 (if (= d0 d1) timestr))))
22277 (setq txt org-agenda-no-heading-message))
22278 (org-add-props txt props
22279 'org-marker marker 'org-hd-marker hdmarker
22280 'type "block" 'date date
22281 'priority (org-get-priority txt) 'org-category category)
22282 (push txt ee)))
22283 (goto-char pos)))
22284 ;; Sort the entries by expiration date.
22285 (nreverse ee)))
22287 ;;; Agenda presentation and sorting
22289 (defconst org-plain-time-of-day-regexp
22290 (concat
22291 "\\(\\<[012]?[0-9]"
22292 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22293 "\\(--?"
22294 "\\(\\<[012]?[0-9]"
22295 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22296 "\\)?")
22297 "Regular expression to match a plain time or time range.
22298 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22299 groups carry important information:
22300 0 the full match
22301 1 the first time, range or not
22302 8 the second time, if it is a range.")
22304 (defconst org-plain-time-extension-regexp
22305 (concat
22306 "\\(\\<[012]?[0-9]"
22307 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22308 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
22309 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
22310 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22311 groups carry important information:
22312 0 the full match
22313 7 hours of duration
22314 9 minutes of duration")
22316 (defconst org-stamp-time-of-day-regexp
22317 (concat
22318 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
22319 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
22320 "\\(--?"
22321 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
22322 "Regular expression to match a timestamp time or time range.
22323 After a match, the following groups carry important information:
22324 0 the full match
22325 1 date plus weekday, for backreferencing to make sure both times on same day
22326 2 the first time, range or not
22327 4 the second time, if it is a range.")
22329 (defvar org-prefix-has-time nil
22330 "A flag, set by `org-compile-prefix-format'.
22331 The flag is set if the currently compiled format contains a `%t'.")
22332 (defvar org-prefix-has-tag nil
22333 "A flag, set by `org-compile-prefix-format'.
22334 The flag is set if the currently compiled format contains a `%T'.")
22336 (defun org-format-agenda-item (extra txt &optional category tags dotime
22337 noprefix remove-re)
22338 "Format TXT to be inserted into the agenda buffer.
22339 In particular, it adds the prefix and corresponding text properties. EXTRA
22340 must be a string and replaces the `%s' specifier in the prefix format.
22341 CATEGORY (string, symbol or nil) may be used to overrule the default
22342 category taken from local variable or file name. It will replace the `%c'
22343 specifier in the format. DOTIME, when non-nil, indicates that a
22344 time-of-day should be extracted from TXT for sorting of this entry, and for
22345 the `%t' specifier in the format. When DOTIME is a string, this string is
22346 searched for a time before TXT is. NOPREFIX is a flag and indicates that
22347 only the correctly processes TXT should be returned - this is used by
22348 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
22349 Any match of REMOVE-RE will be removed from TXT."
22350 (save-match-data
22351 ;; Diary entries sometimes have extra whitespace at the beginning
22352 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
22353 (let* ((category (or category
22354 org-category
22355 (if buffer-file-name
22356 (file-name-sans-extension
22357 (file-name-nondirectory buffer-file-name))
22358 "")))
22359 (tag (if tags (nth (1- (length tags)) tags) ""))
22360 time ; time and tag are needed for the eval of the prefix format
22361 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
22362 (time-of-day (and dotime (org-get-time-of-day ts)))
22363 stamp plain s0 s1 s2 rtn srp)
22364 (when (and dotime time-of-day org-prefix-has-time)
22365 ;; Extract starting and ending time and move them to prefix
22366 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
22367 (setq plain (string-match org-plain-time-of-day-regexp ts)))
22368 (setq s0 (match-string 0 ts)
22369 srp (and stamp (match-end 3))
22370 s1 (match-string (if plain 1 2) ts)
22371 s2 (match-string (if plain 8 (if srp 4 6)) ts))
22373 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
22374 ;; them, we might want to remove them there to avoid duplication.
22375 ;; The user can turn this off with a variable.
22376 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
22377 (string-match (concat (regexp-quote s0) " *") txt)
22378 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
22379 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
22380 (= (match-beginning 0) 0)
22382 (setq txt (replace-match "" nil nil txt))))
22383 ;; Normalize the time(s) to 24 hour
22384 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
22385 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
22387 (when (and s1 (not s2) org-agenda-default-appointment-duration
22388 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
22389 (let ((m (+ (string-to-number (match-string 2 s1))
22390 (* 60 (string-to-number (match-string 1 s1)))
22391 org-agenda-default-appointment-duration))
22393 (setq h (/ m 60) m (- m (* h 60)))
22394 (setq s2 (format "%02d:%02d" h m))))
22396 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22397 txt)
22398 ;; Tags are in the string
22399 (if (or (eq org-agenda-remove-tags t)
22400 (and org-agenda-remove-tags
22401 org-prefix-has-tag))
22402 (setq txt (replace-match "" t t txt))
22403 (setq txt (replace-match
22404 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
22405 (match-string 2 txt))
22406 t t txt))))
22408 (when remove-re
22409 (while (string-match remove-re txt)
22410 (setq txt (replace-match "" t t txt))))
22412 ;; Create the final string
22413 (if noprefix
22414 (setq rtn txt)
22415 ;; Prepare the variables needed in the eval of the compiled format
22416 (setq time (cond (s2 (concat s1 "-" s2))
22417 (s1 (concat s1 "......"))
22418 (t ""))
22419 extra (or extra "")
22420 category (if (symbolp category) (symbol-name category) category))
22421 ;; Evaluate the compiled format
22422 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
22424 ;; And finally add the text properties
22425 (org-add-props rtn nil
22426 'org-category (downcase category) 'tags tags
22427 'org-highest-priority org-highest-priority
22428 'org-lowest-priority org-lowest-priority
22429 'prefix-length (- (length rtn) (length txt))
22430 'time-of-day time-of-day
22431 'txt txt
22432 'time time
22433 'extra extra
22434 'dotime dotime))))
22436 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
22437 (defvar org-agenda-sorting-strategy-selected nil)
22439 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
22440 (catch 'exit
22441 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
22442 ((and todayp (member 'today (car org-agenda-time-grid))))
22443 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
22444 ((member 'weekly (car org-agenda-time-grid)))
22445 (t (throw 'exit list)))
22446 (let* ((have (delq nil (mapcar
22447 (lambda (x) (get-text-property 1 'time-of-day x))
22448 list)))
22449 (string (nth 1 org-agenda-time-grid))
22450 (gridtimes (nth 2 org-agenda-time-grid))
22451 (req (car org-agenda-time-grid))
22452 (remove (member 'remove-match req))
22453 new time)
22454 (if (and (member 'require-timed req) (not have))
22455 ;; don't show empty grid
22456 (throw 'exit list))
22457 (while (setq time (pop gridtimes))
22458 (unless (and remove (member time have))
22459 (setq time (int-to-string time))
22460 (push (org-format-agenda-item
22461 nil string "" nil
22462 (concat (substring time 0 -2) ":" (substring time -2)))
22463 new)
22464 (put-text-property
22465 1 (length (car new)) 'face 'org-time-grid (car new))))
22466 (if (member 'time-up org-agenda-sorting-strategy-selected)
22467 (append new list)
22468 (append list new)))))
22470 (defun org-compile-prefix-format (key)
22471 "Compile the prefix format into a Lisp form that can be evaluated.
22472 The resulting form is returned and stored in the variable
22473 `org-prefix-format-compiled'."
22474 (setq org-prefix-has-time nil org-prefix-has-tag nil)
22475 (let ((s (cond
22476 ((stringp org-agenda-prefix-format)
22477 org-agenda-prefix-format)
22478 ((assq key org-agenda-prefix-format)
22479 (cdr (assq key org-agenda-prefix-format)))
22480 (t " %-12:c%?-12t% s")))
22481 (start 0)
22482 varform vars var e c f opt)
22483 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
22484 s start)
22485 (setq var (cdr (assoc (match-string 4 s)
22486 '(("c" . category) ("t" . time) ("s" . extra)
22487 ("T" . tag))))
22488 c (or (match-string 3 s) "")
22489 opt (match-beginning 1)
22490 start (1+ (match-beginning 0)))
22491 (if (equal var 'time) (setq org-prefix-has-time t))
22492 (if (equal var 'tag) (setq org-prefix-has-tag t))
22493 (setq f (concat "%" (match-string 2 s) "s"))
22494 (if opt
22495 (setq varform
22496 `(if (equal "" ,var)
22498 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22499 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22500 (setq s (replace-match "%s" t nil s))
22501 (push varform vars))
22502 (setq vars (nreverse vars))
22503 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22505 (defun org-set-sorting-strategy (key)
22506 (if (symbolp (car org-agenda-sorting-strategy))
22507 ;; the old format
22508 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22509 (setq org-agenda-sorting-strategy-selected
22510 (or (cdr (assq key org-agenda-sorting-strategy))
22511 (cdr (assq 'agenda org-agenda-sorting-strategy))
22512 '(time-up category-keep priority-down)))))
22514 (defun org-get-time-of-day (s &optional string mod24)
22515 "Check string S for a time of day.
22516 If found, return it as a military time number between 0 and 2400.
22517 If not found, return nil.
22518 The optional STRING argument forces conversion into a 5 character wide string
22519 HH:MM."
22520 (save-match-data
22521 (when
22522 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22523 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22524 (let* ((h (string-to-number (match-string 1 s)))
22525 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22526 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22527 (am-p (equal ampm "am"))
22528 (h1 (cond ((not ampm) h)
22529 ((= h 12) (if am-p 0 12))
22530 (t (+ h (if am-p 0 12)))))
22531 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22532 (mod h1 24) h1))
22533 (t0 (+ (* 100 h2) m))
22534 (t1 (concat (if (>= h1 24) "+" " ")
22535 (if (< t0 100) "0" "")
22536 (if (< t0 10) "0" "")
22537 (int-to-string t0))))
22538 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22540 (defun org-finalize-agenda-entries (list &optional nosort)
22541 "Sort and concatenate the agenda items."
22542 (setq list (mapcar 'org-agenda-highlight-todo list))
22543 (if nosort
22544 list
22545 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22547 (defun org-agenda-highlight-todo (x)
22548 (let (re pl)
22549 (if (eq x 'line)
22550 (save-excursion
22551 (beginning-of-line 1)
22552 (setq re (get-text-property (point) 'org-todo-regexp))
22553 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22554 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22555 (add-text-properties (match-beginning 0) (match-end 0)
22556 (list 'face (org-get-todo-face 0)))
22557 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22558 (delete-region (match-beginning 1) (1- (match-end 0)))
22559 (goto-char (match-beginning 1))
22560 (insert (format org-agenda-todo-keyword-format s)))))
22561 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22562 pl (get-text-property 0 'prefix-length x))
22563 (when (and re
22564 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22565 x (or pl 0)) pl))
22566 (add-text-properties
22567 (or (match-end 1) (match-end 0)) (match-end 0)
22568 (list 'face (org-get-todo-face (match-string 2 x)))
22570 (setq x (concat (substring x 0 (match-end 1))
22571 (format org-agenda-todo-keyword-format
22572 (match-string 2 x))
22574 (substring x (match-end 3)))))
22575 x)))
22577 (defsubst org-cmp-priority (a b)
22578 "Compare the priorities of string A and B."
22579 (let ((pa (or (get-text-property 1 'priority a) 0))
22580 (pb (or (get-text-property 1 'priority b) 0)))
22581 (cond ((> pa pb) +1)
22582 ((< pa pb) -1)
22583 (t nil))))
22585 (defsubst org-cmp-category (a b)
22586 "Compare the string values of categories of strings A and B."
22587 (let ((ca (or (get-text-property 1 'org-category a) ""))
22588 (cb (or (get-text-property 1 'org-category b) "")))
22589 (cond ((string-lessp ca cb) -1)
22590 ((string-lessp cb ca) +1)
22591 (t nil))))
22593 (defsubst org-cmp-tag (a b)
22594 "Compare the string values of categories of strings A and B."
22595 (let ((ta (car (last (get-text-property 1 'tags a))))
22596 (tb (car (last (get-text-property 1 'tags b)))))
22597 (cond ((not ta) +1)
22598 ((not tb) -1)
22599 ((string-lessp ta tb) -1)
22600 ((string-lessp tb ta) +1)
22601 (t nil))))
22603 (defsubst org-cmp-time (a b)
22604 "Compare the time-of-day values of strings A and B."
22605 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22606 (ta (or (get-text-property 1 'time-of-day a) def))
22607 (tb (or (get-text-property 1 'time-of-day b) def)))
22608 (cond ((< ta tb) -1)
22609 ((< tb ta) +1)
22610 (t nil))))
22612 (defun org-entries-lessp (a b)
22613 "Predicate for sorting agenda entries."
22614 ;; The following variables will be used when the form is evaluated.
22615 ;; So even though the compiler complains, keep them.
22616 (let* ((time-up (org-cmp-time a b))
22617 (time-down (if time-up (- time-up) nil))
22618 (priority-up (org-cmp-priority a b))
22619 (priority-down (if priority-up (- priority-up) nil))
22620 (category-up (org-cmp-category a b))
22621 (category-down (if category-up (- category-up) nil))
22622 (category-keep (if category-up +1 nil))
22623 (tag-up (org-cmp-tag a b))
22624 (tag-down (if tag-up (- tag-up) nil)))
22625 (cdr (assoc
22626 (eval (cons 'or org-agenda-sorting-strategy-selected))
22627 '((-1 . t) (1 . nil) (nil . nil))))))
22629 ;;; Agenda restriction lock
22631 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22632 "Overlay to mark the headline to which arenda commands are restricted.")
22633 (org-overlay-put org-agenda-restriction-lock-overlay
22634 'face 'org-agenda-restriction-lock)
22635 (org-overlay-put org-agenda-restriction-lock-overlay
22636 'help-echo "Agendas are currently limited to this subtree.")
22637 (org-detach-overlay org-agenda-restriction-lock-overlay)
22638 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22639 "Overlay marking the agenda restriction line in speedbar.")
22640 (org-overlay-put org-speedbar-restriction-lock-overlay
22641 'face 'org-agenda-restriction-lock)
22642 (org-overlay-put org-speedbar-restriction-lock-overlay
22643 'help-echo "Agendas are currently limited to this item.")
22644 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22646 (defun org-agenda-set-restriction-lock (&optional type)
22647 "Set restriction lock for agenda, to current subtree or file.
22648 Restriction will be the file if TYPE is `file', or if type is the
22649 universal prefix '(4), or if the cursor is before the first headline
22650 in the file. Otherwise, restriction will be to the current subtree."
22651 (interactive "P")
22652 (and (equal type '(4)) (setq type 'file))
22653 (setq type (cond
22654 (type type)
22655 ((org-at-heading-p) 'subtree)
22656 ((condition-case nil (org-back-to-heading t) (error nil))
22657 'subtree)
22658 (t 'file)))
22659 (if (eq type 'subtree)
22660 (progn
22661 (setq org-agenda-restrict t)
22662 (setq org-agenda-overriding-restriction 'subtree)
22663 (put 'org-agenda-files 'org-restrict
22664 (list (buffer-file-name (buffer-base-buffer))))
22665 (org-back-to-heading t)
22666 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22667 (move-marker org-agenda-restrict-begin (point))
22668 (move-marker org-agenda-restrict-end
22669 (save-excursion (org-end-of-subtree t)))
22670 (message "Locking agenda restriction to subtree"))
22671 (put 'org-agenda-files 'org-restrict
22672 (list (buffer-file-name (buffer-base-buffer))))
22673 (setq org-agenda-restrict nil)
22674 (setq org-agenda-overriding-restriction 'file)
22675 (move-marker org-agenda-restrict-begin nil)
22676 (move-marker org-agenda-restrict-end nil)
22677 (message "Locking agenda restriction to file"))
22678 (setq current-prefix-arg nil)
22679 (org-agenda-maybe-redo))
22681 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22682 "Remove the agenda restriction lock."
22683 (interactive "P")
22684 (org-detach-overlay org-agenda-restriction-lock-overlay)
22685 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22686 (setq org-agenda-overriding-restriction nil)
22687 (setq org-agenda-restrict nil)
22688 (put 'org-agenda-files 'org-restrict nil)
22689 (move-marker org-agenda-restrict-begin nil)
22690 (move-marker org-agenda-restrict-end nil)
22691 (setq current-prefix-arg nil)
22692 (message "Agenda restriction lock removed")
22693 (or noupdate (org-agenda-maybe-redo)))
22695 (defun org-agenda-maybe-redo ()
22696 "If there is any window showing the agenda view, update it."
22697 (let ((w (get-buffer-window org-agenda-buffer-name t))
22698 (w0 (selected-window)))
22699 (when w
22700 (select-window w)
22701 (org-agenda-redo)
22702 (select-window w0)
22703 (if org-agenda-overriding-restriction
22704 (message "Agenda view shifted to new %s restriction"
22705 org-agenda-overriding-restriction)
22706 (message "Agenda restriction lock removed")))))
22708 ;;; Agenda commands
22710 (defun org-agenda-check-type (error &rest types)
22711 "Check if agenda buffer is of allowed type.
22712 If ERROR is non-nil, throw an error, otherwise just return nil."
22713 (if (memq org-agenda-type types)
22715 (if error
22716 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22717 nil)))
22719 (defun org-agenda-quit ()
22720 "Exit agenda by removing the window or the buffer."
22721 (interactive)
22722 (let ((buf (current-buffer)))
22723 (if (not (one-window-p)) (delete-window))
22724 (kill-buffer buf)
22725 (org-agenda-reset-markers)
22726 (org-columns-remove-overlays))
22727 ;; Maybe restore the pre-agenda window configuration.
22728 (and org-agenda-restore-windows-after-quit
22729 (not (eq org-agenda-window-setup 'other-frame))
22730 org-pre-agenda-window-conf
22731 (set-window-configuration org-pre-agenda-window-conf)))
22733 (defun org-agenda-exit ()
22734 "Exit agenda by removing the window or the buffer.
22735 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22736 Org-mode buffers visited directly by the user will not be touched."
22737 (interactive)
22738 (org-release-buffers org-agenda-new-buffers)
22739 (setq org-agenda-new-buffers nil)
22740 (org-agenda-quit))
22742 (defun org-agenda-execute (arg)
22743 "Execute another agenda command, keeping same window.\\<global-map>
22744 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22745 (interactive "P")
22746 (let ((org-agenda-window-setup 'current-window))
22747 (org-agenda arg)))
22749 (defun org-save-all-org-buffers ()
22750 "Save all Org-mode buffers without user confirmation."
22751 (interactive)
22752 (message "Saving all Org-mode buffers...")
22753 (save-some-buffers t 'org-mode-p)
22754 (message "Saving all Org-mode buffers... done"))
22756 (defun org-agenda-redo ()
22757 "Rebuild Agenda.
22758 When this is the global TODO list, a prefix argument will be interpreted."
22759 (interactive)
22760 (let* ((org-agenda-keep-modes t)
22761 (line (org-current-line))
22762 (window-line (- line (org-current-line (window-start))))
22763 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22764 (message "Rebuilding agenda buffer...")
22765 (org-let lprops '(eval org-agenda-redo-command))
22766 (setq org-agenda-undo-list nil
22767 org-agenda-pending-undo-list nil)
22768 (message "Rebuilding agenda buffer...done")
22769 (goto-line line)
22770 (recenter window-line)))
22772 (defun org-agenda-manipulate-query-add ()
22773 "Manipulate the query by adding a search term with positive selection.
22774 Positive selection means, the term must be matched for selection of an entry."
22775 (interactive)
22776 (org-agenda-manipulate-query ?\[))
22777 (defun org-agenda-manipulate-query-subtract ()
22778 "Manipulate the query by adding a search term with negative selection.
22779 Negative selection means, term must not be matched for selection of an entry."
22780 (interactive)
22781 (org-agenda-manipulate-query ?\]))
22782 (defun org-agenda-manipulate-query-add-re ()
22783 "Manipulate the query by adding a search regexp with positive selection.
22784 Positive selection means, the regexp must match for selection of an entry."
22785 (interactive)
22786 (org-agenda-manipulate-query ?\{))
22787 (defun org-agenda-manipulate-query-subtract-re ()
22788 "Manipulate the query by adding a search regexp with negative selection.
22789 Negative selection means, regexp must not match for selection of an entry."
22790 (interactive)
22791 (org-agenda-manipulate-query ?\}))
22792 (defun org-agenda-manipulate-query (char)
22793 (cond
22794 ((eq org-agenda-type 'search)
22795 (org-add-to-string
22796 'org-agenda-query-string
22797 (cdr (assoc char '((?\[ . " +") (?\] . " -")
22798 (?\{ . " +{}") (?\} . " -{}")))))
22799 (setq org-agenda-redo-command
22800 (list 'org-search-view
22801 (+ (length org-agenda-query-string)
22802 (if (member char '(?\{ ?\})) 0 1))
22803 org-agenda-query-string))
22804 (set-register org-agenda-query-register org-agenda-query-string)
22805 (org-agenda-redo))
22806 (t (error "Canot manipulate query for %s-type agenda buffers"
22807 org-agenda-type))))
22809 (defun org-add-to-string (var string)
22810 (set var (concat (symbol-value var) string)))
22812 (defun org-agenda-goto-date (date)
22813 "Jump to DATE in agenda."
22814 (interactive (list (org-read-date)))
22815 (org-agenda-list nil date))
22817 (defun org-agenda-goto-today ()
22818 "Go to today."
22819 (interactive)
22820 (org-agenda-check-type t 'timeline 'agenda)
22821 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22822 (cond
22823 (tdpos (goto-char tdpos))
22824 ((eq org-agenda-type 'agenda)
22825 (let* ((sd (time-to-days
22826 (time-subtract (current-time)
22827 (list 0 (* 3600 org-extend-today-until) 0))))
22828 (comp (org-agenda-compute-time-span sd org-agenda-span))
22829 (org-agenda-overriding-arguments org-agenda-last-arguments))
22830 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22831 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22832 (org-agenda-redo)
22833 (org-agenda-find-same-or-today-or-agenda)))
22834 (t (error "Cannot find today")))))
22836 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22837 (goto-char
22838 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22839 (text-property-any (point-min) (point-max) 'org-today t)
22840 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22841 (point-min))))
22843 (defun org-agenda-later (arg)
22844 "Go forward in time by thee current span.
22845 With prefix ARG, go forward that many times the current span."
22846 (interactive "p")
22847 (org-agenda-check-type t 'agenda)
22848 (let* ((span org-agenda-span)
22849 (sd org-starting-day)
22850 (greg (calendar-gregorian-from-absolute sd))
22851 (cnt (get-text-property (point) 'org-day-cnt))
22852 greg2 nd)
22853 (cond
22854 ((eq span 'day)
22855 (setq sd (+ arg sd) nd 1))
22856 ((eq span 'week)
22857 (setq sd (+ (* 7 arg) sd) nd 7))
22858 ((eq span 'month)
22859 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22860 sd (calendar-absolute-from-gregorian greg2))
22861 (setcar greg2 (1+ (car greg2)))
22862 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22863 ((eq span 'year)
22864 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22865 sd (calendar-absolute-from-gregorian greg2))
22866 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22867 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22868 (let ((org-agenda-overriding-arguments
22869 (list (car org-agenda-last-arguments) sd nd t)))
22870 (org-agenda-redo)
22871 (org-agenda-find-same-or-today-or-agenda cnt))))
22873 (defun org-agenda-earlier (arg)
22874 "Go backward in time by the current span.
22875 With prefix ARG, go backward that many times the current span."
22876 (interactive "p")
22877 (org-agenda-later (- arg)))
22879 (defun org-agenda-day-view ()
22880 "Switch to daily view for agenda."
22881 (interactive)
22882 (setq org-agenda-ndays 1)
22883 (org-agenda-change-time-span 'day))
22884 (defun org-agenda-week-view ()
22885 "Switch to daily view for agenda."
22886 (interactive)
22887 (setq org-agenda-ndays 7)
22888 (org-agenda-change-time-span 'week))
22889 (defun org-agenda-month-view ()
22890 "Switch to daily view for agenda."
22891 (interactive)
22892 (org-agenda-change-time-span 'month))
22893 (defun org-agenda-year-view ()
22894 "Switch to daily view for agenda."
22895 (interactive)
22896 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22897 (org-agenda-change-time-span 'year)
22898 (error "Abort")))
22900 (defun org-agenda-change-time-span (span)
22901 "Change the agenda view to SPAN.
22902 SPAN may be `day', `week', `month', `year'."
22903 (org-agenda-check-type t 'agenda)
22904 (if (equal org-agenda-span span)
22905 (error "Viewing span is already \"%s\"" span))
22906 (let* ((sd (or (get-text-property (point) 'day)
22907 org-starting-day))
22908 (computed (org-agenda-compute-time-span sd span))
22909 (org-agenda-overriding-arguments
22910 (list (car org-agenda-last-arguments)
22911 (car computed) (cdr computed) t)))
22912 (org-agenda-redo)
22913 (org-agenda-find-same-or-today-or-agenda))
22914 (org-agenda-set-mode-name)
22915 (message "Switched to %s view" span))
22917 (defun org-agenda-compute-time-span (sd span)
22918 "Compute starting date and number of days for agenda.
22919 SPAN may be `day', `week', `month', `year'. The return value
22920 is a cons cell with the starting date and the number of days,
22921 so that the date SD will be in that range."
22922 (let* ((greg (calendar-gregorian-from-absolute sd))
22924 (cond
22925 ((eq span 'day)
22926 (setq nd 1))
22927 ((eq span 'week)
22928 (let* ((nt (calendar-day-of-week
22929 (calendar-gregorian-from-absolute sd)))
22930 (d (if org-agenda-start-on-weekday
22931 (- nt org-agenda-start-on-weekday)
22932 0)))
22933 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22934 (setq nd 7)))
22935 ((eq span 'month)
22936 (setq sd (calendar-absolute-from-gregorian
22937 (list (car greg) 1 (nth 2 greg)))
22938 nd (- (calendar-absolute-from-gregorian
22939 (list (1+ (car greg)) 1 (nth 2 greg)))
22940 sd)))
22941 ((eq span 'year)
22942 (setq sd (calendar-absolute-from-gregorian
22943 (list 1 1 (nth 2 greg)))
22944 nd (- (calendar-absolute-from-gregorian
22945 (list 1 1 (1+ (nth 2 greg))))
22946 sd))))
22947 (cons sd nd)))
22949 ;; FIXME: does not work if user makes date format that starts with a blank
22950 (defun org-agenda-next-date-line (&optional arg)
22951 "Jump to the next line indicating a date in agenda buffer."
22952 (interactive "p")
22953 (org-agenda-check-type t 'agenda 'timeline)
22954 (beginning-of-line 1)
22955 (if (looking-at "^\\S-") (forward-char 1))
22956 (if (not (re-search-forward "^\\S-" nil t arg))
22957 (progn
22958 (backward-char 1)
22959 (error "No next date after this line in this buffer")))
22960 (goto-char (match-beginning 0)))
22962 (defun org-agenda-previous-date-line (&optional arg)
22963 "Jump to the previous line indicating a date in agenda buffer."
22964 (interactive "p")
22965 (org-agenda-check-type t 'agenda 'timeline)
22966 (beginning-of-line 1)
22967 (if (not (re-search-backward "^\\S-" nil t arg))
22968 (error "No previous date before this line in this buffer")))
22970 ;; Initialize the highlight
22971 (defvar org-hl (org-make-overlay 1 1))
22972 (org-overlay-put org-hl 'face 'highlight)
22974 (defun org-highlight (begin end &optional buffer)
22975 "Highlight a region with overlay."
22976 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22977 org-hl begin end (or buffer (current-buffer))))
22979 (defun org-unhighlight ()
22980 "Detach overlay INDEX."
22981 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22983 ;; FIXME this is currently not used.
22984 (defun org-highlight-until-next-command (beg end &optional buffer)
22985 (org-highlight beg end buffer)
22986 (add-hook 'pre-command-hook 'org-unhighlight-once))
22987 (defun org-unhighlight-once ()
22988 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22989 (org-unhighlight))
22991 (defun org-agenda-follow-mode ()
22992 "Toggle follow mode in an agenda buffer."
22993 (interactive)
22994 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22995 (org-agenda-set-mode-name)
22996 (message "Follow mode is %s"
22997 (if org-agenda-follow-mode "on" "off")))
22999 (defun org-agenda-log-mode ()
23000 "Toggle log mode in an agenda buffer."
23001 (interactive)
23002 (org-agenda-check-type t 'agenda 'timeline)
23003 (setq org-agenda-show-log (not org-agenda-show-log))
23004 (org-agenda-set-mode-name)
23005 (org-agenda-redo)
23006 (message "Log mode is %s"
23007 (if org-agenda-show-log "on" "off")))
23009 (defun org-agenda-toggle-diary ()
23010 "Toggle diary inclusion in an agenda buffer."
23011 (interactive)
23012 (org-agenda-check-type t 'agenda)
23013 (setq org-agenda-include-diary (not org-agenda-include-diary))
23014 (org-agenda-redo)
23015 (org-agenda-set-mode-name)
23016 (message "Diary inclusion turned %s"
23017 (if org-agenda-include-diary "on" "off")))
23019 (defun org-agenda-toggle-time-grid ()
23020 "Toggle time grid in an agenda buffer."
23021 (interactive)
23022 (org-agenda-check-type t 'agenda)
23023 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
23024 (org-agenda-redo)
23025 (org-agenda-set-mode-name)
23026 (message "Time-grid turned %s"
23027 (if org-agenda-use-time-grid "on" "off")))
23029 (defun org-agenda-set-mode-name ()
23030 "Set the mode name to indicate all the small mode settings."
23031 (setq mode-name
23032 (concat "Org-Agenda"
23033 (if (equal org-agenda-ndays 1) " Day" "")
23034 (if (equal org-agenda-ndays 7) " Week" "")
23035 (if org-agenda-follow-mode " Follow" "")
23036 (if org-agenda-include-diary " Diary" "")
23037 (if org-agenda-use-time-grid " Grid" "")
23038 (if org-agenda-show-log " Log" "")))
23039 (force-mode-line-update))
23041 (defun org-agenda-post-command-hook ()
23042 (and (eolp) (not (bolp)) (backward-char 1))
23043 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
23044 (if (and org-agenda-follow-mode
23045 (get-text-property (point) 'org-marker))
23046 (org-agenda-show)))
23048 (defun org-agenda-show-priority ()
23049 "Show the priority of the current item.
23050 This priority is composed of the main priority given with the [#A] cookies,
23051 and by additional input from the age of a schedules or deadline entry."
23052 (interactive)
23053 (let* ((pri (get-text-property (point-at-bol) 'priority)))
23054 (message "Priority is %d" (if pri pri -1000))))
23056 (defun org-agenda-show-tags ()
23057 "Show the tags applicable to the current item."
23058 (interactive)
23059 (let* ((tags (get-text-property (point-at-bol) 'tags)))
23060 (if tags
23061 (message "Tags are :%s:"
23062 (org-no-properties (mapconcat 'identity tags ":")))
23063 (message "No tags associated with this line"))))
23065 (defun org-agenda-goto (&optional highlight)
23066 "Go to the Org-mode file which contains the item at point."
23067 (interactive)
23068 (let* ((marker (or (get-text-property (point) 'org-marker)
23069 (org-agenda-error)))
23070 (buffer (marker-buffer marker))
23071 (pos (marker-position marker)))
23072 (switch-to-buffer-other-window buffer)
23073 (widen)
23074 (goto-char pos)
23075 (when (org-mode-p)
23076 (org-show-context 'agenda)
23077 (save-excursion
23078 (and (outline-next-heading)
23079 (org-flag-heading nil)))) ; show the next heading
23080 (recenter (/ (window-height) 2))
23081 (run-hooks 'org-agenda-after-show-hook)
23082 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
23084 (defvar org-agenda-after-show-hook nil
23085 "Normal hook run after an item has been shown from the agenda.
23086 Point is in the buffer where the item originated.")
23088 (defun org-agenda-kill ()
23089 "Kill the entry or subtree belonging to the current agenda entry."
23090 (interactive)
23091 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
23092 (let* ((marker (or (get-text-property (point) 'org-marker)
23093 (org-agenda-error)))
23094 (buffer (marker-buffer marker))
23095 (pos (marker-position marker))
23096 (type (get-text-property (point) 'type))
23097 dbeg dend (n 0) conf)
23098 (org-with-remote-undo buffer
23099 (with-current-buffer buffer
23100 (save-excursion
23101 (goto-char pos)
23102 (if (and (org-mode-p) (not (member type '("sexp"))))
23103 (setq dbeg (progn (org-back-to-heading t) (point))
23104 dend (org-end-of-subtree t t))
23105 (setq dbeg (point-at-bol)
23106 dend (min (point-max) (1+ (point-at-eol)))))
23107 (goto-char dbeg)
23108 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
23109 (setq conf (or (eq t org-agenda-confirm-kill)
23110 (and (numberp org-agenda-confirm-kill)
23111 (> n org-agenda-confirm-kill))))
23112 (and conf
23113 (not (y-or-n-p
23114 (format "Delete entry with %d lines in buffer \"%s\"? "
23115 n (buffer-name buffer))))
23116 (error "Abort"))
23117 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
23118 (with-current-buffer buffer (delete-region dbeg dend))
23119 (message "Agenda item and source killed"))))
23121 (defun org-agenda-archive ()
23122 "Kill the entry or subtree belonging to the current agenda entry."
23123 (interactive)
23124 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
23125 (let* ((marker (or (get-text-property (point) 'org-marker)
23126 (org-agenda-error)))
23127 (buffer (marker-buffer marker))
23128 (pos (marker-position marker)))
23129 (org-with-remote-undo buffer
23130 (with-current-buffer buffer
23131 (if (org-mode-p)
23132 (save-excursion
23133 (goto-char pos)
23134 (org-remove-subtree-entries-from-agenda)
23135 (org-back-to-heading t)
23136 (org-archive-subtree))
23137 (error "Archiving works only in Org-mode files"))))))
23139 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
23140 "Remove all lines in the agenda that correspond to a given subtree.
23141 The subtree is the one in buffer BUF, starting at BEG and ending at END.
23142 If this information is not given, the function uses the tree at point."
23143 (let ((buf (or buf (current-buffer))) m p)
23144 (save-excursion
23145 (unless (and beg end)
23146 (org-back-to-heading t)
23147 (setq beg (point))
23148 (org-end-of-subtree t)
23149 (setq end (point)))
23150 (set-buffer (get-buffer org-agenda-buffer-name))
23151 (save-excursion
23152 (goto-char (point-max))
23153 (beginning-of-line 1)
23154 (while (not (bobp))
23155 (when (and (setq m (get-text-property (point) 'org-marker))
23156 (equal buf (marker-buffer m))
23157 (setq p (marker-position m))
23158 (>= p beg)
23159 (<= p end))
23160 (let ((inhibit-read-only t))
23161 (delete-region (point-at-bol) (1+ (point-at-eol)))))
23162 (beginning-of-line 0))))))
23164 (defun org-agenda-open-link ()
23165 "Follow the link in the current line, if any."
23166 (interactive)
23167 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
23168 (save-excursion
23169 (save-restriction
23170 (narrow-to-region (point-at-bol) (point-at-eol))
23171 (org-open-at-point))))
23173 (defun org-agenda-copy-local-variable (var)
23174 "Get a variable from a referenced buffer and install it here."
23175 (let ((m (get-text-property (point) 'org-marker)))
23176 (when (and m (buffer-live-p (marker-buffer m)))
23177 (org-set-local var (with-current-buffer (marker-buffer m)
23178 (symbol-value var))))))
23180 (defun org-agenda-switch-to (&optional delete-other-windows)
23181 "Go to the Org-mode file which contains the item at point."
23182 (interactive)
23183 (let* ((marker (or (get-text-property (point) 'org-marker)
23184 (org-agenda-error)))
23185 (buffer (marker-buffer marker))
23186 (pos (marker-position marker)))
23187 (switch-to-buffer buffer)
23188 (and delete-other-windows (delete-other-windows))
23189 (widen)
23190 (goto-char pos)
23191 (when (org-mode-p)
23192 (org-show-context 'agenda)
23193 (save-excursion
23194 (and (outline-next-heading)
23195 (org-flag-heading nil)))))) ; show the next heading
23197 (defun org-agenda-goto-mouse (ev)
23198 "Go to the Org-mode file which contains the item at the mouse click."
23199 (interactive "e")
23200 (mouse-set-point ev)
23201 (org-agenda-goto))
23203 (defun org-agenda-show ()
23204 "Display the Org-mode file which contains the item at point."
23205 (interactive)
23206 (let ((win (selected-window)))
23207 (org-agenda-goto t)
23208 (select-window win)))
23210 (defun org-agenda-recenter (arg)
23211 "Display the Org-mode file which contains the item at point and recenter."
23212 (interactive "P")
23213 (let ((win (selected-window)))
23214 (org-agenda-goto t)
23215 (recenter arg)
23216 (select-window win)))
23218 (defun org-agenda-show-mouse (ev)
23219 "Display the Org-mode file which contains the item at the mouse click."
23220 (interactive "e")
23221 (mouse-set-point ev)
23222 (org-agenda-show))
23224 (defun org-agenda-check-no-diary ()
23225 "Check if the entry is a diary link and abort if yes."
23226 (if (get-text-property (point) 'org-agenda-diary-link)
23227 (org-agenda-error)))
23229 (defun org-agenda-error ()
23230 (error "Command not allowed in this line"))
23232 (defun org-agenda-tree-to-indirect-buffer ()
23233 "Show the subtree corresponding to the current entry in an indirect buffer.
23234 This calls the command `org-tree-to-indirect-buffer' from the original
23235 Org-mode buffer.
23236 With numerical prefix arg ARG, go up to this level and then take that tree.
23237 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
23238 dedicated frame)."
23239 (interactive)
23240 (org-agenda-check-no-diary)
23241 (let* ((marker (or (get-text-property (point) 'org-marker)
23242 (org-agenda-error)))
23243 (buffer (marker-buffer marker))
23244 (pos (marker-position marker)))
23245 (with-current-buffer buffer
23246 (save-excursion
23247 (goto-char pos)
23248 (call-interactively 'org-tree-to-indirect-buffer)))))
23250 (defvar org-last-heading-marker (make-marker)
23251 "Marker pointing to the headline that last changed its TODO state
23252 by a remote command from the agenda.")
23254 (defun org-agenda-todo-nextset ()
23255 "Switch TODO entry to next sequence."
23256 (interactive)
23257 (org-agenda-todo 'nextset))
23259 (defun org-agenda-todo-previousset ()
23260 "Switch TODO entry to previous sequence."
23261 (interactive)
23262 (org-agenda-todo 'previousset))
23264 (defun org-agenda-todo (&optional arg)
23265 "Cycle TODO state of line at point, also in Org-mode file.
23266 This changes the line at point, all other lines in the agenda referring to
23267 the same tree node, and the headline of the tree node in the Org-mode file."
23268 (interactive "P")
23269 (org-agenda-check-no-diary)
23270 (let* ((col (current-column))
23271 (marker (or (get-text-property (point) 'org-marker)
23272 (org-agenda-error)))
23273 (buffer (marker-buffer marker))
23274 (pos (marker-position marker))
23275 (hdmarker (get-text-property (point) 'org-hd-marker))
23276 (inhibit-read-only t)
23277 newhead)
23278 (org-with-remote-undo buffer
23279 (with-current-buffer buffer
23280 (widen)
23281 (goto-char pos)
23282 (org-show-context 'agenda)
23283 (save-excursion
23284 (and (outline-next-heading)
23285 (org-flag-heading nil))) ; show the next heading
23286 (org-todo arg)
23287 (and (bolp) (forward-char 1))
23288 (setq newhead (org-get-heading))
23289 (save-excursion
23290 (org-back-to-heading)
23291 (move-marker org-last-heading-marker (point))))
23292 (beginning-of-line 1)
23293 (save-excursion
23294 (org-agenda-change-all-lines newhead hdmarker 'fixface))
23295 (move-to-column col))))
23297 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
23298 "Change all lines in the agenda buffer which match HDMARKER.
23299 The new content of the line will be NEWHEAD (as modified by
23300 `org-format-agenda-item'). HDMARKER is checked with
23301 `equal' against all `org-hd-marker' text properties in the file.
23302 If FIXFACE is non-nil, the face of each item is modified acording to
23303 the new TODO state."
23304 (let* ((inhibit-read-only t)
23305 props m pl undone-face done-face finish new dotime cat tags)
23306 (save-excursion
23307 (goto-char (point-max))
23308 (beginning-of-line 1)
23309 (while (not finish)
23310 (setq finish (bobp))
23311 (when (and (setq m (get-text-property (point) 'org-hd-marker))
23312 (equal m hdmarker))
23313 (setq props (text-properties-at (point))
23314 dotime (get-text-property (point) 'dotime)
23315 cat (get-text-property (point) 'org-category)
23316 tags (get-text-property (point) 'tags)
23317 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
23318 pl (get-text-property (point) 'prefix-length)
23319 undone-face (get-text-property (point) 'undone-face)
23320 done-face (get-text-property (point) 'done-face))
23321 (move-to-column pl)
23322 (cond
23323 ((equal new "")
23324 (beginning-of-line 1)
23325 (and (looking-at ".*\n?") (replace-match "")))
23326 ((looking-at ".*")
23327 (replace-match new t t)
23328 (beginning-of-line 1)
23329 (add-text-properties (point-at-bol) (point-at-eol) props)
23330 (when fixface
23331 (add-text-properties
23332 (point-at-bol) (point-at-eol)
23333 (list 'face
23334 (if org-last-todo-state-is-todo
23335 undone-face done-face))))
23336 (org-agenda-highlight-todo 'line)
23337 (beginning-of-line 1))
23338 (t (error "Line update did not work"))))
23339 (beginning-of-line 0)))
23340 (org-finalize-agenda)))
23342 (defun org-agenda-align-tags (&optional line)
23343 "Align all tags in agenda items to `org-agenda-tags-column'."
23344 (let ((inhibit-read-only t) l c)
23345 (save-excursion
23346 (goto-char (if line (point-at-bol) (point-min)))
23347 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
23348 (if line (point-at-eol) nil) t)
23349 (add-text-properties
23350 (match-beginning 2) (match-end 2)
23351 (list 'face (delq nil (list 'org-tag (get-text-property
23352 (match-beginning 2) 'face)))))
23353 (setq l (- (match-end 2) (match-beginning 2))
23354 c (if (< org-agenda-tags-column 0)
23355 (- (abs org-agenda-tags-column) l)
23356 org-agenda-tags-column))
23357 (delete-region (match-beginning 1) (match-end 1))
23358 (goto-char (match-beginning 1))
23359 (insert (org-add-props
23360 (make-string (max 1 (- c (current-column))) ?\ )
23361 (text-properties-at (point))))))))
23363 (defun org-agenda-priority-up ()
23364 "Increase the priority of line at point, also in Org-mode file."
23365 (interactive)
23366 (org-agenda-priority 'up))
23368 (defun org-agenda-priority-down ()
23369 "Decrease the priority of line at point, also in Org-mode file."
23370 (interactive)
23371 (org-agenda-priority 'down))
23373 (defun org-agenda-priority (&optional force-direction)
23374 "Set the priority of line at point, also in Org-mode file.
23375 This changes the line at point, all other lines in the agenda referring to
23376 the same tree node, and the headline of the tree node in the Org-mode file."
23377 (interactive)
23378 (org-agenda-check-no-diary)
23379 (let* ((marker (or (get-text-property (point) 'org-marker)
23380 (org-agenda-error)))
23381 (hdmarker (get-text-property (point) 'org-hd-marker))
23382 (buffer (marker-buffer hdmarker))
23383 (pos (marker-position hdmarker))
23384 (inhibit-read-only t)
23385 newhead)
23386 (org-with-remote-undo buffer
23387 (with-current-buffer buffer
23388 (widen)
23389 (goto-char pos)
23390 (org-show-context 'agenda)
23391 (save-excursion
23392 (and (outline-next-heading)
23393 (org-flag-heading nil))) ; show the next heading
23394 (funcall 'org-priority force-direction)
23395 (end-of-line 1)
23396 (setq newhead (org-get-heading)))
23397 (org-agenda-change-all-lines newhead hdmarker)
23398 (beginning-of-line 1))))
23400 (defun org-get-tags-at (&optional pos)
23401 "Get a list of all headline tags applicable at POS.
23402 POS defaults to point. If tags are inherited, the list contains
23403 the targets in the same sequence as the headlines appear, i.e.
23404 the tags of the current headline come last."
23405 (interactive)
23406 (let (tags lastpos)
23407 (save-excursion
23408 (save-restriction
23409 (widen)
23410 (goto-char (or pos (point)))
23411 (save-match-data
23412 (condition-case nil
23413 (progn
23414 (org-back-to-heading t)
23415 (while (not (equal lastpos (point)))
23416 (setq lastpos (point))
23417 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
23418 (setq tags (append (org-split-string
23419 (org-match-string-no-properties 1) ":")
23420 tags)))
23421 (or org-use-tag-inheritance (error ""))
23422 (org-up-heading-all 1)))
23423 (error nil))))
23424 tags)))
23426 ;; FIXME: should fix the tags property of the agenda line.
23427 (defun org-agenda-set-tags ()
23428 "Set tags for the current headline."
23429 (interactive)
23430 (org-agenda-check-no-diary)
23431 (if (and (org-region-active-p) (interactive-p))
23432 (call-interactively 'org-change-tag-in-region)
23433 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23434 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23435 (org-agenda-error)))
23436 (buffer (marker-buffer hdmarker))
23437 (pos (marker-position hdmarker))
23438 (inhibit-read-only t)
23439 newhead)
23440 (org-with-remote-undo buffer
23441 (with-current-buffer buffer
23442 (widen)
23443 (goto-char pos)
23444 (save-excursion
23445 (org-show-context 'agenda))
23446 (save-excursion
23447 (and (outline-next-heading)
23448 (org-flag-heading nil))) ; show the next heading
23449 (goto-char pos)
23450 (call-interactively 'org-set-tags)
23451 (end-of-line 1)
23452 (setq newhead (org-get-heading)))
23453 (org-agenda-change-all-lines newhead hdmarker)
23454 (beginning-of-line 1)))))
23456 (defun org-agenda-toggle-archive-tag ()
23457 "Toggle the archive tag for the current entry."
23458 (interactive)
23459 (org-agenda-check-no-diary)
23460 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23461 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23462 (org-agenda-error)))
23463 (buffer (marker-buffer hdmarker))
23464 (pos (marker-position hdmarker))
23465 (inhibit-read-only t)
23466 newhead)
23467 (org-with-remote-undo buffer
23468 (with-current-buffer buffer
23469 (widen)
23470 (goto-char pos)
23471 (org-show-context 'agenda)
23472 (save-excursion
23473 (and (outline-next-heading)
23474 (org-flag-heading nil))) ; show the next heading
23475 (call-interactively 'org-toggle-archive-tag)
23476 (end-of-line 1)
23477 (setq newhead (org-get-heading)))
23478 (org-agenda-change-all-lines newhead hdmarker)
23479 (beginning-of-line 1))))
23481 (defun org-agenda-date-later (arg &optional what)
23482 "Change the date of this item to one day later."
23483 (interactive "p")
23484 (org-agenda-check-type t 'agenda 'timeline)
23485 (org-agenda-check-no-diary)
23486 (let* ((marker (or (get-text-property (point) 'org-marker)
23487 (org-agenda-error)))
23488 (buffer (marker-buffer marker))
23489 (pos (marker-position marker)))
23490 (org-with-remote-undo buffer
23491 (with-current-buffer buffer
23492 (widen)
23493 (goto-char pos)
23494 (if (not (org-at-timestamp-p))
23495 (error "Cannot find time stamp"))
23496 (org-timestamp-change arg (or what 'day)))
23497 (org-agenda-show-new-time marker org-last-changed-timestamp))
23498 (message "Time stamp changed to %s" org-last-changed-timestamp)))
23500 (defun org-agenda-date-earlier (arg &optional what)
23501 "Change the date of this item to one day earlier."
23502 (interactive "p")
23503 (org-agenda-date-later (- arg) what))
23505 (defun org-agenda-show-new-time (marker stamp &optional prefix)
23506 "Show new date stamp via text properties."
23507 ;; We use text properties to make this undoable
23508 (let ((inhibit-read-only t))
23509 (setq stamp (concat " " prefix " => " stamp))
23510 (save-excursion
23511 (goto-char (point-max))
23512 (while (not (bobp))
23513 (when (equal marker (get-text-property (point) 'org-marker))
23514 (move-to-column (- (window-width) (length stamp)) t)
23515 (if (featurep 'xemacs)
23516 ;; Use `duplicable' property to trigger undo recording
23517 (let ((ex (make-extent nil nil))
23518 (gl (make-glyph stamp)))
23519 (set-glyph-face gl 'secondary-selection)
23520 (set-extent-properties
23521 ex (list 'invisible t 'end-glyph gl 'duplicable t))
23522 (insert-extent ex (1- (point)) (point-at-eol)))
23523 (add-text-properties
23524 (1- (point)) (point-at-eol)
23525 (list 'display (org-add-props stamp nil
23526 'face 'secondary-selection))))
23527 (beginning-of-line 1))
23528 (beginning-of-line 0)))))
23530 (defun org-agenda-date-prompt (arg)
23531 "Change the date of this item. Date is prompted for, with default today.
23532 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23533 be used to request time specification in the time stamp."
23534 (interactive "P")
23535 (org-agenda-check-type t 'agenda 'timeline)
23536 (org-agenda-check-no-diary)
23537 (let* ((marker (or (get-text-property (point) 'org-marker)
23538 (org-agenda-error)))
23539 (buffer (marker-buffer marker))
23540 (pos (marker-position marker)))
23541 (org-with-remote-undo buffer
23542 (with-current-buffer buffer
23543 (widen)
23544 (goto-char pos)
23545 (if (not (org-at-timestamp-p))
23546 (error "Cannot find time stamp"))
23547 (org-time-stamp arg)
23548 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23550 (defun org-agenda-schedule (arg)
23551 "Schedule the item at point."
23552 (interactive "P")
23553 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23554 (org-agenda-check-no-diary)
23555 (let* ((marker (or (get-text-property (point) 'org-marker)
23556 (org-agenda-error)))
23557 (type (marker-insertion-type marker))
23558 (buffer (marker-buffer marker))
23559 (pos (marker-position marker))
23560 (org-insert-labeled-timestamps-at-point nil)
23562 (when type (message "%s" type) (sit-for 3))
23563 (set-marker-insertion-type marker t)
23564 (org-with-remote-undo buffer
23565 (with-current-buffer buffer
23566 (widen)
23567 (goto-char pos)
23568 (setq ts (org-schedule arg)))
23569 (org-agenda-show-new-time marker ts "S"))
23570 (message "Item scheduled for %s" ts)))
23572 (defun org-agenda-deadline (arg)
23573 "Schedule the item at point."
23574 (interactive "P")
23575 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23576 (org-agenda-check-no-diary)
23577 (let* ((marker (or (get-text-property (point) 'org-marker)
23578 (org-agenda-error)))
23579 (buffer (marker-buffer marker))
23580 (pos (marker-position marker))
23581 (org-insert-labeled-timestamps-at-point nil)
23583 (org-with-remote-undo buffer
23584 (with-current-buffer buffer
23585 (widen)
23586 (goto-char pos)
23587 (setq ts (org-deadline arg)))
23588 (org-agenda-show-new-time marker ts "S"))
23589 (message "Deadline for this item set to %s" ts)))
23591 (defun org-get-heading (&optional no-tags)
23592 "Return the heading of the current entry, without the stars."
23593 (save-excursion
23594 (org-back-to-heading t)
23595 (if (looking-at
23596 (if no-tags
23597 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23598 "\\*+[ \t]+\\([^\r\n]*\\)"))
23599 (match-string 1) "")))
23601 (defun org-agenda-clock-in (&optional arg)
23602 "Start the clock on the currently selected item."
23603 (interactive "P")
23604 (org-agenda-check-no-diary)
23605 (let* ((marker (or (get-text-property (point) 'org-marker)
23606 (org-agenda-error)))
23607 (pos (marker-position marker)))
23608 (org-with-remote-undo (marker-buffer marker)
23609 (with-current-buffer (marker-buffer marker)
23610 (widen)
23611 (goto-char pos)
23612 (org-clock-in)))))
23614 (defun org-agenda-clock-out (&optional arg)
23615 "Stop the currently running clock."
23616 (interactive "P")
23617 (unless (marker-buffer org-clock-marker)
23618 (error "No running clock"))
23619 (org-with-remote-undo (marker-buffer org-clock-marker)
23620 (org-clock-out)))
23622 (defun org-agenda-clock-cancel (&optional arg)
23623 "Cancel the currently running clock."
23624 (interactive "P")
23625 (unless (marker-buffer org-clock-marker)
23626 (error "No running clock"))
23627 (org-with-remote-undo (marker-buffer org-clock-marker)
23628 (org-clock-cancel)))
23630 (defun org-agenda-diary-entry ()
23631 "Make a diary entry, like the `i' command from the calendar.
23632 All the standard commands work: block, weekly etc."
23633 (interactive)
23634 (org-agenda-check-type t 'agenda 'timeline)
23635 (require 'diary-lib)
23636 (let* ((char (progn
23637 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23638 (read-char-exclusive)))
23639 (cmd (cdr (assoc char
23640 '((?d . insert-diary-entry)
23641 (?w . insert-weekly-diary-entry)
23642 (?m . insert-monthly-diary-entry)
23643 (?y . insert-yearly-diary-entry)
23644 (?a . insert-anniversary-diary-entry)
23645 (?b . insert-block-diary-entry)
23646 (?c . insert-cyclic-diary-entry)))))
23647 (oldf (symbol-function 'calendar-cursor-to-date))
23648 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23649 (point (point))
23650 (mark (or (mark t) (point))))
23651 (unless cmd
23652 (error "No command associated with <%c>" char))
23653 (unless (and (get-text-property point 'day)
23654 (or (not (equal ?b char))
23655 (get-text-property mark 'day)))
23656 (error "Don't know which date to use for diary entry"))
23657 ;; We implement this by hacking the `calendar-cursor-to-date' function
23658 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23659 (let ((calendar-mark-ring
23660 (list (calendar-gregorian-from-absolute
23661 (or (get-text-property mark 'day)
23662 (get-text-property point 'day))))))
23663 (unwind-protect
23664 (progn
23665 (fset 'calendar-cursor-to-date
23666 (lambda (&optional error)
23667 (calendar-gregorian-from-absolute
23668 (get-text-property point 'day))))
23669 (call-interactively cmd))
23670 (fset 'calendar-cursor-to-date oldf)))))
23673 (defun org-agenda-execute-calendar-command (cmd)
23674 "Execute a calendar command from the agenda, with the date associated to
23675 the cursor position."
23676 (org-agenda-check-type t 'agenda 'timeline)
23677 (require 'diary-lib)
23678 (unless (get-text-property (point) 'day)
23679 (error "Don't know which date to use for calendar command"))
23680 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23681 (point (point))
23682 (date (calendar-gregorian-from-absolute
23683 (get-text-property point 'day)))
23684 ;; the following 3 vars are needed in the calendar
23685 (displayed-day (extract-calendar-day date))
23686 (displayed-month (extract-calendar-month date))
23687 (displayed-year (extract-calendar-year date)))
23688 (unwind-protect
23689 (progn
23690 (fset 'calendar-cursor-to-date
23691 (lambda (&optional error)
23692 (calendar-gregorian-from-absolute
23693 (get-text-property point 'day))))
23694 (call-interactively cmd))
23695 (fset 'calendar-cursor-to-date oldf))))
23697 (defun org-agenda-phases-of-moon ()
23698 "Display the phases of the moon for the 3 months around the cursor date."
23699 (interactive)
23700 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23702 (defun org-agenda-holidays ()
23703 "Display the holidays for the 3 months around the cursor date."
23704 (interactive)
23705 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23707 (defvar calendar-longitude)
23708 (defvar calendar-latitude)
23709 (defvar calendar-location-name)
23711 (defun org-agenda-sunrise-sunset (arg)
23712 "Display sunrise and sunset for the cursor date.
23713 Latitude and longitude can be specified with the variables
23714 `calendar-latitude' and `calendar-longitude'. When called with prefix
23715 argument, latitude and longitude will be prompted for."
23716 (interactive "P")
23717 (require 'solar)
23718 (let ((calendar-longitude (if arg nil calendar-longitude))
23719 (calendar-latitude (if arg nil calendar-latitude))
23720 (calendar-location-name
23721 (if arg "the given coordinates" calendar-location-name)))
23722 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23724 (defun org-agenda-goto-calendar ()
23725 "Open the Emacs calendar with the date at the cursor."
23726 (interactive)
23727 (org-agenda-check-type t 'agenda 'timeline)
23728 (let* ((day (or (get-text-property (point) 'day)
23729 (error "Don't know which date to open in calendar")))
23730 (date (calendar-gregorian-from-absolute day))
23731 (calendar-move-hook nil)
23732 (view-calendar-holidays-initially nil)
23733 (view-diary-entries-initially nil))
23734 (calendar)
23735 (calendar-goto-date date)))
23737 (defun org-calendar-goto-agenda ()
23738 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23739 This is a command that has to be installed in `calendar-mode-map'."
23740 (interactive)
23741 (org-agenda-list nil (calendar-absolute-from-gregorian
23742 (calendar-cursor-to-date))
23743 nil))
23745 (defun org-agenda-convert-date ()
23746 (interactive)
23747 (org-agenda-check-type t 'agenda 'timeline)
23748 (let ((day (get-text-property (point) 'day))
23749 date s)
23750 (unless day
23751 (error "Don't know which date to convert"))
23752 (setq date (calendar-gregorian-from-absolute day))
23753 (setq s (concat
23754 "Gregorian: " (calendar-date-string date) "\n"
23755 "ISO: " (calendar-iso-date-string date) "\n"
23756 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23757 "Julian: " (calendar-julian-date-string date) "\n"
23758 "Astron. JD: " (calendar-astro-date-string date)
23759 " (Julian date number at noon UTC)\n"
23760 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23761 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23762 "French: " (calendar-french-date-string date) "\n"
23763 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23764 "Mayan: " (calendar-mayan-date-string date) "\n"
23765 "Coptic: " (calendar-coptic-date-string date) "\n"
23766 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23767 "Persian: " (calendar-persian-date-string date) "\n"
23768 "Chinese: " (calendar-chinese-date-string date) "\n"))
23769 (with-output-to-temp-buffer "*Dates*"
23770 (princ s))
23771 (if (fboundp 'fit-window-to-buffer)
23772 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23775 ;;;; Embedded LaTeX
23777 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23778 "Keymap for the minor `org-cdlatex-mode'.")
23780 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23781 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23782 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23783 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23784 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23786 (defvar org-cdlatex-texmathp-advice-is-done nil
23787 "Flag remembering if we have applied the advice to texmathp already.")
23789 (define-minor-mode org-cdlatex-mode
23790 "Toggle the minor `org-cdlatex-mode'.
23791 This mode supports entering LaTeX environment and math in LaTeX fragments
23792 in Org-mode.
23793 \\{org-cdlatex-mode-map}"
23794 nil " OCDL" nil
23795 (when org-cdlatex-mode (require 'cdlatex))
23796 (unless org-cdlatex-texmathp-advice-is-done
23797 (setq org-cdlatex-texmathp-advice-is-done t)
23798 (defadvice texmathp (around org-math-always-on activate)
23799 "Always return t in org-mode buffers.
23800 This is because we want to insert math symbols without dollars even outside
23801 the LaTeX math segments. If Orgmode thinks that point is actually inside
23802 en embedded LaTeX fragement, let texmathp do its job.
23803 \\[org-cdlatex-mode-map]"
23804 (interactive)
23805 (let (p)
23806 (cond
23807 ((not (org-mode-p)) ad-do-it)
23808 ((eq this-command 'cdlatex-math-symbol)
23809 (setq ad-return-value t
23810 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23812 (let ((p (org-inside-LaTeX-fragment-p)))
23813 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23814 (setq ad-return-value t
23815 texmathp-why '("Org-mode embedded math" . 0))
23816 (if p ad-do-it)))))))))
23818 (defun turn-on-org-cdlatex ()
23819 "Unconditionally turn on `org-cdlatex-mode'."
23820 (org-cdlatex-mode 1))
23822 (defun org-inside-LaTeX-fragment-p ()
23823 "Test if point is inside a LaTeX fragment.
23824 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23825 sequence appearing also before point.
23826 Even though the matchers for math are configurable, this function assumes
23827 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23828 delimiters are skipped when they have been removed by customization.
23829 The return value is nil, or a cons cell with the delimiter and
23830 and the position of this delimiter.
23832 This function does a reasonably good job, but can locally be fooled by
23833 for example currency specifications. For example it will assume being in
23834 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23835 fragments that are properly closed, but during editing, we have to live
23836 with the uncertainty caused by missing closing delimiters. This function
23837 looks only before point, not after."
23838 (catch 'exit
23839 (let ((pos (point))
23840 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23841 (lim (progn
23842 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23843 (point)))
23844 dd-on str (start 0) m re)
23845 (goto-char pos)
23846 (when dodollar
23847 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23848 re (nth 1 (assoc "$" org-latex-regexps)))
23849 (while (string-match re str start)
23850 (cond
23851 ((= (match-end 0) (length str))
23852 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23853 ((= (match-end 0) (- (length str) 5))
23854 (throw 'exit nil))
23855 (t (setq start (match-end 0))))))
23856 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23857 (goto-char pos)
23858 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23859 (and (match-beginning 2) (throw 'exit nil))
23860 ;; count $$
23861 (while (re-search-backward "\\$\\$" lim t)
23862 (setq dd-on (not dd-on)))
23863 (goto-char pos)
23864 (if dd-on (cons "$$" m))))))
23867 (defun org-try-cdlatex-tab ()
23868 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23869 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23870 - inside a LaTeX fragment, or
23871 - after the first word in a line, where an abbreviation expansion could
23872 insert a LaTeX environment."
23873 (when org-cdlatex-mode
23874 (cond
23875 ((save-excursion
23876 (skip-chars-backward "a-zA-Z0-9*")
23877 (skip-chars-backward " \t")
23878 (bolp))
23879 (cdlatex-tab) t)
23880 ((org-inside-LaTeX-fragment-p)
23881 (cdlatex-tab) t)
23882 (t nil))))
23884 (defun org-cdlatex-underscore-caret (&optional arg)
23885 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23886 Revert to the normal definition outside of these fragments."
23887 (interactive "P")
23888 (if (org-inside-LaTeX-fragment-p)
23889 (call-interactively 'cdlatex-sub-superscript)
23890 (let (org-cdlatex-mode)
23891 (call-interactively (key-binding (vector last-input-event))))))
23893 (defun org-cdlatex-math-modify (&optional arg)
23894 "Execute `cdlatex-math-modify' in LaTeX fragments.
23895 Revert to the normal definition outside of these fragments."
23896 (interactive "P")
23897 (if (org-inside-LaTeX-fragment-p)
23898 (call-interactively 'cdlatex-math-modify)
23899 (let (org-cdlatex-mode)
23900 (call-interactively (key-binding (vector last-input-event))))))
23902 (defvar org-latex-fragment-image-overlays nil
23903 "List of overlays carrying the images of latex fragments.")
23904 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23906 (defun org-remove-latex-fragment-image-overlays ()
23907 "Remove all overlays with LaTeX fragment images in current buffer."
23908 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23909 (setq org-latex-fragment-image-overlays nil))
23911 (defun org-preview-latex-fragment (&optional subtree)
23912 "Preview the LaTeX fragment at point, or all locally or globally.
23913 If the cursor is in a LaTeX fragment, create the image and overlay
23914 it over the source code. If there is no fragment at point, display
23915 all fragments in the current text, from one headline to the next. With
23916 prefix SUBTREE, display all fragments in the current subtree. With a
23917 double prefix `C-u C-u', or when the cursor is before the first headline,
23918 display all fragments in the buffer.
23919 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23920 (interactive "P")
23921 (org-remove-latex-fragment-image-overlays)
23922 (save-excursion
23923 (save-restriction
23924 (let (beg end at msg)
23925 (cond
23926 ((or (equal subtree '(16))
23927 (not (save-excursion
23928 (re-search-backward (concat "^" outline-regexp) nil t))))
23929 (setq beg (point-min) end (point-max)
23930 msg "Creating images for buffer...%s"))
23931 ((equal subtree '(4))
23932 (org-back-to-heading)
23933 (setq beg (point) end (org-end-of-subtree t)
23934 msg "Creating images for subtree...%s"))
23936 (if (setq at (org-inside-LaTeX-fragment-p))
23937 (goto-char (max (point-min) (- (cdr at) 2)))
23938 (org-back-to-heading))
23939 (setq beg (point) end (progn (outline-next-heading) (point))
23940 msg (if at "Creating image...%s"
23941 "Creating images for entry...%s"))))
23942 (message msg "")
23943 (narrow-to-region beg end)
23944 (goto-char beg)
23945 (org-format-latex
23946 (concat "ltxpng/" (file-name-sans-extension
23947 (file-name-nondirectory
23948 buffer-file-name)))
23949 default-directory 'overlays msg at 'forbuffer)
23950 (message msg "done. Use `C-c C-c' to remove images.")))))
23952 (defvar org-latex-regexps
23953 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23954 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23955 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23956 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23957 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23958 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23959 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23960 "Regular expressions for matching embedded LaTeX.")
23962 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23963 "Replace LaTeX fragments with links to an image, and produce images."
23964 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23965 (let* ((prefixnodir (file-name-nondirectory prefix))
23966 (absprefix (expand-file-name prefix dir))
23967 (todir (file-name-directory absprefix))
23968 (opt org-format-latex-options)
23969 (matchers (plist-get opt :matchers))
23970 (re-list org-latex-regexps)
23971 (cnt 0) txt link beg end re e checkdir
23972 m n block linkfile movefile ov)
23973 ;; Check if there are old images files with this prefix, and remove them
23974 (when (file-directory-p todir)
23975 (mapc 'delete-file
23976 (directory-files
23977 todir 'full
23978 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23979 ;; Check the different regular expressions
23980 (while (setq e (pop re-list))
23981 (setq m (car e) re (nth 1 e) n (nth 2 e)
23982 block (if (nth 3 e) "\n\n" ""))
23983 (when (member m matchers)
23984 (goto-char (point-min))
23985 (while (re-search-forward re nil t)
23986 (when (or (not at) (equal (cdr at) (match-beginning n)))
23987 (setq txt (match-string n)
23988 beg (match-beginning n) end (match-end n)
23989 cnt (1+ cnt)
23990 linkfile (format "%s_%04d.png" prefix cnt)
23991 movefile (format "%s_%04d.png" absprefix cnt)
23992 link (concat block "[[file:" linkfile "]]" block))
23993 (if msg (message msg cnt))
23994 (goto-char beg)
23995 (unless checkdir ; make sure the directory exists
23996 (setq checkdir t)
23997 (or (file-directory-p todir) (make-directory todir)))
23998 (org-create-formula-image
23999 txt movefile opt forbuffer)
24000 (if overlays
24001 (progn
24002 (setq ov (org-make-overlay beg end))
24003 (if (featurep 'xemacs)
24004 (progn
24005 (org-overlay-put ov 'invisible t)
24006 (org-overlay-put
24007 ov 'end-glyph
24008 (make-glyph (vector 'png :file movefile))))
24009 (org-overlay-put
24010 ov 'display
24011 (list 'image :type 'png :file movefile :ascent 'center)))
24012 (push ov org-latex-fragment-image-overlays)
24013 (goto-char end))
24014 (delete-region beg end)
24015 (insert link))))))))
24017 ;; This function borrows from Ganesh Swami's latex2png.el
24018 (defun org-create-formula-image (string tofile options buffer)
24019 (let* ((tmpdir (if (featurep 'xemacs)
24020 (temp-directory)
24021 temporary-file-directory))
24022 (texfilebase (make-temp-name
24023 (expand-file-name "orgtex" tmpdir)))
24024 (texfile (concat texfilebase ".tex"))
24025 (dvifile (concat texfilebase ".dvi"))
24026 (pngfile (concat texfilebase ".png"))
24027 (fnh (face-attribute 'default :height nil))
24028 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
24029 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
24030 (fg (or (plist-get options (if buffer :foreground :html-foreground))
24031 "Black"))
24032 (bg (or (plist-get options (if buffer :background :html-background))
24033 "Transparent")))
24034 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
24035 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
24036 (with-temp-file texfile
24037 (insert org-format-latex-header
24038 "\n\\begin{document}\n" string "\n\\end{document}\n"))
24039 (let ((dir default-directory))
24040 (condition-case nil
24041 (progn
24042 (cd tmpdir)
24043 (call-process "latex" nil nil nil texfile))
24044 (error nil))
24045 (cd dir))
24046 (if (not (file-exists-p dvifile))
24047 (progn (message "Failed to create dvi file from %s" texfile) nil)
24048 (call-process "dvipng" nil nil nil
24049 "-E" "-fg" fg "-bg" bg
24050 "-D" dpi
24051 ;;"-x" scale "-y" scale
24052 "-T" "tight"
24053 "-o" pngfile
24054 dvifile)
24055 (if (not (file-exists-p pngfile))
24056 (progn (message "Failed to create png file from %s" texfile) nil)
24057 ;; Use the requested file name and clean up
24058 (copy-file pngfile tofile 'replace)
24059 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
24060 (delete-file (concat texfilebase e)))
24061 pngfile))))
24063 (defun org-dvipng-color (attr)
24064 "Return an rgb color specification for dvipng."
24065 (apply 'format "rgb %s %s %s"
24066 (mapcar 'org-normalize-color
24067 (color-values (face-attribute 'default attr nil)))))
24069 (defun org-normalize-color (value)
24070 "Return string to be used as color value for an RGB component."
24071 (format "%g" (/ value 65535.0)))
24073 ;;;; Exporting
24075 ;;; Variables, constants, and parameter plists
24077 (defconst org-level-max 20)
24079 (defvar org-export-html-preamble nil
24080 "Preamble, to be inserted just after <body>. Set by publishing functions.")
24081 (defvar org-export-html-postamble nil
24082 "Preamble, to be inserted just before </body>. Set by publishing functions.")
24083 (defvar org-export-html-auto-preamble t
24084 "Should default preamble be inserted? Set by publishing functions.")
24085 (defvar org-export-html-auto-postamble t
24086 "Should default postamble be inserted? Set by publishing functions.")
24087 (defvar org-current-export-file nil) ; dynamically scoped parameter
24088 (defvar org-current-export-dir nil) ; dynamically scoped parameter
24091 (defconst org-export-plist-vars
24092 '((:language . org-export-default-language)
24093 (:customtime . org-display-custom-times)
24094 (:headline-levels . org-export-headline-levels)
24095 (:section-numbers . org-export-with-section-numbers)
24096 (:table-of-contents . org-export-with-toc)
24097 (:preserve-breaks . org-export-preserve-breaks)
24098 (:archived-trees . org-export-with-archived-trees)
24099 (:emphasize . org-export-with-emphasize)
24100 (:sub-superscript . org-export-with-sub-superscripts)
24101 (:special-strings . org-export-with-special-strings)
24102 (:footnotes . org-export-with-footnotes)
24103 (:drawers . org-export-with-drawers)
24104 (:tags . org-export-with-tags)
24105 (:TeX-macros . org-export-with-TeX-macros)
24106 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
24107 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
24108 (:fixed-width . org-export-with-fixed-width)
24109 (:timestamps . org-export-with-timestamps)
24110 (:author-info . org-export-author-info)
24111 (:time-stamp-file . org-export-time-stamp-file)
24112 (:tables . org-export-with-tables)
24113 (:table-auto-headline . org-export-highlight-first-table-line)
24114 (:style . org-export-html-style)
24115 (:agenda-style . org-agenda-export-html-style)
24116 (:convert-org-links . org-export-html-link-org-files-as-html)
24117 (:inline-images . org-export-html-inline-images)
24118 (:html-extension . org-export-html-extension)
24119 (:html-table-tag . org-export-html-table-tag)
24120 (:expand-quoted-html . org-export-html-expand)
24121 (:timestamp . org-export-html-with-timestamp)
24122 (:publishing-directory . org-export-publishing-directory)
24123 (:preamble . org-export-html-preamble)
24124 (:postamble . org-export-html-postamble)
24125 (:auto-preamble . org-export-html-auto-preamble)
24126 (:auto-postamble . org-export-html-auto-postamble)
24127 (:author . user-full-name)
24128 (:email . user-mail-address)))
24130 (defun org-default-export-plist ()
24131 "Return the property list with default settings for the export variables."
24132 (let ((l org-export-plist-vars) rtn e)
24133 (while (setq e (pop l))
24134 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
24135 rtn))
24137 (defun org-infile-export-plist ()
24138 "Return the property list with file-local settings for export."
24139 (save-excursion
24140 (save-restriction
24141 (widen)
24142 (goto-char 0)
24143 (let ((re (org-make-options-regexp
24144 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
24145 p key val text options)
24146 (while (re-search-forward re nil t)
24147 (setq key (org-match-string-no-properties 1)
24148 val (org-match-string-no-properties 2))
24149 (cond
24150 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
24151 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
24152 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
24153 ((string-equal key "DATE") (setq p (plist-put p :date val)))
24154 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
24155 ((string-equal key "TEXT")
24156 (setq text (if text (concat text "\n" val) val)))
24157 ((string-equal key "OPTIONS") (setq options val))))
24158 (setq p (plist-put p :text text))
24159 (when options
24160 (let ((op '(("H" . :headline-levels)
24161 ("num" . :section-numbers)
24162 ("toc" . :table-of-contents)
24163 ("\\n" . :preserve-breaks)
24164 ("@" . :expand-quoted-html)
24165 (":" . :fixed-width)
24166 ("|" . :tables)
24167 ("^" . :sub-superscript)
24168 ("-" . :special-strings)
24169 ("f" . :footnotes)
24170 ("d" . :drawers)
24171 ("tags" . :tags)
24172 ("*" . :emphasize)
24173 ("TeX" . :TeX-macros)
24174 ("LaTeX" . :LaTeX-fragments)
24175 ("skip" . :skip-before-1st-heading)
24176 ("author" . :author-info)
24177 ("timestamp" . :time-stamp-file)))
24179 (while (setq o (pop op))
24180 (if (string-match (concat (regexp-quote (car o))
24181 ":\\([^ \t\n\r;,.]*\\)")
24182 options)
24183 (setq p (plist-put p (cdr o)
24184 (car (read-from-string
24185 (match-string 1 options)))))))))
24186 p))))
24188 (defun org-export-directory (type plist)
24189 (let* ((val (plist-get plist :publishing-directory))
24190 (dir (if (listp val)
24191 (or (cdr (assoc type val)) ".")
24192 val)))
24193 dir))
24195 (defun org-skip-comments (lines)
24196 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
24197 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
24198 (re2 "^\\(\\*+\\)[ \t\n\r]")
24199 (case-fold-search nil)
24200 rtn line level)
24201 (while (setq line (pop lines))
24202 (cond
24203 ((and (string-match re1 line)
24204 (setq level (- (match-end 1) (match-beginning 1))))
24205 ;; Beginning of a COMMENT subtree. Skip it.
24206 (while (and (setq line (pop lines))
24207 (or (not (string-match re2 line))
24208 (> (- (match-end 1) (match-beginning 1)) level))))
24209 (setq lines (cons line lines)))
24210 ((string-match "^#" line)
24211 ;; an ordinary comment line
24213 ((and org-export-table-remove-special-lines
24214 (string-match "^[ \t]*|" line)
24215 (or (string-match "^[ \t]*| *[!_^] *|" line)
24216 (and (string-match "| *<[0-9]+> *|" line)
24217 (not (string-match "| *[^ <|]" line)))))
24218 ;; a special table line that should be removed
24220 (t (setq rtn (cons line rtn)))))
24221 (nreverse rtn)))
24223 (defun org-export (&optional arg)
24224 (interactive)
24225 (let ((help "[t] insert the export option template
24226 \[v] limit export to visible part of outline tree
24228 \[a] export as ASCII
24230 \[h] export as HTML
24231 \[H] export as HTML to temporary buffer
24232 \[R] export region as HTML
24233 \[b] export as HTML and browse immediately
24234 \[x] export as XOXO
24236 \[l] export as LaTeX
24237 \[L] export as LaTeX to temporary buffer
24239 \[i] export current file as iCalendar file
24240 \[I] export all agenda files as iCalendar files
24241 \[c] export agenda files into combined iCalendar file
24243 \[F] publish current file
24244 \[P] publish current project
24245 \[X] publish... (project will be prompted for)
24246 \[A] publish all projects")
24247 (cmds
24248 '((?t . org-insert-export-options-template)
24249 (?v . org-export-visible)
24250 (?a . org-export-as-ascii)
24251 (?h . org-export-as-html)
24252 (?b . org-export-as-html-and-open)
24253 (?H . org-export-as-html-to-buffer)
24254 (?R . org-export-region-as-html)
24255 (?x . org-export-as-xoxo)
24256 (?l . org-export-as-latex)
24257 (?L . org-export-as-latex-to-buffer)
24258 (?i . org-export-icalendar-this-file)
24259 (?I . org-export-icalendar-all-agenda-files)
24260 (?c . org-export-icalendar-combine-agenda-files)
24261 (?F . org-publish-current-file)
24262 (?P . org-publish-current-project)
24263 (?X . org-publish)
24264 (?A . org-publish-all)))
24265 r1 r2 ass)
24266 (save-window-excursion
24267 (delete-other-windows)
24268 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
24269 (princ help))
24270 (message "Select command: ")
24271 (setq r1 (read-char-exclusive)))
24272 (setq r2 (if (< r1 27) (+ r1 96) r1))
24273 (if (setq ass (assq r2 cmds))
24274 (call-interactively (cdr ass))
24275 (error "No command associated with key %c" r1))))
24277 (defconst org-html-entities
24278 '(("nbsp")
24279 ("iexcl")
24280 ("cent")
24281 ("pound")
24282 ("curren")
24283 ("yen")
24284 ("brvbar")
24285 ("vert" . "&#124;")
24286 ("sect")
24287 ("uml")
24288 ("copy")
24289 ("ordf")
24290 ("laquo")
24291 ("not")
24292 ("shy")
24293 ("reg")
24294 ("macr")
24295 ("deg")
24296 ("plusmn")
24297 ("sup2")
24298 ("sup3")
24299 ("acute")
24300 ("micro")
24301 ("para")
24302 ("middot")
24303 ("odot"."o")
24304 ("star"."*")
24305 ("cedil")
24306 ("sup1")
24307 ("ordm")
24308 ("raquo")
24309 ("frac14")
24310 ("frac12")
24311 ("frac34")
24312 ("iquest")
24313 ("Agrave")
24314 ("Aacute")
24315 ("Acirc")
24316 ("Atilde")
24317 ("Auml")
24318 ("Aring") ("AA"."&Aring;")
24319 ("AElig")
24320 ("Ccedil")
24321 ("Egrave")
24322 ("Eacute")
24323 ("Ecirc")
24324 ("Euml")
24325 ("Igrave")
24326 ("Iacute")
24327 ("Icirc")
24328 ("Iuml")
24329 ("ETH")
24330 ("Ntilde")
24331 ("Ograve")
24332 ("Oacute")
24333 ("Ocirc")
24334 ("Otilde")
24335 ("Ouml")
24336 ("times")
24337 ("Oslash")
24338 ("Ugrave")
24339 ("Uacute")
24340 ("Ucirc")
24341 ("Uuml")
24342 ("Yacute")
24343 ("THORN")
24344 ("szlig")
24345 ("agrave")
24346 ("aacute")
24347 ("acirc")
24348 ("atilde")
24349 ("auml")
24350 ("aring")
24351 ("aelig")
24352 ("ccedil")
24353 ("egrave")
24354 ("eacute")
24355 ("ecirc")
24356 ("euml")
24357 ("igrave")
24358 ("iacute")
24359 ("icirc")
24360 ("iuml")
24361 ("eth")
24362 ("ntilde")
24363 ("ograve")
24364 ("oacute")
24365 ("ocirc")
24366 ("otilde")
24367 ("ouml")
24368 ("divide")
24369 ("oslash")
24370 ("ugrave")
24371 ("uacute")
24372 ("ucirc")
24373 ("uuml")
24374 ("yacute")
24375 ("thorn")
24376 ("yuml")
24377 ("fnof")
24378 ("Alpha")
24379 ("Beta")
24380 ("Gamma")
24381 ("Delta")
24382 ("Epsilon")
24383 ("Zeta")
24384 ("Eta")
24385 ("Theta")
24386 ("Iota")
24387 ("Kappa")
24388 ("Lambda")
24389 ("Mu")
24390 ("Nu")
24391 ("Xi")
24392 ("Omicron")
24393 ("Pi")
24394 ("Rho")
24395 ("Sigma")
24396 ("Tau")
24397 ("Upsilon")
24398 ("Phi")
24399 ("Chi")
24400 ("Psi")
24401 ("Omega")
24402 ("alpha")
24403 ("beta")
24404 ("gamma")
24405 ("delta")
24406 ("epsilon")
24407 ("varepsilon"."&epsilon;")
24408 ("zeta")
24409 ("eta")
24410 ("theta")
24411 ("iota")
24412 ("kappa")
24413 ("lambda")
24414 ("mu")
24415 ("nu")
24416 ("xi")
24417 ("omicron")
24418 ("pi")
24419 ("rho")
24420 ("sigmaf") ("varsigma"."&sigmaf;")
24421 ("sigma")
24422 ("tau")
24423 ("upsilon")
24424 ("phi")
24425 ("chi")
24426 ("psi")
24427 ("omega")
24428 ("thetasym") ("vartheta"."&thetasym;")
24429 ("upsih")
24430 ("piv")
24431 ("bull") ("bullet"."&bull;")
24432 ("hellip") ("dots"."&hellip;")
24433 ("prime")
24434 ("Prime")
24435 ("oline")
24436 ("frasl")
24437 ("weierp")
24438 ("image")
24439 ("real")
24440 ("trade")
24441 ("alefsym")
24442 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
24443 ("uarr") ("uparrow"."&uarr;")
24444 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
24445 ("darr")("downarrow"."&darr;")
24446 ("harr") ("leftrightarrow"."&harr;")
24447 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
24448 ("lArr") ("Leftarrow"."&lArr;")
24449 ("uArr") ("Uparrow"."&uArr;")
24450 ("rArr") ("Rightarrow"."&rArr;")
24451 ("dArr") ("Downarrow"."&dArr;")
24452 ("hArr") ("Leftrightarrow"."&hArr;")
24453 ("forall")
24454 ("part") ("partial"."&part;")
24455 ("exist") ("exists"."&exist;")
24456 ("empty") ("emptyset"."&empty;")
24457 ("nabla")
24458 ("isin") ("in"."&isin;")
24459 ("notin")
24460 ("ni")
24461 ("prod")
24462 ("sum")
24463 ("minus")
24464 ("lowast") ("ast"."&lowast;")
24465 ("radic")
24466 ("prop") ("proptp"."&prop;")
24467 ("infin") ("infty"."&infin;")
24468 ("ang") ("angle"."&ang;")
24469 ("and") ("wedge"."&and;")
24470 ("or") ("vee"."&or;")
24471 ("cap")
24472 ("cup")
24473 ("int")
24474 ("there4")
24475 ("sim")
24476 ("cong") ("simeq"."&cong;")
24477 ("asymp")("approx"."&asymp;")
24478 ("ne") ("neq"."&ne;")
24479 ("equiv")
24480 ("le")
24481 ("ge")
24482 ("sub") ("subset"."&sub;")
24483 ("sup") ("supset"."&sup;")
24484 ("nsub")
24485 ("sube")
24486 ("supe")
24487 ("oplus")
24488 ("otimes")
24489 ("perp")
24490 ("sdot") ("cdot"."&sdot;")
24491 ("lceil")
24492 ("rceil")
24493 ("lfloor")
24494 ("rfloor")
24495 ("lang")
24496 ("rang")
24497 ("loz") ("Diamond"."&loz;")
24498 ("spades") ("spadesuit"."&spades;")
24499 ("clubs") ("clubsuit"."&clubs;")
24500 ("hearts") ("diamondsuit"."&hearts;")
24501 ("diams") ("diamondsuit"."&diams;")
24502 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
24503 ("quot")
24504 ("amp")
24505 ("lt")
24506 ("gt")
24507 ("OElig")
24508 ("oelig")
24509 ("Scaron")
24510 ("scaron")
24511 ("Yuml")
24512 ("circ")
24513 ("tilde")
24514 ("ensp")
24515 ("emsp")
24516 ("thinsp")
24517 ("zwnj")
24518 ("zwj")
24519 ("lrm")
24520 ("rlm")
24521 ("ndash")
24522 ("mdash")
24523 ("lsquo")
24524 ("rsquo")
24525 ("sbquo")
24526 ("ldquo")
24527 ("rdquo")
24528 ("bdquo")
24529 ("dagger")
24530 ("Dagger")
24531 ("permil")
24532 ("lsaquo")
24533 ("rsaquo")
24534 ("euro")
24536 ("arccos"."arccos")
24537 ("arcsin"."arcsin")
24538 ("arctan"."arctan")
24539 ("arg"."arg")
24540 ("cos"."cos")
24541 ("cosh"."cosh")
24542 ("cot"."cot")
24543 ("coth"."coth")
24544 ("csc"."csc")
24545 ("deg"."deg")
24546 ("det"."det")
24547 ("dim"."dim")
24548 ("exp"."exp")
24549 ("gcd"."gcd")
24550 ("hom"."hom")
24551 ("inf"."inf")
24552 ("ker"."ker")
24553 ("lg"."lg")
24554 ("lim"."lim")
24555 ("liminf"."liminf")
24556 ("limsup"."limsup")
24557 ("ln"."ln")
24558 ("log"."log")
24559 ("max"."max")
24560 ("min"."min")
24561 ("Pr"."Pr")
24562 ("sec"."sec")
24563 ("sin"."sin")
24564 ("sinh"."sinh")
24565 ("sup"."sup")
24566 ("tan"."tan")
24567 ("tanh"."tanh")
24569 "Entities for TeX->HTML translation.
24570 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24571 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24572 In that case, \"\\ent\" will be translated to \"&other;\".
24573 The list contains HTML entities for Latin-1, Greek and other symbols.
24574 It is supplemented by a number of commonly used TeX macros with appropriate
24575 translations. There is currently no way for users to extend this.")
24577 ;;; General functions for all backends
24579 (defun org-cleaned-string-for-export (string &rest parameters)
24580 "Cleanup a buffer STRING so that links can be created safely."
24581 (interactive)
24582 (let* ((re-radio (and org-target-link-regexp
24583 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24584 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24585 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24586 (re-archive (concat ":" org-archive-tag ":"))
24587 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24588 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24589 (htmlp (plist-get parameters :for-html))
24590 (asciip (plist-get parameters :for-ascii))
24591 (latexp (plist-get parameters :for-LaTeX))
24592 (commentsp (plist-get parameters :comments))
24593 (archived-trees (plist-get parameters :archived-trees))
24594 (inhibit-read-only t)
24595 (drawers org-drawers)
24596 (exp-drawers (plist-get parameters :drawers))
24597 (outline-regexp "\\*+ ")
24598 a b xx
24599 rtn p)
24600 (with-current-buffer (get-buffer-create " org-mode-tmp")
24601 (erase-buffer)
24602 (insert string)
24603 ;; Remove license-to-kill stuff
24604 (while (setq p (text-property-any (point-min) (point-max)
24605 :org-license-to-kill t))
24606 (delete-region p (next-single-property-change p :org-license-to-kill)))
24608 (let ((org-inhibit-startup t)) (org-mode))
24609 (untabify (point-min) (point-max))
24611 ;; Get rid of drawers
24612 (unless (eq t exp-drawers)
24613 (goto-char (point-min))
24614 (let ((re (concat "^[ \t]*:\\("
24615 (mapconcat
24616 'identity
24617 (org-delete-all exp-drawers
24618 (copy-sequence drawers))
24619 "\\|")
24620 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24621 (while (re-search-forward re nil t)
24622 (replace-match ""))))
24624 ;; Get the correct stuff before the first headline
24625 (when (plist-get parameters :skip-before-1st-heading)
24626 (goto-char (point-min))
24627 (when (re-search-forward "^\\*+[ \t]" nil t)
24628 (delete-region (point-min) (match-beginning 0))
24629 (goto-char (point-min))
24630 (insert "\n")))
24631 (when (plist-get parameters :add-text)
24632 (goto-char (point-min))
24633 (insert (plist-get parameters :add-text) "\n"))
24635 ;; Get rid of archived trees
24636 (when (not (eq archived-trees t))
24637 (goto-char (point-min))
24638 (while (re-search-forward re-archive nil t)
24639 (if (not (org-on-heading-p t))
24640 (org-end-of-subtree t)
24641 (beginning-of-line 1)
24642 (setq a (if archived-trees
24643 (1+ (point-at-eol)) (point))
24644 b (org-end-of-subtree t))
24645 (if (> b a) (delete-region a b)))))
24647 ;; Find targets in comments and move them out of comments,
24648 ;; but mark them as targets that should be invisible
24649 (goto-char (point-min))
24650 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24651 (replace-match "\\1(INVISIBLE)"))
24653 ;; Protect backend specific stuff, throw away the others.
24654 (let ((formatters
24655 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24656 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24657 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24658 fmt)
24659 (goto-char (point-min))
24660 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24661 (goto-char (match-end 0))
24662 (while (not (looking-at "#\\+END_EXAMPLE"))
24663 (insert ": ")
24664 (beginning-of-line 2)))
24665 (goto-char (point-min))
24666 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24667 (add-text-properties (match-beginning 0) (match-end 0)
24668 '(org-protected t)))
24669 (while formatters
24670 (setq fmt (pop formatters))
24671 (when (car fmt)
24672 (goto-char (point-min))
24673 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24674 ":[ \t]*\\(.*\\)") nil t)
24675 (replace-match "\\1" t)
24676 (add-text-properties
24677 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24678 '(org-protected t))))
24679 (goto-char (point-min))
24680 (while (re-search-forward
24681 (concat "^#\\+"
24682 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24683 (cadddr fmt) "\\>.*\n?") nil t)
24684 (if (car fmt)
24685 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24686 '(org-protected t))
24687 (delete-region (match-beginning 0) (match-end 0))))))
24689 ;; Protect quoted subtrees
24690 (goto-char (point-min))
24691 (while (re-search-forward re-quote nil t)
24692 (goto-char (match-beginning 0))
24693 (end-of-line 1)
24694 (add-text-properties (point) (org-end-of-subtree t)
24695 '(org-protected t)))
24697 ;; Protect verbatim elements
24698 (goto-char (point-min))
24699 (while (re-search-forward org-verbatim-re nil t)
24700 (add-text-properties (match-beginning 4) (match-end 4)
24701 '(org-protected t))
24702 (goto-char (1+ (match-end 4))))
24704 ;; Remove subtrees that are commented
24705 (goto-char (point-min))
24706 (while (re-search-forward re-commented nil t)
24707 (goto-char (match-beginning 0))
24708 (delete-region (point) (org-end-of-subtree t)))
24710 ;; Remove special table lines
24711 (when org-export-table-remove-special-lines
24712 (goto-char (point-min))
24713 (while (re-search-forward "^[ \t]*|" nil t)
24714 (beginning-of-line 1)
24715 (if (or (looking-at "[ \t]*| *[!_^] *|")
24716 (and (looking-at ".*?| *<[0-9]+> *|")
24717 (not (looking-at ".*?| *[^ <|]"))))
24718 (delete-region (max (point-min) (1- (point-at-bol)))
24719 (point-at-eol))
24720 (end-of-line 1))))
24722 ;; Specific LaTeX stuff
24723 (when latexp
24724 (require 'org-export-latex nil)
24725 (org-export-latex-cleaned-string))
24727 (when asciip
24728 (org-export-ascii-clean-string))
24730 ;; Specific HTML stuff
24731 (when htmlp
24732 ;; Convert LaTeX fragments to images
24733 (when (plist-get parameters :LaTeX-fragments)
24734 (org-format-latex
24735 (concat "ltxpng/" (file-name-sans-extension
24736 (file-name-nondirectory
24737 org-current-export-file)))
24738 org-current-export-dir nil "Creating LaTeX image %s"))
24739 (message "Exporting..."))
24741 ;; Remove or replace comments
24742 (goto-char (point-min))
24743 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24744 (if commentsp
24745 (progn (add-text-properties
24746 (match-beginning 0) (match-end 0) '(org-protected t))
24747 (replace-match (format commentsp (match-string 1)) t t))
24748 (replace-match "")))
24750 ;; Find matches for radio targets and turn them into internal links
24751 (goto-char (point-min))
24752 (when re-radio
24753 (while (re-search-forward re-radio nil t)
24754 (org-if-unprotected
24755 (replace-match "\\1[[\\2]]"))))
24757 ;; Find all links that contain a newline and put them into a single line
24758 (goto-char (point-min))
24759 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24760 (org-if-unprotected
24761 (replace-match "\\1 \\3")
24762 (goto-char (match-beginning 0))))
24765 ;; Normalize links: Convert angle and plain links into bracket links
24766 ;; Expand link abbreviations
24767 (goto-char (point-min))
24768 (while (re-search-forward re-plain-link nil t)
24769 (goto-char (1- (match-end 0)))
24770 (org-if-unprotected
24771 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24772 ":" (match-string 3) "]]")))
24773 ;; added 'org-link face to links
24774 (put-text-property 0 (length s) 'face 'org-link s)
24775 (replace-match s t t))))
24776 (goto-char (point-min))
24777 (while (re-search-forward re-angle-link nil t)
24778 (goto-char (1- (match-end 0)))
24779 (org-if-unprotected
24780 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24781 ":" (match-string 3) "]]")))
24782 (put-text-property 0 (length s) 'face 'org-link s)
24783 (replace-match s t t))))
24784 (goto-char (point-min))
24785 (while (re-search-forward org-bracket-link-regexp nil t)
24786 (org-if-unprotected
24787 (let* ((s (concat "[[" (setq xx (save-match-data
24788 (org-link-expand-abbrev (match-string 1))))
24790 (if (match-end 3)
24791 (match-string 2)
24792 (concat "[" xx "]"))
24793 "]")))
24794 (put-text-property 0 (length s) 'face 'org-link s)
24795 (replace-match s t t))))
24797 ;; Find multiline emphasis and put them into single line
24798 (when (plist-get parameters :emph-multiline)
24799 (goto-char (point-min))
24800 (while (re-search-forward org-emph-re nil t)
24801 (if (not (= (char-after (match-beginning 3))
24802 (char-after (match-beginning 4))))
24803 (org-if-unprotected
24804 (subst-char-in-region (match-beginning 0) (match-end 0)
24805 ?\n ?\ t)
24806 (goto-char (1- (match-end 0))))
24807 (goto-char (1+ (match-beginning 0))))))
24809 (setq rtn (buffer-string)))
24810 (kill-buffer " org-mode-tmp")
24811 rtn))
24813 (defun org-export-grab-title-from-buffer ()
24814 "Get a title for the current document, from looking at the buffer."
24815 (let ((inhibit-read-only t))
24816 (save-excursion
24817 (goto-char (point-min))
24818 (let ((end (save-excursion (outline-next-heading) (point))))
24819 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24820 ;; Mark the line so that it will not be exported as normal text.
24821 (org-unmodified
24822 (add-text-properties (match-beginning 0) (match-end 0)
24823 (list :org-license-to-kill t)))
24824 ;; Return the title string
24825 (org-trim (match-string 0)))))))
24827 (defun org-export-get-title-from-subtree ()
24828 "Return subtree title and exclude it from export."
24829 (let (title (m (mark)))
24830 (save-excursion
24831 (goto-char (region-beginning))
24832 (when (and (org-at-heading-p)
24833 (>= (org-end-of-subtree t t) (region-end)))
24834 ;; This is a subtree, we take the title from the first heading
24835 (goto-char (region-beginning))
24836 (looking-at org-todo-line-regexp)
24837 (setq title (match-string 3))
24838 (org-unmodified
24839 (add-text-properties (point) (1+ (point-at-eol))
24840 (list :org-license-to-kill t)))))
24841 title))
24843 (defun org-solidify-link-text (s &optional alist)
24844 "Take link text and make a safe target out of it."
24845 (save-match-data
24846 (let* ((rtn
24847 (mapconcat
24848 'identity
24849 (org-split-string s "[ \t\r\n]+") "--"))
24850 (a (assoc rtn alist)))
24851 (or (cdr a) rtn))))
24853 (defun org-get-min-level (lines)
24854 "Get the minimum level in LINES."
24855 (let ((re "^\\(\\*+\\) ") l min)
24856 (catch 'exit
24857 (while (setq l (pop lines))
24858 (if (string-match re l)
24859 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24860 1)))
24862 ;; Variable holding the vector with section numbers
24863 (defvar org-section-numbers (make-vector org-level-max 0))
24865 (defun org-init-section-numbers ()
24866 "Initialize the vector for the section numbers."
24867 (let* ((level -1)
24868 (numbers (nreverse (org-split-string "" "\\.")))
24869 (depth (1- (length org-section-numbers)))
24870 (i depth) number-string)
24871 (while (>= i 0)
24872 (if (> i level)
24873 (aset org-section-numbers i 0)
24874 (setq number-string (or (car numbers) "0"))
24875 (if (string-match "\\`[A-Z]\\'" number-string)
24876 (aset org-section-numbers i
24877 (- (string-to-char number-string) ?A -1))
24878 (aset org-section-numbers i (string-to-number number-string)))
24879 (pop numbers))
24880 (setq i (1- i)))))
24882 (defun org-section-number (&optional level)
24883 "Return a string with the current section number.
24884 When LEVEL is non-nil, increase section numbers on that level."
24885 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24886 (when level
24887 (when (> level -1)
24888 (aset org-section-numbers
24889 level (1+ (aref org-section-numbers level))))
24890 (setq idx (1+ level))
24891 (while (<= idx depth)
24892 (if (not (= idx 1))
24893 (aset org-section-numbers idx 0))
24894 (setq idx (1+ idx))))
24895 (setq idx 0)
24896 (while (<= idx depth)
24897 (setq n (aref org-section-numbers idx))
24898 (setq string (concat string (if (not (string= string "")) "." "")
24899 (int-to-string n)))
24900 (setq idx (1+ idx)))
24901 (save-match-data
24902 (if (string-match "\\`\\([@0]\\.\\)+" string)
24903 (setq string (replace-match "" t nil string)))
24904 (if (string-match "\\(\\.0\\)+\\'" string)
24905 (setq string (replace-match "" t nil string))))
24906 string))
24908 ;;; ASCII export
24910 (defvar org-last-level nil) ; dynamically scoped variable
24911 (defvar org-min-level nil) ; dynamically scoped variable
24912 (defvar org-levels-open nil) ; dynamically scoped parameter
24913 (defvar org-ascii-current-indentation nil) ; For communication
24915 (defun org-export-as-ascii (arg)
24916 "Export the outline as a pretty ASCII file.
24917 If there is an active region, export only the region.
24918 The prefix ARG specifies how many levels of the outline should become
24919 underlined headlines. The default is 3."
24920 (interactive "P")
24921 (setq-default org-todo-line-regexp org-todo-line-regexp)
24922 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24923 (org-infile-export-plist)))
24924 (region-p (org-region-active-p))
24925 (subtree-p
24926 (when region-p
24927 (save-excursion
24928 (goto-char (region-beginning))
24929 (and (org-at-heading-p)
24930 (>= (org-end-of-subtree t t) (region-end))))))
24931 (custom-times org-display-custom-times)
24932 (org-ascii-current-indentation '(0 . 0))
24933 (level 0) line txt
24934 (umax nil)
24935 (umax-toc nil)
24936 (case-fold-search nil)
24937 (filename (concat (file-name-as-directory
24938 (org-export-directory :ascii opt-plist))
24939 (file-name-sans-extension
24940 (or (and subtree-p
24941 (org-entry-get (region-beginning)
24942 "EXPORT_FILE_NAME" t))
24943 (file-name-nondirectory buffer-file-name)))
24944 ".txt"))
24945 (filename (if (equal (file-truename filename)
24946 (file-truename buffer-file-name))
24947 (concat filename ".txt")
24948 filename))
24949 (buffer (find-file-noselect filename))
24950 (org-levels-open (make-vector org-level-max nil))
24951 (odd org-odd-levels-only)
24952 (date (plist-get opt-plist :date))
24953 (author (plist-get opt-plist :author))
24954 (title (or (and subtree-p (org-export-get-title-from-subtree))
24955 (plist-get opt-plist :title)
24956 (and (not
24957 (plist-get opt-plist :skip-before-1st-heading))
24958 (org-export-grab-title-from-buffer))
24959 (file-name-sans-extension
24960 (file-name-nondirectory buffer-file-name))))
24961 (email (plist-get opt-plist :email))
24962 (language (plist-get opt-plist :language))
24963 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24964 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24965 (todo nil)
24966 (lang-words nil)
24967 (region
24968 (buffer-substring
24969 (if (org-region-active-p) (region-beginning) (point-min))
24970 (if (org-region-active-p) (region-end) (point-max))))
24971 (lines (org-split-string
24972 (org-cleaned-string-for-export
24973 region
24974 :for-ascii t
24975 :skip-before-1st-heading
24976 (plist-get opt-plist :skip-before-1st-heading)
24977 :drawers (plist-get opt-plist :drawers)
24978 :verbatim-multiline t
24979 :archived-trees
24980 (plist-get opt-plist :archived-trees)
24981 :add-text (plist-get opt-plist :text))
24982 "\n"))
24983 thetoc have-headings first-heading-pos
24984 table-open table-buffer)
24986 (let ((inhibit-read-only t))
24987 (org-unmodified
24988 (remove-text-properties (point-min) (point-max)
24989 '(:org-license-to-kill t))))
24991 (setq org-min-level (org-get-min-level lines))
24992 (setq org-last-level org-min-level)
24993 (org-init-section-numbers)
24995 (find-file-noselect filename)
24997 (setq lang-words (or (assoc language org-export-language-setup)
24998 (assoc "en" org-export-language-setup)))
24999 (switch-to-buffer-other-window buffer)
25000 (erase-buffer)
25001 (fundamental-mode)
25002 ;; create local variables for all options, to make sure all called
25003 ;; functions get the correct information
25004 (mapc (lambda (x)
25005 (set (make-local-variable (cdr x))
25006 (plist-get opt-plist (car x))))
25007 org-export-plist-vars)
25008 (org-set-local 'org-odd-levels-only odd)
25009 (setq umax (if arg (prefix-numeric-value arg)
25010 org-export-headline-levels))
25011 (setq umax-toc (if (integerp org-export-with-toc)
25012 (min org-export-with-toc umax)
25013 umax))
25015 ;; File header
25016 (if title (org-insert-centered title ?=))
25017 (insert "\n")
25018 (if (and (or author email)
25019 org-export-author-info)
25020 (insert (concat (nth 1 lang-words) ": " (or author "")
25021 (if email (concat " <" email ">") "")
25022 "\n")))
25024 (cond
25025 ((and date (string-match "%" date))
25026 (setq date (format-time-string date (current-time))))
25027 (date)
25028 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25030 (if (and date org-export-time-stamp-file)
25031 (insert (concat (nth 2 lang-words) ": " date"\n")))
25033 (insert "\n\n")
25035 (if org-export-with-toc
25036 (progn
25037 (push (concat (nth 3 lang-words) "\n") thetoc)
25038 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
25039 (mapc '(lambda (line)
25040 (if (string-match org-todo-line-regexp
25041 line)
25042 ;; This is a headline
25043 (progn
25044 (setq have-headings t)
25045 (setq level (- (match-end 1) (match-beginning 1))
25046 level (org-tr-level level)
25047 txt (match-string 3 line)
25048 todo
25049 (or (and org-export-mark-todo-in-toc
25050 (match-beginning 2)
25051 (not (member (match-string 2 line)
25052 org-done-keywords)))
25053 ; TODO, not DONE
25054 (and org-export-mark-todo-in-toc
25055 (= level umax-toc)
25056 (org-search-todo-below
25057 line lines level))))
25058 (setq txt (org-html-expand-for-ascii txt))
25060 (while (string-match org-bracket-link-regexp txt)
25061 (setq txt
25062 (replace-match
25063 (match-string (if (match-end 2) 3 1) txt)
25064 t t txt)))
25066 (if (and (memq org-export-with-tags '(not-in-toc nil))
25067 (string-match
25068 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
25069 txt))
25070 (setq txt (replace-match "" t t txt)))
25071 (if (string-match quote-re0 txt)
25072 (setq txt (replace-match "" t t txt)))
25074 (if org-export-with-section-numbers
25075 (setq txt (concat (org-section-number level)
25076 " " txt)))
25077 (if (<= level umax-toc)
25078 (progn
25079 (push
25080 (concat
25081 (make-string
25082 (* (max 0 (- level org-min-level)) 4) ?\ )
25083 (format (if todo "%s (*)\n" "%s\n") txt))
25084 thetoc)
25085 (setq org-last-level level))
25086 ))))
25087 lines)
25088 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25090 (org-init-section-numbers)
25091 (while (setq line (pop lines))
25092 ;; Remove the quoted HTML tags.
25093 (setq line (org-html-expand-for-ascii line))
25094 ;; Remove targets
25095 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
25096 (setq line (replace-match "" t t line)))
25097 ;; Replace internal links
25098 (while (string-match org-bracket-link-regexp line)
25099 (setq line (replace-match
25100 (if (match-end 3) "[\\3]" "[\\1]")
25101 t nil line)))
25102 (when custom-times
25103 (setq line (org-translate-time line)))
25104 (cond
25105 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25106 ;; a Headline
25107 (setq first-heading-pos (or first-heading-pos (point)))
25108 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25109 txt (match-string 2 line))
25110 (org-ascii-level-start level txt umax lines))
25112 ((and org-export-with-tables
25113 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25114 (if (not table-open)
25115 ;; New table starts
25116 (setq table-open t table-buffer nil))
25117 ;; Accumulate lines
25118 (setq table-buffer (cons line table-buffer))
25119 (when (or (not lines)
25120 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25121 (car lines))))
25122 (setq table-open nil
25123 table-buffer (nreverse table-buffer))
25124 (insert (mapconcat
25125 (lambda (x)
25126 (org-fix-indentation x org-ascii-current-indentation))
25127 (org-format-table-ascii table-buffer)
25128 "\n") "\n")))
25130 (setq line (org-fix-indentation line org-ascii-current-indentation))
25131 (if (and org-export-with-fixed-width
25132 (string-match "^\\([ \t]*\\)\\(:\\)" line))
25133 (setq line (replace-match "\\1" nil nil line)))
25134 (insert line "\n"))))
25136 (normal-mode)
25138 ;; insert the table of contents
25139 (when thetoc
25140 (goto-char (point-min))
25141 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
25142 (progn
25143 (goto-char (match-beginning 0))
25144 (replace-match ""))
25145 (goto-char first-heading-pos))
25146 (mapc 'insert thetoc)
25147 (or (looking-at "[ \t]*\n[ \t]*\n")
25148 (insert "\n\n")))
25150 ;; Convert whitespace place holders
25151 (goto-char (point-min))
25152 (let (beg end)
25153 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25154 (setq end (next-single-property-change beg 'org-whitespace))
25155 (goto-char beg)
25156 (delete-region beg end)
25157 (insert (make-string (- end beg) ?\ ))))
25159 (save-buffer)
25160 ;; remove display and invisible chars
25161 (let (beg end)
25162 (goto-char (point-min))
25163 (while (setq beg (next-single-property-change (point) 'display))
25164 (setq end (next-single-property-change beg 'display))
25165 (delete-region beg end)
25166 (goto-char beg)
25167 (insert "=>"))
25168 (goto-char (point-min))
25169 (while (setq beg (next-single-property-change (point) 'org-cwidth))
25170 (setq end (next-single-property-change beg 'org-cwidth))
25171 (delete-region beg end)
25172 (goto-char beg)))
25173 (goto-char (point-min))))
25175 (defun org-export-ascii-clean-string ()
25176 "Do extra work for ASCII export"
25177 (goto-char (point-min))
25178 (while (re-search-forward org-verbatim-re nil t)
25179 (goto-char (match-end 2))
25180 (backward-delete-char 1) (insert "'")
25181 (goto-char (match-beginning 2))
25182 (delete-char 1) (insert "`")
25183 (goto-char (match-end 2))))
25185 (defun org-search-todo-below (line lines level)
25186 "Search the subtree below LINE for any TODO entries."
25187 (let ((rest (cdr (memq line lines)))
25188 (re org-todo-line-regexp)
25189 line lv todo)
25190 (catch 'exit
25191 (while (setq line (pop rest))
25192 (if (string-match re line)
25193 (progn
25194 (setq lv (- (match-end 1) (match-beginning 1))
25195 todo (and (match-beginning 2)
25196 (not (member (match-string 2 line)
25197 org-done-keywords))))
25198 ; TODO, not DONE
25199 (if (<= lv level) (throw 'exit nil))
25200 (if todo (throw 'exit t))))))))
25202 (defun org-html-expand-for-ascii (line)
25203 "Handle quoted HTML for ASCII export."
25204 (if org-export-html-expand
25205 (while (string-match "@<[^<>\n]*>" line)
25206 ;; We just remove the tags for now.
25207 (setq line (replace-match "" nil nil line))))
25208 line)
25210 (defun org-insert-centered (s &optional underline)
25211 "Insert the string S centered and underline it with character UNDERLINE."
25212 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
25213 (insert (make-string ind ?\ ) s "\n")
25214 (if underline
25215 (insert (make-string ind ?\ )
25216 (make-string (string-width s) underline)
25217 "\n"))))
25219 (defun org-ascii-level-start (level title umax &optional lines)
25220 "Insert a new level in ASCII export."
25221 (let (char (n (- level umax 1)) (ind 0))
25222 (if (> level umax)
25223 (progn
25224 (insert (make-string (* 2 n) ?\ )
25225 (char-to-string (nth (% n (length org-export-ascii-bullets))
25226 org-export-ascii-bullets))
25227 " " title "\n")
25228 ;; find the indentation of the next non-empty line
25229 (catch 'stop
25230 (while lines
25231 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
25232 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
25233 (throw 'stop (setq ind (org-get-indentation (car lines)))))
25234 (pop lines)))
25235 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
25236 (if (or (not (equal (char-before) ?\n))
25237 (not (equal (char-before (1- (point))) ?\n)))
25238 (insert "\n"))
25239 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
25240 (unless org-export-with-tags
25241 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25242 (setq title (replace-match "" t t title))))
25243 (if org-export-with-section-numbers
25244 (setq title (concat (org-section-number level) " " title)))
25245 (insert title "\n" (make-string (string-width title) char) "\n")
25246 (setq org-ascii-current-indentation '(0 . 0)))))
25248 (defun org-export-visible (type arg)
25249 "Create a copy of the visible part of the current buffer, and export it.
25250 The copy is created in a temporary buffer and removed after use.
25251 TYPE is the final key (as a string) that also select the export command in
25252 the `C-c C-e' export dispatcher.
25253 As a special case, if the you type SPC at the prompt, the temporary
25254 org-mode file will not be removed but presented to you so that you can
25255 continue to use it. The prefix arg ARG is passed through to the exporting
25256 command."
25257 (interactive
25258 (list (progn
25259 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
25260 (read-char-exclusive))
25261 current-prefix-arg))
25262 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
25263 (error "Invalid export key"))
25264 (let* ((binding (cdr (assoc type
25265 '((?a . org-export-as-ascii)
25266 (?\C-a . org-export-as-ascii)
25267 (?b . org-export-as-html-and-open)
25268 (?\C-b . org-export-as-html-and-open)
25269 (?h . org-export-as-html)
25270 (?H . org-export-as-html-to-buffer)
25271 (?R . org-export-region-as-html)
25272 (?x . org-export-as-xoxo)))))
25273 (keepp (equal type ?\ ))
25274 (file buffer-file-name)
25275 (buffer (get-buffer-create "*Org Export Visible*"))
25276 s e)
25277 ;; Need to hack the drawers here.
25278 (save-excursion
25279 (goto-char (point-min))
25280 (while (re-search-forward org-drawer-regexp nil t)
25281 (goto-char (match-beginning 1))
25282 (or (org-invisible-p) (org-flag-drawer nil))))
25283 (with-current-buffer buffer (erase-buffer))
25284 (save-excursion
25285 (setq s (goto-char (point-min)))
25286 (while (not (= (point) (point-max)))
25287 (goto-char (org-find-invisible))
25288 (append-to-buffer buffer s (point))
25289 (setq s (goto-char (org-find-visible))))
25290 (org-cycle-hide-drawers 'all)
25291 (goto-char (point-min))
25292 (unless keepp
25293 ;; Copy all comment lines to the end, to make sure #+ settings are
25294 ;; still available for the second export step. Kind of a hack, but
25295 ;; does do the trick.
25296 (if (looking-at "#[^\r\n]*")
25297 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
25298 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
25299 (append-to-buffer buffer (1+ (match-beginning 0))
25300 (min (point-max) (1+ (match-end 0))))))
25301 (set-buffer buffer)
25302 (let ((buffer-file-name file)
25303 (org-inhibit-startup t))
25304 (org-mode)
25305 (show-all)
25306 (unless keepp (funcall binding arg))))
25307 (if (not keepp)
25308 (kill-buffer buffer)
25309 (switch-to-buffer-other-window buffer)
25310 (goto-char (point-min)))))
25312 (defun org-find-visible ()
25313 (let ((s (point)))
25314 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25315 (get-char-property s 'invisible)))
25317 (defun org-find-invisible ()
25318 (let ((s (point)))
25319 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25320 (not (get-char-property s 'invisible))))
25323 ;;; HTML export
25325 (defun org-get-current-options ()
25326 "Return a string with current options as keyword options.
25327 Does include HTML export options as well as TODO and CATEGORY stuff."
25328 (format
25329 "#+TITLE: %s
25330 #+AUTHOR: %s
25331 #+EMAIL: %s
25332 #+LANGUAGE: %s
25333 #+TEXT: Some descriptive text to be emitted. Several lines OK.
25334 #+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
25335 #+CATEGORY: %s
25336 #+SEQ_TODO: %s
25337 #+TYP_TODO: %s
25338 #+PRIORITIES: %c %c %c
25339 #+DRAWERS: %s
25340 #+STARTUP: %s %s %s %s %s
25341 #+TAGS: %s
25342 #+ARCHIVE: %s
25343 #+LINK: %s
25345 (buffer-name) (user-full-name) user-mail-address org-export-default-language
25346 org-export-headline-levels
25347 org-export-with-section-numbers
25348 org-export-with-toc
25349 org-export-preserve-breaks
25350 org-export-html-expand
25351 org-export-with-fixed-width
25352 org-export-with-tables
25353 org-export-with-sub-superscripts
25354 org-export-with-special-strings
25355 org-export-with-footnotes
25356 org-export-with-emphasize
25357 org-export-with-TeX-macros
25358 org-export-with-LaTeX-fragments
25359 org-export-skip-text-before-1st-heading
25360 org-export-with-drawers
25361 org-export-with-tags
25362 (file-name-nondirectory buffer-file-name)
25363 "TODO FEEDBACK VERIFY DONE"
25364 "Me Jason Marie DONE"
25365 org-highest-priority org-lowest-priority org-default-priority
25366 (mapconcat 'identity org-drawers " ")
25367 (cdr (assoc org-startup-folded
25368 '((nil . "showall") (t . "overview") (content . "content"))))
25369 (if org-odd-levels-only "odd" "oddeven")
25370 (if org-hide-leading-stars "hidestars" "showstars")
25371 (if org-startup-align-all-tables "align" "noalign")
25372 (cond ((eq org-log-done t) "logdone")
25373 ((equal org-log-done 'note) "lognotedone")
25374 ((not org-log-done) "nologdone"))
25375 (or (mapconcat (lambda (x)
25376 (cond
25377 ((equal '(:startgroup) x) "{")
25378 ((equal '(:endgroup) x) "}")
25379 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
25380 (t (car x))))
25381 (or org-tag-alist (org-get-buffer-tags)) " ") "")
25382 org-archive-location
25383 "org file:~/org/%s.org"
25386 (defun org-insert-export-options-template ()
25387 "Insert into the buffer a template with information for exporting."
25388 (interactive)
25389 (if (not (bolp)) (newline))
25390 (let ((s (org-get-current-options)))
25391 (and (string-match "#\\+CATEGORY" s)
25392 (setq s (substring s 0 (match-beginning 0))))
25393 (insert s)))
25395 (defun org-toggle-fixed-width-section (arg)
25396 "Toggle the fixed-width export.
25397 If there is no active region, the QUOTE keyword at the current headline is
25398 inserted or removed. When present, it causes the text between this headline
25399 and the next to be exported as fixed-width text, and unmodified.
25400 If there is an active region, this command adds or removes a colon as the
25401 first character of this line. If the first character of a line is a colon,
25402 this line is also exported in fixed-width font."
25403 (interactive "P")
25404 (let* ((cc 0)
25405 (regionp (org-region-active-p))
25406 (beg (if regionp (region-beginning) (point)))
25407 (end (if regionp (region-end)))
25408 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
25409 (case-fold-search nil)
25410 (re "[ \t]*\\(:\\)")
25411 off)
25412 (if regionp
25413 (save-excursion
25414 (goto-char beg)
25415 (setq cc (current-column))
25416 (beginning-of-line 1)
25417 (setq off (looking-at re))
25418 (while (> nlines 0)
25419 (setq nlines (1- nlines))
25420 (beginning-of-line 1)
25421 (cond
25422 (arg
25423 (move-to-column cc t)
25424 (insert ":\n")
25425 (forward-line -1))
25426 ((and off (looking-at re))
25427 (replace-match "" t t nil 1))
25428 ((not off) (move-to-column cc t) (insert ":")))
25429 (forward-line 1)))
25430 (save-excursion
25431 (org-back-to-heading)
25432 (if (looking-at (concat outline-regexp
25433 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
25434 (replace-match "" t t nil 1)
25435 (if (looking-at outline-regexp)
25436 (progn
25437 (goto-char (match-end 0))
25438 (insert org-quote-string " "))))))))
25440 (defun org-export-as-html-and-open (arg)
25441 "Export the outline as HTML and immediately open it with a browser.
25442 If there is an active region, export only the region.
25443 The prefix ARG specifies how many levels of the outline should become
25444 headlines. The default is 3. Lower levels will become bulleted lists."
25445 (interactive "P")
25446 (org-export-as-html arg 'hidden)
25447 (org-open-file buffer-file-name))
25449 (defun org-export-as-html-batch ()
25450 "Call `org-export-as-html', may be used in batch processing as
25451 emacs --batch
25452 --load=$HOME/lib/emacs/org.el
25453 --eval \"(setq org-export-headline-levels 2)\"
25454 --visit=MyFile --funcall org-export-as-html-batch"
25455 (org-export-as-html org-export-headline-levels 'hidden))
25457 (defun org-export-as-html-to-buffer (arg)
25458 "Call `org-exort-as-html` with output to a temporary buffer.
25459 No file is created. The prefix ARG is passed through to `org-export-as-html'."
25460 (interactive "P")
25461 (org-export-as-html arg nil nil "*Org HTML Export*")
25462 (switch-to-buffer-other-window "*Org HTML Export*"))
25464 (defun org-replace-region-by-html (beg end)
25465 "Assume the current region has org-mode syntax, and convert it to HTML.
25466 This can be used in any buffer. For example, you could write an
25467 itemized list in org-mode syntax in an HTML buffer and then use this
25468 command to convert it."
25469 (interactive "r")
25470 (let (reg html buf pop-up-frames)
25471 (save-window-excursion
25472 (if (org-mode-p)
25473 (setq html (org-export-region-as-html
25474 beg end t 'string))
25475 (setq reg (buffer-substring beg end)
25476 buf (get-buffer-create "*Org tmp*"))
25477 (with-current-buffer buf
25478 (erase-buffer)
25479 (insert reg)
25480 (org-mode)
25481 (setq html (org-export-region-as-html
25482 (point-min) (point-max) t 'string)))
25483 (kill-buffer buf)))
25484 (delete-region beg end)
25485 (insert html)))
25487 (defun org-export-region-as-html (beg end &optional body-only buffer)
25488 "Convert region from BEG to END in org-mode buffer to HTML.
25489 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
25490 contents, and only produce the region of converted text, useful for
25491 cut-and-paste operations.
25492 If BUFFER is a buffer or a string, use/create that buffer as a target
25493 of the converted HTML. If BUFFER is the symbol `string', return the
25494 produced HTML as a string and leave not buffer behind. For example,
25495 a Lisp program could call this function in the following way:
25497 (setq html (org-export-region-as-html beg end t 'string))
25499 When called interactively, the output buffer is selected, and shown
25500 in a window. A non-interactive call will only retunr the buffer."
25501 (interactive "r\nP")
25502 (when (interactive-p)
25503 (setq buffer "*Org HTML Export*"))
25504 (let ((transient-mark-mode t) (zmacs-regions t)
25505 rtn)
25506 (goto-char end)
25507 (set-mark (point)) ;; to activate the region
25508 (goto-char beg)
25509 (setq rtn (org-export-as-html
25510 nil nil nil
25511 buffer body-only))
25512 (if (fboundp 'deactivate-mark) (deactivate-mark))
25513 (if (and (interactive-p) (bufferp rtn))
25514 (switch-to-buffer-other-window rtn)
25515 rtn)))
25517 (defvar html-table-tag nil) ; dynamically scoped into this.
25518 (defun org-export-as-html (arg &optional hidden ext-plist
25519 to-buffer body-only pub-dir)
25520 "Export the outline as a pretty HTML file.
25521 If there is an active region, export only the region. The prefix
25522 ARG specifies how many levels of the outline should become
25523 headlines. The default is 3. Lower levels will become bulleted
25524 lists. When HIDDEN is non-nil, don't display the HTML buffer.
25525 EXT-PLIST is a property list with external parameters overriding
25526 org-mode's default settings, but still inferior to file-local
25527 settings. When TO-BUFFER is non-nil, create a buffer with that
25528 name and export to that buffer. If TO-BUFFER is the symbol
25529 `string', don't leave any buffer behind but just return the
25530 resulting HTML as a string. When BODY-ONLY is set, don't produce
25531 the file header and footer, simply return the content of
25532 <body>...</body>, without even the body tags themselves. When
25533 PUB-DIR is set, use this as the publishing directory."
25534 (interactive "P")
25536 ;; Make sure we have a file name when we need it.
25537 (when (and (not (or to-buffer body-only))
25538 (not buffer-file-name))
25539 (if (buffer-base-buffer)
25540 (org-set-local 'buffer-file-name
25541 (with-current-buffer (buffer-base-buffer)
25542 buffer-file-name))
25543 (error "Need a file name to be able to export.")))
25545 (message "Exporting...")
25546 (setq-default org-todo-line-regexp org-todo-line-regexp)
25547 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25548 (setq-default org-done-keywords org-done-keywords)
25549 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25550 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25551 ext-plist
25552 (org-infile-export-plist)))
25554 (style (plist-get opt-plist :style))
25555 (html-extension (plist-get opt-plist :html-extension))
25556 (link-validate (plist-get opt-plist :link-validation-function))
25557 valid thetoc have-headings first-heading-pos
25558 (odd org-odd-levels-only)
25559 (region-p (org-region-active-p))
25560 (subtree-p
25561 (when region-p
25562 (save-excursion
25563 (goto-char (region-beginning))
25564 (and (org-at-heading-p)
25565 (>= (org-end-of-subtree t t) (region-end))))))
25566 ;; The following two are dynamically scoped into other
25567 ;; routines below.
25568 (org-current-export-dir
25569 (or pub-dir (org-export-directory :html opt-plist)))
25570 (org-current-export-file buffer-file-name)
25571 (level 0) (line "") (origline "") txt todo
25572 (umax nil)
25573 (umax-toc nil)
25574 (filename (if to-buffer nil
25575 (expand-file-name
25576 (concat
25577 (file-name-sans-extension
25578 (or (and subtree-p
25579 (org-entry-get (region-beginning)
25580 "EXPORT_FILE_NAME" t))
25581 (file-name-nondirectory buffer-file-name)))
25582 "." html-extension)
25583 (file-name-as-directory
25584 (or pub-dir (org-export-directory :html opt-plist))))))
25585 (current-dir (if buffer-file-name
25586 (file-name-directory buffer-file-name)
25587 default-directory))
25588 (buffer (if to-buffer
25589 (cond
25590 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25591 (t (get-buffer-create to-buffer)))
25592 (find-file-noselect filename)))
25593 (org-levels-open (make-vector org-level-max nil))
25594 (date (plist-get opt-plist :date))
25595 (author (plist-get opt-plist :author))
25596 (title (or (and subtree-p (org-export-get-title-from-subtree))
25597 (plist-get opt-plist :title)
25598 (and (not
25599 (plist-get opt-plist :skip-before-1st-heading))
25600 (org-export-grab-title-from-buffer))
25601 (and buffer-file-name
25602 (file-name-sans-extension
25603 (file-name-nondirectory buffer-file-name)))
25604 "UNTITLED"))
25605 (html-table-tag (plist-get opt-plist :html-table-tag))
25606 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25607 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25608 (inquote nil)
25609 (infixed nil)
25610 (in-local-list nil)
25611 (local-list-num nil)
25612 (local-list-indent nil)
25613 (llt org-plain-list-ordered-item-terminator)
25614 (email (plist-get opt-plist :email))
25615 (language (plist-get opt-plist :language))
25616 (lang-words nil)
25617 (target-alist nil) tg
25618 (head-count 0) cnt
25619 (start 0)
25620 (coding-system (and (boundp 'buffer-file-coding-system)
25621 buffer-file-coding-system))
25622 (coding-system-for-write (or org-export-html-coding-system
25623 coding-system))
25624 (save-buffer-coding-system (or org-export-html-coding-system
25625 coding-system))
25626 (charset (and coding-system-for-write
25627 (fboundp 'coding-system-get)
25628 (coding-system-get coding-system-for-write
25629 'mime-charset)))
25630 (region
25631 (buffer-substring
25632 (if region-p (region-beginning) (point-min))
25633 (if region-p (region-end) (point-max))))
25634 (lines
25635 (org-split-string
25636 (org-cleaned-string-for-export
25637 region
25638 :emph-multiline t
25639 :for-html t
25640 :skip-before-1st-heading
25641 (plist-get opt-plist :skip-before-1st-heading)
25642 :drawers (plist-get opt-plist :drawers)
25643 :archived-trees
25644 (plist-get opt-plist :archived-trees)
25645 :add-text
25646 (plist-get opt-plist :text)
25647 :LaTeX-fragments
25648 (plist-get opt-plist :LaTeX-fragments))
25649 "[\r\n]"))
25650 table-open type
25651 table-buffer table-orig-buffer
25652 ind start-is-num starter didclose
25653 rpl path desc descp desc1 desc2 link
25656 (let ((inhibit-read-only t))
25657 (org-unmodified
25658 (remove-text-properties (point-min) (point-max)
25659 '(:org-license-to-kill t))))
25661 (message "Exporting...")
25663 (setq org-min-level (org-get-min-level lines))
25664 (setq org-last-level org-min-level)
25665 (org-init-section-numbers)
25667 (cond
25668 ((and date (string-match "%" date))
25669 (setq date (format-time-string date (current-time))))
25670 (date)
25671 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25673 ;; Get the language-dependent settings
25674 (setq lang-words (or (assoc language org-export-language-setup)
25675 (assoc "en" org-export-language-setup)))
25677 ;; Switch to the output buffer
25678 (set-buffer buffer)
25679 (let ((inhibit-read-only t)) (erase-buffer))
25680 (fundamental-mode)
25682 (and (fboundp 'set-buffer-file-coding-system)
25683 (set-buffer-file-coding-system coding-system-for-write))
25685 (let ((case-fold-search nil)
25686 (org-odd-levels-only odd))
25687 ;; create local variables for all options, to make sure all called
25688 ;; functions get the correct information
25689 (mapc (lambda (x)
25690 (set (make-local-variable (cdr x))
25691 (plist-get opt-plist (car x))))
25692 org-export-plist-vars)
25693 (setq umax (if arg (prefix-numeric-value arg)
25694 org-export-headline-levels))
25695 (setq umax-toc (if (integerp org-export-with-toc)
25696 (min org-export-with-toc umax)
25697 umax))
25698 (unless body-only
25699 ;; File header
25700 (insert (format
25701 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25702 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25703 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25704 lang=\"%s\" xml:lang=\"%s\">
25705 <head>
25706 <title>%s</title>
25707 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25708 <meta name=\"generator\" content=\"Org-mode\"/>
25709 <meta name=\"generated\" content=\"%s\"/>
25710 <meta name=\"author\" content=\"%s\"/>
25712 </head><body>
25714 language language (org-html-expand title)
25715 (or charset "iso-8859-1") date author style))
25717 (insert (or (plist-get opt-plist :preamble) ""))
25719 (when (plist-get opt-plist :auto-preamble)
25720 (if title (insert (format org-export-html-title-format
25721 (org-html-expand title))))))
25723 (if (and org-export-with-toc (not body-only))
25724 (progn
25725 (push (format "<h%d>%s</h%d>\n"
25726 org-export-html-toplevel-hlevel
25727 (nth 3 lang-words)
25728 org-export-html-toplevel-hlevel)
25729 thetoc)
25730 (push "<ul>\n<li>" thetoc)
25731 (setq lines
25732 (mapcar '(lambda (line)
25733 (if (string-match org-todo-line-regexp line)
25734 ;; This is a headline
25735 (progn
25736 (setq have-headings t)
25737 (setq level (- (match-end 1) (match-beginning 1))
25738 level (org-tr-level level)
25739 txt (save-match-data
25740 (org-html-expand
25741 (org-export-cleanup-toc-line
25742 (match-string 3 line))))
25743 todo
25744 (or (and org-export-mark-todo-in-toc
25745 (match-beginning 2)
25746 (not (member (match-string 2 line)
25747 org-done-keywords)))
25748 ; TODO, not DONE
25749 (and org-export-mark-todo-in-toc
25750 (= level umax-toc)
25751 (org-search-todo-below
25752 line lines level))))
25753 (if (string-match
25754 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25755 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25756 (if (string-match quote-re0 txt)
25757 (setq txt (replace-match "" t t txt)))
25758 (if org-export-with-section-numbers
25759 (setq txt (concat (org-section-number level)
25760 " " txt)))
25761 (if (<= level (max umax umax-toc))
25762 (setq head-count (+ head-count 1)))
25763 (if (<= level umax-toc)
25764 (progn
25765 (if (> level org-last-level)
25766 (progn
25767 (setq cnt (- level org-last-level))
25768 (while (>= (setq cnt (1- cnt)) 0)
25769 (push "\n<ul>\n<li>" thetoc))
25770 (push "\n" thetoc)))
25771 (if (< level org-last-level)
25772 (progn
25773 (setq cnt (- org-last-level level))
25774 (while (>= (setq cnt (1- cnt)) 0)
25775 (push "</li>\n</ul>" thetoc))
25776 (push "\n" thetoc)))
25777 ;; Check for targets
25778 (while (string-match org-target-regexp line)
25779 (setq tg (match-string 1 line)
25780 line (replace-match
25781 (concat "@<span class=\"target\">" tg "@</span> ")
25782 t t line))
25783 (push (cons (org-solidify-link-text tg)
25784 (format "sec-%d" head-count))
25785 target-alist))
25786 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25787 (setq txt (replace-match "" t t txt)))
25788 (push
25789 (format
25790 (if todo
25791 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25792 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25793 head-count txt) thetoc)
25795 (setq org-last-level level))
25797 line)
25798 lines))
25799 (while (> org-last-level (1- org-min-level))
25800 (setq org-last-level (1- org-last-level))
25801 (push "</li>\n</ul>\n" thetoc))
25802 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25804 (setq head-count 0)
25805 (org-init-section-numbers)
25807 (while (setq line (pop lines) origline line)
25808 (catch 'nextline
25810 ;; end of quote section?
25811 (when (and inquote (string-match "^\\*+ " line))
25812 (insert "</pre>\n")
25813 (setq inquote nil))
25814 ;; inside a quote section?
25815 (when inquote
25816 (insert (org-html-protect line) "\n")
25817 (throw 'nextline nil))
25819 ;; verbatim lines
25820 (when (and org-export-with-fixed-width
25821 (string-match "^[ \t]*:\\(.*\\)" line))
25822 (when (not infixed)
25823 (setq infixed t)
25824 (insert "<pre>\n"))
25825 (insert (org-html-protect (match-string 1 line)) "\n")
25826 (when (and lines
25827 (not (string-match "^[ \t]*\\(:.*\\)"
25828 (car lines))))
25829 (setq infixed nil)
25830 (insert "</pre>\n"))
25831 (throw 'nextline nil))
25833 ;; Protected HTML
25834 (when (get-text-property 0 'org-protected line)
25835 (let (par)
25836 (when (re-search-backward
25837 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25838 (setq par (match-string 1))
25839 (replace-match "\\2\n"))
25840 (insert line "\n")
25841 (while (and lines
25842 (or (= (length (car lines)) 0)
25843 (get-text-property 0 'org-protected (car lines))))
25844 (insert (pop lines) "\n"))
25845 (and par (insert "<p>\n")))
25846 (throw 'nextline nil))
25848 ;; Horizontal line
25849 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25850 (insert "\n<hr/>\n")
25851 (throw 'nextline nil))
25853 ;; make targets to anchors
25854 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25855 (cond
25856 ((match-end 2)
25857 (setq line (replace-match
25858 (concat "@<a name=\""
25859 (org-solidify-link-text (match-string 1 line))
25860 "\">\\nbsp@</a>")
25861 t t line)))
25862 ((and org-export-with-toc (equal (string-to-char line) ?*))
25863 (setq line (replace-match
25864 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25865 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25866 t t line)))
25868 (setq line (replace-match
25869 (concat "@<a name=\""
25870 (org-solidify-link-text (match-string 1 line))
25871 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25872 t t line)))))
25874 (setq line (org-html-handle-time-stamps line))
25876 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25877 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25878 ;; Also handle sub_superscripts and checkboxes
25879 (or (string-match org-table-hline-regexp line)
25880 (setq line (org-html-expand line)))
25882 ;; Format the links
25883 (setq start 0)
25884 (while (string-match org-bracket-link-analytic-regexp line start)
25885 (setq start (match-beginning 0))
25886 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25887 (setq path (match-string 3 line))
25888 (setq desc1 (if (match-end 5) (match-string 5 line))
25889 desc2 (if (match-end 2) (concat type ":" path) path)
25890 descp (and desc1 (not (equal desc1 desc2)))
25891 desc (or desc1 desc2))
25892 ;; Make an image out of the description if that is so wanted
25893 (when (and descp (org-file-image-p desc))
25894 (save-match-data
25895 (if (string-match "^file:" desc)
25896 (setq desc (substring desc (match-end 0)))))
25897 (setq desc (concat "<img src=\"" desc "\"/>")))
25898 ;; FIXME: do we need to unescape here somewhere?
25899 (cond
25900 ((equal type "internal")
25901 (setq rpl
25902 (concat
25903 "<a href=\"#"
25904 (org-solidify-link-text
25905 (save-match-data (org-link-unescape path)) target-alist)
25906 "\">" desc "</a>")))
25907 ((member type '("http" "https"))
25908 ;; standard URL, just check if we need to inline an image
25909 (if (and (or (eq t org-export-html-inline-images)
25910 (and org-export-html-inline-images (not descp)))
25911 (org-file-image-p path))
25912 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25913 (setq link (concat type ":" path))
25914 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25915 ((member type '("ftp" "mailto" "news"))
25916 ;; standard URL
25917 (setq link (concat type ":" path))
25918 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25919 ((string= type "file")
25920 ;; FILE link
25921 (let* ((filename path)
25922 (abs-p (file-name-absolute-p filename))
25923 thefile file-is-image-p search)
25924 (save-match-data
25925 (if (string-match "::\\(.*\\)" filename)
25926 (setq search (match-string 1 filename)
25927 filename (replace-match "" t nil filename)))
25928 (setq valid
25929 (if (functionp link-validate)
25930 (funcall link-validate filename current-dir)
25932 (setq file-is-image-p (org-file-image-p filename))
25933 (setq thefile (if abs-p (expand-file-name filename) filename))
25934 (when (and org-export-html-link-org-files-as-html
25935 (string-match "\\.org$" thefile))
25936 (setq thefile (concat (substring thefile 0
25937 (match-beginning 0))
25938 "." html-extension))
25939 (if (and search
25940 ;; make sure this is can be used as target search
25941 (not (string-match "^[0-9]*$" search))
25942 (not (string-match "^\\*" search))
25943 (not (string-match "^/.*/$" search)))
25944 (setq thefile (concat thefile "#"
25945 (org-solidify-link-text
25946 (org-link-unescape search)))))
25947 (when (string-match "^file:" desc)
25948 (setq desc (replace-match "" t t desc))
25949 (if (string-match "\\.org$" desc)
25950 (setq desc (replace-match "" t t desc))))))
25951 (setq rpl (if (and file-is-image-p
25952 (or (eq t org-export-html-inline-images)
25953 (and org-export-html-inline-images
25954 (not descp))))
25955 (concat "<img src=\"" thefile "\"/>")
25956 (concat "<a href=\"" thefile "\">" desc "</a>")))
25957 (if (not valid) (setq rpl desc))))
25958 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25959 (setq rpl (concat "<i>&lt;" type ":"
25960 (save-match-data (org-link-unescape path))
25961 "&gt;</i>"))))
25962 (setq line (replace-match rpl t t line)
25963 start (+ start (length rpl))))
25965 ;; TODO items
25966 (if (and (string-match org-todo-line-regexp line)
25967 (match-beginning 2))
25969 (setq line
25970 (concat (substring line 0 (match-beginning 2))
25971 "<span class=\""
25972 (if (member (match-string 2 line)
25973 org-done-keywords)
25974 "done" "todo")
25975 "\">" (match-string 2 line)
25976 "</span>" (substring line (match-end 2)))))
25978 ;; Does this contain a reference to a footnote?
25979 (when org-export-with-footnotes
25980 (setq start 0)
25981 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25982 (if (get-text-property (match-beginning 2) 'org-protected line)
25983 (setq start (match-end 2))
25984 (let ((n (match-string 2 line)))
25985 (setq line
25986 (replace-match
25987 (format
25988 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25989 (match-string 1 line) n n n)
25990 t t line))))))
25992 (cond
25993 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25994 ;; This is a headline
25995 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25996 txt (match-string 2 line))
25997 (if (string-match quote-re0 txt)
25998 (setq txt (replace-match "" t t txt)))
25999 (if (<= level (max umax umax-toc))
26000 (setq head-count (+ head-count 1)))
26001 (when in-local-list
26002 ;; Close any local lists before inserting a new header line
26003 (while local-list-num
26004 (org-close-li)
26005 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
26006 (pop local-list-num))
26007 (setq local-list-indent nil
26008 in-local-list nil))
26009 (setq first-heading-pos (or first-heading-pos (point)))
26010 (org-html-level-start level txt umax
26011 (and org-export-with-toc (<= level umax))
26012 head-count)
26013 ;; QUOTES
26014 (when (string-match quote-re line)
26015 (insert "<pre>")
26016 (setq inquote t)))
26018 ((and org-export-with-tables
26019 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
26020 (if (not table-open)
26021 ;; New table starts
26022 (setq table-open t table-buffer nil table-orig-buffer nil))
26023 ;; Accumulate lines
26024 (setq table-buffer (cons line table-buffer)
26025 table-orig-buffer (cons origline table-orig-buffer))
26026 (when (or (not lines)
26027 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
26028 (car lines))))
26029 (setq table-open nil
26030 table-buffer (nreverse table-buffer)
26031 table-orig-buffer (nreverse table-orig-buffer))
26032 (org-close-par-maybe)
26033 (insert (org-format-table-html table-buffer table-orig-buffer))))
26035 ;; Normal lines
26036 (when (string-match
26037 (cond
26038 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
26039 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
26040 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
26041 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
26042 line)
26043 (setq ind (org-get-string-indentation line)
26044 start-is-num (match-beginning 4)
26045 starter (if (match-beginning 2)
26046 (substring (match-string 2 line) 0 -1))
26047 line (substring line (match-beginning 5)))
26048 (unless (string-match "[^ \t]" line)
26049 ;; empty line. Pretend indentation is large.
26050 (setq ind (if org-empty-line-terminates-plain-lists
26052 (1+ (or (car local-list-indent) 1)))))
26053 (setq didclose nil)
26054 (while (and in-local-list
26055 (or (and (= ind (car local-list-indent))
26056 (not starter))
26057 (< ind (car local-list-indent))))
26058 (setq didclose t)
26059 (org-close-li)
26060 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
26061 (pop local-list-num) (pop local-list-indent)
26062 (setq in-local-list local-list-indent))
26063 (cond
26064 ((and starter
26065 (or (not in-local-list)
26066 (> ind (car local-list-indent))))
26067 ;; Start new (level of) list
26068 (org-close-par-maybe)
26069 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
26070 (push start-is-num local-list-num)
26071 (push ind local-list-indent)
26072 (setq in-local-list t))
26073 (starter
26074 ;; continue current list
26075 (org-close-li)
26076 (insert "<li>\n"))
26077 (didclose
26078 ;; we did close a list, normal text follows: need <p>
26079 (org-open-par)))
26080 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
26081 (setq line
26082 (replace-match
26083 (if (equal (match-string 1 line) "X")
26084 "<b>[X]</b>"
26085 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
26086 t t line))))
26088 ;; Empty lines start a new paragraph. If hand-formatted lists
26089 ;; are not fully interpreted, lines starting with "-", "+", "*"
26090 ;; also start a new paragraph.
26091 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
26093 ;; Is this the start of a footnote?
26094 (when org-export-with-footnotes
26095 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
26096 (org-close-par-maybe)
26097 (let ((n (match-string 1 line)))
26098 (setq line (replace-match
26099 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
26101 ;; Check if the line break needs to be conserved
26102 (cond
26103 ((string-match "\\\\\\\\[ \t]*$" line)
26104 (setq line (replace-match "<br/>" t t line)))
26105 (org-export-preserve-breaks
26106 (setq line (concat line "<br/>"))))
26108 (insert line "\n")))))
26110 ;; Properly close all local lists and other lists
26111 (when inquote (insert "</pre>\n"))
26112 (when in-local-list
26113 ;; Close any local lists before inserting a new header line
26114 (while local-list-num
26115 (org-close-li)
26116 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
26117 (pop local-list-num))
26118 (setq local-list-indent nil
26119 in-local-list nil))
26120 (org-html-level-start 1 nil umax
26121 (and org-export-with-toc (<= level umax))
26122 head-count)
26124 (unless body-only
26125 (when (plist-get opt-plist :auto-postamble)
26126 (insert "<div id=\"postamble\">")
26127 (when (and org-export-author-info author)
26128 (insert "<p class=\"author\"> "
26129 (nth 1 lang-words) ": " author "\n")
26130 (when email
26131 (if (listp (split-string email ",+ *"))
26132 (mapc (lambda(e)
26133 (insert "<a href=\"mailto:" e "\">&lt;"
26134 e "&gt;</a>\n"))
26135 (split-string email ",+ *"))
26136 (insert "<a href=\"mailto:" email "\">&lt;"
26137 email "&gt;</a>\n")))
26138 (insert "</p>\n"))
26139 (when (and date org-export-time-stamp-file)
26140 (insert "<p class=\"date\"> "
26141 (nth 2 lang-words) ": "
26142 date "</p>\n"))
26143 (insert "</div>"))
26145 (if org-export-html-with-timestamp
26146 (insert org-export-html-html-helper-timestamp))
26147 (insert (or (plist-get opt-plist :postamble) ""))
26148 (insert "</body>\n</html>\n"))
26150 (normal-mode)
26151 (if (eq major-mode default-major-mode) (html-mode))
26153 ;; insert the table of contents
26154 (goto-char (point-min))
26155 (when thetoc
26156 (if (or (re-search-forward
26157 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
26158 (re-search-forward
26159 "\\[TABLE-OF-CONTENTS\\]" nil t))
26160 (progn
26161 (goto-char (match-beginning 0))
26162 (replace-match ""))
26163 (goto-char first-heading-pos)
26164 (when (looking-at "\\s-*</p>")
26165 (goto-char (match-end 0))
26166 (insert "\n")))
26167 (insert "<div id=\"table-of-contents\">\n")
26168 (mapc 'insert thetoc)
26169 (insert "</div>\n"))
26170 ;; remove empty paragraphs and lists
26171 (goto-char (point-min))
26172 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
26173 (replace-match ""))
26174 (goto-char (point-min))
26175 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
26176 (replace-match ""))
26177 (goto-char (point-min))
26178 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
26179 (replace-match ""))
26180 ;; Convert whitespace place holders
26181 (goto-char (point-min))
26182 (let (beg end n)
26183 (while (setq beg (next-single-property-change (point) 'org-whitespace))
26184 (setq n (get-text-property beg 'org-whitespace)
26185 end (next-single-property-change beg 'org-whitespace))
26186 (goto-char beg)
26187 (delete-region beg end)
26188 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
26189 (make-string n ?x)))))
26190 (or to-buffer (save-buffer))
26191 (goto-char (point-min))
26192 (message "Exporting... done")
26193 (if (eq to-buffer 'string)
26194 (prog1 (buffer-substring (point-min) (point-max))
26195 (kill-buffer (current-buffer)))
26196 (current-buffer)))))
26198 (defvar org-table-colgroup-info nil)
26199 (defun org-format-table-ascii (lines)
26200 "Format a table for ascii export."
26201 (if (stringp lines)
26202 (setq lines (org-split-string lines "\n")))
26203 (if (not (string-match "^[ \t]*|" (car lines)))
26204 ;; Table made by table.el - test for spanning
26205 lines
26207 ;; A normal org table
26208 ;; Get rid of hlines at beginning and end
26209 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26210 (setq lines (nreverse lines))
26211 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26212 (setq lines (nreverse lines))
26213 (when org-export-table-remove-special-lines
26214 ;; Check if the table has a marking column. If yes remove the
26215 ;; column and the special lines
26216 (setq lines (org-table-clean-before-export lines)))
26217 ;; Get rid of the vertical lines except for grouping
26218 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
26219 rtn line vl1 start)
26220 (while (setq line (pop lines))
26221 (if (string-match org-table-hline-regexp line)
26222 (and (string-match "|\\(.*\\)|" line)
26223 (setq line (replace-match " \\1" t nil line)))
26224 (setq start 0 vl1 vl)
26225 (while (string-match "|" line start)
26226 (setq start (match-end 0))
26227 (or (pop vl1) (setq line (replace-match " " t t line)))))
26228 (push line rtn))
26229 (nreverse rtn))))
26231 (defun org-colgroup-info-to-vline-list (info)
26232 (let (vl new last)
26233 (while info
26234 (setq last new new (pop info))
26235 (if (or (memq last '(:end :startend))
26236 (memq new '(:start :startend)))
26237 (push t vl)
26238 (push nil vl)))
26239 (setq vl (nreverse vl))
26240 (and vl (setcar vl nil))
26241 vl))
26243 (defun org-format-table-html (lines olines)
26244 "Find out which HTML converter to use and return the HTML code."
26245 (if (stringp lines)
26246 (setq lines (org-split-string lines "\n")))
26247 (if (string-match "^[ \t]*|" (car lines))
26248 ;; A normal org table
26249 (org-format-org-table-html lines)
26250 ;; Table made by table.el - test for spanning
26251 (let* ((hlines (delq nil (mapcar
26252 (lambda (x)
26253 (if (string-match "^[ \t]*\\+-" x) x
26254 nil))
26255 lines)))
26256 (first (car hlines))
26257 (ll (and (string-match "\\S-+" first)
26258 (match-string 0 first)))
26259 (re (concat "^[ \t]*" (regexp-quote ll)))
26260 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
26261 hlines))))
26262 (if (and (not spanning)
26263 (not org-export-prefer-native-exporter-for-tables))
26264 ;; We can use my own converter with HTML conversions
26265 (org-format-table-table-html lines)
26266 ;; Need to use the code generator in table.el, with the original text.
26267 (org-format-table-table-html-using-table-generate-source olines)))))
26269 (defun org-format-org-table-html (lines &optional splice)
26270 "Format a table into HTML."
26271 ;; Get rid of hlines at beginning and end
26272 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26273 (setq lines (nreverse lines))
26274 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26275 (setq lines (nreverse lines))
26276 (when org-export-table-remove-special-lines
26277 ;; Check if the table has a marking column. If yes remove the
26278 ;; column and the special lines
26279 (setq lines (org-table-clean-before-export lines)))
26281 (let ((head (and org-export-highlight-first-table-line
26282 (delq nil (mapcar
26283 (lambda (x) (string-match "^[ \t]*|-" x))
26284 (cdr lines)))))
26285 (nlines 0) fnum i
26286 tbopen line fields html gr colgropen)
26287 (if splice (setq head nil))
26288 (unless splice (push (if head "<thead>" "<tbody>") html))
26289 (setq tbopen t)
26290 (while (setq line (pop lines))
26291 (catch 'next-line
26292 (if (string-match "^[ \t]*|-" line)
26293 (progn
26294 (unless splice
26295 (push (if head "</thead>" "</tbody>") html)
26296 (if lines (push "<tbody>" html) (setq tbopen nil)))
26297 (setq head nil) ;; head ends here, first time around
26298 ;; ignore this line
26299 (throw 'next-line t)))
26300 ;; Break the line into fields
26301 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26302 (unless fnum (setq fnum (make-vector (length fields) 0)))
26303 (setq nlines (1+ nlines) i -1)
26304 (push (concat "<tr>"
26305 (mapconcat
26306 (lambda (x)
26307 (setq i (1+ i))
26308 (if (and (< i nlines)
26309 (string-match org-table-number-regexp x))
26310 (incf (aref fnum i)))
26311 (if head
26312 (concat (car org-export-table-header-tags) x
26313 (cdr org-export-table-header-tags))
26314 (concat (car org-export-table-data-tags) x
26315 (cdr org-export-table-data-tags))))
26316 fields "")
26317 "</tr>")
26318 html)))
26319 (unless splice (if tbopen (push "</tbody>" html)))
26320 (unless splice (push "</table>\n" html))
26321 (setq html (nreverse html))
26322 (unless splice
26323 ;; Put in col tags with the alignment (unfortuntely often ignored...)
26324 (push (mapconcat
26325 (lambda (x)
26326 (setq gr (pop org-table-colgroup-info))
26327 (format "%s<col align=\"%s\"></col>%s"
26328 (if (memq gr '(:start :startend))
26329 (prog1
26330 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
26331 (setq colgropen t))
26333 (if (> (/ (float x) nlines) org-table-number-fraction)
26334 "right" "left")
26335 (if (memq gr '(:end :startend))
26336 (progn (setq colgropen nil) "</colgroup>")
26337 "")))
26338 fnum "")
26339 html)
26340 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
26341 (push html-table-tag html))
26342 (concat (mapconcat 'identity html "\n") "\n")))
26344 (defun org-table-clean-before-export (lines)
26345 "Check if the table has a marking column.
26346 If yes remove the column and the special lines."
26347 (setq org-table-colgroup-info nil)
26348 (if (memq nil
26349 (mapcar
26350 (lambda (x) (or (string-match "^[ \t]*|-" x)
26351 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
26352 lines))
26353 (progn
26354 (setq org-table-clean-did-remove-column nil)
26355 (delq nil
26356 (mapcar
26357 (lambda (x)
26358 (cond
26359 ((string-match "^[ \t]*| */ *|" x)
26360 (setq org-table-colgroup-info
26361 (mapcar (lambda (x)
26362 (cond ((member x '("<" "&lt;")) :start)
26363 ((member x '(">" "&gt;")) :end)
26364 ((member x '("<>" "&lt;&gt;")) :startend)
26365 (t nil)))
26366 (org-split-string x "[ \t]*|[ \t]*")))
26367 nil)
26368 (t x)))
26369 lines)))
26370 (setq org-table-clean-did-remove-column t)
26371 (delq nil
26372 (mapcar
26373 (lambda (x)
26374 (cond
26375 ((string-match "^[ \t]*| */ *|" x)
26376 (setq org-table-colgroup-info
26377 (mapcar (lambda (x)
26378 (cond ((member x '("<" "&lt;")) :start)
26379 ((member x '(">" "&gt;")) :end)
26380 ((member x '("<>" "&lt;&gt;")) :startend)
26381 (t nil)))
26382 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
26383 nil)
26384 ((string-match "^[ \t]*| *[!_^/] *|" x)
26385 nil) ; ignore this line
26386 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
26387 (string-match "^\\([ \t]*\\)|[^|]*|" x))
26388 ;; remove the first column
26389 (replace-match "\\1|" t nil x))))
26390 lines))))
26392 (defun org-format-table-table-html (lines)
26393 "Format a table generated by table.el into HTML.
26394 This conversion does *not* use `table-generate-source' from table.el.
26395 This has the advantage that Org-mode's HTML conversions can be used.
26396 But it has the disadvantage, that no cell- or row-spanning is allowed."
26397 (let (line field-buffer
26398 (head org-export-highlight-first-table-line)
26399 fields html empty)
26400 (setq html (concat html-table-tag "\n"))
26401 (while (setq line (pop lines))
26402 (setq empty "&nbsp;")
26403 (catch 'next-line
26404 (if (string-match "^[ \t]*\\+-" line)
26405 (progn
26406 (if field-buffer
26407 (progn
26408 (setq
26409 html
26410 (concat
26411 html
26412 "<tr>"
26413 (mapconcat
26414 (lambda (x)
26415 (if (equal x "") (setq x empty))
26416 (if head
26417 (concat (car org-export-table-header-tags) x
26418 (cdr org-export-table-header-tags))
26419 (concat (car org-export-table-data-tags) x
26420 (cdr org-export-table-data-tags))))
26421 field-buffer "\n")
26422 "</tr>\n"))
26423 (setq head nil)
26424 (setq field-buffer nil)))
26425 ;; Ignore this line
26426 (throw 'next-line t)))
26427 ;; Break the line into fields and store the fields
26428 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26429 (if field-buffer
26430 (setq field-buffer (mapcar
26431 (lambda (x)
26432 (concat x "<br/>" (pop fields)))
26433 field-buffer))
26434 (setq field-buffer fields))))
26435 (setq html (concat html "</table>\n"))
26436 html))
26438 (defun org-format-table-table-html-using-table-generate-source (lines)
26439 "Format a table into html, using `table-generate-source' from table.el.
26440 This has the advantage that cell- or row-spanning is allowed.
26441 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
26442 (require 'table)
26443 (with-current-buffer (get-buffer-create " org-tmp1 ")
26444 (erase-buffer)
26445 (insert (mapconcat 'identity lines "\n"))
26446 (goto-char (point-min))
26447 (if (not (re-search-forward "|[^+]" nil t))
26448 (error "Error processing table"))
26449 (table-recognize-table)
26450 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
26451 (table-generate-source 'html " org-tmp2 ")
26452 (set-buffer " org-tmp2 ")
26453 (buffer-substring (point-min) (point-max))))
26455 (defun org-html-handle-time-stamps (s)
26456 "Format time stamps in string S, or remove them."
26457 (catch 'exit
26458 (let (r b)
26459 (while (string-match org-maybe-keyword-time-regexp s)
26460 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
26461 ;; never export CLOCK
26462 (throw 'exit ""))
26463 (or b (setq b (substring s 0 (match-beginning 0))))
26464 (if (not org-export-with-timestamps)
26465 (setq r (concat r (substring s 0 (match-beginning 0)))
26466 s (substring s (match-end 0)))
26467 (setq r (concat
26468 r (substring s 0 (match-beginning 0))
26469 (if (match-end 1)
26470 (format "@<span class=\"timestamp-kwd\">%s @</span>"
26471 (match-string 1 s)))
26472 (format " @<span class=\"timestamp\">%s@</span>"
26473 (substring
26474 (org-translate-time (match-string 3 s)) 1 -1)))
26475 s (substring s (match-end 0)))))
26476 ;; Line break if line started and ended with time stamp stuff
26477 (if (not r)
26479 (setq r (concat r s))
26480 (unless (string-match "\\S-" (concat b s))
26481 (setq r (concat r "@<br/>")))
26482 r))))
26484 (defun org-html-protect (s)
26485 ;; convert & to &amp;, < to &lt; and > to &gt;
26486 (let ((start 0))
26487 (while (string-match "&" s start)
26488 (setq s (replace-match "&amp;" t t s)
26489 start (1+ (match-beginning 0))))
26490 (while (string-match "<" s)
26491 (setq s (replace-match "&lt;" t t s)))
26492 (while (string-match ">" s)
26493 (setq s (replace-match "&gt;" t t s))))
26496 (defun org-export-cleanup-toc-line (s)
26497 "Remove tags and time staps from lines going into the toc."
26498 (when (memq org-export-with-tags '(not-in-toc nil))
26499 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
26500 (setq s (replace-match "" t t s))))
26501 (when org-export-remove-timestamps-from-toc
26502 (while (string-match org-maybe-keyword-time-regexp s)
26503 (setq s (replace-match "" t t s))))
26504 (while (string-match org-bracket-link-regexp s)
26505 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
26506 t t s)))
26509 (defun org-html-expand (string)
26510 "Prepare STRING for HTML export. Applies all active conversions.
26511 If there are links in the string, don't modify these."
26512 (let* ((re (concat org-bracket-link-regexp "\\|"
26513 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
26514 m s l res)
26515 (while (setq m (string-match re string))
26516 (setq s (substring string 0 m)
26517 l (match-string 0 string)
26518 string (substring string (match-end 0)))
26519 (push (org-html-do-expand s) res)
26520 (push l res))
26521 (push (org-html-do-expand string) res)
26522 (apply 'concat (nreverse res))))
26524 (defun org-html-do-expand (s)
26525 "Apply all active conversions to translate special ASCII to HTML."
26526 (setq s (org-html-protect s))
26527 (if org-export-html-expand
26528 (let ((start 0))
26529 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
26530 (setq s (replace-match "<\\1>" t nil s)))))
26531 (if org-export-with-emphasize
26532 (setq s (org-export-html-convert-emphasize s)))
26533 (if org-export-with-special-strings
26534 (setq s (org-export-html-convert-special-strings s)))
26535 (if org-export-with-sub-superscripts
26536 (setq s (org-export-html-convert-sub-super s)))
26537 (if org-export-with-TeX-macros
26538 (let ((start 0) wd ass)
26539 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26540 (if (get-text-property (match-beginning 0) 'org-protected s)
26541 (setq start (match-end 0))
26542 (setq wd (match-string 1 s))
26543 (if (setq ass (assoc wd org-html-entities))
26544 (setq s (replace-match (or (cdr ass)
26545 (concat "&" (car ass) ";"))
26546 t t s))
26547 (setq start (+ start (length wd))))))))
26550 (defun org-create-multibrace-regexp (left right n)
26551 "Create a regular expression which will match a balanced sexp.
26552 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26553 as single character strings.
26554 The regexp returned will match the entire expression including the
26555 delimiters. It will also define a single group which contains the
26556 match except for the outermost delimiters. The maximum depth of
26557 stacked delimiters is N. Escaping delimiters is not possible."
26558 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26559 (or "\\|")
26560 (re nothing)
26561 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26562 (while (> n 1)
26563 (setq n (1- n)
26564 re (concat re or next)
26565 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26566 (concat left "\\(" re "\\)" right)))
26568 (defvar org-match-substring-regexp
26569 (concat
26570 "\\([^\\]\\)\\([_^]\\)\\("
26571 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26572 "\\|"
26573 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26574 "\\|"
26575 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26576 "The regular expression matching a sub- or superscript.")
26578 (defvar org-match-substring-with-braces-regexp
26579 (concat
26580 "\\([^\\]\\)\\([_^]\\)\\("
26581 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26582 "\\)")
26583 "The regular expression matching a sub- or superscript, forcing braces.")
26585 (defconst org-export-html-special-string-regexps
26586 '(("\\\\-" . "&shy;")
26587 ("---\\([^-]\\)" . "&mdash;\\1")
26588 ("--\\([^-]\\)" . "&ndash;\\1")
26589 ("\\.\\.\\." . "&hellip;"))
26590 "Regular expressions for special string conversion.")
26592 (defun org-export-html-convert-special-strings (string)
26593 "Convert special characters in STRING to HTML."
26594 (let ((all org-export-html-special-string-regexps)
26595 e a re rpl start)
26596 (while (setq a (pop all))
26597 (setq re (car a) rpl (cdr a) start 0)
26598 (while (string-match re string start)
26599 (if (get-text-property (match-beginning 0) 'org-protected string)
26600 (setq start (match-end 0))
26601 (setq string (replace-match rpl t nil string)))))
26602 string))
26604 (defun org-export-html-convert-sub-super (string)
26605 "Convert sub- and superscripts in STRING to HTML."
26606 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26607 (while (string-match org-match-substring-regexp string s)
26608 (cond
26609 ((and requireb (match-end 8)) (setq s (match-end 2)))
26610 ((get-text-property (match-beginning 2) 'org-protected string)
26611 (setq s (match-end 2)))
26613 (setq s (match-end 1)
26614 key (if (string= (match-string 2 string) "_") "sub" "sup")
26615 c (or (match-string 8 string)
26616 (match-string 6 string)
26617 (match-string 5 string))
26618 string (replace-match
26619 (concat (match-string 1 string)
26620 "<" key ">" c "</" key ">")
26621 t t string)))))
26622 (while (string-match "\\\\\\([_^]\\)" string)
26623 (setq string (replace-match (match-string 1 string) t t string)))
26624 string))
26626 (defun org-export-html-convert-emphasize (string)
26627 "Apply emphasis."
26628 (let ((s 0) rpl)
26629 (while (string-match org-emph-re string s)
26630 (if (not (equal
26631 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26632 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26633 (setq s (match-beginning 0)
26635 (concat
26636 (match-string 1 string)
26637 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26638 (match-string 4 string)
26639 (nth 3 (assoc (match-string 3 string)
26640 org-emphasis-alist))
26641 (match-string 5 string))
26642 string (replace-match rpl t t string)
26643 s (+ s (- (length rpl) 2)))
26644 (setq s (1+ s))))
26645 string))
26647 (defvar org-par-open nil)
26648 (defun org-open-par ()
26649 "Insert <p>, but first close previous paragraph if any."
26650 (org-close-par-maybe)
26651 (insert "\n<p>")
26652 (setq org-par-open t))
26653 (defun org-close-par-maybe ()
26654 "Close paragraph if there is one open."
26655 (when org-par-open
26656 (insert "</p>")
26657 (setq org-par-open nil)))
26658 (defun org-close-li ()
26659 "Close <li> if necessary."
26660 (org-close-par-maybe)
26661 (insert "</li>\n"))
26663 (defvar body-only) ; dynamically scoped into this.
26664 (defun org-html-level-start (level title umax with-toc head-count)
26665 "Insert a new level in HTML export.
26666 When TITLE is nil, just close all open levels."
26667 (org-close-par-maybe)
26668 (let ((l org-level-max))
26669 (while (>= l level)
26670 (if (aref org-levels-open (1- l))
26671 (progn
26672 (org-html-level-close l umax)
26673 (aset org-levels-open (1- l) nil)))
26674 (setq l (1- l)))
26675 (when title
26676 ;; If title is nil, this means this function is called to close
26677 ;; all levels, so the rest is done only if title is given
26678 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26679 (setq title (replace-match
26680 (if org-export-with-tags
26681 (save-match-data
26682 (concat
26683 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26684 (mapconcat 'identity (org-split-string
26685 (match-string 1 title) ":")
26686 "&nbsp;")
26687 "</span>"))
26689 t t title)))
26690 (if (> level umax)
26691 (progn
26692 (if (aref org-levels-open (1- level))
26693 (progn
26694 (org-close-li)
26695 (insert "<li>" title "<br/>\n"))
26696 (aset org-levels-open (1- level) t)
26697 (org-close-par-maybe)
26698 (insert "<ul>\n<li>" title "<br/>\n")))
26699 (aset org-levels-open (1- level) t)
26700 (if (and org-export-with-section-numbers (not body-only))
26701 (setq title (concat (org-section-number level) " " title)))
26702 (setq level (+ level org-export-html-toplevel-hlevel -1))
26703 (if with-toc
26704 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26705 level level head-count title level))
26706 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26707 (org-open-par)))))
26709 (defun org-html-level-close (level max-outline-level)
26710 "Terminate one level in HTML export."
26711 (if (<= level max-outline-level)
26712 (insert "</div>\n")
26713 (org-close-li)
26714 (insert "</ul>\n")))
26716 ;;; iCalendar export
26718 ;;;###autoload
26719 (defun org-export-icalendar-this-file ()
26720 "Export current file as an iCalendar file.
26721 The iCalendar file will be located in the same directory as the Org-mode
26722 file, but with extension `.ics'."
26723 (interactive)
26724 (org-export-icalendar nil buffer-file-name))
26726 ;;;###autoload
26727 (defun org-export-icalendar-all-agenda-files ()
26728 "Export all files in `org-agenda-files' to iCalendar .ics files.
26729 Each iCalendar file will be located in the same directory as the Org-mode
26730 file, but with extension `.ics'."
26731 (interactive)
26732 (apply 'org-export-icalendar nil (org-agenda-files t)))
26734 ;;;###autoload
26735 (defun org-export-icalendar-combine-agenda-files ()
26736 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26737 The file is stored under the name `org-combined-agenda-icalendar-file'."
26738 (interactive)
26739 (apply 'org-export-icalendar t (org-agenda-files t)))
26741 (defun org-export-icalendar (combine &rest files)
26742 "Create iCalendar files for all elements of FILES.
26743 If COMBINE is non-nil, combine all calendar entries into a single large
26744 file and store it under the name `org-combined-agenda-icalendar-file'."
26745 (save-excursion
26746 (org-prepare-agenda-buffers files)
26747 (let* ((dir (org-export-directory
26748 :ical (list :publishing-directory
26749 org-export-publishing-directory)))
26750 file ical-file ical-buffer category started org-agenda-new-buffers)
26751 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26752 (when combine
26753 (setq ical-file
26754 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26755 org-combined-agenda-icalendar-file
26756 (expand-file-name org-combined-agenda-icalendar-file dir))
26757 ical-buffer (org-get-agenda-file-buffer ical-file))
26758 (set-buffer ical-buffer) (erase-buffer))
26759 (while (setq file (pop files))
26760 (catch 'nextfile
26761 (org-check-agenda-file file)
26762 (set-buffer (org-get-agenda-file-buffer file))
26763 (unless combine
26764 (setq ical-file (concat (file-name-as-directory dir)
26765 (file-name-sans-extension
26766 (file-name-nondirectory buffer-file-name))
26767 ".ics"))
26768 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26769 (with-current-buffer ical-buffer (erase-buffer)))
26770 (setq category (or org-category
26771 (file-name-sans-extension
26772 (file-name-nondirectory buffer-file-name))))
26773 (if (symbolp category) (setq category (symbol-name category)))
26774 (let ((standard-output ical-buffer))
26775 (if combine
26776 (and (not started) (setq started t)
26777 (org-start-icalendar-file org-icalendar-combined-name))
26778 (org-start-icalendar-file category))
26779 (org-print-icalendar-entries combine)
26780 (when (or (and combine (not files)) (not combine))
26781 (org-finish-icalendar-file)
26782 (set-buffer ical-buffer)
26783 (save-buffer)
26784 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26785 (org-release-buffers org-agenda-new-buffers))))
26787 (defvar org-after-save-iCalendar-file-hook nil
26788 "Hook run after an iCalendar file has been saved.
26789 The iCalendar buffer is still current when this hook is run.
26790 A good way to use this is to tell a desktop calenndar application to re-read
26791 the iCalendar file.")
26793 (defun org-print-icalendar-entries (&optional combine)
26794 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26795 When COMBINE is non nil, add the category to each line."
26796 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26797 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26798 (dts (org-ical-ts-to-string
26799 (format-time-string (cdr org-time-stamp-formats) (current-time))
26800 "DTSTART"))
26801 hd ts ts2 state status (inc t) pos b sexp rrule
26802 scheduledp deadlinep tmp pri category entry location summary desc
26803 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26804 (org-refresh-category-properties)
26805 (save-excursion
26806 (goto-char (point-min))
26807 (while (re-search-forward re1 nil t)
26808 (catch :skip
26809 (org-agenda-skip)
26810 (when (boundp 'org-icalendar-verify-function)
26811 (unless (funcall org-icalendar-verify-function)
26812 (outline-next-heading)
26813 (backward-char 1)
26814 (throw :skip nil)))
26815 (setq pos (match-beginning 0)
26816 ts (match-string 0)
26817 inc t
26818 hd (org-get-heading)
26819 summary (org-icalendar-cleanup-string
26820 (org-entry-get nil "SUMMARY"))
26821 desc (org-icalendar-cleanup-string
26822 (or (org-entry-get nil "DESCRIPTION")
26823 (and org-icalendar-include-body (org-get-entry)))
26824 t org-icalendar-include-body)
26825 location (org-icalendar-cleanup-string
26826 (org-entry-get nil "LOCATION"))
26827 category (org-get-category))
26828 (if (looking-at re2)
26829 (progn
26830 (goto-char (match-end 0))
26831 (setq ts2 (match-string 1) inc nil))
26832 (setq tmp (buffer-substring (max (point-min)
26833 (- pos org-ds-keyword-length))
26834 pos)
26835 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26836 (progn
26837 (setq inc nil)
26838 (replace-match "\\1" t nil ts))
26840 deadlinep (string-match org-deadline-regexp tmp)
26841 scheduledp (string-match org-scheduled-regexp tmp)
26842 ;; donep (org-entry-is-done-p)
26844 (if (or (string-match org-tr-regexp hd)
26845 (string-match org-ts-regexp hd))
26846 (setq hd (replace-match "" t t hd)))
26847 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26848 (setq rrule
26849 (concat "\nRRULE:FREQ="
26850 (cdr (assoc
26851 (match-string 2 ts)
26852 '(("d" . "DAILY")("w" . "WEEKLY")
26853 ("m" . "MONTHLY")("y" . "YEARLY"))))
26854 ";INTERVAL=" (match-string 1 ts)))
26855 (setq rrule ""))
26856 (setq summary (or summary hd))
26857 (if (string-match org-bracket-link-regexp summary)
26858 (setq summary
26859 (replace-match (if (match-end 3)
26860 (match-string 3 summary)
26861 (match-string 1 summary))
26862 t t summary)))
26863 (if deadlinep (setq summary (concat "DL: " summary)))
26864 (if scheduledp (setq summary (concat "S: " summary)))
26865 (if (string-match "\\`<%%" ts)
26866 (with-current-buffer sexp-buffer
26867 (insert (substring ts 1 -1) " " summary "\n"))
26868 (princ (format "BEGIN:VEVENT
26870 %s%s
26871 SUMMARY:%s%s%s
26872 CATEGORIES:%s
26873 END:VEVENT\n"
26874 (org-ical-ts-to-string ts "DTSTART")
26875 (org-ical-ts-to-string ts2 "DTEND" inc)
26876 rrule summary
26877 (if (and desc (string-match "\\S-" desc))
26878 (concat "\nDESCRIPTION: " desc) "")
26879 (if (and location (string-match "\\S-" location))
26880 (concat "\nLOCATION: " location) "")
26881 category)))))
26883 (when (and org-icalendar-include-sexps
26884 (condition-case nil (require 'icalendar) (error nil))
26885 (fboundp 'icalendar-export-region))
26886 ;; Get all the literal sexps
26887 (goto-char (point-min))
26888 (while (re-search-forward "^&?%%(" nil t)
26889 (catch :skip
26890 (org-agenda-skip)
26891 (setq b (match-beginning 0))
26892 (goto-char (1- (match-end 0)))
26893 (forward-sexp 1)
26894 (end-of-line 1)
26895 (setq sexp (buffer-substring b (point)))
26896 (with-current-buffer sexp-buffer
26897 (insert sexp "\n"))
26898 (princ (org-diary-to-ical-string sexp-buffer)))))
26900 (when org-icalendar-include-todo
26901 (goto-char (point-min))
26902 (while (re-search-forward org-todo-line-regexp nil t)
26903 (catch :skip
26904 (org-agenda-skip)
26905 (when (boundp 'org-icalendar-verify-function)
26906 (unless (funcall org-icalendar-verify-function)
26907 (outline-next-heading)
26908 (backward-char 1)
26909 (throw :skip nil)))
26910 (setq state (match-string 2))
26911 (setq status (if (member state org-done-keywords)
26912 "COMPLETED" "NEEDS-ACTION"))
26913 (when (and state
26914 (or (not (member state org-done-keywords))
26915 (eq org-icalendar-include-todo 'all))
26916 (not (member org-archive-tag (org-get-tags-at)))
26918 (setq hd (match-string 3)
26919 summary (org-icalendar-cleanup-string
26920 (org-entry-get nil "SUMMARY"))
26921 desc (org-icalendar-cleanup-string
26922 (or (org-entry-get nil "DESCRIPTION")
26923 (and org-icalendar-include-body (org-get-entry)))
26924 t org-icalendar-include-body)
26925 location (org-icalendar-cleanup-string
26926 (org-entry-get nil "LOCATION")))
26927 (if (string-match org-bracket-link-regexp hd)
26928 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26929 (match-string 1 hd))
26930 t t hd)))
26931 (if (string-match org-priority-regexp hd)
26932 (setq pri (string-to-char (match-string 2 hd))
26933 hd (concat (substring hd 0 (match-beginning 1))
26934 (substring hd (match-end 1))))
26935 (setq pri org-default-priority))
26936 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26937 (- org-lowest-priority org-highest-priority))))))
26939 (princ (format "BEGIN:VTODO
26941 SUMMARY:%s%s%s
26942 CATEGORIES:%s
26943 SEQUENCE:1
26944 PRIORITY:%d
26945 STATUS:%s
26946 END:VTODO\n"
26948 (or summary hd)
26949 (if (and location (string-match "\\S-" location))
26950 (concat "\nLOCATION: " location) "")
26951 (if (and desc (string-match "\\S-" desc))
26952 (concat "\nDESCRIPTION: " desc) "")
26953 category pri status)))))))))
26955 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26956 "Take out stuff and quote what needs to be quoted.
26957 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26958 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26959 characters."
26960 (if (not s)
26962 (when is-body
26963 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26964 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26965 (while (string-match re s) (setq s (replace-match "" t t s)))
26966 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26967 (let ((start 0))
26968 (while (string-match "\\([,;\\]\\)" s start)
26969 (setq start (+ (match-beginning 0) 2)
26970 s (replace-match "\\\\\\1" nil nil s))))
26971 (when is-body
26972 (while (string-match "[ \t]*\n[ \t]*" s)
26973 (setq s (replace-match "\\n" t t s))))
26974 (setq s (org-trim s))
26975 (if is-body
26976 (if maxlength
26977 (if (and (numberp maxlength)
26978 (> (length s) maxlength))
26979 (setq s (substring s 0 maxlength)))))
26982 (defun org-get-entry ()
26983 "Clean-up description string."
26984 (save-excursion
26985 (org-back-to-heading t)
26986 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26988 (defun org-start-icalendar-file (name)
26989 "Start an iCalendar file by inserting the header."
26990 (let ((user user-full-name)
26991 (name (or name "unknown"))
26992 (timezone (cadr (current-time-zone))))
26993 (princ
26994 (format "BEGIN:VCALENDAR
26995 VERSION:2.0
26996 X-WR-CALNAME:%s
26997 PRODID:-//%s//Emacs with Org-mode//EN
26998 X-WR-TIMEZONE:%s
26999 CALSCALE:GREGORIAN\n" name user timezone))))
27001 (defun org-finish-icalendar-file ()
27002 "Finish an iCalendar file by inserting the END statement."
27003 (princ "END:VCALENDAR\n"))
27005 (defun org-ical-ts-to-string (s keyword &optional inc)
27006 "Take a time string S and convert it to iCalendar format.
27007 KEYWORD is added in front, to make a complete line like DTSTART....
27008 When INC is non-nil, increase the hour by two (if time string contains
27009 a time), or the day by one (if it does not contain a time)."
27010 (let ((t1 (org-parse-time-string s 'nodefault))
27011 t2 fmt have-time time)
27012 (if (and (car t1) (nth 1 t1) (nth 2 t1))
27013 (setq t2 t1 have-time t)
27014 (setq t2 (org-parse-time-string s)))
27015 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
27016 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
27017 (when inc
27018 (if have-time
27019 (if org-agenda-default-appointment-duration
27020 (setq mi (+ org-agenda-default-appointment-duration mi))
27021 (setq h (+ 2 h)))
27022 (setq d (1+ d))))
27023 (setq time (encode-time s mi h d m y)))
27024 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
27025 (concat keyword (format-time-string fmt time))))
27027 ;;; XOXO export
27029 (defun org-export-as-xoxo-insert-into (buffer &rest output)
27030 (with-current-buffer buffer
27031 (apply 'insert output)))
27032 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
27034 (defun org-export-as-xoxo (&optional buffer)
27035 "Export the org buffer as XOXO.
27036 The XOXO buffer is named *xoxo-<source buffer name>*"
27037 (interactive (list (current-buffer)))
27038 ;; A quickie abstraction
27040 ;; Output everything as XOXO
27041 (with-current-buffer (get-buffer buffer)
27042 (let* ((pos (point))
27043 (opt-plist (org-combine-plists (org-default-export-plist)
27044 (org-infile-export-plist)))
27045 (filename (concat (file-name-as-directory
27046 (org-export-directory :xoxo opt-plist))
27047 (file-name-sans-extension
27048 (file-name-nondirectory buffer-file-name))
27049 ".html"))
27050 (out (find-file-noselect filename))
27051 (last-level 1)
27052 (hanging-li nil))
27053 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
27054 ;; Check the output buffer is empty.
27055 (with-current-buffer out (erase-buffer))
27056 ;; Kick off the output
27057 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
27058 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
27059 (let* ((hd (match-string-no-properties 1))
27060 (level (length hd))
27061 (text (concat
27062 (match-string-no-properties 2)
27063 (save-excursion
27064 (goto-char (match-end 0))
27065 (let ((str ""))
27066 (catch 'loop
27067 (while 't
27068 (forward-line)
27069 (if (looking-at "^[ \t]\\(.*\\)")
27070 (setq str (concat str (match-string-no-properties 1)))
27071 (throw 'loop str)))))))))
27073 ;; Handle level rendering
27074 (cond
27075 ((> level last-level)
27076 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
27078 ((< level last-level)
27079 (dotimes (- (- last-level level) 1)
27080 (if hanging-li
27081 (org-export-as-xoxo-insert-into out "</li>\n"))
27082 (org-export-as-xoxo-insert-into out "</ol>\n"))
27083 (when hanging-li
27084 (org-export-as-xoxo-insert-into out "</li>\n")
27085 (setq hanging-li nil)))
27087 ((equal level last-level)
27088 (if hanging-li
27089 (org-export-as-xoxo-insert-into out "</li>\n")))
27092 (setq last-level level)
27094 ;; And output the new li
27095 (setq hanging-li 't)
27096 (if (equal ?+ (elt text 0))
27097 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
27098 (org-export-as-xoxo-insert-into out "<li>" text))))
27100 ;; Finally finish off the ol
27101 (dotimes (- last-level 1)
27102 (if hanging-li
27103 (org-export-as-xoxo-insert-into out "</li>\n"))
27104 (org-export-as-xoxo-insert-into out "</ol>\n"))
27106 (goto-char pos)
27107 ;; Finish the buffer off and clean it up.
27108 (switch-to-buffer-other-window out)
27109 (indent-region (point-min) (point-max) nil)
27110 (save-buffer)
27111 (goto-char (point-min))
27115 ;;;; Key bindings
27117 ;; Make `C-c C-x' a prefix key
27118 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
27120 ;; TAB key with modifiers
27121 (org-defkey org-mode-map "\C-i" 'org-cycle)
27122 (org-defkey org-mode-map [(tab)] 'org-cycle)
27123 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
27124 (org-defkey org-mode-map [(meta tab)] 'org-complete)
27125 (org-defkey org-mode-map "\M-\t" 'org-complete)
27126 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
27127 ;; The following line is necessary under Suse GNU/Linux
27128 (unless (featurep 'xemacs)
27129 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
27130 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
27131 (define-key org-mode-map [backtab] 'org-shifttab)
27133 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
27134 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
27135 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
27137 ;; Cursor keys with modifiers
27138 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
27139 (org-defkey org-mode-map [(meta right)] 'org-metaright)
27140 (org-defkey org-mode-map [(meta up)] 'org-metaup)
27141 (org-defkey org-mode-map [(meta down)] 'org-metadown)
27143 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
27144 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
27145 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
27146 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
27148 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
27149 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
27150 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
27151 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
27153 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
27154 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
27156 ;;; Extra keys for tty access.
27157 ;; We only set them when really needed because otherwise the
27158 ;; menus don't show the simple keys
27160 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
27161 (not window-system))
27162 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
27163 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
27164 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
27165 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
27166 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
27167 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
27168 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
27169 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
27170 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
27171 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
27172 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
27173 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
27174 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
27175 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
27176 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
27177 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
27178 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
27179 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
27180 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
27181 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
27182 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
27183 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
27185 ;; All the other keys
27187 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
27188 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
27189 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
27190 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
27191 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
27192 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
27193 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
27194 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
27195 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
27196 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
27197 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
27198 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
27199 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
27200 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
27201 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
27202 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
27203 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
27204 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
27205 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
27206 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
27207 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
27208 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
27209 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
27210 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
27211 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
27212 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
27213 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
27214 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
27215 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
27216 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
27217 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
27218 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
27219 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
27220 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
27221 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
27222 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
27223 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
27224 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
27225 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
27226 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
27227 (org-defkey org-mode-map "\C-c^" 'org-sort)
27228 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
27229 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
27230 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
27231 (org-defkey org-mode-map "\C-m" 'org-return)
27232 (org-defkey org-mode-map "\C-j" 'org-return-indent)
27233 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
27234 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
27235 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
27236 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
27237 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
27238 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
27239 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
27240 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
27241 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
27242 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
27243 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
27244 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
27245 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
27246 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
27247 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
27249 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
27250 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
27251 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
27252 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
27254 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
27255 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
27256 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
27257 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
27258 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
27259 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
27260 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
27261 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
27262 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
27263 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
27264 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
27265 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
27267 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
27269 (when (featurep 'xemacs)
27270 (org-defkey org-mode-map 'button3 'popup-mode-menu))
27272 (defsubst org-table-p () (org-at-table-p))
27274 (defun org-self-insert-command (N)
27275 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
27276 If the cursor is in a table looking at whitespace, the whitespace is
27277 overwritten, and the table is not marked as requiring realignment."
27278 (interactive "p")
27279 (if (and (org-table-p)
27280 (progn
27281 ;; check if we blank the field, and if that triggers align
27282 (and org-table-auto-blank-field
27283 (member last-command
27284 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
27285 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
27286 ;; got extra space, this field does not determine column width
27287 (let (org-table-may-need-update) (org-table-blank-field))
27288 ;; no extra space, this field may determine column width
27289 (org-table-blank-field)))
27291 (eq N 1)
27292 (looking-at "[^|\n]* |"))
27293 (let (org-table-may-need-update)
27294 (goto-char (1- (match-end 0)))
27295 (delete-backward-char 1)
27296 (goto-char (match-beginning 0))
27297 (self-insert-command N))
27298 (setq org-table-may-need-update t)
27299 (self-insert-command N)
27300 (org-fix-tags-on-the-fly)))
27302 (defun org-fix-tags-on-the-fly ()
27303 (when (and (equal (char-after (point-at-bol)) ?*)
27304 (org-on-heading-p))
27305 (org-align-tags-here org-tags-column)))
27307 (defun org-delete-backward-char (N)
27308 "Like `delete-backward-char', insert whitespace at field end in tables.
27309 When deleting backwards, in tables this function will insert whitespace in
27310 front of the next \"|\" separator, to keep the table aligned. The table will
27311 still be marked for re-alignment if the field did fill the entire column,
27312 because, in this case the deletion might narrow the column."
27313 (interactive "p")
27314 (if (and (org-table-p)
27315 (eq N 1)
27316 (string-match "|" (buffer-substring (point-at-bol) (point)))
27317 (looking-at ".*?|"))
27318 (let ((pos (point))
27319 (noalign (looking-at "[^|\n\r]* |"))
27320 (c org-table-may-need-update))
27321 (backward-delete-char N)
27322 (skip-chars-forward "^|")
27323 (insert " ")
27324 (goto-char (1- pos))
27325 ;; noalign: if there were two spaces at the end, this field
27326 ;; does not determine the width of the column.
27327 (if noalign (setq org-table-may-need-update c)))
27328 (backward-delete-char N)
27329 (org-fix-tags-on-the-fly)))
27331 (defun org-delete-char (N)
27332 "Like `delete-char', but insert whitespace at field end in tables.
27333 When deleting characters, in tables this function will insert whitespace in
27334 front of the next \"|\" separator, to keep the table aligned. The table will
27335 still be marked for re-alignment if the field did fill the entire column,
27336 because, in this case the deletion might narrow the column."
27337 (interactive "p")
27338 (if (and (org-table-p)
27339 (not (bolp))
27340 (not (= (char-after) ?|))
27341 (eq N 1))
27342 (if (looking-at ".*?|")
27343 (let ((pos (point))
27344 (noalign (looking-at "[^|\n\r]* |"))
27345 (c org-table-may-need-update))
27346 (replace-match (concat
27347 (substring (match-string 0) 1 -1)
27348 " |"))
27349 (goto-char pos)
27350 ;; noalign: if there were two spaces at the end, this field
27351 ;; does not determine the width of the column.
27352 (if noalign (setq org-table-may-need-update c)))
27353 (delete-char N))
27354 (delete-char N)
27355 (org-fix-tags-on-the-fly)))
27357 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
27358 (put 'org-self-insert-command 'delete-selection t)
27359 (put 'orgtbl-self-insert-command 'delete-selection t)
27360 (put 'org-delete-char 'delete-selection 'supersede)
27361 (put 'org-delete-backward-char 'delete-selection 'supersede)
27363 ;; Make `flyspell-mode' delay after some commands
27364 (put 'org-self-insert-command 'flyspell-delayed t)
27365 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
27366 (put 'org-delete-char 'flyspell-delayed t)
27367 (put 'org-delete-backward-char 'flyspell-delayed t)
27369 ;; Make pabbrev-mode expand after org-mode commands
27370 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
27371 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
27373 ;; How to do this: Measure non-white length of current string
27374 ;; If equal to column width, we should realign.
27376 (defun org-remap (map &rest commands)
27377 "In MAP, remap the functions given in COMMANDS.
27378 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
27379 (let (new old)
27380 (while commands
27381 (setq old (pop commands) new (pop commands))
27382 (if (fboundp 'command-remapping)
27383 (org-defkey map (vector 'remap old) new)
27384 (substitute-key-definition old new map global-map)))))
27386 (when (eq org-enable-table-editor 'optimized)
27387 ;; If the user wants maximum table support, we need to hijack
27388 ;; some standard editing functions
27389 (org-remap org-mode-map
27390 'self-insert-command 'org-self-insert-command
27391 'delete-char 'org-delete-char
27392 'delete-backward-char 'org-delete-backward-char)
27393 (org-defkey org-mode-map "|" 'org-force-self-insert))
27395 (defun org-shiftcursor-error ()
27396 "Throw an error because Shift-Cursor command was applied in wrong context."
27397 (error "This command is active in special context like tables, headlines or timestamps"))
27399 (defun org-shifttab (&optional arg)
27400 "Global visibility cycling or move to previous table field.
27401 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
27402 on context.
27403 See the individual commands for more information."
27404 (interactive "P")
27405 (cond
27406 ((org-at-table-p) (call-interactively 'org-table-previous-field))
27407 (arg (message "Content view to level: ")
27408 (org-content (prefix-numeric-value arg))
27409 (setq org-cycle-global-status 'overview))
27410 (t (call-interactively 'org-global-cycle))))
27412 (defun org-shiftmetaleft ()
27413 "Promote subtree or delete table column.
27414 Calls `org-promote-subtree', `org-outdent-item',
27415 or `org-table-delete-column', depending on context.
27416 See the individual commands for more information."
27417 (interactive)
27418 (cond
27419 ((org-at-table-p) (call-interactively 'org-table-delete-column))
27420 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
27421 ((org-at-item-p) (call-interactively 'org-outdent-item))
27422 (t (org-shiftcursor-error))))
27424 (defun org-shiftmetaright ()
27425 "Demote subtree or insert table column.
27426 Calls `org-demote-subtree', `org-indent-item',
27427 or `org-table-insert-column', depending on context.
27428 See the individual commands for more information."
27429 (interactive)
27430 (cond
27431 ((org-at-table-p) (call-interactively 'org-table-insert-column))
27432 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
27433 ((org-at-item-p) (call-interactively 'org-indent-item))
27434 (t (org-shiftcursor-error))))
27436 (defun org-shiftmetaup (&optional arg)
27437 "Move subtree up or kill table row.
27438 Calls `org-move-subtree-up' or `org-table-kill-row' or
27439 `org-move-item-up' depending on context. See the individual commands
27440 for more information."
27441 (interactive "P")
27442 (cond
27443 ((org-at-table-p) (call-interactively 'org-table-kill-row))
27444 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27445 ((org-at-item-p) (call-interactively 'org-move-item-up))
27446 (t (org-shiftcursor-error))))
27447 (defun org-shiftmetadown (&optional arg)
27448 "Move subtree down or insert table row.
27449 Calls `org-move-subtree-down' or `org-table-insert-row' or
27450 `org-move-item-down', depending on context. See the individual
27451 commands for more information."
27452 (interactive "P")
27453 (cond
27454 ((org-at-table-p) (call-interactively 'org-table-insert-row))
27455 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27456 ((org-at-item-p) (call-interactively 'org-move-item-down))
27457 (t (org-shiftcursor-error))))
27459 (defun org-metaleft (&optional arg)
27460 "Promote heading or move table column to left.
27461 Calls `org-do-promote' or `org-table-move-column', depending on context.
27462 With no specific context, calls the Emacs default `backward-word'.
27463 See the individual commands for more information."
27464 (interactive "P")
27465 (cond
27466 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
27467 ((or (org-on-heading-p) (org-region-active-p))
27468 (call-interactively 'org-do-promote))
27469 ((org-at-item-p) (call-interactively 'org-outdent-item))
27470 (t (call-interactively 'backward-word))))
27472 (defun org-metaright (&optional arg)
27473 "Demote subtree or move table column to right.
27474 Calls `org-do-demote' or `org-table-move-column', depending on context.
27475 With no specific context, calls the Emacs default `forward-word'.
27476 See the individual commands for more information."
27477 (interactive "P")
27478 (cond
27479 ((org-at-table-p) (call-interactively 'org-table-move-column))
27480 ((or (org-on-heading-p) (org-region-active-p))
27481 (call-interactively 'org-do-demote))
27482 ((org-at-item-p) (call-interactively 'org-indent-item))
27483 (t (call-interactively 'forward-word))))
27485 (defun org-metaup (&optional arg)
27486 "Move subtree up or move table row up.
27487 Calls `org-move-subtree-up' or `org-table-move-row' or
27488 `org-move-item-up', depending on context. See the individual commands
27489 for more information."
27490 (interactive "P")
27491 (cond
27492 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
27493 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27494 ((org-at-item-p) (call-interactively 'org-move-item-up))
27495 (t (transpose-lines 1) (beginning-of-line -1))))
27497 (defun org-metadown (&optional arg)
27498 "Move subtree down or move table row down.
27499 Calls `org-move-subtree-down' or `org-table-move-row' or
27500 `org-move-item-down', depending on context. See the individual
27501 commands for more information."
27502 (interactive "P")
27503 (cond
27504 ((org-at-table-p) (call-interactively 'org-table-move-row))
27505 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27506 ((org-at-item-p) (call-interactively 'org-move-item-down))
27507 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
27509 (defun org-shiftup (&optional arg)
27510 "Increase item in timestamp or increase priority of current headline.
27511 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
27512 depending on context. See the individual commands for more information."
27513 (interactive "P")
27514 (cond
27515 ((org-at-timestamp-p t)
27516 (call-interactively (if org-edit-timestamp-down-means-later
27517 'org-timestamp-down 'org-timestamp-up)))
27518 ((org-on-heading-p) (call-interactively 'org-priority-up))
27519 ((org-at-item-p) (call-interactively 'org-previous-item))
27520 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
27522 (defun org-shiftdown (&optional arg)
27523 "Decrease item in timestamp or decrease priority of current headline.
27524 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
27525 depending on context. See the individual commands for more information."
27526 (interactive "P")
27527 (cond
27528 ((org-at-timestamp-p t)
27529 (call-interactively (if org-edit-timestamp-down-means-later
27530 'org-timestamp-up 'org-timestamp-down)))
27531 ((org-on-heading-p) (call-interactively 'org-priority-down))
27532 (t (call-interactively 'org-next-item))))
27534 (defun org-shiftright ()
27535 "Next TODO keyword or timestamp one day later, depending on context."
27536 (interactive)
27537 (cond
27538 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
27539 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
27540 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
27541 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
27542 (t (org-shiftcursor-error))))
27544 (defun org-shiftleft ()
27545 "Previous TODO keyword or timestamp one day earlier, depending on context."
27546 (interactive)
27547 (cond
27548 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27549 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27550 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27551 ((org-at-property-p)
27552 (call-interactively 'org-property-previous-allowed-value))
27553 (t (org-shiftcursor-error))))
27555 (defun org-shiftcontrolright ()
27556 "Switch to next TODO set."
27557 (interactive)
27558 (cond
27559 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27560 (t (org-shiftcursor-error))))
27562 (defun org-shiftcontrolleft ()
27563 "Switch to previous TODO set."
27564 (interactive)
27565 (cond
27566 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27567 (t (org-shiftcursor-error))))
27569 (defun org-ctrl-c-ret ()
27570 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27571 (interactive)
27572 (cond
27573 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27574 (t (call-interactively 'org-insert-heading))))
27576 (defun org-copy-special ()
27577 "Copy region in table or copy current subtree.
27578 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27579 See the individual commands for more information."
27580 (interactive)
27581 (call-interactively
27582 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27584 (defun org-cut-special ()
27585 "Cut region in table or cut current subtree.
27586 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27587 See the individual commands for more information."
27588 (interactive)
27589 (call-interactively
27590 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27592 (defun org-paste-special (arg)
27593 "Paste rectangular region into table, or past subtree relative to level.
27594 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27595 See the individual commands for more information."
27596 (interactive "P")
27597 (if (org-at-table-p)
27598 (org-table-paste-rectangle)
27599 (org-paste-subtree arg)))
27601 (defun org-ctrl-c-ctrl-c (&optional arg)
27602 "Set tags in headline, or update according to changed information at point.
27604 This command does many different things, depending on context:
27606 - If the cursor is in a headline, prompt for tags and insert them
27607 into the current line, aligned to `org-tags-column'. When called
27608 with prefix arg, realign all tags in the current buffer.
27610 - If the cursor is in one of the special #+KEYWORD lines, this
27611 triggers scanning the buffer for these lines and updating the
27612 information.
27614 - If the cursor is inside a table, realign the table. This command
27615 works even if the automatic table editor has been turned off.
27617 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27618 the entire table.
27620 - If the cursor is a the beginning of a dynamic block, update it.
27622 - If the cursor is inside a table created by the table.el package,
27623 activate that table.
27625 - If the current buffer is a remember buffer, close note and file it.
27626 with a prefix argument, file it without further interaction to the default
27627 location.
27629 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27630 links in this buffer.
27632 - If the cursor is on a numbered item in a plain list, renumber the
27633 ordered list.
27635 - If the cursor is on a checkbox, toggle it."
27636 (interactive "P")
27637 (let ((org-enable-table-editor t))
27638 (cond
27639 ((or org-clock-overlays
27640 org-occur-highlights
27641 org-latex-fragment-image-overlays)
27642 (org-remove-clock-overlays)
27643 (org-remove-occur-highlights)
27644 (org-remove-latex-fragment-image-overlays)
27645 (message "Temporary highlights/overlays removed from current buffer"))
27646 ((and (local-variable-p 'org-finish-function (current-buffer))
27647 (fboundp org-finish-function))
27648 (funcall org-finish-function))
27649 ((org-at-property-p)
27650 (call-interactively 'org-property-action))
27651 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27652 ((org-on-heading-p) (call-interactively 'org-set-tags))
27653 ((org-at-table.el-p)
27654 (require 'table)
27655 (beginning-of-line 1)
27656 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27657 (call-interactively 'table-recognize-table))
27658 ((org-at-table-p)
27659 (org-table-maybe-eval-formula)
27660 (if arg
27661 (call-interactively 'org-table-recalculate)
27662 (org-table-maybe-recalculate-line))
27663 (call-interactively 'org-table-align))
27664 ((org-at-item-checkbox-p)
27665 (call-interactively 'org-toggle-checkbox))
27666 ((org-at-item-p)
27667 (call-interactively 'org-maybe-renumber-ordered-list))
27668 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27669 ;; Dynamic block
27670 (beginning-of-line 1)
27671 (org-update-dblock))
27672 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27673 (cond
27674 ((equal (match-string 1) "TBLFM")
27675 ;; Recalculate the table before this line
27676 (save-excursion
27677 (beginning-of-line 1)
27678 (skip-chars-backward " \r\n\t")
27679 (if (org-at-table-p)
27680 (org-call-with-arg 'org-table-recalculate t))))
27682 (call-interactively 'org-mode-restart))))
27683 (t (error "C-c C-c can do nothing useful at this location.")))))
27685 (defun org-mode-restart ()
27686 "Restart Org-mode, to scan again for special lines.
27687 Also updates the keyword regular expressions."
27688 (interactive)
27689 (let ((org-inhibit-startup t)) (org-mode))
27690 (message "Org-mode restarted to refresh keyword and special line setup"))
27692 (defun org-kill-note-or-show-branches ()
27693 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27694 (interactive)
27695 (if (not org-finish-function)
27696 (call-interactively 'show-branches)
27697 (let ((org-note-abort t))
27698 (funcall org-finish-function))))
27700 (defun org-return (&optional indent)
27701 "Goto next table row or insert a newline.
27702 Calls `org-table-next-row' or `newline', depending on context.
27703 See the individual commands for more information."
27704 (interactive)
27705 (cond
27706 ((bobp) (if indent (newline-and-indent) (newline)))
27707 ((and (org-at-heading-p)
27708 (looking-at
27709 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27710 (org-show-entry)
27711 (end-of-line 1)
27712 (newline))
27713 ((org-at-table-p)
27714 (org-table-justify-field-maybe)
27715 (call-interactively 'org-table-next-row))
27716 (t (if indent (newline-and-indent) (newline)))))
27718 (defun org-return-indent ()
27719 "Goto next table row or insert a newline and indent.
27720 Calls `org-table-next-row' or `newline-and-indent', depending on
27721 context. See the individual commands for more information."
27722 (interactive)
27723 (org-return t))
27725 (defun org-ctrl-c-star ()
27726 "Compute table, or change heading status of lines.
27727 Calls `org-table-recalculate' or `org-toggle-region-headlines',
27728 depending on context. This will also turn a plain list item or a normal
27729 line into a subheading."
27730 (interactive)
27731 (cond
27732 ((org-at-table-p)
27733 (call-interactively 'org-table-recalculate))
27734 ((org-region-active-p)
27735 ;; Convert all lines in region to list items
27736 (call-interactively 'org-toggle-region-headings))
27737 ((org-on-heading-p)
27738 (org-toggle-region-headings (point-at-bol)
27739 (min (1+ (point-at-eol)) (point-max))))
27740 ((org-at-item-p)
27741 ;; Convert to heading
27742 (let ((level (save-match-data
27743 (save-excursion
27744 (condition-case nil
27745 (progn
27746 (org-back-to-heading t)
27747 (funcall outline-level))
27748 (error 0))))))
27749 (replace-match
27750 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
27751 (t (org-toggle-region-headings (point-at-bol)
27752 (min (1+ (point-at-eol)) (point-max))))))
27754 (defun org-ctrl-c-minus ()
27755 "Insert separator line in table or modify bullet status of line.
27756 Also turns a plain line or a region of lines into list items.
27757 Calls `org-table-insert-hline', `org-toggle-region-items', or
27758 `org-cycle-list-bullet', depending on context."
27759 (interactive)
27760 (cond
27761 ((org-at-table-p)
27762 (call-interactively 'org-table-insert-hline))
27763 ((org-on-heading-p)
27764 ;; Convert to item
27765 (save-excursion
27766 (beginning-of-line 1)
27767 (if (looking-at "\\*+ ")
27768 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
27769 ((org-region-active-p)
27770 ;; Convert all lines in region to list items
27771 (call-interactively 'org-toggle-region-items))
27772 ((org-in-item-p)
27773 (call-interactively 'org-cycle-list-bullet))
27774 (t (org-toggle-region-items (point-at-bol)
27775 (min (1+ (point-at-eol)) (point-max))))))
27777 (defun org-toggle-region-items (beg end)
27778 "Convert all lines in region to list items.
27779 If the first line is already an item, convert all list items in the region
27780 to normal lines."
27781 (interactive "r")
27782 (let (l2 l)
27783 (save-excursion
27784 (goto-char end)
27785 (setq l2 (org-current-line))
27786 (goto-char beg)
27787 (beginning-of-line 1)
27788 (setq l (1- (org-current-line)))
27789 (if (org-at-item-p)
27790 ;; We already have items, de-itemize
27791 (while (< (setq l (1+ l)) l2)
27792 (when (org-at-item-p)
27793 (goto-char (match-beginning 2))
27794 (delete-region (match-beginning 2) (match-end 2))
27795 (and (looking-at "[ \t]+") (replace-match "")))
27796 (beginning-of-line 2))
27797 (while (< (setq l (1+ l)) l2)
27798 (unless (org-at-item-p)
27799 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27800 (replace-match "\\1- \\2")))
27801 (beginning-of-line 2))))))
27803 (defun org-toggle-region-headings (beg end)
27804 "Convert all lines in region to list items.
27805 If the first line is already an item, convert all list items in the region
27806 to normal lines."
27807 (interactive "r")
27808 (let (l2 l)
27809 (save-excursion
27810 (goto-char end)
27811 (setq l2 (org-current-line))
27812 (goto-char beg)
27813 (beginning-of-line 1)
27814 (setq l (1- (org-current-line)))
27815 (if (org-on-heading-p)
27816 ;; We already have headlines, de-star them
27817 (while (< (setq l (1+ l)) l2)
27818 (when (org-on-heading-p t)
27819 (and (looking-at outline-regexp) (replace-match "")))
27820 (beginning-of-line 2))
27821 (let* ((stars (save-excursion
27822 (re-search-backward org-complex-heading-regexp nil t)
27823 (or (match-string 1) "*")))
27824 (add-stars (if org-odd-levels-only "**" "*"))
27825 (rpl (concat stars add-stars " \\2")))
27826 (while (< (setq l (1+ l)) l2)
27827 (unless (org-on-heading-p)
27828 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27829 (replace-match rpl)))
27830 (beginning-of-line 2)))))))
27832 (defun org-meta-return (&optional arg)
27833 "Insert a new heading or wrap a region in a table.
27834 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27835 See the individual commands for more information."
27836 (interactive "P")
27837 (cond
27838 ((org-at-table-p)
27839 (call-interactively 'org-table-wrap-region))
27840 (t (call-interactively 'org-insert-heading))))
27842 ;;; Menu entries
27844 ;; Define the Org-mode menus
27845 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27846 '("Tbl"
27847 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27848 ["Next Field" org-cycle (org-at-table-p)]
27849 ["Previous Field" org-shifttab (org-at-table-p)]
27850 ["Next Row" org-return (org-at-table-p)]
27851 "--"
27852 ["Blank Field" org-table-blank-field (org-at-table-p)]
27853 ["Edit Field" org-table-edit-field (org-at-table-p)]
27854 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27855 "--"
27856 ("Column"
27857 ["Move Column Left" org-metaleft (org-at-table-p)]
27858 ["Move Column Right" org-metaright (org-at-table-p)]
27859 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27860 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27861 ("Row"
27862 ["Move Row Up" org-metaup (org-at-table-p)]
27863 ["Move Row Down" org-metadown (org-at-table-p)]
27864 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27865 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27866 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27867 "--"
27868 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27869 ("Rectangle"
27870 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27871 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27872 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27873 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27874 "--"
27875 ("Calculate"
27876 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27877 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27878 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27879 "--"
27880 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27881 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27882 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27883 "--"
27884 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27885 "--"
27886 ["Sum Column/Rectangle" org-table-sum
27887 (or (org-at-table-p) (org-region-active-p))]
27888 ["Which Column?" org-table-current-column (org-at-table-p)])
27889 ["Debug Formulas"
27890 org-table-toggle-formula-debugger
27891 :style toggle :selected org-table-formula-debug]
27892 ["Show Col/Row Numbers"
27893 org-table-toggle-coordinate-overlays
27894 :style toggle :selected org-table-overlay-coordinates]
27895 "--"
27896 ["Create" org-table-create (and (not (org-at-table-p))
27897 org-enable-table-editor)]
27898 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27899 ["Import from File" org-table-import (not (org-at-table-p))]
27900 ["Export to File" org-table-export (org-at-table-p)]
27901 "--"
27902 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27904 (easy-menu-define org-org-menu org-mode-map "Org menu"
27905 '("Org"
27906 ("Show/Hide"
27907 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27908 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27909 ["Sparse Tree" org-occur t]
27910 ["Reveal Context" org-reveal t]
27911 ["Show All" show-all t]
27912 "--"
27913 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27914 "--"
27915 ["New Heading" org-insert-heading t]
27916 ("Navigate Headings"
27917 ["Up" outline-up-heading t]
27918 ["Next" outline-next-visible-heading t]
27919 ["Previous" outline-previous-visible-heading t]
27920 ["Next Same Level" outline-forward-same-level t]
27921 ["Previous Same Level" outline-backward-same-level t]
27922 "--"
27923 ["Jump" org-goto t])
27924 ("Edit Structure"
27925 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27926 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27927 "--"
27928 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27929 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27930 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27931 "--"
27932 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27933 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27934 ["Demote Heading" org-metaright (not (org-at-table-p))]
27935 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27936 "--"
27937 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27938 "--"
27939 ["Convert to odd levels" org-convert-to-odd-levels t]
27940 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27941 ("Editing"
27942 ["Emphasis..." org-emphasize t])
27943 ("Archive"
27944 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27945 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27946 ; :active t :keys "C-u C-c C-x C-a"]
27947 ["Sparse trees open ARCHIVE trees"
27948 (setq org-sparse-tree-open-archived-trees
27949 (not org-sparse-tree-open-archived-trees))
27950 :style toggle :selected org-sparse-tree-open-archived-trees]
27951 ["Cycling opens ARCHIVE trees"
27952 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27953 :style toggle :selected org-cycle-open-archived-trees]
27954 ["Agenda includes ARCHIVE trees"
27955 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27956 :style toggle :selected (not org-agenda-skip-archived-trees)]
27957 "--"
27958 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27959 ; ["Check and Move Children" (org-archive-subtree '(4))
27960 ; :active t :keys "C-u C-c C-x C-s"]
27962 "--"
27963 ("TODO Lists"
27964 ["TODO/DONE/-" org-todo t]
27965 ("Select keyword"
27966 ["Next keyword" org-shiftright (org-on-heading-p)]
27967 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27968 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27969 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27970 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27971 ["Show TODO Tree" org-show-todo-tree t]
27972 ["Global TODO list" org-todo-list t]
27973 "--"
27974 ["Set Priority" org-priority t]
27975 ["Priority Up" org-shiftup t]
27976 ["Priority Down" org-shiftdown t])
27977 ("TAGS and Properties"
27978 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27979 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27980 "--"
27981 ["Set property" 'org-set-property t]
27982 ["Column view of properties" org-columns t]
27983 ["Insert Column View DBlock" org-insert-columns-dblock t])
27984 ("Dates and Scheduling"
27985 ["Timestamp" org-time-stamp t]
27986 ["Timestamp (inactive)" org-time-stamp-inactive t]
27987 ("Change Date"
27988 ["1 Day Later" org-shiftright t]
27989 ["1 Day Earlier" org-shiftleft t]
27990 ["1 ... Later" org-shiftup t]
27991 ["1 ... Earlier" org-shiftdown t])
27992 ["Compute Time Range" org-evaluate-time-range t]
27993 ["Schedule Item" org-schedule t]
27994 ["Deadline" org-deadline t]
27995 "--"
27996 ["Custom time format" org-toggle-time-stamp-overlays
27997 :style radio :selected org-display-custom-times]
27998 "--"
27999 ["Goto Calendar" org-goto-calendar t]
28000 ["Date from Calendar" org-date-from-calendar t])
28001 ("Logging work"
28002 ["Clock in" org-clock-in t]
28003 ["Clock out" org-clock-out t]
28004 ["Clock cancel" org-clock-cancel t]
28005 ["Goto running clock" org-clock-goto t]
28006 ["Display times" org-clock-display t]
28007 ["Create clock table" org-clock-report t]
28008 "--"
28009 ["Record DONE time"
28010 (progn (setq org-log-done (not org-log-done))
28011 (message "Switching to %s will %s record a timestamp"
28012 (car org-done-keywords)
28013 (if org-log-done "automatically" "not")))
28014 :style toggle :selected org-log-done])
28015 "--"
28016 ["Agenda Command..." org-agenda t]
28017 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
28018 ("File List for Agenda")
28019 ("Special views current file"
28020 ["TODO Tree" org-show-todo-tree t]
28021 ["Check Deadlines" org-check-deadlines t]
28022 ["Timeline" org-timeline t]
28023 ["Tags Tree" org-tags-sparse-tree t])
28024 "--"
28025 ("Hyperlinks"
28026 ["Store Link (Global)" org-store-link t]
28027 ["Insert Link" org-insert-link t]
28028 ["Follow Link" org-open-at-point t]
28029 "--"
28030 ["Next link" org-next-link t]
28031 ["Previous link" org-previous-link t]
28032 "--"
28033 ["Descriptive Links"
28034 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
28035 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
28036 ["Literal Links"
28037 (progn
28038 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
28039 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
28040 "--"
28041 ["Export/Publish..." org-export t]
28042 ("LaTeX"
28043 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
28044 :selected org-cdlatex-mode]
28045 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
28046 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
28047 ["Modify math symbol" org-cdlatex-math-modify
28048 (org-inside-LaTeX-fragment-p)]
28049 ["Export LaTeX fragments as images"
28050 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
28051 :style toggle :selected org-export-with-LaTeX-fragments])
28052 "--"
28053 ("Documentation"
28054 ["Show Version" org-version t]
28055 ["Info Documentation" org-info t])
28056 ("Customize"
28057 ["Browse Org Group" org-customize t]
28058 "--"
28059 ["Expand This Menu" org-create-customize-menu
28060 (fboundp 'customize-menu-create)])
28061 "--"
28062 ["Refresh setup" org-mode-restart t]
28065 (defun org-info (&optional node)
28066 "Read documentation for Org-mode in the info system.
28067 With optional NODE, go directly to that node."
28068 (interactive)
28069 (info (format "(org)%s" (or node ""))))
28071 (defun org-install-agenda-files-menu ()
28072 (let ((bl (buffer-list)))
28073 (save-excursion
28074 (while bl
28075 (set-buffer (pop bl))
28076 (if (org-mode-p) (setq bl nil)))
28077 (when (org-mode-p)
28078 (easy-menu-change
28079 '("Org") "File List for Agenda"
28080 (append
28081 (list
28082 ["Edit File List" (org-edit-agenda-file-list) t]
28083 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
28084 ["Remove Current File from List" org-remove-file t]
28085 ["Cycle through agenda files" org-cycle-agenda-files t]
28086 ["Occur in all agenda files" org-occur-in-agenda-files t]
28087 "--")
28088 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
28090 ;;;; Documentation
28092 (defun org-customize ()
28093 "Call the customize function with org as argument."
28094 (interactive)
28095 (customize-browse 'org))
28097 (defun org-create-customize-menu ()
28098 "Create a full customization menu for Org-mode, insert it into the menu."
28099 (interactive)
28100 (if (fboundp 'customize-menu-create)
28101 (progn
28102 (easy-menu-change
28103 '("Org") "Customize"
28104 `(["Browse Org group" org-customize t]
28105 "--"
28106 ,(customize-menu-create 'org)
28107 ["Set" Custom-set t]
28108 ["Save" Custom-save t]
28109 ["Reset to Current" Custom-reset-current t]
28110 ["Reset to Saved" Custom-reset-saved t]
28111 ["Reset to Standard Settings" Custom-reset-standard t]))
28112 (message "\"Org\"-menu now contains full customization menu"))
28113 (error "Cannot expand menu (outdated version of cus-edit.el)")))
28115 ;;;; Miscellaneous stuff
28118 ;;; Generally useful functions
28120 (defun org-context ()
28121 "Return a list of contexts of the current cursor position.
28122 If several contexts apply, all are returned.
28123 Each context entry is a list with a symbol naming the context, and
28124 two positions indicating start and end of the context. Possible
28125 contexts are:
28127 :headline anywhere in a headline
28128 :headline-stars on the leading stars in a headline
28129 :todo-keyword on a TODO keyword (including DONE) in a headline
28130 :tags on the TAGS in a headline
28131 :priority on the priority cookie in a headline
28132 :item on the first line of a plain list item
28133 :item-bullet on the bullet/number of a plain list item
28134 :checkbox on the checkbox in a plain list item
28135 :table in an org-mode table
28136 :table-special on a special filed in a table
28137 :table-table in a table.el table
28138 :link on a hyperlink
28139 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
28140 :target on a <<target>>
28141 :radio-target on a <<<radio-target>>>
28142 :latex-fragment on a LaTeX fragment
28143 :latex-preview on a LaTeX fragment with overlayed preview image
28145 This function expects the position to be visible because it uses font-lock
28146 faces as a help to recognize the following contexts: :table-special, :link,
28147 and :keyword."
28148 (let* ((f (get-text-property (point) 'face))
28149 (faces (if (listp f) f (list f)))
28150 (p (point)) clist o)
28151 ;; First the large context
28152 (cond
28153 ((org-on-heading-p t)
28154 (push (list :headline (point-at-bol) (point-at-eol)) clist)
28155 (when (progn
28156 (beginning-of-line 1)
28157 (looking-at org-todo-line-tags-regexp))
28158 (push (org-point-in-group p 1 :headline-stars) clist)
28159 (push (org-point-in-group p 2 :todo-keyword) clist)
28160 (push (org-point-in-group p 4 :tags) clist))
28161 (goto-char p)
28162 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
28163 (if (looking-at "\\[#[A-Z0-9]\\]")
28164 (push (org-point-in-group p 0 :priority) clist)))
28166 ((org-at-item-p)
28167 (push (org-point-in-group p 2 :item-bullet) clist)
28168 (push (list :item (point-at-bol)
28169 (save-excursion (org-end-of-item) (point)))
28170 clist)
28171 (and (org-at-item-checkbox-p)
28172 (push (org-point-in-group p 0 :checkbox) clist)))
28174 ((org-at-table-p)
28175 (push (list :table (org-table-begin) (org-table-end)) clist)
28176 (if (memq 'org-formula faces)
28177 (push (list :table-special
28178 (previous-single-property-change p 'face)
28179 (next-single-property-change p 'face)) clist)))
28180 ((org-at-table-p 'any)
28181 (push (list :table-table) clist)))
28182 (goto-char p)
28184 ;; Now the small context
28185 (cond
28186 ((org-at-timestamp-p)
28187 (push (org-point-in-group p 0 :timestamp) clist))
28188 ((memq 'org-link faces)
28189 (push (list :link
28190 (previous-single-property-change p 'face)
28191 (next-single-property-change p 'face)) clist))
28192 ((memq 'org-special-keyword faces)
28193 (push (list :keyword
28194 (previous-single-property-change p 'face)
28195 (next-single-property-change p 'face)) clist))
28196 ((org-on-target-p)
28197 (push (org-point-in-group p 0 :target) clist)
28198 (goto-char (1- (match-beginning 0)))
28199 (if (looking-at org-radio-target-regexp)
28200 (push (org-point-in-group p 0 :radio-target) clist))
28201 (goto-char p))
28202 ((setq o (car (delq nil
28203 (mapcar
28204 (lambda (x)
28205 (if (memq x org-latex-fragment-image-overlays) x))
28206 (org-overlays-at (point))))))
28207 (push (list :latex-fragment
28208 (org-overlay-start o) (org-overlay-end o)) clist)
28209 (push (list :latex-preview
28210 (org-overlay-start o) (org-overlay-end o)) clist))
28211 ((org-inside-LaTeX-fragment-p)
28212 ;; FIXME: positions wrong.
28213 (push (list :latex-fragment (point) (point)) clist)))
28215 (setq clist (nreverse (delq nil clist)))
28216 clist))
28218 ;; FIXME: Compare with at-regexp-p Do we need both?
28219 (defun org-in-regexp (re &optional nlines visually)
28220 "Check if point is inside a match of regexp.
28221 Normally only the current line is checked, but you can include NLINES extra
28222 lines both before and after point into the search.
28223 If VISUALLY is set, require that the cursor is not after the match but
28224 really on, so that the block visually is on the match."
28225 (catch 'exit
28226 (let ((pos (point))
28227 (eol (point-at-eol (+ 1 (or nlines 0))))
28228 (inc (if visually 1 0)))
28229 (save-excursion
28230 (beginning-of-line (- 1 (or nlines 0)))
28231 (while (re-search-forward re eol t)
28232 (if (and (<= (match-beginning 0) pos)
28233 (>= (+ inc (match-end 0)) pos))
28234 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
28236 (defun org-at-regexp-p (regexp)
28237 "Is point inside a match of REGEXP in the current line?"
28238 (catch 'exit
28239 (save-excursion
28240 (let ((pos (point)) (end (point-at-eol)))
28241 (beginning-of-line 1)
28242 (while (re-search-forward regexp end t)
28243 (if (and (<= (match-beginning 0) pos)
28244 (>= (match-end 0) pos))
28245 (throw 'exit t)))
28246 nil))))
28248 (defun org-occur-in-agenda-files (regexp &optional nlines)
28249 "Call `multi-occur' with buffers for all agenda files."
28250 (interactive "sOrg-files matching: \np")
28251 (let* ((files (org-agenda-files))
28252 (tnames (mapcar 'file-truename files))
28253 (extra org-agenda-text-search-extra-files)
28255 (while (setq f (pop extra))
28256 (unless (member (file-truename f) tnames)
28257 (add-to-list 'files f 'append)
28258 (add-to-list 'tnames (file-truename f) 'append)))
28259 (multi-occur
28260 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
28261 regexp)))
28263 (if (boundp 'occur-mode-find-occurrence-hook)
28264 ;; Emacs 23
28265 (add-hook 'occur-mode-find-occurrence-hook
28266 (lambda ()
28267 (when (org-mode-p)
28268 (org-reveal))))
28269 ;; Emacs 22
28270 (defadvice occur-mode-goto-occurrence
28271 (after org-occur-reveal activate)
28272 (and (org-mode-p) (org-reveal)))
28273 (defadvice occur-mode-goto-occurrence-other-window
28274 (after org-occur-reveal activate)
28275 (and (org-mode-p) (org-reveal)))
28276 (defadvice occur-mode-display-occurrence
28277 (after org-occur-reveal activate)
28278 (when (org-mode-p)
28279 (let ((pos (occur-mode-find-occurrence)))
28280 (with-current-buffer (marker-buffer pos)
28281 (save-excursion
28282 (goto-char pos)
28283 (org-reveal)))))))
28285 (defun org-uniquify (list)
28286 "Remove duplicate elements from LIST."
28287 (let (res)
28288 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
28289 res))
28291 (defun org-delete-all (elts list)
28292 "Remove all elements in ELTS from LIST."
28293 (while elts
28294 (setq list (delete (pop elts) list)))
28295 list)
28297 (defun org-back-over-empty-lines ()
28298 "Move backwards over witespace, to the beginning of the first empty line.
28299 Returns the number o empty lines passed."
28300 (let ((pos (point)))
28301 (skip-chars-backward " \t\n\r")
28302 (beginning-of-line 2)
28303 (goto-char (min (point) pos))
28304 (count-lines (point) pos)))
28306 (defun org-skip-whitespace ()
28307 (skip-chars-forward " \t\n\r"))
28309 (defun org-point-in-group (point group &optional context)
28310 "Check if POINT is in match-group GROUP.
28311 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
28312 match. If the match group does ot exist or point is not inside it,
28313 return nil."
28314 (and (match-beginning group)
28315 (>= point (match-beginning group))
28316 (<= point (match-end group))
28317 (if context
28318 (list context (match-beginning group) (match-end group))
28319 t)))
28321 (defun org-switch-to-buffer-other-window (&rest args)
28322 "Switch to buffer in a second window on the current frame.
28323 In particular, do not allow pop-up frames."
28324 (let (pop-up-frames special-display-buffer-names special-display-regexps
28325 special-display-function)
28326 (apply 'switch-to-buffer-other-window args)))
28328 (defun org-combine-plists (&rest plists)
28329 "Create a single property list from all plists in PLISTS.
28330 The process starts by copying the first list, and then setting properties
28331 from the other lists. Settings in the last list are the most significant
28332 ones and overrule settings in the other lists."
28333 (let ((rtn (copy-sequence (pop plists)))
28334 p v ls)
28335 (while plists
28336 (setq ls (pop plists))
28337 (while ls
28338 (setq p (pop ls) v (pop ls))
28339 (setq rtn (plist-put rtn p v))))
28340 rtn))
28342 (defun org-move-line-down (arg)
28343 "Move the current line down. With prefix argument, move it past ARG lines."
28344 (interactive "p")
28345 (let ((col (current-column))
28346 beg end pos)
28347 (beginning-of-line 1) (setq beg (point))
28348 (beginning-of-line 2) (setq end (point))
28349 (beginning-of-line (+ 1 arg))
28350 (setq pos (move-marker (make-marker) (point)))
28351 (insert (delete-and-extract-region beg end))
28352 (goto-char pos)
28353 (move-to-column col)))
28355 (defun org-move-line-up (arg)
28356 "Move the current line up. With prefix argument, move it past ARG lines."
28357 (interactive "p")
28358 (let ((col (current-column))
28359 beg end pos)
28360 (beginning-of-line 1) (setq beg (point))
28361 (beginning-of-line 2) (setq end (point))
28362 (beginning-of-line (- arg))
28363 (setq pos (move-marker (make-marker) (point)))
28364 (insert (delete-and-extract-region beg end))
28365 (goto-char pos)
28366 (move-to-column col)))
28368 (defun org-replace-escapes (string table)
28369 "Replace %-escapes in STRING with values in TABLE.
28370 TABLE is an association list with keys like \"%a\" and string values.
28371 The sequences in STRING may contain normal field width and padding information,
28372 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
28373 so values can contain further %-escapes if they are define later in TABLE."
28374 (let ((case-fold-search nil)
28375 e re rpl)
28376 (while (setq e (pop table))
28377 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
28378 (while (string-match re string)
28379 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
28380 (cdr e)))
28381 (setq string (replace-match rpl t t string))))
28382 string))
28385 (defun org-sublist (list start end)
28386 "Return a section of LIST, from START to END.
28387 Counting starts at 1."
28388 (let (rtn (c start))
28389 (setq list (nthcdr (1- start) list))
28390 (while (and list (<= c end))
28391 (push (pop list) rtn)
28392 (setq c (1+ c)))
28393 (nreverse rtn)))
28395 (defun org-find-base-buffer-visiting (file)
28396 "Like `find-buffer-visiting' but alway return the base buffer and
28397 not an indirect buffer"
28398 (let ((buf (find-buffer-visiting file)))
28399 (if buf
28400 (or (buffer-base-buffer buf) buf)
28401 nil)))
28403 (defun org-image-file-name-regexp ()
28404 "Return regexp matching the file names of images."
28405 (if (fboundp 'image-file-name-regexp)
28406 (image-file-name-regexp)
28407 (let ((image-file-name-extensions
28408 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
28409 "xbm" "xpm" "pbm" "pgm" "ppm")))
28410 (concat "\\."
28411 (regexp-opt (nconc (mapcar 'upcase
28412 image-file-name-extensions)
28413 image-file-name-extensions)
28415 "\\'"))))
28417 (defun org-file-image-p (file)
28418 "Return non-nil if FILE is an image."
28419 (save-match-data
28420 (string-match (org-image-file-name-regexp) file)))
28422 ;;; Paragraph filling stuff.
28423 ;; We want this to be just right, so use the full arsenal.
28425 (defun org-indent-line-function ()
28426 "Indent line like previous, but further if previous was headline or item."
28427 (interactive)
28428 (let* ((pos (point))
28429 (itemp (org-at-item-p))
28430 column bpos bcol tpos tcol bullet btype bullet-type)
28431 ;; Find the previous relevant line
28432 (beginning-of-line 1)
28433 (cond
28434 ((looking-at "#") (setq column 0))
28435 ((looking-at "\\*+ ") (setq column 0))
28437 (beginning-of-line 0)
28438 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
28439 (beginning-of-line 0))
28440 (cond
28441 ((looking-at "\\*+[ \t]+")
28442 (goto-char (match-end 0))
28443 (setq column (current-column)))
28444 ((org-in-item-p)
28445 (org-beginning-of-item)
28446 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28447 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
28448 (setq bpos (match-beginning 1) tpos (match-end 0)
28449 bcol (progn (goto-char bpos) (current-column))
28450 tcol (progn (goto-char tpos) (current-column))
28451 bullet (match-string 1)
28452 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
28453 (if (not itemp)
28454 (setq column tcol)
28455 (goto-char pos)
28456 (beginning-of-line 1)
28457 (if (looking-at "\\S-")
28458 (progn
28459 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28460 (setq bullet (match-string 1)
28461 btype (if (string-match "[0-9]" bullet) "n" bullet))
28462 (setq column (if (equal btype bullet-type) bcol tcol)))
28463 (setq column (org-get-indentation)))))
28464 (t (setq column (org-get-indentation))))))
28465 (goto-char pos)
28466 (if (<= (current-column) (current-indentation))
28467 (indent-line-to column)
28468 (save-excursion (indent-line-to column)))
28469 (setq column (current-column))
28470 (beginning-of-line 1)
28471 (if (looking-at
28472 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
28473 (replace-match (concat "\\1" (format org-property-format
28474 (match-string 2) (match-string 3)))
28475 t nil))
28476 (move-to-column column)))
28478 (defun org-set-autofill-regexps ()
28479 (interactive)
28480 ;; In the paragraph separator we include headlines, because filling
28481 ;; text in a line directly attached to a headline would otherwise
28482 ;; fill the headline as well.
28483 (org-set-local 'comment-start-skip "^#+[ \t]*")
28484 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
28485 ;; The paragraph starter includes hand-formatted lists.
28486 (org-set-local 'paragraph-start
28487 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
28488 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
28489 ;; But only if the user has not turned off tables or fixed-width regions
28490 (org-set-local
28491 'auto-fill-inhibit-regexp
28492 (concat "\\*+ \\|#\\+"
28493 "\\|[ \t]*" org-keyword-time-regexp
28494 (if (or org-enable-table-editor org-enable-fixed-width-editor)
28495 (concat
28496 "\\|[ \t]*["
28497 (if org-enable-table-editor "|" "")
28498 (if org-enable-fixed-width-editor ":" "")
28499 "]"))))
28500 ;; We use our own fill-paragraph function, to make sure that tables
28501 ;; and fixed-width regions are not wrapped. That function will pass
28502 ;; through to `fill-paragraph' when appropriate.
28503 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
28504 ; Adaptive filling: To get full control, first make sure that
28505 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
28506 (org-set-local 'adaptive-fill-regexp "\000")
28507 (org-set-local 'adaptive-fill-function
28508 'org-adaptive-fill-function)
28509 (org-set-local
28510 'align-mode-rules-list
28511 '((org-in-buffer-settings
28512 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
28513 (modes . '(org-mode))))))
28515 (defun org-fill-paragraph (&optional justify)
28516 "Re-align a table, pass through to fill-paragraph if no table."
28517 (let ((table-p (org-at-table-p))
28518 (table.el-p (org-at-table.el-p)))
28519 (cond ((and (equal (char-after (point-at-bol)) ?*)
28520 (save-excursion (goto-char (point-at-bol))
28521 (looking-at outline-regexp)))
28522 t) ; skip headlines
28523 (table.el-p t) ; skip table.el tables
28524 (table-p (org-table-align) t) ; align org-mode tables
28525 (t nil)))) ; call paragraph-fill
28527 ;; For reference, this is the default value of adaptive-fill-regexp
28528 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
28530 (defun org-adaptive-fill-function ()
28531 "Return a fill prefix for org-mode files.
28532 In particular, this makes sure hanging paragraphs for hand-formatted lists
28533 work correctly."
28534 (cond ((looking-at "#[ \t]+")
28535 (match-string 0))
28536 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
28537 (save-excursion
28538 (goto-char (match-end 0))
28539 (make-string (current-column) ?\ )))
28540 (t nil)))
28542 ;;;; Functions extending outline functionality
28545 (defun org-beginning-of-line (&optional arg)
28546 "Go to the beginning of the current line. If that is invisible, continue
28547 to a visible line beginning. This makes the function of C-a more intuitive.
28548 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28549 first attempt, and only move to after the tags when the cursor is already
28550 beyond the end of the headline."
28551 (interactive "P")
28552 (let ((pos (point)))
28553 (beginning-of-line 1)
28554 (if (bobp)
28556 (backward-char 1)
28557 (if (org-invisible-p)
28558 (while (and (not (bobp)) (org-invisible-p))
28559 (backward-char 1)
28560 (beginning-of-line 1))
28561 (forward-char 1)))
28562 (when org-special-ctrl-a/e
28563 (cond
28564 ((and (looking-at org-todo-line-regexp)
28565 (= (char-after (match-end 1)) ?\ ))
28566 (goto-char
28567 (if (eq org-special-ctrl-a/e t)
28568 (cond ((> pos (match-beginning 3)) (match-beginning 3))
28569 ((= pos (point)) (match-beginning 3))
28570 (t (point)))
28571 (cond ((> pos (point)) (point))
28572 ((not (eq last-command this-command)) (point))
28573 (t (match-beginning 3))))))
28574 ((org-at-item-p)
28575 (goto-char
28576 (if (eq org-special-ctrl-a/e t)
28577 (cond ((> pos (match-end 4)) (match-end 4))
28578 ((= pos (point)) (match-end 4))
28579 (t (point)))
28580 (cond ((> pos (point)) (point))
28581 ((not (eq last-command this-command)) (point))
28582 (t (match-end 4))))))))))
28584 (defun org-end-of-line (&optional arg)
28585 "Go to the end of the line.
28586 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28587 first attempt, and only move to after the tags when the cursor is already
28588 beyond the end of the headline."
28589 (interactive "P")
28590 (if (or (not org-special-ctrl-a/e)
28591 (not (org-on-heading-p)))
28592 (end-of-line arg)
28593 (let ((pos (point)))
28594 (beginning-of-line 1)
28595 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
28596 (if (eq org-special-ctrl-a/e t)
28597 (if (or (< pos (match-beginning 1))
28598 (= pos (match-end 0)))
28599 (goto-char (match-beginning 1))
28600 (goto-char (match-end 0)))
28601 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
28602 (goto-char (match-end 0))
28603 (goto-char (match-beginning 1))))
28604 (end-of-line arg)))))
28606 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
28607 (define-key org-mode-map "\C-e" 'org-end-of-line)
28609 (defun org-kill-line (&optional arg)
28610 "Kill line, to tags or end of line."
28611 (interactive "P")
28612 (cond
28613 ((or (not org-special-ctrl-k)
28614 (bolp)
28615 (not (org-on-heading-p)))
28616 (call-interactively 'kill-line))
28617 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
28618 (kill-region (point) (match-beginning 1))
28619 (org-set-tags nil t))
28620 (t (kill-region (point) (point-at-eol)))))
28622 (define-key org-mode-map "\C-k" 'org-kill-line)
28624 (defun org-invisible-p ()
28625 "Check if point is at a character currently not visible."
28626 ;; Early versions of noutline don't have `outline-invisible-p'.
28627 (if (fboundp 'outline-invisible-p)
28628 (outline-invisible-p)
28629 (get-char-property (point) 'invisible)))
28631 (defun org-invisible-p2 ()
28632 "Check if point is at a character currently not visible."
28633 (save-excursion
28634 (if (and (eolp) (not (bobp))) (backward-char 1))
28635 ;; Early versions of noutline don't have `outline-invisible-p'.
28636 (if (fboundp 'outline-invisible-p)
28637 (outline-invisible-p)
28638 (get-char-property (point) 'invisible))))
28640 (defalias 'org-back-to-heading 'outline-back-to-heading)
28641 (defalias 'org-on-heading-p 'outline-on-heading-p)
28642 (defalias 'org-at-heading-p 'outline-on-heading-p)
28643 (defun org-at-heading-or-item-p ()
28644 (or (org-on-heading-p) (org-at-item-p)))
28646 (defun org-on-target-p ()
28647 (or (org-in-regexp org-radio-target-regexp)
28648 (org-in-regexp org-target-regexp)))
28650 (defun org-up-heading-all (arg)
28651 "Move to the heading line of which the present line is a subheading.
28652 This function considers both visible and invisible heading lines.
28653 With argument, move up ARG levels."
28654 (if (fboundp 'outline-up-heading-all)
28655 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28656 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28658 (defun org-up-heading-safe ()
28659 "Move to the heading line of which the present line is a subheading.
28660 This version will not throw an error. It will return the level of the
28661 headline found, or nil if no higher level is found."
28662 (let ((pos (point)) start-level level
28663 (re (concat "^" outline-regexp)))
28664 (catch 'exit
28665 (outline-back-to-heading t)
28666 (setq start-level (funcall outline-level))
28667 (if (equal start-level 1) (throw 'exit nil))
28668 (while (re-search-backward re nil t)
28669 (setq level (funcall outline-level))
28670 (if (< level start-level) (throw 'exit level)))
28671 nil)))
28673 (defun org-first-sibling-p ()
28674 "Is this heading the first child of its parents?"
28675 (interactive)
28676 (let ((re (concat "^" outline-regexp))
28677 level l)
28678 (unless (org-at-heading-p t)
28679 (error "Not at a heading"))
28680 (setq level (funcall outline-level))
28681 (save-excursion
28682 (if (not (re-search-backward re nil t))
28684 (setq l (funcall outline-level))
28685 (< l level)))))
28687 (defun org-goto-sibling (&optional previous)
28688 "Goto the next sibling, even if it is invisible.
28689 When PREVIOUS is set, go to the previous sibling instead. Returns t
28690 when a sibling was found. When none is found, return nil and don't
28691 move point."
28692 (let ((fun (if previous 're-search-backward 're-search-forward))
28693 (pos (point))
28694 (re (concat "^" outline-regexp))
28695 level l)
28696 (when (condition-case nil (org-back-to-heading t) (error nil))
28697 (setq level (funcall outline-level))
28698 (catch 'exit
28699 (or previous (forward-char 1))
28700 (while (funcall fun re nil t)
28701 (setq l (funcall outline-level))
28702 (when (< l level) (goto-char pos) (throw 'exit nil))
28703 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28704 (goto-char pos)
28705 nil))))
28707 (defun org-show-siblings ()
28708 "Show all siblings of the current headline."
28709 (save-excursion
28710 (while (org-goto-sibling) (org-flag-heading nil)))
28711 (save-excursion
28712 (while (org-goto-sibling 'previous)
28713 (org-flag-heading nil))))
28715 (defun org-show-hidden-entry ()
28716 "Show an entry where even the heading is hidden."
28717 (save-excursion
28718 (org-show-entry)))
28720 (defun org-flag-heading (flag &optional entry)
28721 "Flag the current heading. FLAG non-nil means make invisible.
28722 When ENTRY is non-nil, show the entire entry."
28723 (save-excursion
28724 (org-back-to-heading t)
28725 ;; Check if we should show the entire entry
28726 (if entry
28727 (progn
28728 (org-show-entry)
28729 (save-excursion
28730 (and (outline-next-heading)
28731 (org-flag-heading nil))))
28732 (outline-flag-region (max (point-min) (1- (point)))
28733 (save-excursion (outline-end-of-heading) (point))
28734 flag))))
28736 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28737 ;; This is an exact copy of the original function, but it uses
28738 ;; `org-back-to-heading', to make it work also in invisible
28739 ;; trees. And is uses an invisible-OK argument.
28740 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28741 (org-back-to-heading invisible-OK)
28742 (let ((first t)
28743 (level (funcall outline-level)))
28744 (while (and (not (eobp))
28745 (or first (> (funcall outline-level) level)))
28746 (setq first nil)
28747 (outline-next-heading))
28748 (unless to-heading
28749 (if (memq (preceding-char) '(?\n ?\^M))
28750 (progn
28751 ;; Go to end of line before heading
28752 (forward-char -1)
28753 (if (memq (preceding-char) '(?\n ?\^M))
28754 ;; leave blank line before heading
28755 (forward-char -1))))))
28756 (point))
28758 (defun org-show-subtree ()
28759 "Show everything after this heading at deeper levels."
28760 (outline-flag-region
28761 (point)
28762 (save-excursion
28763 (outline-end-of-subtree) (outline-next-heading) (point))
28764 nil))
28766 (defun org-show-entry ()
28767 "Show the body directly following this heading.
28768 Show the heading too, if it is currently invisible."
28769 (interactive)
28770 (save-excursion
28771 (condition-case nil
28772 (progn
28773 (org-back-to-heading t)
28774 (outline-flag-region
28775 (max (point-min) (1- (point)))
28776 (save-excursion
28777 (re-search-forward
28778 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28779 (or (match-beginning 1) (point-max)))
28780 nil))
28781 (error nil))))
28783 (defun org-make-options-regexp (kwds)
28784 "Make a regular expression for keyword lines."
28785 (concat
28787 "#?[ \t]*\\+\\("
28788 (mapconcat 'regexp-quote kwds "\\|")
28789 "\\):[ \t]*"
28790 "\\(.+\\)"))
28792 ;; Make isearch reveal the necessary context
28793 (defun org-isearch-end ()
28794 "Reveal context after isearch exits."
28795 (when isearch-success ; only if search was successful
28796 (if (featurep 'xemacs)
28797 ;; Under XEmacs, the hook is run in the correct place,
28798 ;; we directly show the context.
28799 (org-show-context 'isearch)
28800 ;; In Emacs the hook runs *before* restoring the overlays.
28801 ;; So we have to use a one-time post-command-hook to do this.
28802 ;; (Emacs 22 has a special variable, see function `org-mode')
28803 (unless (and (boundp 'isearch-mode-end-hook-quit)
28804 isearch-mode-end-hook-quit)
28805 ;; Only when the isearch was not quitted.
28806 (org-add-hook 'post-command-hook 'org-isearch-post-command
28807 'append 'local)))))
28809 (defun org-isearch-post-command ()
28810 "Remove self from hook, and show context."
28811 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28812 (org-show-context 'isearch))
28815 ;;;; Integration with and fixes for other packages
28817 ;;; Imenu support
28819 (defvar org-imenu-markers nil
28820 "All markers currently used by Imenu.")
28821 (make-variable-buffer-local 'org-imenu-markers)
28823 (defun org-imenu-new-marker (&optional pos)
28824 "Return a new marker for use by Imenu, and remember the marker."
28825 (let ((m (make-marker)))
28826 (move-marker m (or pos (point)))
28827 (push m org-imenu-markers)
28830 (defun org-imenu-get-tree ()
28831 "Produce the index for Imenu."
28832 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28833 (setq org-imenu-markers nil)
28834 (let* ((n org-imenu-depth)
28835 (re (concat "^" outline-regexp))
28836 (subs (make-vector (1+ n) nil))
28837 (last-level 0)
28838 m tree level head)
28839 (save-excursion
28840 (save-restriction
28841 (widen)
28842 (goto-char (point-max))
28843 (while (re-search-backward re nil t)
28844 (setq level (org-reduced-level (funcall outline-level)))
28845 (when (<= level n)
28846 (looking-at org-complex-heading-regexp)
28847 (setq head (org-match-string-no-properties 4)
28848 m (org-imenu-new-marker))
28849 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28850 (if (>= level last-level)
28851 (push (cons head m) (aref subs level))
28852 (push (cons head (aref subs (1+ level))) (aref subs level))
28853 (loop for i from (1+ level) to n do (aset subs i nil)))
28854 (setq last-level level)))))
28855 (aref subs 1)))
28857 (eval-after-load "imenu"
28858 '(progn
28859 (add-hook 'imenu-after-jump-hook
28860 (lambda () (org-show-context 'org-goto)))))
28862 ;; Speedbar support
28864 (defun org-speedbar-set-agenda-restriction ()
28865 "Restrict future agenda commands to the location at point in speedbar.
28866 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28867 (interactive)
28868 (let (p m tp np dir txt w)
28869 (cond
28870 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28871 'org-imenu t))
28872 (setq m (get-text-property p 'org-imenu-marker))
28873 (save-excursion
28874 (save-restriction
28875 (set-buffer (marker-buffer m))
28876 (goto-char m)
28877 (org-agenda-set-restriction-lock 'subtree))))
28878 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28879 'speedbar-function 'speedbar-find-file))
28880 (setq tp (previous-single-property-change
28881 (1+ p) 'speedbar-function)
28882 np (next-single-property-change
28883 tp 'speedbar-function)
28884 dir (speedbar-line-directory)
28885 txt (buffer-substring-no-properties (or tp (point-min))
28886 (or np (point-max))))
28887 (save-excursion
28888 (save-restriction
28889 (set-buffer (find-file-noselect
28890 (let ((default-directory dir))
28891 (expand-file-name txt))))
28892 (unless (org-mode-p)
28893 (error "Cannot restrict to non-Org-mode file"))
28894 (org-agenda-set-restriction-lock 'file))))
28895 (t (error "Don't know how to restrict Org-mode's agenda")))
28896 (org-move-overlay org-speedbar-restriction-lock-overlay
28897 (point-at-bol) (point-at-eol))
28898 (setq current-prefix-arg nil)
28899 (org-agenda-maybe-redo)))
28901 (eval-after-load "speedbar"
28902 '(progn
28903 (speedbar-add-supported-extension ".org")
28904 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28905 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28906 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28907 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28908 (add-hook 'speedbar-visiting-tag-hook
28909 (lambda () (org-show-context 'org-goto)))))
28912 ;;; Fixes and Hacks
28914 ;; Make flyspell not check words in links, to not mess up our keymap
28915 (defun org-mode-flyspell-verify ()
28916 "Don't let flyspell put overlays at active buttons."
28917 (not (get-text-property (point) 'keymap)))
28919 ;; Make `bookmark-jump' show the jump location if it was hidden.
28920 (eval-after-load "bookmark"
28921 '(if (boundp 'bookmark-after-jump-hook)
28922 ;; We can use the hook
28923 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28924 ;; Hook not available, use advice
28925 (defadvice bookmark-jump (after org-make-visible activate)
28926 "Make the position visible."
28927 (org-bookmark-jump-unhide))))
28929 (defun org-bookmark-jump-unhide ()
28930 "Unhide the current position, to show the bookmark location."
28931 (and (org-mode-p)
28932 (or (org-invisible-p)
28933 (save-excursion (goto-char (max (point-min) (1- (point))))
28934 (org-invisible-p)))
28935 (org-show-context 'bookmark-jump)))
28937 ;; Make session.el ignore our circular variable
28938 (eval-after-load "session"
28939 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28941 ;;;; Experimental code
28943 (defun org-closed-in-range ()
28944 "Sparse tree of items closed in a certain time range.
28945 Still experimental, may disappear in the future."
28946 (interactive)
28947 ;; Get the time interval from the user.
28948 (let* ((time1 (time-to-seconds
28949 (org-read-date nil 'to-time nil "Starting date: ")))
28950 (time2 (time-to-seconds
28951 (org-read-date nil 'to-time nil "End date:")))
28952 ;; callback function
28953 (callback (lambda ()
28954 (let ((time
28955 (time-to-seconds
28956 (apply 'encode-time
28957 (org-parse-time-string
28958 (match-string 1))))))
28959 ;; check if time in interval
28960 (and (>= time time1) (<= time time2))))))
28961 ;; make tree, check each match with the callback
28962 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28965 ;;;; Finish up
28967 (provide 'org)
28969 (run-hooks 'org-load-hook)
28971 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28972 ;;; org.el ends here