]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
* textmodes/org-export-latex.el: New file.
[gnu-emacs] / lisp / textmodes / org.el
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.23a
9 ;;
10 ;; This file is part of GNU Emacs.
11 ;;
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.
16
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.
21
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 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;
28 ;;; Commentary:
29 ;;
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.
32 ;;
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.
47 ;;
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
51 ;;
52 ;; http://orgmode.org/org.html#Installation
53 ;;
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.
61 ;;
62 ;; A list of recent changes can be found at
63 ;; http://orgmode.org/Changes.html
64 ;;
65 ;;; Code:
66
67 ;;;; Require other packages
68
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)
82
83 ;;;; Customization variables
84
85 ;;; Version
86
87 (defconst org-version "5.23a"
88 "The version number of the file org.el.")
89
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))))
98
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?")
106
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))
110
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)))
115
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))
126 s))
127
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))))
135
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)))))
144
145 ;;; The custom variables
146
147 (defgroup org nil
148 "Outline-based notes management and organizer."
149 :tag "Org"
150 :group 'outlines
151 :group 'hypermedia
152 :group 'calendar)
153
154 (defcustom org-load-hook nil
155 "Hook that is run after org.el has been loaded."
156 :group 'org
157 :type 'hook)
158
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 ;FIXME: this does not ork correctly, ignore it for now."
164 ; :group 'org
165 ; :type
166 ; '(set :greedy t
167 ; (const :tag " Mouse support (org-mouse.el)" org-mouse)
168 ; (const :tag "<A> Publishing (org-publish.el)" org-publish)
169 ; (const :tag "<A> LaTeX export (org-export-latex.el)" org-export-latex)
170 ; (const :tag " IRC/ERC links (org-irc.el)" org-irc)
171 ; (const :tag " Apple Mail message links under OS X (org-mac-message.el)" org-mac-message)))
172 ;
173 ;(defun org-load-default-extensions ()
174 ; "Load all extensions listed in `org-default-extensions'."
175 ; (mapc (lambda (ext)
176 ; (condition-case nil (require ext)
177 ; (error (message "Problems while trying to load feature `%s'" ext))))
178 ; org-default-extensions))
179
180 ;(eval-after-load "org" '(org-load-default-extensions))
181
182 ;; FIXME: Needs a separate group...
183 (defcustom org-completion-fallback-command 'hippie-expand
184 "The expansion command called by \\[org-complete] in normal context.
185 Normal means, no org-mode-specific context."
186 :group 'org
187 :type 'function)
188
189 (defgroup org-startup nil
190 "Options concerning startup of Org-mode."
191 :tag "Org Startup"
192 :group 'org)
193
194 (defcustom org-startup-folded t
195 "Non-nil means, entering Org-mode will switch to OVERVIEW.
196 This can also be configured on a per-file basis by adding one of
197 the following lines anywhere in the buffer:
198
199 #+STARTUP: fold
200 #+STARTUP: nofold
201 #+STARTUP: content"
202 :group 'org-startup
203 :type '(choice
204 (const :tag "nofold: show all" nil)
205 (const :tag "fold: overview" t)
206 (const :tag "content: all headlines" content)))
207
208 (defcustom org-startup-truncated t
209 "Non-nil means, entering Org-mode will set `truncate-lines'.
210 This is useful since some lines containing links can be very long and
211 uninteresting. Also tables look terrible when wrapped."
212 :group 'org-startup
213 :type 'boolean)
214
215 (defcustom org-startup-align-all-tables nil
216 "Non-nil means, align all tables when visiting a file.
217 This is useful when the column width in tables is forced with <N> cookies
218 in table fields. Such tables will look correct only after the first re-align.
219 This can also be configured on a per-file basis by adding one of
220 the following lines anywhere in the buffer:
221 #+STARTUP: align
222 #+STARTUP: noalign"
223 :group 'org-startup
224 :type 'boolean)
225
226 (defcustom org-insert-mode-line-in-empty-file nil
227 "Non-nil means insert the first line setting Org-mode in empty files.
228 When the function `org-mode' is called interactively in an empty file, this
229 normally means that the file name does not automatically trigger Org-mode.
230 To ensure that the file will always be in Org-mode in the future, a
231 line enforcing Org-mode will be inserted into the buffer, if this option
232 has been set."
233 :group 'org-startup
234 :type 'boolean)
235
236 (defcustom org-replace-disputed-keys nil
237 "Non-nil means use alternative key bindings for some keys.
238 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
239 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
240 If you want to use Org-mode together with one of these other modes,
241 or more generally if you would like to move some Org-mode commands to
242 other keys, set this variable and configure the keys with the variable
243 `org-disputed-keys'.
244
245 This option is only relevant at load-time of Org-mode, and must be set
246 *before* org.el is loaded. Changing it requires a restart of Emacs to
247 become effective."
248 :group 'org-startup
249 :type 'boolean)
250
251 (if (fboundp 'defvaralias)
252 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
253
254 (defcustom org-disputed-keys
255 '(([(shift up)] . [(meta p)])
256 ([(shift down)] . [(meta n)])
257 ([(shift left)] . [(meta -)])
258 ([(shift right)] . [(meta +)])
259 ([(control shift right)] . [(meta shift +)])
260 ([(control shift left)] . [(meta shift -)]))
261 "Keys for which Org-mode and other modes compete.
262 This is an alist, cars are the default keys, second element specifies
263 the alternative to use when `org-replace-disputed-keys' is t.
264
265 Keys can be specified in any syntax supported by `define-key'.
266 The value of this option takes effect only at Org-mode's startup,
267 therefore you'll have to restart Emacs to apply it after changing."
268 :group 'org-startup
269 :type 'alist)
270
271 (defun org-key (key)
272 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
273 Or return the original if not disputed."
274 (if org-replace-disputed-keys
275 (let* ((nkey (key-description key))
276 (x (org-find-if (lambda (x)
277 (equal (key-description (car x)) nkey))
278 org-disputed-keys)))
279 (if x (cdr x) key))
280 key))
281
282 (defun org-find-if (predicate seq)
283 (catch 'exit
284 (while seq
285 (if (funcall predicate (car seq))
286 (throw 'exit (car seq))
287 (pop seq)))))
288
289 (defun org-defkey (keymap key def)
290 "Define a key, possibly translated, as returned by `org-key'."
291 (define-key keymap (org-key key) def))
292
293 (defcustom org-ellipsis nil
294 "The ellipsis to use in the Org-mode outline.
295 When nil, just use the standard three dots. When a string, use that instead,
296 When a face, use the standart 3 dots, but with the specified face.
297 The change affects only Org-mode (which will then use its own display table).
298 Changing this requires executing `M-x org-mode' in a buffer to become
299 effective."
300 :group 'org-startup
301 :type '(choice (const :tag "Default" nil)
302 (face :tag "Face" :value org-warning)
303 (string :tag "String" :value "...#")))
304
305 (defvar org-display-table nil
306 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
307
308 (defgroup org-keywords nil
309 "Keywords in Org-mode."
310 :tag "Org Keywords"
311 :group 'org)
312
313 (defcustom org-deadline-string "DEADLINE:"
314 "String to mark deadline entries.
315 A deadline is this string, followed by a time stamp. Should be a word,
316 terminated by a colon. You can insert a schedule keyword and
317 a timestamp with \\[org-deadline].
318 Changes become only effective after restarting Emacs."
319 :group 'org-keywords
320 :type 'string)
321
322 (defcustom org-scheduled-string "SCHEDULED:"
323 "String to mark scheduled TODO entries.
324 A schedule is this string, followed by a time stamp. Should be a word,
325 terminated by a colon. You can insert a schedule keyword and
326 a timestamp with \\[org-schedule].
327 Changes become only effective after restarting Emacs."
328 :group 'org-keywords
329 :type 'string)
330
331 (defcustom org-closed-string "CLOSED:"
332 "String used as the prefix for timestamps logging closing a TODO entry."
333 :group 'org-keywords
334 :type 'string)
335
336 (defcustom org-clock-string "CLOCK:"
337 "String used as prefix for timestamps clocking work hours on an item."
338 :group 'org-keywords
339 :type 'string)
340
341 (defcustom org-comment-string "COMMENT"
342 "Entries starting with this keyword will never be exported.
343 An entry can be toggled between COMMENT and normal with
344 \\[org-toggle-comment].
345 Changes become only effective after restarting Emacs."
346 :group 'org-keywords
347 :type 'string)
348
349 (defcustom org-quote-string "QUOTE"
350 "Entries starting with this keyword will be exported in fixed-width font.
351 Quoting applies only to the text in the entry following the headline, and does
352 not extend beyond the next headline, even if that is lower level.
353 An entry can be toggled between QUOTE and normal with
354 \\[org-toggle-fixed-width-section]."
355 :group 'org-keywords
356 :type 'string)
357
358 (defconst org-repeat-re
359 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
360 "Regular expression for specifying repeated events.
361 After a match, group 1 contains the repeat expression.")
362
363 (defgroup org-structure nil
364 "Options concerning the general structure of Org-mode files."
365 :tag "Org Structure"
366 :group 'org)
367
368 (defgroup org-reveal-location nil
369 "Options about how to make context of a location visible."
370 :tag "Org Reveal Location"
371 :group 'org-structure)
372
373 (defconst org-context-choice
374 '(choice
375 (const :tag "Always" t)
376 (const :tag "Never" nil)
377 (repeat :greedy t :tag "Individual contexts"
378 (cons
379 (choice :tag "Context"
380 (const agenda)
381 (const org-goto)
382 (const occur-tree)
383 (const tags-tree)
384 (const link-search)
385 (const mark-goto)
386 (const bookmark-jump)
387 (const isearch)
388 (const default))
389 (boolean))))
390 "Contexts for the reveal options.")
391
392 (defcustom org-show-hierarchy-above '((default . t))
393 "Non-nil means, show full hierarchy when revealing a location.
394 Org-mode often shows locations in an org-mode file which might have
395 been invisible before. When this is set, the hierarchy of headings
396 above the exposed location is shown.
397 Turning this off for example for sparse trees makes them very compact.
398 Instead of t, this can also be an alist specifying this option for different
399 contexts. Valid contexts are
400 agenda when exposing an entry from the agenda
401 org-goto when using the command `org-goto' on key C-c C-j
402 occur-tree when using the command `org-occur' on key C-c /
403 tags-tree when constructing a sparse tree based on tags matches
404 link-search when exposing search matches associated with a link
405 mark-goto when exposing the jump goal of a mark
406 bookmark-jump when exposing a bookmark location
407 isearch when exiting from an incremental search
408 default default for all contexts not set explicitly"
409 :group 'org-reveal-location
410 :type org-context-choice)
411
412 (defcustom org-show-following-heading '((default . nil))
413 "Non-nil means, show following heading when revealing a location.
414 Org-mode often shows locations in an org-mode file which might have
415 been invisible before. When this is set, the heading following the
416 match is shown.
417 Turning this off for example for sparse trees makes them very compact,
418 but makes it harder to edit the location of the match. In such a case,
419 use the command \\[org-reveal] to show more context.
420 Instead of t, this can also be an alist specifying this option for different
421 contexts. See `org-show-hierarchy-above' for valid contexts."
422 :group 'org-reveal-location
423 :type org-context-choice)
424
425 (defcustom org-show-siblings '((default . nil) (isearch t))
426 "Non-nil means, show all sibling heading when revealing a location.
427 Org-mode often shows locations in an org-mode file which might have
428 been invisible before. When this is set, the sibling of the current entry
429 heading are all made visible. If `org-show-hierarchy-above' is t,
430 the same happens on each level of the hierarchy above the current entry.
431
432 By default this is on for the isearch context, off for all other contexts.
433 Turning this off for example for sparse trees makes them very compact,
434 but makes it harder to edit the location of the match. In such a case,
435 use the command \\[org-reveal] to show more context.
436 Instead of t, this can also be an alist specifying this option for different
437 contexts. See `org-show-hierarchy-above' for valid contexts."
438 :group 'org-reveal-location
439 :type org-context-choice)
440
441 (defcustom org-show-entry-below '((default . nil))
442 "Non-nil means, show the entry below a headline when revealing a location.
443 Org-mode often shows locations in an org-mode file which might have
444 been invisible before. When this is set, the text below the headline that is
445 exposed is also shown.
446
447 By default this is off for all contexts.
448 Instead of t, this can also be an alist specifying this option for different
449 contexts. See `org-show-hierarchy-above' for valid contexts."
450 :group 'org-reveal-location
451 :type org-context-choice)
452
453 (defgroup org-cycle nil
454 "Options concerning visibility cycling in Org-mode."
455 :tag "Org Cycle"
456 :group 'org-structure)
457
458 (defcustom org-drawers '("PROPERTIES" "CLOCK")
459 "Names of drawers. Drawers are not opened by cycling on the headline above.
460 Drawers only open with a TAB on the drawer line itself. A drawer looks like
461 this:
462 :DRAWERNAME:
463 .....
464 :END:
465 The drawer \"PROPERTIES\" is special for capturing properties through
466 the property API.
467
468 Drawers can be defined on the per-file basis with a line like:
469
470 #+DRAWERS: HIDDEN STATE PROPERTIES"
471 :group 'org-structure
472 :type '(repeat (string :tag "Drawer Name")))
473
474 (defcustom org-cycle-global-at-bob nil
475 "Cycle globally if cursor is at beginning of buffer and not at a headline.
476 This makes it possible to do global cycling without having to use S-TAB or
477 C-u TAB. For this special case to work, the first line of the buffer
478 must not be a headline - it may be empty ot some other text. When used in
479 this way, `org-cycle-hook' is disables temporarily, to make sure the
480 cursor stays at the beginning of the buffer.
481 When this option is nil, don't do anything special at the beginning
482 of the buffer."
483 :group 'org-cycle
484 :type 'boolean)
485
486 (defcustom org-cycle-emulate-tab t
487 "Where should `org-cycle' emulate TAB.
488 nil Never
489 white Only in completely white lines
490 whitestart Only at the beginning of lines, before the first non-white char
491 t Everywhere except in headlines
492 exc-hl-bol Everywhere except at the start of a headline
493 If TAB is used in a place where it does not emulate TAB, the current subtree
494 visibility is cycled."
495 :group 'org-cycle
496 :type '(choice (const :tag "Never" nil)
497 (const :tag "Only in completely white lines" white)
498 (const :tag "Before first char in a line" whitestart)
499 (const :tag "Everywhere except in headlines" t)
500 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
501 ))
502
503 (defcustom org-cycle-separator-lines 2
504 "Number of empty lines needed to keep an empty line between collapsed trees.
505 If you leave an empty line between the end of a subtree and the following
506 headline, this empty line is hidden when the subtree is folded.
507 Org-mode will leave (exactly) one empty line visible if the number of
508 empty lines is equal or larger to the number given in this variable.
509 So the default 2 means, at least 2 empty lines after the end of a subtree
510 are needed to produce free space between a collapsed subtree and the
511 following headline.
512
513 Special case: when 0, never leave empty lines in collapsed view."
514 :group 'org-cycle
515 :type 'integer)
516
517 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
518 org-cycle-hide-drawers
519 org-cycle-show-empty-lines
520 org-optimize-window-after-visibility-change)
521 "Hook that is run after `org-cycle' has changed the buffer visibility.
522 The function(s) in this hook must accept a single argument which indicates
523 the new state that was set by the most recent `org-cycle' command. The
524 argument is a symbol. After a global state change, it can have the values
525 `overview', `content', or `all'. After a local state change, it can have
526 the values `folded', `children', or `subtree'."
527 :group 'org-cycle
528 :type 'hook)
529
530 (defgroup org-edit-structure nil
531 "Options concerning structure editing in Org-mode."
532 :tag "Org Edit Structure"
533 :group 'org-structure)
534
535 (defcustom org-odd-levels-only nil
536 "Non-nil means, skip even levels and only use odd levels for the outline.
537 This has the effect that two stars are being added/taken away in
538 promotion/demotion commands. It also influences how levels are
539 handled by the exporters.
540 Changing it requires restart of `font-lock-mode' to become effective
541 for fontification also in regions already fontified.
542 You may also set this on a per-file basis by adding one of the following
543 lines to the buffer:
544
545 #+STARTUP: odd
546 #+STARTUP: oddeven"
547 :group 'org-edit-structure
548 :group 'org-font-lock
549 :type 'boolean)
550
551 (defcustom org-adapt-indentation t
552 "Non-nil means, adapt indentation when promoting and demoting.
553 When this is set and the *entire* text in an entry is indented, the
554 indentation is increased by one space in a demotion command, and
555 decreased by one in a promotion command. If any line in the entry
556 body starts at column 0, indentation is not changed at all."
557 :group 'org-edit-structure
558 :type 'boolean)
559
560 (defcustom org-special-ctrl-a/e nil
561 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
562 When t, `C-a' will bring back the cursor to the beginning of the
563 headline text, i.e. after the stars and after a possible TODO keyword.
564 In an item, this will be the position after the bullet.
565 When the cursor is already at that position, another `C-a' will bring
566 it to the beginning of the line.
567 `C-e' will jump to the end of the headline, ignoring the presence of tags
568 in the headline. A second `C-e' will then jump to the true end of the
569 line, after any tags.
570 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
571 and only a directly following, identical keypress will bring the cursor
572 to the special positions."
573 :group 'org-edit-structure
574 :type '(choice
575 (const :tag "off" nil)
576 (const :tag "after bullet first" t)
577 (const :tag "border first" reversed)))
578
579 (if (fboundp 'defvaralias)
580 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
581
582 (defcustom org-special-ctrl-k nil
583 "Non-nil means `C-k' will behave specially in headlines.
584 When nil, `C-k' will call the default `kill-line' command.
585 When t, the following will happen while the cursor is in the headline:
586
587 - When the cursor is at the beginning of a headline, kill the entire
588 line and possible the folded subtree below the line.
589 - When in the middle of the headline text, kill the headline up to the tags.
590 - When after the headline text, kill the tags."
591 :group 'org-edit-structure
592 :type 'boolean)
593
594 (defcustom org-M-RET-may-split-line '((default . t))
595 "Non-nil means, M-RET will split the line at the cursor position.
596 When nil, it will go to the end of the line before making a
597 new line.
598 You may also set this option in a different way for different
599 contexts. Valid contexts are:
600
601 headline when creating a new headline
602 item when creating a new item
603 table in a table field
604 default the value to be used for all contexts not explicitly
605 customized"
606 :group 'org-structure
607 :group 'org-table
608 :type '(choice
609 (const :tag "Always" t)
610 (const :tag "Never" nil)
611 (repeat :greedy t :tag "Individual contexts"
612 (cons
613 (choice :tag "Context"
614 (const headline)
615 (const item)
616 (const table)
617 (const default))
618 (boolean)))))
619
620
621 (defcustom org-blank-before-new-entry '((heading . nil)
622 (plain-list-item . nil))
623 "Should `org-insert-heading' leave a blank line before new heading/item?
624 The value is an alist, with `heading' and `plain-list-item' as car,
625 and a boolean flag as cdr."
626 :group 'org-edit-structure
627 :type '(list
628 (cons (const heading) (boolean))
629 (cons (const plain-list-item) (boolean))))
630
631 (defcustom org-insert-heading-hook nil
632 "Hook being run after inserting a new heading."
633 :group 'org-edit-structure
634 :type 'hook)
635
636 (defcustom org-enable-fixed-width-editor t
637 "Non-nil means, lines starting with \":\" are treated as fixed-width.
638 This currently only means, they are never auto-wrapped.
639 When nil, such lines will be treated like ordinary lines.
640 See also the QUOTE keyword."
641 :group 'org-edit-structure
642 :type 'boolean)
643
644 (defcustom org-goto-auto-isearch t
645 "Non-nil means, typing characters in org-goto starts incremental search."
646 :group 'org-edit-structure
647 :type 'boolean)
648
649 (defgroup org-sparse-trees nil
650 "Options concerning sparse trees in Org-mode."
651 :tag "Org Sparse Trees"
652 :group 'org-structure)
653
654 (defcustom org-highlight-sparse-tree-matches t
655 "Non-nil means, highlight all matches that define a sparse tree.
656 The highlights will automatically disappear the next time the buffer is
657 changed by an edit command."
658 :group 'org-sparse-trees
659 :type 'boolean)
660
661 (defcustom org-remove-highlights-with-change t
662 "Non-nil means, any change to the buffer will remove temporary highlights.
663 Such highlights are created by `org-occur' and `org-clock-display'.
664 When nil, `C-c C-c needs to be used to get rid of the highlights.
665 The highlights created by `org-preview-latex-fragment' always need
666 `C-c C-c' to be removed."
667 :group 'org-sparse-trees
668 :group 'org-time
669 :type 'boolean)
670
671
672 (defcustom org-occur-hook '(org-first-headline-recenter)
673 "Hook that is run after `org-occur' has constructed a sparse tree.
674 This can be used to recenter the window to show as much of the structure
675 as possible."
676 :group 'org-sparse-trees
677 :type 'hook)
678
679 (defgroup org-plain-lists nil
680 "Options concerning plain lists in Org-mode."
681 :tag "Org Plain lists"
682 :group 'org-structure)
683
684 (defcustom org-cycle-include-plain-lists nil
685 "Non-nil means, include plain lists into visibility cycling.
686 This means that during cycling, plain list items will *temporarily* be
687 interpreted as outline headlines with a level given by 1000+i where i is the
688 indentation of the bullet. In all other operations, plain list items are
689 not seen as headlines. For example, you cannot assign a TODO keyword to
690 such an item."
691 :group 'org-plain-lists
692 :type 'boolean)
693
694 (defcustom org-plain-list-ordered-item-terminator t
695 "The character that makes a line with leading number an ordered list item.
696 Valid values are ?. and ?\). To get both terminators, use t. While
697 ?. may look nicer, it creates the danger that a line with leading
698 number may be incorrectly interpreted as an item. ?\) therefore is
699 the safe choice."
700 :group 'org-plain-lists
701 :type '(choice (const :tag "dot like in \"2.\"" ?.)
702 (const :tag "paren like in \"2)\"" ?\))
703 (const :tab "both" t)))
704
705 (defcustom org-auto-renumber-ordered-lists t
706 "Non-nil means, automatically renumber ordered plain lists.
707 Renumbering happens when the sequence have been changed with
708 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
709 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
710 :group 'org-plain-lists
711 :type 'boolean)
712
713 (defcustom org-provide-checkbox-statistics t
714 "Non-nil means, update checkbox statistics after insert and toggle.
715 When this is set, checkbox statistics is updated each time you either insert
716 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
717 with \\[org-ctrl-c-ctrl-c\\]."
718 :group 'org-plain-lists
719 :type 'boolean)
720
721 (defgroup org-archive nil
722 "Options concerning archiving in Org-mode."
723 :tag "Org Archive"
724 :group 'org-structure)
725
726 (defcustom org-archive-tag "ARCHIVE"
727 "The tag that marks a subtree as archived.
728 An archived subtree does not open during visibility cycling, and does
729 not contribute to the agenda listings.
730 After changing this, font-lock must be restarted in the relevant buffers to
731 get the proper fontification."
732 :group 'org-archive
733 :group 'org-keywords
734 :type 'string)
735
736 (defcustom org-agenda-skip-archived-trees t
737 "Non-nil means, the agenda will skip any items located in archived trees.
738 An archived tree is a tree marked with the tag ARCHIVE."
739 :group 'org-archive
740 :group 'org-agenda-skip
741 :type 'boolean)
742
743 (defcustom org-cycle-open-archived-trees nil
744 "Non-nil means, `org-cycle' will open archived trees.
745 An archived tree is a tree marked with the tag ARCHIVE.
746 When nil, archived trees will stay folded. You can still open them with
747 normal outline commands like `show-all', but not with the cycling commands."
748 :group 'org-archive
749 :group 'org-cycle
750 :type 'boolean)
751
752 (defcustom org-sparse-tree-open-archived-trees nil
753 "Non-nil means sparse tree construction shows matches in archived trees.
754 When nil, matches in these trees are highlighted, but the trees are kept in
755 collapsed state."
756 :group 'org-archive
757 :group 'org-sparse-trees
758 :type 'boolean)
759
760 (defcustom org-archive-location "%s_archive::"
761 "The location where subtrees should be archived.
762 This string consists of two parts, separated by a double-colon.
763
764 The first part is a file name - when omitted, archiving happens in the same
765 file. %s will be replaced by the current file name (without directory part).
766 Archiving to a different file is useful to keep archived entries from
767 contributing to the Org-mode Agenda.
768
769 The part after the double colon is a headline. The archived entries will be
770 filed under that headline. When omitted, the subtrees are simply filed away
771 at the end of the file, as top-level entries.
772
773 Here are a few examples:
774 \"%s_archive::\"
775 If the current file is Projects.org, archive in file
776 Projects.org_archive, as top-level trees. This is the default.
777
778 \"::* Archived Tasks\"
779 Archive in the current file, under the top-level headline
780 \"* Archived Tasks\".
781
782 \"~/org/archive.org::\"
783 Archive in file ~/org/archive.org (absolute path), as top-level trees.
784
785 \"basement::** Finished Tasks\"
786 Archive in file ./basement (relative path), as level 3 trees
787 below the level 2 heading \"** Finished Tasks\".
788
789 You may set this option on a per-file basis by adding to the buffer a
790 line like
791
792 #+ARCHIVE: basement::** Finished Tasks"
793 :group 'org-archive
794 :type 'string)
795
796 (defcustom org-archive-mark-done t
797 "Non-nil means, mark entries as DONE when they are moved to the archive file.
798 This can be a string to set the keyword to use. When t, Org-mode will
799 use the first keyword in its list that means done."
800 :group 'org-archive
801 :type '(choice
802 (const :tag "No" nil)
803 (const :tag "Yes" t)
804 (string :tag "Use this keyword")))
805
806 (defcustom org-archive-stamp-time t
807 "Non-nil means, add a time stamp to entries moved to an archive file.
808 This variable is obsolete and has no effect anymore, instead add ot remove
809 `time' from the variablle `org-archive-save-context-info'."
810 :group 'org-archive
811 :type 'boolean)
812
813 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
814 "Parts of context info that should be stored as properties when archiving.
815 When a subtree is moved to an archive file, it looses information given by
816 context, like inherited tags, the category, and possibly also the TODO
817 state (depending on the variable `org-archive-mark-done').
818 This variable can be a list of any of the following symbols:
819
820 time The time of archiving.
821 file The file where the entry originates.
822 itags The local tags, in the headline of the subtree.
823 ltags The tags the subtree inherits from further up the hierarchy.
824 todo The pre-archive TODO state.
825 category The category, taken from file name or #+CATEGORY lines.
826 olpath The outline path to the item. These are all headlines above
827 the current item, separated by /, like a file path.
828
829 For each symbol present in the list, a property will be created in
830 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
831 information."
832 :group 'org-archive
833 :type '(set :greedy t
834 (const :tag "Time" time)
835 (const :tag "File" file)
836 (const :tag "Category" category)
837 (const :tag "TODO state" todo)
838 (const :tag "TODO state" priority)
839 (const :tag "Inherited tags" itags)
840 (const :tag "Outline path" olpath)
841 (const :tag "Local tags" ltags)))
842
843 (defgroup org-imenu-and-speedbar nil
844 "Options concerning imenu and speedbar in Org-mode."
845 :tag "Org Imenu and Speedbar"
846 :group 'org-structure)
847
848 (defcustom org-imenu-depth 2
849 "The maximum level for Imenu access to Org-mode headlines.
850 This also applied for speedbar access."
851 :group 'org-imenu-and-speedbar
852 :type 'number)
853
854 (defgroup org-table nil
855 "Options concerning tables in Org-mode."
856 :tag "Org Table"
857 :group 'org)
858
859 (defcustom org-enable-table-editor 'optimized
860 "Non-nil means, lines starting with \"|\" are handled by the table editor.
861 When nil, such lines will be treated like ordinary lines.
862
863 When equal to the symbol `optimized', the table editor will be optimized to
864 do the following:
865 - Automatic overwrite mode in front of whitespace in table fields.
866 This makes the structure of the table stay in tact as long as the edited
867 field does not exceed the column width.
868 - Minimize the number of realigns. Normally, the table is aligned each time
869 TAB or RET are pressed to move to another field. With optimization this
870 happens only if changes to a field might have changed the column width.
871 Optimization requires replacing the functions `self-insert-command',
872 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
873 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
874 very good at guessing when a re-align will be necessary, but you can always
875 force one with \\[org-ctrl-c-ctrl-c].
876
877 If you would like to use the optimized version in Org-mode, but the
878 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
879
880 This variable can be used to turn on and off the table editor during a session,
881 but in order to toggle optimization, a restart is required.
882
883 See also the variable `org-table-auto-blank-field'."
884 :group 'org-table
885 :type '(choice
886 (const :tag "off" nil)
887 (const :tag "on" t)
888 (const :tag "on, optimized" optimized)))
889
890 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
891 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
892 In the optimized version, the table editor takes over all simple keys that
893 normally just insert a character. In tables, the characters are inserted
894 in a way to minimize disturbing the table structure (i.e. in overwrite mode
895 for empty fields). Outside tables, the correct binding of the keys is
896 restored.
897
898 The default for this option is t if the optimized version is also used in
899 Org-mode. See the variable `org-enable-table-editor' for details. Changing
900 this variable requires a restart of Emacs to become effective."
901 :group 'org-table
902 :type 'boolean)
903
904 (defcustom orgtbl-radio-table-templates
905 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
906 % END RECEIVE ORGTBL %n
907 \\begin{comment}
908 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
909 | | |
910 \\end{comment}\n")
911 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
912 @c END RECEIVE ORGTBL %n
913 @ignore
914 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
915 | | |
916 @end ignore\n")
917 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
918 <!-- END RECEIVE ORGTBL %n -->
919 <!--
920 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
921 | | |
922 -->\n"))
923 "Templates for radio tables in different major modes.
924 All occurrences of %n in a template will be replaced with the name of the
925 table, obtained by prompting the user."
926 :group 'org-table
927 :type '(repeat
928 (list (symbol :tag "Major mode")
929 (string :tag "Format"))))
930
931 (defgroup org-table-settings nil
932 "Settings for tables in Org-mode."
933 :tag "Org Table Settings"
934 :group 'org-table)
935
936 (defcustom org-table-default-size "5x2"
937 "The default size for newly created tables, Columns x Rows."
938 :group 'org-table-settings
939 :type 'string)
940
941 (defcustom org-table-number-regexp
942 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
943 "Regular expression for recognizing numbers in table columns.
944 If a table column contains mostly numbers, it will be aligned to the
945 right. If not, it will be aligned to the left.
946
947 The default value of this option is a regular expression which allows
948 anything which looks remotely like a number as used in scientific
949 context. For example, all of the following will be considered a
950 number:
951 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
952
953 Other options offered by the customize interface are more restrictive."
954 :group 'org-table-settings
955 :type '(choice
956 (const :tag "Positive Integers"
957 "^[0-9]+$")
958 (const :tag "Integers"
959 "^[-+]?[0-9]+$")
960 (const :tag "Floating Point Numbers"
961 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
962 (const :tag "Floating Point Number or Integer"
963 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
964 (const :tag "Exponential, Floating point, Integer"
965 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
966 (const :tag "Very General Number-Like, including hex"
967 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
968 (string :tag "Regexp:")))
969
970 (defcustom org-table-number-fraction 0.5
971 "Fraction of numbers in a column required to make the column align right.
972 In a column all non-white fields are considered. If at least this
973 fraction of fields is matched by `org-table-number-fraction',
974 alignment to the right border applies."
975 :group 'org-table-settings
976 :type 'number)
977
978 (defgroup org-table-editing nil
979 "Behavior of tables during editing in Org-mode."
980 :tag "Org Table Editing"
981 :group 'org-table)
982
983 (defcustom org-table-automatic-realign t
984 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
985 When nil, aligning is only done with \\[org-table-align], or after column
986 removal/insertion."
987 :group 'org-table-editing
988 :type 'boolean)
989
990 (defcustom org-table-auto-blank-field t
991 "Non-nil means, automatically blank table field when starting to type into it.
992 This only happens when typing immediately after a field motion
993 command (TAB, S-TAB or RET).
994 Only relevant when `org-enable-table-editor' is equal to `optimized'."
995 :group 'org-table-editing
996 :type 'boolean)
997
998 (defcustom org-table-tab-jumps-over-hlines t
999 "Non-nil means, tab in the last column of a table with jump over a hline.
1000 If a horizontal separator line is following the current line,
1001 `org-table-next-field' can either create a new row before that line, or jump
1002 over the line. When this option is nil, a new line will be created before
1003 this line."
1004 :group 'org-table-editing
1005 :type 'boolean)
1006
1007 (defcustom org-table-tab-recognizes-table.el t
1008 "Non-nil means, TAB will automatically notice a table.el table.
1009 When it sees such a table, it moves point into it and - if necessary -
1010 calls `table-recognize-table'."
1011 :group 'org-table-editing
1012 :type 'boolean)
1013
1014 (defgroup org-table-calculation nil
1015 "Options concerning tables in Org-mode."
1016 :tag "Org Table Calculation"
1017 :group 'org-table)
1018
1019 (defcustom org-table-use-standard-references t
1020 "Should org-mode work with table refrences like B3 instead of @3$2?
1021 Possible values are:
1022 nil never use them
1023 from accept as input, do not present for editing
1024 t: accept as input and present for editing"
1025 :group 'org-table-calculation
1026 :type '(choice
1027 (const :tag "Never, don't even check unser input for them" nil)
1028 (const :tag "Always, both as user input, and when editing" t)
1029 (const :tag "Convert user input, don't offer during editing" 'from)))
1030
1031 (defcustom org-table-copy-increment t
1032 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1033 :group 'org-table-calculation
1034 :type 'boolean)
1035
1036 (defcustom org-calc-default-modes
1037 '(calc-internal-prec 12
1038 calc-float-format (float 5)
1039 calc-angle-mode deg
1040 calc-prefer-frac nil
1041 calc-symbolic-mode nil
1042 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1043 calc-display-working-message t
1044 )
1045 "List with Calc mode settings for use in calc-eval for table formulas.
1046 The list must contain alternating symbols (Calc modes variables and values).
1047 Don't remove any of the default settings, just change the values. Org-mode
1048 relies on the variables to be present in the list."
1049 :group 'org-table-calculation
1050 :type 'plist)
1051
1052 (defcustom org-table-formula-evaluate-inline t
1053 "Non-nil means, TAB and RET evaluate a formula in current table field.
1054 If the current field starts with an equal sign, it is assumed to be a formula
1055 which should be evaluated as described in the manual and in the documentation
1056 string of the command `org-table-eval-formula'. This feature requires the
1057 Emacs calc package.
1058 When this variable is nil, formula calculation is only available through
1059 the command \\[org-table-eval-formula]."
1060 :group 'org-table-calculation
1061 :type 'boolean)
1062
1063 (defcustom org-table-formula-use-constants t
1064 "Non-nil means, interpret constants in formulas in tables.
1065 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1066 by the value given in `org-table-formula-constants', or by a value obtained
1067 from the `constants.el' package."
1068 :group 'org-table-calculation
1069 :type 'boolean)
1070
1071 (defcustom org-table-formula-constants nil
1072 "Alist with constant names and values, for use in table formulas.
1073 The car of each element is a name of a constant, without the `$' before it.
1074 The cdr is the value as a string. For example, if you'd like to use the
1075 speed of light in a formula, you would configure
1076
1077 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1078
1079 and then use it in an equation like `$1*$c'.
1080
1081 Constants can also be defined on a per-file basis using a line like
1082
1083 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1084 :group 'org-table-calculation
1085 :type '(repeat
1086 (cons (string :tag "name")
1087 (string :tag "value"))))
1088
1089 (defvar org-table-formula-constants-local nil
1090 "Local version of `org-table-formula-constants'.")
1091 (make-variable-buffer-local 'org-table-formula-constants-local)
1092
1093 (defcustom org-table-allow-automatic-line-recalculation t
1094 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1095 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1096 :group 'org-table-calculation
1097 :type 'boolean)
1098
1099 (defgroup org-link nil
1100 "Options concerning links in Org-mode."
1101 :tag "Org Link"
1102 :group 'org)
1103
1104 (defvar org-link-abbrev-alist-local nil
1105 "Buffer-local version of `org-link-abbrev-alist', which see.
1106 The value of this is taken from the #+LINK lines.")
1107 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1108
1109 (defcustom org-link-abbrev-alist nil
1110 "Alist of link abbreviations.
1111 The car of each element is a string, to be replaced at the start of a link.
1112 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1113 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1114
1115 [[linkkey:tag][description]]
1116
1117 If REPLACE is a string, the tag will simply be appended to create the link.
1118 If the string contains \"%s\", the tag will be inserted there.
1119
1120 REPLACE may also be a function that will be called with the tag as the
1121 only argument to create the link, which should be returned as a string.
1122
1123 See the manual for examples."
1124 :group 'org-link
1125 :type 'alist)
1126
1127 (defcustom org-descriptive-links t
1128 "Non-nil means, hide link part and only show description of bracket links.
1129 Bracket links are like [[link][descritpion]]. This variable sets the initial
1130 state in new org-mode buffers. The setting can then be toggled on a
1131 per-buffer basis from the Org->Hyperlinks menu."
1132 :group 'org-link
1133 :type 'boolean)
1134
1135 (defcustom org-link-file-path-type 'adaptive
1136 "How the path name in file links should be stored.
1137 Valid values are:
1138
1139 relative Relative to the current directory, i.e. the directory of the file
1140 into which the link is being inserted.
1141 absolute Absolute path, if possible with ~ for home directory.
1142 noabbrev Absolute path, no abbreviation of home directory.
1143 adaptive Use relative path for files in the current directory and sub-
1144 directories of it. For other files, use an absolute path."
1145 :group 'org-link
1146 :type '(choice
1147 (const relative)
1148 (const absolute)
1149 (const noabbrev)
1150 (const adaptive)))
1151
1152 (defcustom org-activate-links '(bracket angle plain radio tag date)
1153 "Types of links that should be activated in Org-mode files.
1154 This is a list of symbols, each leading to the activation of a certain link
1155 type. In principle, it does not hurt to turn on most link types - there may
1156 be a small gain when turning off unused link types. The types are:
1157
1158 bracket The recommended [[link][description]] or [[link]] links with hiding.
1159 angular Links in angular brackes that may contain whitespace like
1160 <bbdb:Carsten Dominik>.
1161 plain Plain links in normal text, no whitespace, like http://google.com.
1162 radio Text that is matched by a radio target, see manual for details.
1163 tag Tag settings in a headline (link to tag search).
1164 date Time stamps (link to calendar).
1165
1166 Changing this variable requires a restart of Emacs to become effective."
1167 :group 'org-link
1168 :type '(set (const :tag "Double bracket links (new style)" bracket)
1169 (const :tag "Angular bracket links (old style)" angular)
1170 (const :tag "Plain text links" plain)
1171 (const :tag "Radio target matches" radio)
1172 (const :tag "Tags" tag)
1173 (const :tag "Timestamps" date)))
1174
1175 (defgroup org-link-store nil
1176 "Options concerning storing links in Org-mode."
1177 :tag "Org Store Link"
1178 :group 'org-link)
1179
1180 (defcustom org-email-link-description-format "Email %c: %.30s"
1181 "Format of the description part of a link to an email or usenet message.
1182 The following %-excapes will be replaced by corresponding information:
1183
1184 %F full \"From\" field
1185 %f name, taken from \"From\" field, address if no name
1186 %T full \"To\" field
1187 %t first name in \"To\" field, address if no name
1188 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1189 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1190 %s subject
1191 %m message-id.
1192
1193 You may use normal field width specification between the % and the letter.
1194 This is for example useful to limit the length of the subject.
1195
1196 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1197 :group 'org-link-store
1198 :type 'string)
1199
1200 (defcustom org-from-is-user-regexp
1201 (let (r1 r2)
1202 (when (and user-mail-address (not (string= user-mail-address "")))
1203 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1204 (when (and user-full-name (not (string= user-full-name "")))
1205 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1206 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1207 "Regexp mached against the \"From:\" header of an email or usenet message.
1208 It should match if the message is from the user him/herself."
1209 :group 'org-link-store
1210 :type 'regexp)
1211
1212 (defcustom org-context-in-file-links t
1213 "Non-nil means, file links from `org-store-link' contain context.
1214 A search string will be added to the file name with :: as separator and
1215 used to find the context when the link is activated by the command
1216 `org-open-at-point'.
1217 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1218 negates this setting for the duration of the command."
1219 :group 'org-link-store
1220 :type 'boolean)
1221
1222 (defcustom org-keep-stored-link-after-insertion nil
1223 "Non-nil means, keep link in list for entire session.
1224
1225 The command `org-store-link' adds a link pointing to the current
1226 location to an internal list. These links accumulate during a session.
1227 The command `org-insert-link' can be used to insert links into any
1228 Org-mode file (offering completion for all stored links). When this
1229 option is nil, every link which has been inserted once using \\[org-insert-link]
1230 will be removed from the list, to make completing the unused links
1231 more efficient."
1232 :group 'org-link-store
1233 :type 'boolean)
1234
1235 (defcustom org-usenet-links-prefer-google nil
1236 "Non-nil means, `org-store-link' will create web links to Google groups.
1237 When nil, Gnus will be used for such links.
1238 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1239 negates this setting for the duration of the command."
1240 :group 'org-link-store
1241 :type 'boolean)
1242
1243 (defgroup org-link-follow nil
1244 "Options concerning following links in Org-mode."
1245 :tag "Org Follow Link"
1246 :group 'org-link)
1247
1248 (defcustom org-follow-link-hook nil
1249 "Hook that is run after a link has been followed."
1250 :group 'org-link-follow
1251 :type 'hook)
1252
1253 (defcustom org-tab-follows-link nil
1254 "Non-nil means, on links TAB will follow the link.
1255 Needs to be set before org.el is loaded."
1256 :group 'org-link-follow
1257 :type 'boolean)
1258
1259 (defcustom org-return-follows-link nil
1260 "Non-nil means, on links RET will follow the link.
1261 Needs to be set before org.el is loaded."
1262 :group 'org-link-follow
1263 :type 'boolean)
1264
1265 (defcustom org-mouse-1-follows-link
1266 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1267 "Non-nil means, mouse-1 on a link will follow the link.
1268 A longer mouse click will still set point. Does not work on XEmacs.
1269 Needs to be set before org.el is loaded."
1270 :group 'org-link-follow
1271 :type 'boolean)
1272
1273 (defcustom org-mark-ring-length 4
1274 "Number of different positions to be recorded in the ring
1275 Changing this requires a restart of Emacs to work correctly."
1276 :group 'org-link-follow
1277 :type 'interger)
1278
1279 (defcustom org-link-frame-setup
1280 '((vm . vm-visit-folder-other-frame)
1281 (gnus . gnus-other-frame)
1282 (file . find-file-other-window))
1283 "Setup the frame configuration for following links.
1284 When following a link with Emacs, it may often be useful to display
1285 this link in another window or frame. This variable can be used to
1286 set this up for the different types of links.
1287 For VM, use any of
1288 `vm-visit-folder'
1289 `vm-visit-folder-other-frame'
1290 For Gnus, use any of
1291 `gnus'
1292 `gnus-other-frame'
1293 For FILE, use any of
1294 `find-file'
1295 `find-file-other-window'
1296 `find-file-other-frame'
1297 For the calendar, use the variable `calendar-setup'.
1298 For BBDB, it is currently only possible to display the matches in
1299 another window."
1300 :group 'org-link-follow
1301 :type '(list
1302 (cons (const vm)
1303 (choice
1304 (const vm-visit-folder)
1305 (const vm-visit-folder-other-window)
1306 (const vm-visit-folder-other-frame)))
1307 (cons (const gnus)
1308 (choice
1309 (const gnus)
1310 (const gnus-other-frame)))
1311 (cons (const file)
1312 (choice
1313 (const find-file)
1314 (const find-file-other-window)
1315 (const find-file-other-frame)))))
1316
1317 (defcustom org-display-internal-link-with-indirect-buffer nil
1318 "Non-nil means, use indirect buffer to display infile links.
1319 Activating internal links (from one location in a file to another location
1320 in the same file) normally just jumps to the location. When the link is
1321 activated with a C-u prefix (or with mouse-3), the link is displayed in
1322 another window. When this option is set, the other window actually displays
1323 an indirect buffer clone of the current buffer, to avoid any visibility
1324 changes to the current buffer."
1325 :group 'org-link-follow
1326 :type 'boolean)
1327
1328 (defcustom org-open-non-existing-files nil
1329 "Non-nil means, `org-open-file' will open non-existing files.
1330 When nil, an error will be generated."
1331 :group 'org-link-follow
1332 :type 'boolean)
1333
1334 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1335 "Function and arguments to call for following mailto links.
1336 This is a list with the first element being a lisp function, and the
1337 remaining elements being arguments to the function. In string arguments,
1338 %a will be replaced by the address, and %s will be replaced by the subject
1339 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1340 :group 'org-link-follow
1341 :type '(choice
1342 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1343 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1344 (const :tag "message-mail" (message-mail "%a" "%s"))
1345 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1346
1347 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1348 "Non-nil means, ask for confirmation before executing shell links.
1349 Shell links can be dangerous: just think about a link
1350
1351 [[shell:rm -rf ~/*][Google Search]]
1352
1353 This link would show up in your Org-mode document as \"Google Search\",
1354 but really it would remove your entire home directory.
1355 Therefore we advise against setting this variable to nil.
1356 Just change it to `y-or-n-p' of you want to confirm with a
1357 single keystroke rather than having to type \"yes\"."
1358 :group 'org-link-follow
1359 :type '(choice
1360 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1361 (const :tag "with y-or-n (faster)" y-or-n-p)
1362 (const :tag "no confirmation (dangerous)" nil)))
1363
1364 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1365 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1366 Elisp links can be dangerous: just think about a link
1367
1368 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1369
1370 This link would show up in your Org-mode document as \"Google Search\",
1371 but really it would remove your entire home directory.
1372 Therefore we advise against setting this variable to nil.
1373 Just change it to `y-or-n-p' of you want to confirm with a
1374 single keystroke rather than having to type \"yes\"."
1375 :group 'org-link-follow
1376 :type '(choice
1377 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1378 (const :tag "with y-or-n (faster)" y-or-n-p)
1379 (const :tag "no confirmation (dangerous)" nil)))
1380
1381 (defconst org-file-apps-defaults-gnu
1382 '((remote . emacs)
1383 (t . mailcap))
1384 "Default file applications on a UNIX or GNU/Linux system.
1385 See `org-file-apps'.")
1386
1387 (defconst org-file-apps-defaults-macosx
1388 '((remote . emacs)
1389 (t . "open %s")
1390 ("ps" . "gv %s")
1391 ("ps.gz" . "gv %s")
1392 ("eps" . "gv %s")
1393 ("eps.gz" . "gv %s")
1394 ("dvi" . "xdvi %s")
1395 ("fig" . "xfig %s"))
1396 "Default file applications on a MacOS X system.
1397 The system \"open\" is known as a default, but we use X11 applications
1398 for some files for which the OS does not have a good default.
1399 See `org-file-apps'.")
1400
1401 (defconst org-file-apps-defaults-windowsnt
1402 (list
1403 '(remote . emacs)
1404 (cons t
1405 (list (if (featurep 'xemacs)
1406 'mswindows-shell-execute
1407 'w32-shell-execute)
1408 "open" 'file)))
1409 "Default file applications on a Windows NT system.
1410 The system \"open\" is used for most files.
1411 See `org-file-apps'.")
1412
1413 (defcustom org-file-apps
1414 '(
1415 ("txt" . emacs)
1416 ("tex" . emacs)
1417 ("ltx" . emacs)
1418 ("org" . emacs)
1419 ("el" . emacs)
1420 ("bib" . emacs)
1421 )
1422 "External applications for opening `file:path' items in a document.
1423 Org-mode uses system defaults for different file types, but
1424 you can use this variable to set the application for a given file
1425 extension. The entries in this list are cons cells where the car identifies
1426 files and the cdr the corresponding command. Possible values for the
1427 file identifier are
1428 \"ext\" A string identifying an extension
1429 `directory' Matches a directory
1430 `remote' Matches a remote file, accessible through tramp or efs.
1431 Remote files most likely should be visited through Emacs
1432 because external applications cannot handle such paths.
1433 t Default for all remaining files
1434
1435 Possible values for the command are:
1436 `emacs' The file will be visited by the current Emacs process.
1437 `default' Use the default application for this file type.
1438 string A command to be executed by a shell; %s will be replaced
1439 by the path to the file.
1440 sexp A Lisp form which will be evaluated. The file path will
1441 be available in the Lisp variable `file'.
1442 For more examples, see the system specific constants
1443 `org-file-apps-defaults-macosx'
1444 `org-file-apps-defaults-windowsnt'
1445 `org-file-apps-defaults-gnu'."
1446 :group 'org-link-follow
1447 :type '(repeat
1448 (cons (choice :value ""
1449 (string :tag "Extension")
1450 (const :tag "Default for unrecognized files" t)
1451 (const :tag "Remote file" remote)
1452 (const :tag "Links to a directory" directory))
1453 (choice :value ""
1454 (const :tag "Visit with Emacs" emacs)
1455 (const :tag "Use system default" default)
1456 (string :tag "Command")
1457 (sexp :tag "Lisp form")))))
1458
1459 (defcustom org-mhe-search-all-folders nil
1460 "Non-nil means, that the search for the mh-message will be extended to
1461 all folders if the message cannot be found in the folder given in the link.
1462 Searching all folders is very efficient with one of the search engines
1463 supported by MH-E, but will be slow with pick."
1464 :group 'org-link-follow
1465 :type 'boolean)
1466
1467 (defgroup org-remember nil
1468 "Options concerning interaction with remember.el."
1469 :tag "Org Remember"
1470 :group 'org)
1471
1472 (defcustom org-directory "~/org"
1473 "Directory with org files.
1474 This directory will be used as default to prompt for org files.
1475 Used by the hooks for remember.el."
1476 :group 'org-remember
1477 :type 'directory)
1478
1479 (defcustom org-default-notes-file "~/.notes"
1480 "Default target for storing notes.
1481 Used by the hooks for remember.el. This can be a string, or nil to mean
1482 the value of `remember-data-file'.
1483 You can set this on a per-template basis with the variable
1484 `org-remember-templates'."
1485 :group 'org-remember
1486 :type '(choice
1487 (const :tag "Default from remember-data-file" nil)
1488 file))
1489
1490 (defcustom org-remember-store-without-prompt t
1491 "Non-nil means, `C-c C-c' stores remember note without further promts.
1492 In this case, you need `C-u C-c C-c' to get the prompts for
1493 note file and headline.
1494 When this variable is nil, `C-c C-c' give you the prompts, and
1495 `C-u C-c C-c' trigger the fasttrack."
1496 :group 'org-remember
1497 :type 'boolean)
1498
1499 (defcustom org-remember-interactive-interface 'refile
1500 "The interface to be used for interactive filing of remember notes.
1501 This is only used when the interactive mode for selecting a filing
1502 location is used (see the variable `org-remember-store-without-prompt').
1503 Allowed vaues are:
1504 outline The interface shows an outline of the relevant file
1505 and the correct heading is found by moving through
1506 the outline or by searching with incremental search.
1507 outline-path-completion Headlines in the current buffer are offered via
1508 completion.
1509 refile Use the refile interface, and offer headlines,
1510 possibly from different buffers."
1511 :group 'org-remember
1512 :type '(choice
1513 (const :tag "Refile" refile)
1514 (const :tag "Outline" outline)
1515 (const :tag "Outline-path-completion" outline-path-completion)))
1516
1517 (defcustom org-goto-interface 'outline
1518 "The default interface to be used for `org-goto'.
1519 Allowed vaues are:
1520 outline The interface shows an outline of the relevant file
1521 and the correct heading is found by moving through
1522 the outline or by searching with incremental search.
1523 outline-path-completion Headlines in the current buffer are offered via
1524 completion."
1525 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1526 :type '(choice
1527 (const :tag "Outline" outline)
1528 (const :tag "Outline-path-completion" outline-path-completion)))
1529
1530 (defcustom org-remember-default-headline ""
1531 "The headline that should be the default location in the notes file.
1532 When filing remember notes, the cursor will start at that position.
1533 You can set this on a per-template basis with the variable
1534 `org-remember-templates'."
1535 :group 'org-remember
1536 :type 'string)
1537
1538 (defcustom org-remember-templates nil
1539 "Templates for the creation of remember buffers.
1540 When nil, just let remember make the buffer.
1541 When not nil, this is a list of 5-element lists. In each entry, the first
1542 element is the name of the template, which should be a single short word.
1543 The second element is a character, a unique key to select this template.
1544 The third element is the template. The fourth element is optional and can
1545 specify a destination file for remember items created with this template.
1546 The default file is given by `org-default-notes-file'. An optional fifth
1547 element can specify the headline in that file that should be offered
1548 first when the user is asked to file the entry. The default headline is
1549 given in the variable `org-remember-default-headline'.
1550
1551 An optional sixth element specifies the contexts in which the user can
1552 select the template. This element can be either a list of major modes
1553 or a function. `org-remember' will first check whether the function
1554 returns `t' or if we are in any of the listed major modes, and select
1555 the template accordingly.
1556
1557 The template specifies the structure of the remember buffer. It should have
1558 a first line starting with a star, to act as the org-mode headline.
1559 Furthermore, the following %-escapes will be replaced with content:
1560
1561 %^{prompt} Prompt the user for a string and replace this sequence with it.
1562 A default value and a completion table ca be specified like this:
1563 %^{prompt|default|completion2|completion3|...}
1564 %t time stamp, date only
1565 %T time stamp with date and time
1566 %u, %U like the above, but inactive time stamps
1567 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1568 You may define a prompt like %^{Please specify birthday}t
1569 %n user name (taken from `user-full-name')
1570 %a annotation, normally the link created with org-store-link
1571 %i initial content, the region active. If %i is indented,
1572 the entire inserted text will be indented as well.
1573 %c content of the clipboard, or current kill ring head
1574 %^g prompt for tags, with completion on tags in target file
1575 %^G prompt for tags, with completion all tags in all agenda files
1576 %:keyword specific information for certain link types, see below
1577 %[pathname] insert the contents of the file given by `pathname'
1578 %(sexp) evaluate elisp `(sexp)' and replace with the result
1579 %! Store this note immediately after filling the template
1580
1581 %? After completing the template, position cursor here.
1582
1583 Apart from these general escapes, you can access information specific to the
1584 link type that is created. For example, calling `remember' in emails or gnus
1585 will record the author and the subject of the message, which you can access
1586 with %:author and %:subject, respectively. Here is a complete list of what
1587 is recorded for each link type.
1588
1589 Link type | Available information
1590 -------------------+------------------------------------------------------
1591 bbdb | %:type %:name %:company
1592 vm, wl, mh, rmail | %:type %:subject %:message-id
1593 | %:from %:fromname %:fromaddress
1594 | %:to %:toname %:toaddress
1595 | %:fromto (either \"to NAME\" or \"from NAME\")
1596 gnus | %:group, for messages also all email fields
1597 w3, w3m | %:type %:url
1598 info | %:type %:file %:node
1599 calendar | %:type %:date"
1600 :group 'org-remember
1601 :get (lambda (var) ; Make sure all entries have at least 5 elements
1602 (mapcar (lambda (x)
1603 (if (not (stringp (car x))) (setq x (cons "" x)))
1604 (cond ((= (length x) 4) (append x '("")))
1605 ((= (length x) 3) (append x '("" "")))
1606 (t x)))
1607 (default-value var)))
1608 :type '(repeat
1609 :tag "enabled"
1610 (list :value ("" ?a "\n" nil nil nil)
1611 (string :tag "Name")
1612 (character :tag "Selection Key")
1613 (string :tag "Template")
1614 (choice
1615 (file :tag "Destination file")
1616 (const :tag "Prompt for file" nil))
1617 (choice
1618 (string :tag "Destination headline")
1619 (const :tag "Selection interface for heading"))
1620 (choice
1621 (const :tag "Use by default" nil)
1622 (const :tag "Use in all contexts" t)
1623 (repeat :tag "Use only if in major mode"
1624 (symbol :tag "Major mode"))
1625 (function :tag "Perform a check against function")))))
1626
1627 (defcustom org-reverse-note-order nil
1628 "Non-nil means, store new notes at the beginning of a file or entry.
1629 When nil, new notes will be filed to the end of a file or entry.
1630 This can also be a list with cons cells of regular expressions that
1631 are matched against file names, and values."
1632 :group 'org-remember
1633 :type '(choice
1634 (const :tag "Reverse always" t)
1635 (const :tag "Reverse never" nil)
1636 (repeat :tag "By file name regexp"
1637 (cons regexp boolean))))
1638
1639 (defcustom org-refile-targets nil
1640 "Targets for refiling entries with \\[org-refile].
1641 This is list of cons cells. Each cell contains:
1642 - a specification of the files to be considered, either a list of files,
1643 or a symbol whose function or value fields will be used to retrieve
1644 a file name or a list of file names. Nil means, refile to a different
1645 heading in the current buffer.
1646 - A specification of how to find candidate refile targets. This may be
1647 any of
1648 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1649 This tag has to be present in all target headlines, inheritance will
1650 not be considered.
1651 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1652 todo keyword.
1653 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1654 headlines that are refiling targets.
1655 - a cons cell (:level . N). Any headline of level N is considered a target.
1656 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1657 ;; FIXME: what if there are a var and func with same name???
1658 :group 'org-remember
1659 :type '(repeat
1660 (cons
1661 (choice :value org-agenda-files
1662 (const :tag "All agenda files" org-agenda-files)
1663 (const :tag "Current buffer" nil)
1664 (function) (variable) (file))
1665 (choice :tag "Identify target headline by"
1666 (cons :tag "Specific tag" (const :tag) (string))
1667 (cons :tag "TODO keyword" (const :todo) (string))
1668 (cons :tag "Regular expression" (const :regexp) (regexp))
1669 (cons :tag "Level number" (const :level) (integer))
1670 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1671
1672 (defcustom org-refile-use-outline-path nil
1673 "Non-nil means, provide refile targets as paths.
1674 So a level 3 headline will be available as level1/level2/level3.
1675 When the value is `file', also include the file name (without directory)
1676 into the path. When `full-file-path', include the full file path."
1677 :group 'org-remember
1678 :type '(choice
1679 (const :tag "Not" nil)
1680 (const :tag "Yes" t)
1681 (const :tag "Start with file name" file)
1682 (const :tag "Start with full file path" full-file-path)))
1683
1684 (defgroup org-todo nil
1685 "Options concerning TODO items in Org-mode."
1686 :tag "Org TODO"
1687 :group 'org)
1688
1689 (defgroup org-progress nil
1690 "Options concerning Progress logging in Org-mode."
1691 :tag "Org Progress"
1692 :group 'org-time)
1693
1694 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1695 "List of TODO entry keyword sequences and their interpretation.
1696 \\<org-mode-map>This is a list of sequences.
1697
1698 Each sequence starts with a symbol, either `sequence' or `type',
1699 indicating if the keywords should be interpreted as a sequence of
1700 action steps, or as different types of TODO items. The first
1701 keywords are states requiring action - these states will select a headline
1702 for inclusion into the global TODO list Org-mode produces. If one of
1703 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1704 signify that no further action is necessary. If \"|\" is not found,
1705 the last keyword is treated as the only DONE state of the sequence.
1706
1707 The command \\[org-todo] cycles an entry through these states, and one
1708 additional state where no keyword is present. For details about this
1709 cycling, see the manual.
1710
1711 TODO keywords and interpretation can also be set on a per-file basis with
1712 the special #+SEQ_TODO and #+TYP_TODO lines.
1713
1714 Each keyword can optionally specify a character for fast state selection
1715 \(in combination with the variable `org-use-fast-todo-selection')
1716 and specifiers for state change logging, using the same syntax
1717 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1718 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1719 indicates to record a time stamp each time this state is selected.
1720
1721 Each keyword may also specify if a timestamp or a note should be
1722 recorded when entering or leaving the state, by adding additional
1723 characters in the parenthesis after the keyword. This looks like this:
1724 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1725 record only the time of the state change. With X and Y being either
1726 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1727 Y when leaving the state if and only if the *target* state does not
1728 define X. You may omit any of the fast-selection key or X or /Y,
1729 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1730
1731 For backward compatibility, this variable may also be just a list
1732 of keywords - in this case the interptetation (sequence or type) will be
1733 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1734 :group 'org-todo
1735 :group 'org-keywords
1736 :type '(choice
1737 (repeat :tag "Old syntax, just keywords"
1738 (string :tag "Keyword"))
1739 (repeat :tag "New syntax"
1740 (cons
1741 (choice
1742 :tag "Interpretation"
1743 (const :tag "Sequence (cycling hits every state)" sequence)
1744 (const :tag "Type (cycling directly to DONE)" type))
1745 (repeat
1746 (string :tag "Keyword"))))))
1747
1748 (defvar org-todo-keywords-1 nil
1749 "All TODO and DONE keywords active in a buffer.")
1750 (make-variable-buffer-local 'org-todo-keywords-1)
1751 (defvar org-todo-keywords-for-agenda nil)
1752 (defvar org-done-keywords-for-agenda nil)
1753 (defvar org-not-done-keywords nil)
1754 (make-variable-buffer-local 'org-not-done-keywords)
1755 (defvar org-done-keywords nil)
1756 (make-variable-buffer-local 'org-done-keywords)
1757 (defvar org-todo-heads nil)
1758 (make-variable-buffer-local 'org-todo-heads)
1759 (defvar org-todo-sets nil)
1760 (make-variable-buffer-local 'org-todo-sets)
1761 (defvar org-todo-log-states nil)
1762 (make-variable-buffer-local 'org-todo-log-states)
1763 (defvar org-todo-kwd-alist nil)
1764 (make-variable-buffer-local 'org-todo-kwd-alist)
1765 (defvar org-todo-key-alist nil)
1766 (make-variable-buffer-local 'org-todo-key-alist)
1767 (defvar org-todo-key-trigger nil)
1768 (make-variable-buffer-local 'org-todo-key-trigger)
1769
1770 (defcustom org-todo-interpretation 'sequence
1771 "Controls how TODO keywords are interpreted.
1772 This variable is in principle obsolete and is only used for
1773 backward compatibility, if the interpretation of todo keywords is
1774 not given already in `org-todo-keywords'. See that variable for
1775 more information."
1776 :group 'org-todo
1777 :group 'org-keywords
1778 :type '(choice (const sequence)
1779 (const type)))
1780
1781 (defcustom org-use-fast-todo-selection 'prefix
1782 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1783 This variable describes if and under what circumstances the cycling
1784 mechanism for TODO keywords will be replaced by a single-key, direct
1785 selection scheme.
1786
1787 When nil, fast selection is never used.
1788
1789 When the symbol `prefix', it will be used when `org-todo' is called with
1790 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1791 in an agenda buffer.
1792
1793 When t, fast selection is used by default. In this case, the prefix
1794 argument forces cycling instead.
1795
1796 In all cases, the special interface is only used if access keys have actually
1797 been assigned by the user, i.e. if keywords in the configuration are followed
1798 by a letter in parenthesis, like TODO(t)."
1799 :group 'org-todo
1800 :type '(choice
1801 (const :tag "Never" nil)
1802 (const :tag "By default" t)
1803 (const :tag "Only with C-u C-c C-t" prefix)))
1804
1805 (defcustom org-after-todo-state-change-hook nil
1806 "Hook which is run after the state of a TODO item was changed.
1807 The new state (a string with a TODO keyword, or nil) is available in the
1808 Lisp variable `state'."
1809 :group 'org-todo
1810 :type 'hook)
1811
1812 (defcustom org-log-done nil
1813 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1814 When equal to the list (done), also prompt for a closing note.
1815 This can also be configured on a per-file basis by adding one of
1816 the following lines anywhere in the buffer:
1817
1818 #+STARTUP: logdone
1819 #+STARTUP: lognotedone
1820 #+STARTUP: nologdone"
1821 :group 'org-todo
1822 :group 'org-progress
1823 :type '(choice
1824 (const :tag "No logging" nil)
1825 (const :tag "Record CLOSED timestamp" time)
1826 (const :tag "Record CLOSED timestamp with closing note." note)))
1827
1828 ;; Normalize old uses of org-log-done.
1829 (cond
1830 ((eq org-log-done t) (setq org-log-done 'time))
1831 ((and (listp org-log-done) (memq 'done org-log-done))
1832 (setq org-log-done 'note)))
1833
1834 ;; FIXME: document
1835 (defcustom org-log-note-clock-out nil
1836 "Non-nil means, recored a note when clocking out of an item.
1837 This can also be configured on a per-file basis by adding one of
1838 the following lines anywhere in the buffer:
1839
1840 #+STARTUP: lognoteclock-out
1841 #+STARTUP: nolognoteclock-out"
1842 :group 'org-todo
1843 :group 'org-progress
1844 :type 'boolean)
1845
1846 (defcustom org-log-done-with-time t
1847 "Non-nil means, the CLOSED time stamp will contain date and time.
1848 When nil, only the date will be recorded."
1849 :group 'org-progress
1850 :type 'boolean)
1851
1852 (defcustom org-log-note-headings
1853 '((done . "CLOSING NOTE %t")
1854 (state . "State %-12s %t")
1855 (clock-out . ""))
1856 "Headings for notes added when clocking out or closing TODO items.
1857 The value is an alist, with the car being a symbol indicating the note
1858 context, and the cdr is the heading to be used. The heading may also be the
1859 empty string.
1860 %t in the heading will be replaced by a time stamp.
1861 %s will be replaced by the new TODO state, in double quotes.
1862 %u will be replaced by the user name.
1863 %U will be replaced by the full user name."
1864 :group 'org-todo
1865 :group 'org-progress
1866 :type '(list :greedy t
1867 (cons (const :tag "Heading when closing an item" done) string)
1868 (cons (const :tag
1869 "Heading when changing todo state (todo sequence only)"
1870 state) string)
1871 (cons (const :tag "Heading when clocking out" clock-out) string)))
1872
1873 (defcustom org-log-states-order-reversed t
1874 "Non-nil means, the latest state change note will be directly after heading.
1875 When nil, the notes will be orderer according to time."
1876 :group 'org-todo
1877 :group 'org-progress
1878 :type 'boolean)
1879
1880 (defcustom org-log-repeat 'time
1881 "Non-nil means, record moving through the DONE state when triggering repeat.
1882 An auto-repeating tasks is immediately switched back to TODO when marked
1883 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1884 the TODO keyword definition, or recording a cloing note by setting
1885 `org-log-done', there will be no record of the task moving trhough DONE.
1886 This variable forces taking a note anyway. Possible values are:
1887
1888 nil Don't force a record
1889 time Record a time stamp
1890 note Record a note
1891
1892 This option can also be set with on a per-file-basis with
1893
1894 #+STARTUP: logrepeat
1895 #+STARTUP: lognoterepeat
1896 #+STARTUP: nologrepeat
1897
1898 You can have local logging settings for a subtree by setting the LOGGING
1899 property to one or more of these keywords."
1900 :group 'org-todo
1901 :group 'org-progress
1902 :type '(choice
1903 (const :tag "Don't force a record" nil)
1904 (const :tag "Force recording the DONE state" time)
1905 (const :tag "Force recording a note with the DONE state" note)))
1906
1907 (defcustom org-clock-into-drawer 2
1908 "Should clocking info be wrapped into a drawer?
1909 When t, clocking info will always be inserted into a :CLOCK: drawer.
1910 If necessary, the drawer will be created.
1911 When nil, the drawer will not be created, but used when present.
1912 When an integer and the number of clocking entries in an item
1913 reaches or exceeds this number, a drawer will be created."
1914 :group 'org-todo
1915 :group 'org-progress
1916 :type '(choice
1917 (const :tag "Always" t)
1918 (const :tag "Only when drawer exists" nil)
1919 (integer :tag "When at least N clock entries")))
1920
1921 (defcustom org-clock-out-when-done t
1922 "When t, the clock will be stopped when the relevant entry is marked DONE.
1923 Nil means, clock will keep running until stopped explicitly with
1924 `C-c C-x C-o', or until the clock is started in a different item."
1925 :group 'org-progress
1926 :type 'boolean)
1927
1928 (defcustom org-clock-in-switch-to-state nil
1929 "Set task to a special todo state while clocking it.
1930 The value should be the state to which the entry should be switched."
1931 :group 'org-progress
1932 :group 'org-todo
1933 :type '(choice
1934 (const :tag "Don't force a state" nil)
1935 (string :tag "State")))
1936
1937 (defgroup org-priorities nil
1938 "Priorities in Org-mode."
1939 :tag "Org Priorities"
1940 :group 'org-todo)
1941
1942 (defcustom org-highest-priority ?A
1943 "The highest priority of TODO items. A character like ?A, ?B etc.
1944 Must have a smaller ASCII number than `org-lowest-priority'."
1945 :group 'org-priorities
1946 :type 'character)
1947
1948 (defcustom org-lowest-priority ?C
1949 "The lowest priority of TODO items. A character like ?A, ?B etc.
1950 Must have a larger ASCII number than `org-highest-priority'."
1951 :group 'org-priorities
1952 :type 'character)
1953
1954 (defcustom org-default-priority ?B
1955 "The default priority of TODO items.
1956 This is the priority an item get if no explicit priority is given."
1957 :group 'org-priorities
1958 :type 'character)
1959
1960 (defcustom org-priority-start-cycle-with-default t
1961 "Non-nil means, start with default priority when starting to cycle.
1962 When this is nil, the first step in the cycle will be (depending on the
1963 command used) one higher or lower that the default priority."
1964 :group 'org-priorities
1965 :type 'boolean)
1966
1967 (defgroup org-time nil
1968 "Options concerning time stamps and deadlines in Org-mode."
1969 :tag "Org Time"
1970 :group 'org)
1971
1972 (defcustom org-insert-labeled-timestamps-at-point nil
1973 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1974 When nil, these labeled time stamps are forces into the second line of an
1975 entry, just after the headline. When scheduling from the global TODO list,
1976 the time stamp will always be forced into the second line."
1977 :group 'org-time
1978 :type 'boolean)
1979
1980 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1981 "Formats for `format-time-string' which are used for time stamps.
1982 It is not recommended to change this constant.")
1983
1984 (defcustom org-time-stamp-rounding-minutes '(0 5)
1985 "Number of minutes to round time stamps to.
1986 These are two values, the first applies when first creating a time stamp.
1987 The second applies when changing it with the commands `S-up' and `S-down'.
1988 When changing the time stamp, this means that it will change in steps
1989 of N minutes, as given by the second value.
1990
1991 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1992 numbers should be factors of 60, so for example 5, 10, 15.
1993
1994 When this is larger than 1, you can still force an exact time-stamp by using
1995 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1996 and by using a prefix arg to `S-up/down' to specify the exact number
1997 of minutes to shift."
1998 :group 'org-time
1999 :get '(lambda (var) ; Make sure all entries have 5 elements
2000 (if (integerp (default-value var))
2001 (list (default-value var) 5)
2002 (default-value var)))
2003 :type '(list
2004 (integer :tag "when inserting times")
2005 (integer :tag "when modifying times")))
2006
2007 ;; Make sure old customizations of this variable don't lead to problems.
2008 (when (integerp org-time-stamp-rounding-minutes)
2009 (setq org-time-stamp-rounding-minutes
2010 (list org-time-stamp-rounding-minutes
2011 org-time-stamp-rounding-minutes)))
2012
2013 (defcustom org-display-custom-times nil
2014 "Non-nil means, overlay custom formats over all time stamps.
2015 The formats are defined through the variable `org-time-stamp-custom-formats'.
2016 To turn this on on a per-file basis, insert anywhere in the file:
2017 #+STARTUP: customtime"
2018 :group 'org-time
2019 :set 'set-default
2020 :type 'sexp)
2021 (make-variable-buffer-local 'org-display-custom-times)
2022
2023 (defcustom org-time-stamp-custom-formats
2024 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2025 "Custom formats for time stamps. See `format-time-string' for the syntax.
2026 These are overlayed over the default ISO format if the variable
2027 `org-display-custom-times' is set. Time like %H:%M should be at the
2028 end of the second format."
2029 :group 'org-time
2030 :type 'sexp)
2031
2032 (defun org-time-stamp-format (&optional long inactive)
2033 "Get the right format for a time string."
2034 (let ((f (if long (cdr org-time-stamp-formats)
2035 (car org-time-stamp-formats))))
2036 (if inactive
2037 (concat "[" (substring f 1 -1) "]")
2038 f)))
2039
2040 (defcustom org-read-date-prefer-future t
2041 "Non-nil means, assume future for incomplete date input from user.
2042 This affects the following situations:
2043 1. The user gives a day, but no month.
2044 For example, if today is the 15th, and you enter \"3\", Org-mode will
2045 read this as the third of *next* month. However, if you enter \"17\",
2046 it will be considered as *this* month.
2047 2. The user gives a month but not a year.
2048 For example, if it is april and you enter \"feb 2\", this will be read
2049 as feb 2, *next* year. \"May 5\", however, will be this year.
2050
2051 When this option is nil, the current month and year will always be used
2052 as defaults."
2053 :group 'org-time
2054 :type 'boolean)
2055
2056 (defcustom org-read-date-display-live t
2057 "Non-nil means, display current interpretation of date prompt live.
2058 This display will be in an overlay, in the minibuffer."
2059 :group 'org-time
2060 :type 'boolean)
2061
2062 (defcustom org-read-date-popup-calendar t
2063 "Non-nil means, pop up a calendar when prompting for a date.
2064 In the calendar, the date can be selected with mouse-1. However, the
2065 minibuffer will also be active, and you can simply enter the date as well.
2066 When nil, only the minibuffer will be available."
2067 :group 'org-time
2068 :type 'boolean)
2069 (if (fboundp 'defvaralias)
2070 (defvaralias 'org-popup-calendar-for-date-prompt
2071 'org-read-date-popup-calendar))
2072
2073 (defcustom org-extend-today-until 0
2074 "The hour when your day really ends.
2075 This has influence for the following applications:
2076 - When switching the agenda to \"today\". It it is still earlier than
2077 the time given here, the day recognized as TODAY is actually yesterday.
2078 - When a date is read from the user and it is still before the time given
2079 here, the current date and time will be assumed to be yesterday, 23:59.
2080
2081 FIXME:
2082 IMPORTANT: This is still a very experimental feature, it may disappear
2083 again or it may be extended to mean more things."
2084 :group 'org-time
2085 :type 'number)
2086
2087 (defcustom org-edit-timestamp-down-means-later nil
2088 "Non-nil means, S-down will increase the time in a time stamp.
2089 When nil, S-up will increase."
2090 :group 'org-time
2091 :type 'boolean)
2092
2093 (defcustom org-calendar-follow-timestamp-change t
2094 "Non-nil means, make the calendar window follow timestamp changes.
2095 When a timestamp is modified and the calendar window is visible, it will be
2096 moved to the new date."
2097 :group 'org-time
2098 :type 'boolean)
2099
2100 (defcustom org-clock-heading-function nil
2101 "When non-nil, should be a function to create `org-clock-heading'.
2102 This is the string shown in the mode line when a clock is running.
2103 The function is called with point at the beginning of the headline."
2104 :group 'org-time ; FIXME: Should we have a separate group????
2105 :type 'function)
2106
2107 (defgroup org-tags nil
2108 "Options concerning tags in Org-mode."
2109 :tag "Org Tags"
2110 :group 'org)
2111
2112 (defcustom org-tag-alist nil
2113 "List of tags allowed in Org-mode files.
2114 When this list is nil, Org-mode will base TAG input on what is already in the
2115 buffer.
2116 The value of this variable is an alist, the car of each entry must be a
2117 keyword as a string, the cdr may be a character that is used to select
2118 that tag through the fast-tag-selection interface.
2119 See the manual for details."
2120 :group 'org-tags
2121 :type '(repeat
2122 (choice
2123 (cons (string :tag "Tag name")
2124 (character :tag "Access char"))
2125 (const :tag "Start radio group" (:startgroup))
2126 (const :tag "End radio group" (:endgroup)))))
2127
2128 (defcustom org-use-fast-tag-selection 'auto
2129 "Non-nil means, use fast tag selection scheme.
2130 This is a special interface to select and deselect tags with single keys.
2131 When nil, fast selection is never used.
2132 When the symbol `auto', fast selection is used if and only if selection
2133 characters for tags have been configured, either through the variable
2134 `org-tag-alist' or through a #+TAGS line in the buffer.
2135 When t, fast selection is always used and selection keys are assigned
2136 automatically if necessary."
2137 :group 'org-tags
2138 :type '(choice
2139 (const :tag "Always" t)
2140 (const :tag "Never" nil)
2141 (const :tag "When selection characters are configured" 'auto)))
2142
2143 (defcustom org-fast-tag-selection-single-key nil
2144 "Non-nil means, fast tag selection exits after first change.
2145 When nil, you have to press RET to exit it.
2146 During fast tag selection, you can toggle this flag with `C-c'.
2147 This variable can also have the value `expert'. In this case, the window
2148 displaying the tags menu is not even shown, until you press C-c again."
2149 :group 'org-tags
2150 :type '(choice
2151 (const :tag "No" nil)
2152 (const :tag "Yes" t)
2153 (const :tag "Expert" expert)))
2154
2155 (defvar org-fast-tag-selection-include-todo nil
2156 "Non-nil means, fast tags selection interface will also offer TODO states.
2157 This is an undocumented feature, you should not rely on it.")
2158
2159 (defcustom org-tags-column -80
2160 "The column to which tags should be indented in a headline.
2161 If this number is positive, it specifies the column. If it is negative,
2162 it means that the tags should be flushright to that column. For example,
2163 -80 works well for a normal 80 character screen."
2164 :group 'org-tags
2165 :type 'integer)
2166
2167 (defcustom org-auto-align-tags t
2168 "Non-nil means, realign tags after pro/demotion of TODO state change.
2169 These operations change the length of a headline and therefore shift
2170 the tags around. With this options turned on, after each such operation
2171 the tags are again aligned to `org-tags-column'."
2172 :group 'org-tags
2173 :type 'boolean)
2174
2175 (defcustom org-use-tag-inheritance t
2176 "Non-nil means, tags in levels apply also for sublevels.
2177 When nil, only the tags directly given in a specific line apply there.
2178 If you turn off this option, you very likely want to turn on the
2179 companion option `org-tags-match-list-sublevels'."
2180 :group 'org-tags
2181 :type 'boolean)
2182
2183 (defcustom org-tags-match-list-sublevels nil
2184 "Non-nil means list also sublevels of headlines matching tag search.
2185 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2186 the sublevels of a headline matching a tag search often also match
2187 the same search. Listing all of them can create very long lists.
2188 Setting this variable to nil causes subtrees of a match to be skipped.
2189 This option is off by default, because inheritance in on. If you turn
2190 inheritance off, you very likely want to turn this option on.
2191
2192 As a special case, if the tag search is restricted to TODO items, the
2193 value of this variable is ignored and sublevels are always checked, to
2194 make sure all corresponding TODO items find their way into the list."
2195 :group 'org-tags
2196 :type 'boolean)
2197
2198 (defvar org-tags-history nil
2199 "History of minibuffer reads for tags.")
2200 (defvar org-last-tags-completion-table nil
2201 "The last used completion table for tags.")
2202 (defvar org-after-tags-change-hook nil
2203 "Hook that is run after the tags in a line have changed.")
2204
2205 (defgroup org-properties nil
2206 "Options concerning properties in Org-mode."
2207 :tag "Org Properties"
2208 :group 'org)
2209
2210 (defcustom org-property-format "%-10s %s"
2211 "How property key/value pairs should be formatted by `indent-line'.
2212 When `indent-line' hits a property definition, it will format the line
2213 according to this format, mainly to make sure that the values are
2214 lined-up with respect to each other."
2215 :group 'org-properties
2216 :type 'string)
2217
2218 (defcustom org-use-property-inheritance nil
2219 "Non-nil means, properties apply also for sublevels.
2220 This setting is only relevant during property searches, not when querying
2221 an entry with `org-entry-get'. To retrieve a property with inheritance,
2222 you need to call `org-entry-get' with the inheritance flag.
2223 Turning this on can cause significant overhead when doing a search, so
2224 this is turned off by default.
2225 When nil, only the properties directly given in the current entry count.
2226 The value may also be a list of properties that shouldhave inheritance.
2227
2228 However, note that some special properties use inheritance under special
2229 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2230 and the properties ending in \"_ALL\" when they are used as descriptor
2231 for valid values of a property."
2232 :group 'org-properties
2233 :type '(choice
2234 (const :tag "Not" nil)
2235 (const :tag "Always" nil)
2236 (repeat :tag "Specific properties" (string :tag "Property"))))
2237
2238 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2239 "The default column format, if no other format has been defined.
2240 This variable can be set on the per-file basis by inserting a line
2241
2242 #+COLUMNS: %25ITEM ....."
2243 :group 'org-properties
2244 :type 'string)
2245
2246 (defcustom org-global-properties nil
2247 "List of property/value pairs that can be inherited by any entry.
2248 You can set buffer-local values for this by adding lines like
2249
2250 #+PROPERTY: NAME VALUE"
2251 :group 'org-properties
2252 :type '(repeat
2253 (cons (string :tag "Property")
2254 (string :tag "Value"))))
2255
2256 (defvar org-local-properties nil
2257 "List of property/value pairs that can be inherited by any entry.
2258 Valid for the current buffer.
2259 This variable is populated from #+PROPERTY lines.")
2260
2261 (defgroup org-agenda nil
2262 "Options concerning agenda views in Org-mode."
2263 :tag "Org Agenda"
2264 :group 'org)
2265
2266 (defvar org-category nil
2267 "Variable used by org files to set a category for agenda display.
2268 Such files should use a file variable to set it, for example
2269
2270 # -*- mode: org; org-category: \"ELisp\"
2271
2272 or contain a special line
2273
2274 #+CATEGORY: ELisp
2275
2276 If the file does not specify a category, then file's base name
2277 is used instead.")
2278 (make-variable-buffer-local 'org-category)
2279
2280 (defcustom org-agenda-files nil
2281 "The files to be used for agenda display.
2282 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2283 \\[org-remove-file]. You can also use customize to edit the list.
2284
2285 If an entry is a directory, all files in that directory that are matched by
2286 `org-agenda-file-regexp' will be part of the file list.
2287
2288 If the value of the variable is not a list but a single file name, then
2289 the list of agenda files is actually stored and maintained in that file, one
2290 agenda file per line."
2291 :group 'org-agenda
2292 :type '(choice
2293 (repeat :tag "List of files and directories" file)
2294 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2295
2296 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2297 "Regular expression to match files for `org-agenda-files'.
2298 If any element in the list in that variable contains a directory instead
2299 of a normal file, all files in that directory that are matched by this
2300 regular expression will be included."
2301 :group 'org-agenda
2302 :type 'regexp)
2303
2304 (defcustom org-agenda-skip-unavailable-files nil
2305 "t means to just skip non-reachable files in `org-agenda-files'.
2306 Nil means to remove them, after a query, from the list."
2307 :group 'org-agenda
2308 :type 'boolean)
2309
2310 (defcustom org-agenda-text-search-extra-files nil
2311 "List of extra files to be searched by text search commands.
2312 These files will be search in addition to the agenda files bu the
2313 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2314 Note that these files will only be searched for text search commands,
2315 not for the other agenda views like todo lists, tag earches or the weekly
2316 agenda. This variable is intended to list notes and possibly archive files
2317 that should also be searched by these two commands."
2318 :group 'org-agenda
2319 :type '(repeat file))
2320
2321 (if (fboundp 'defvaralias)
2322 (defvaralias 'org-agenda-multi-occur-extra-files
2323 'org-agenda-text-search-extra-files))
2324
2325 (defcustom org-agenda-confirm-kill 1
2326 "When set, remote killing from the agenda buffer needs confirmation.
2327 When t, a confirmation is always needed. When a number N, confirmation is
2328 only needed when the text to be killed contains more than N non-white lines."
2329 :group 'org-agenda
2330 :type '(choice
2331 (const :tag "Never" nil)
2332 (const :tag "Always" t)
2333 (number :tag "When more than N lines")))
2334
2335 (defcustom org-calendar-to-agenda-key [?c]
2336 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2337 The command `org-calendar-goto-agenda' will be bound to this key. The
2338 default is the character `c' because then `c' can be used to switch back and
2339 forth between agenda and calendar."
2340 :group 'org-agenda
2341 :type 'sexp)
2342
2343 (defcustom org-agenda-compact-blocks nil
2344 "Non-nil means, make the block agenda more compact.
2345 This is done by leaving out unnecessary lines."
2346 :group 'org-agenda
2347 :type nil)
2348
2349 (defgroup org-agenda-export nil
2350 "Options concerning exporting agenda views in Org-mode."
2351 :tag "Org Agenda Export"
2352 :group 'org-agenda)
2353
2354 (defcustom org-agenda-with-colors t
2355 "Non-nil means, use colors in agenda views."
2356 :group 'org-agenda-export
2357 :type 'boolean)
2358
2359 (defcustom org-agenda-exporter-settings nil
2360 "Alist of variable/value pairs that should be active during agenda export.
2361 This is a good place to set uptions for ps-print and for htmlize."
2362 :group 'org-agenda-export
2363 :type '(repeat
2364 (list
2365 (variable)
2366 (sexp :tag "Value"))))
2367
2368 (defcustom org-agenda-export-html-style ""
2369 "The style specification for exported HTML Agenda files.
2370 If this variable contains a string, it will replace the default <style>
2371 section as produced by `htmlize'.
2372 Since there are different ways of setting style information, this variable
2373 needs to contain the full HTML structure to provide a style, including the
2374 surrounding HTML tags. The style specifications should include definitions
2375 the fonts used by the agenda, here is an example:
2376
2377 <style type=\"text/css\">
2378 p { font-weight: normal; color: gray; }
2379 .org-agenda-structure {
2380 font-size: 110%;
2381 color: #003399;
2382 font-weight: 600;
2383 }
2384 .org-todo {
2385 color: #cc6666;
2386 font-weight: bold;
2387 }
2388 .org-done {
2389 color: #339933;
2390 }
2391 .title { text-align: center; }
2392 .todo, .deadline { color: red; }
2393 .done { color: green; }
2394 </style>
2395
2396 or, if you want to keep the style in a file,
2397
2398 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2399
2400 As the value of this option simply gets inserted into the HTML <head> header,
2401 you can \"misuse\" it to also add other text to the header. However,
2402 <style>...</style> is required, if not present the variable will be ignored."
2403 :group 'org-agenda-export
2404 :group 'org-export-html
2405 :type 'string)
2406
2407 (defgroup org-agenda-custom-commands nil
2408 "Options concerning agenda views in Org-mode."
2409 :tag "Org Agenda Custom Commands"
2410 :group 'org-agenda)
2411
2412 (defconst org-sorting-choice
2413 '(choice
2414 (const time-up) (const time-down)
2415 (const category-keep) (const category-up) (const category-down)
2416 (const tag-down) (const tag-up)
2417 (const priority-up) (const priority-down))
2418 "Sorting choices.")
2419
2420 (defconst org-agenda-custom-commands-local-options
2421 `(repeat :tag "Local settings for this command. Remember to quote values"
2422 (choice :tag "Setting"
2423 (list :tag "Any variable"
2424 (variable :tag "Variable")
2425 (sexp :tag "Value"))
2426 (list :tag "Files to be searched"
2427 (const org-agenda-files)
2428 (list
2429 (const :format "" quote)
2430 (repeat
2431 (file))))
2432 (list :tag "Sorting strategy"
2433 (const org-agenda-sorting-strategy)
2434 (list
2435 (const :format "" quote)
2436 (repeat
2437 ,org-sorting-choice)))
2438 (list :tag "Prefix format"
2439 (const org-agenda-prefix-format :value " %-12:c%?-12t% s")
2440 (string))
2441 (list :tag "Number of days in agenda"
2442 (const org-agenda-ndays)
2443 (integer :value 1))
2444 (list :tag "Fixed starting date"
2445 (const org-agenda-start-day)
2446 (string :value "2007-11-01"))
2447 (list :tag "Start on day of week"
2448 (const org-agenda-start-on-weekday)
2449 (choice :value 1
2450 (const :tag "Today" nil)
2451 (number :tag "Weekday No.")))
2452 (list :tag "Include data from diary"
2453 (const org-agenda-include-diary)
2454 (boolean))
2455 (list :tag "Deadline Warning days"
2456 (const org-deadline-warning-days)
2457 (integer :value 1))
2458 (list :tag "Standard skipping condition"
2459 :value (org-agenda-skip-function '(org-agenda-skip-entry-if))
2460 (const org-agenda-skip-function)
2461 (list
2462 (const :format "" quote)
2463 (list
2464 (choice
2465 :tag "Skiping range"
2466 (const :tag "Skip entry" org-agenda-skip-entry-if)
2467 (const :tag "Skip subtree" org-agenda-skip-subtree-if))
2468 (repeat :inline t :tag "Conditions for skipping"
2469 (choice
2470 :tag "Condition type"
2471 (list :tag "Regexp matches" :inline t (const :format "" 'regexp) (regexp))
2472 (list :tag "Regexp does not match" :inline t (const :format "" 'notregexp) (regexp))
2473 (const :tag "scheduled" 'scheduled)
2474 (const :tag "not scheduled" 'notscheduled)
2475 (const :tag "deadline" 'deadline)
2476 (const :tag "no deadline" 'notdeadline))))))
2477 (list :tag "Non-standard skipping condition"
2478 :value (org-agenda-skip-function)
2479 (list
2480 (const org-agenda-skip-function)
2481 (sexp :tag "Function or form (quoted!)")))))
2482 "Selection of examples for agenda command settings.
2483 This will be spliced into the custom type of
2484 `org-agenda-custom-commands'.")
2485
2486
2487 (defcustom org-agenda-custom-commands nil
2488 "Custom commands for the agenda.
2489 These commands will be offered on the splash screen displayed by the
2490 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2491
2492 (key desc type match settings files)
2493
2494 key The key (one or more characters as a string) to be associated
2495 with the command.
2496 desc A description of the command, when omitted or nil, a default
2497 description is built using MATCH.
2498 type The command type, any of the following symbols:
2499 agenda The daily/weekly agenda.
2500 todo Entries with a specific TODO keyword, in all agenda files.
2501 search Entries containing search words entry or headline.
2502 tags Tags/Property/TODO match in all agenda files.
2503 tags-todo Tags/P/T match in all agenda files, TODO entries only.
2504 todo-tree Sparse tree of specific TODO keyword in *current* file.
2505 tags-tree Sparse tree with all tags matches in *current* file.
2506 occur-tree Occur sparse tree for *current* file.
2507 ... A user-defined function.
2508 match What to search for:
2509 - a single keyword for TODO keyword searches
2510 - a tags match expression for tags searches
2511 - a word search expression for text searches.
2512 - a regular expression for occur searches
2513 For all other commands, this should be the empty string.
2514 settings A list of option settings, similar to that in a let form, so like
2515 this: ((opt1 val1) (opt2 val2) ...). The values will be
2516 evaluated at the moment of execution, so quote them when needed.
2517 files A list of files file to write the produced agenda buffer to
2518 with the command `org-store-agenda-views'.
2519 If a file name ends in \".html\", an HTML version of the buffer
2520 is written out. If it ends in \".ps\", a postscript version is
2521 produced. Otherwide, only the plain text is written to the file.
2522
2523 You can also define a set of commands, to create a composite agenda buffer.
2524 In this case, an entry looks like this:
2525
2526 (key desc (cmd1 cmd2 ...) general-settings-for-whole-set files)
2527
2528 where
2529
2530 desc A description string to be displayed in the dispatcher menu.
2531 cmd An agenda command, similar to the above. However, tree commands
2532 are no allowed, but instead you can get agenda and global todo list.
2533 So valid commands for a set are:
2534 (agenda \"\" settings)
2535 (alltodo \"\" settings)
2536 (stuck \"\" settings)
2537 (todo \"match\" settings files)
2538 (search \"match\" settings files)
2539 (tags \"match\" settings files)
2540 (tags-todo \"match\" settings files)
2541
2542 Each command can carry a list of options, and another set of options can be
2543 given for the whole set of commands. Individual command options take
2544 precedence over the general options.
2545
2546 When using several characters as key to a command, the first characters
2547 are prefix commands. For the dispatcher to display useful information, you
2548 should provide a description for the prefix, like
2549
2550 (setq org-agenda-custom-commands
2551 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2552 (\"hl\" tags \"+HOME+Lisa\")
2553 (\"hp\" tags \"+HOME+Peter\")
2554 (\"hk\" tags \"+HOME+Kim\")))"
2555 :group 'org-agenda-custom-commands
2556 :type `(repeat
2557 (choice :value ("x" "Describe command here" tags "" nil)
2558 (list :tag "Single command"
2559 (string :tag "Access Key(s) ")
2560 (option (string :tag "Description"))
2561 (choice
2562 (const :tag "Agenda" agenda)
2563 (const :tag "TODO list" alltodo)
2564 (const :tag "Search words" search)
2565 (const :tag "Stuck projects" stuck)
2566 (const :tag "Tags search (all agenda files)" tags)
2567 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2568 (const :tag "TODO keyword search (all agenda files)" todo)
2569 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2570 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2571 (const :tag "Occur tree (current buffer)" occur-tree)
2572 (sexp :tag "Other, user-defined function"))
2573 (string :tag "Match (only for some commands)")
2574 ,org-agenda-custom-commands-local-options
2575 (option (repeat :tag "Export" (file :tag "Export to"))))
2576 (list :tag "Command series, all agenda files"
2577 (string :tag "Access Key(s)")
2578 (string :tag "Description ")
2579 (repeat :tag "Component"
2580 (choice
2581 (list :tag "Agenda"
2582 (const :format "" agenda)
2583 (const :tag "" :format "" "")
2584 ,org-agenda-custom-commands-local-options)
2585 (list :tag "TODO list (all keywords)"
2586 (const :format "" alltodo)
2587 (const :tag "" :format "" "")
2588 ,org-agenda-custom-commands-local-options)
2589 (list :tag "Search words"
2590 (const :format "" search)
2591 (string :tag "Match")
2592 ,org-agenda-custom-commands-local-options)
2593 (list :tag "Stuck projects"
2594 (const :format "" stuck)
2595 (const :tag "" :format "" "")
2596 ,org-agenda-custom-commands-local-options)
2597 (list :tag "Tags search"
2598 (const :format "" tags)
2599 (string :tag "Match")
2600 ,org-agenda-custom-commands-local-options)
2601 (list :tag "Tags search, TODO entries only"
2602 (const :format "" tags-todo)
2603 (string :tag "Match")
2604 ,org-agenda-custom-commands-local-options)
2605 (list :tag "TODO keyword search"
2606 (const :format "" todo)
2607 (string :tag "Match")
2608 ,org-agenda-custom-commands-local-options)
2609 (list :tag "Other, user-defined function"
2610 (symbol :tag "function")
2611 (string :tag "Match")
2612 ,org-agenda-custom-commands-local-options)))
2613
2614 (repeat :tag "Settings for entire command set"
2615 (list (variable :tag "Any variable")
2616 (sexp :tag "Value")))
2617 (option (repeat :tag "Export" (file :tag "Export to"))))
2618 (cons :tag "Prefix key documentation"
2619 (string :tag "Access Key(s)")
2620 (string :tag "Description ")))))
2621
2622 (defcustom org-agenda-query-register ?o
2623 "The register holding the current query string.
2624 The prupose of this is that if you construct a query string interactively,
2625 you can then use it to define a custom command."
2626 :group 'org-agenda-custom-commands
2627 :type 'character)
2628
2629 (defcustom org-stuck-projects
2630 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2631 "How to identify stuck projects.
2632 This is a list of four items:
2633 1. A tags/todo matcher string that is used to identify a project.
2634 The entire tree below a headline matched by this is considered one project.
2635 2. A list of TODO keywords identifying non-stuck projects.
2636 If the project subtree contains any headline with one of these todo
2637 keywords, the project is considered to be not stuck. If you specify
2638 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2639 3. A list of tags identifying non-stuck projects.
2640 If the project subtree contains any headline with one of these tags,
2641 the project is considered to be not stuck. If you specify \"*\" as
2642 a tag, any tag will mark the project unstuck.
2643 4. An arbitrary regular expression matching non-stuck projects.
2644
2645 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2646 or `C-c a #' to produce the list."
2647 :group 'org-agenda-custom-commands
2648 :type '(list
2649 (string :tag "Tags/TODO match to identify a project")
2650 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2651 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2652 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2653
2654
2655 (defgroup org-agenda-skip nil
2656 "Options concerning skipping parts of agenda files."
2657 :tag "Org Agenda Skip"
2658 :group 'org-agenda)
2659
2660 (defcustom org-agenda-todo-list-sublevels t
2661 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2662 When nil, the sublevels of a TODO entry are not checked, resulting in
2663 potentially much shorter TODO lists."
2664 :group 'org-agenda-skip
2665 :group 'org-todo
2666 :type 'boolean)
2667
2668 (defcustom org-agenda-todo-ignore-with-date nil
2669 "Non-nil means, don't show entries with a date in the global todo list.
2670 You can use this if you prefer to mark mere appointments with a TODO keyword,
2671 but don't want them to show up in the TODO list.
2672 When this is set, it also covers deadlines and scheduled items, the settings
2673 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2674 will be ignored."
2675 :group 'org-agenda-skip
2676 :group 'org-todo
2677 :type 'boolean)
2678
2679 (defcustom org-agenda-todo-ignore-scheduled nil
2680 "Non-nil means, don't show scheduled entries in the global todo list.
2681 The idea behind this is that by scheduling it, you have already taken care
2682 of this item.
2683 See also `org-agenda-todo-ignore-with-date'."
2684 :group 'org-agenda-skip
2685 :group 'org-todo
2686 :type 'boolean)
2687
2688 (defcustom org-agenda-todo-ignore-deadlines nil
2689 "Non-nil means, don't show near deadline entries in the global todo list.
2690 Near means closer than `org-deadline-warning-days' days.
2691 The idea behind this is that such items will appear in the agenda anyway.
2692 See also `org-agenda-todo-ignore-with-date'."
2693 :group 'org-agenda-skip
2694 :group 'org-todo
2695 :type 'boolean)
2696
2697 (defcustom org-agenda-skip-scheduled-if-done nil
2698 "Non-nil means don't show scheduled items in agenda when they are done.
2699 This is relevant for the daily/weekly agenda, not for the TODO list. And
2700 it applies only to the actual date of the scheduling. Warnings about
2701 an item with a past scheduling dates are always turned off when the item
2702 is DONE."
2703 :group 'org-agenda-skip
2704 :type 'boolean)
2705
2706 (defcustom org-agenda-skip-deadline-if-done nil
2707 "Non-nil means don't show deadines when the corresponding item is done.
2708 When nil, the deadline is still shown and should give you a happy feeling.
2709 This is relevant for the daily/weekly agenda. And it applied only to the
2710 actualy date of the deadline. Warnings about approching and past-due
2711 deadlines are always turned off when the item is DONE."
2712 :group 'org-agenda-skip
2713 :type 'boolean)
2714
2715 (defcustom org-agenda-skip-timestamp-if-done nil
2716 "Non-nil means don't select item by timestamp or -range if it is DONE."
2717 :group 'org-agenda-skip
2718 :type 'boolean)
2719
2720 (defcustom org-timeline-show-empty-dates 3
2721 "Non-nil means, `org-timeline' also shows dates without an entry.
2722 When nil, only the days which actually have entries are shown.
2723 When t, all days between the first and the last date are shown.
2724 When an integer, show also empty dates, but if there is a gap of more than
2725 N days, just insert a special line indicating the size of the gap."
2726 :group 'org-agenda-skip
2727 :type '(choice
2728 (const :tag "None" nil)
2729 (const :tag "All" t)
2730 (number :tag "at most")))
2731
2732
2733 (defgroup org-agenda-startup nil
2734 "Options concerning initial settings in the Agenda in Org Mode."
2735 :tag "Org Agenda Startup"
2736 :group 'org-agenda)
2737
2738 (defcustom org-finalize-agenda-hook nil
2739 "Hook run just before displaying an agenda buffer."
2740 :group 'org-agenda-startup
2741 :type 'hook)
2742
2743 (defcustom org-agenda-mouse-1-follows-link nil
2744 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2745 A longer mouse click will still set point. Does not work on XEmacs.
2746 Needs to be set before org.el is loaded."
2747 :group 'org-agenda-startup
2748 :type 'boolean)
2749
2750 (defcustom org-agenda-start-with-follow-mode nil
2751 "The initial value of follow-mode in a newly created agenda window."
2752 :group 'org-agenda-startup
2753 :type 'boolean)
2754
2755 (defgroup org-agenda-windows nil
2756 "Options concerning the windows used by the Agenda in Org Mode."
2757 :tag "Org Agenda Windows"
2758 :group 'org-agenda)
2759
2760 (defcustom org-agenda-window-setup 'reorganize-frame
2761 "How the agenda buffer should be displayed.
2762 Possible values for this option are:
2763
2764 current-window Show agenda in the current window, keeping all other windows.
2765 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2766 other-window Use `switch-to-buffer-other-window' to display agenda.
2767 reorganize-frame Show only two windows on the current frame, the current
2768 window and the agenda.
2769 See also the variable `org-agenda-restore-windows-after-quit'."
2770 :group 'org-agenda-windows
2771 :type '(choice
2772 (const current-window)
2773 (const other-frame)
2774 (const other-window)
2775 (const reorganize-frame)))
2776
2777 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2778 "The min and max height of the agenda window as a fraction of frame height.
2779 The value of the variable is a cons cell with two numbers between 0 and 1.
2780 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2781 :group 'org-agenda-windows
2782 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2783
2784 (defcustom org-agenda-restore-windows-after-quit nil
2785 "Non-nil means, restore window configuration open exiting agenda.
2786 Before the window configuration is changed for displaying the agenda,
2787 the current status is recorded. When the agenda is exited with
2788 `q' or `x' and this option is set, the old state is restored. If
2789 `org-agenda-window-setup' is `other-frame', the value of this
2790 option will be ignored.."
2791 :group 'org-agenda-windows
2792 :type 'boolean)
2793
2794 (defcustom org-indirect-buffer-display 'other-window
2795 "How should indirect tree buffers be displayed?
2796 This applies to indirect buffers created with the commands
2797 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2798 Valid values are:
2799 current-window Display in the current window
2800 other-window Just display in another window.
2801 dedicated-frame Create one new frame, and re-use it each time.
2802 new-frame Make a new frame each time. Note that in this case
2803 previously-made indirect buffers are kept, and you need to
2804 kill these buffers yourself."
2805 :group 'org-structure
2806 :group 'org-agenda-windows
2807 :type '(choice
2808 (const :tag "In current window" current-window)
2809 (const :tag "In current frame, other window" other-window)
2810 (const :tag "Each time a new frame" new-frame)
2811 (const :tag "One dedicated frame" dedicated-frame)))
2812
2813 (defgroup org-agenda-daily/weekly nil
2814 "Options concerning the daily/weekly agenda."
2815 :tag "Org Agenda Daily/Weekly"
2816 :group 'org-agenda)
2817
2818 (defcustom org-agenda-ndays 7
2819 "Number of days to include in overview display.
2820 Should be 1 or 7."
2821 :group 'org-agenda-daily/weekly
2822 :type 'number)
2823
2824 (defcustom org-agenda-start-on-weekday 1
2825 "Non-nil means, start the overview always on the specified weekday.
2826 0 denotes Sunday, 1 denotes Monday etc.
2827 When nil, always start on the current day."
2828 :group 'org-agenda-daily/weekly
2829 :type '(choice (const :tag "Today" nil)
2830 (number :tag "Weekday No.")))
2831
2832 (defcustom org-agenda-show-all-dates t
2833 "Non-nil means, `org-agenda' shows every day in the selected range.
2834 When nil, only the days which actually have entries are shown."
2835 :group 'org-agenda-daily/weekly
2836 :type 'boolean)
2837
2838 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2839 "Format string for displaying dates in the agenda.
2840 Used by the daily/weekly agenda and by the timeline. This should be
2841 a format string understood by `format-time-string', or a function returning
2842 the formatted date as a string. The function must take a single argument,
2843 a calendar-style date list like (month day year)."
2844 :group 'org-agenda-daily/weekly
2845 :type '(choice
2846 (string :tag "Format string")
2847 (function :tag "Function")))
2848
2849 (defun org-agenda-format-date-aligned (date)
2850 "Format a date string for display in the daily/weekly agenda, or timeline.
2851 This function makes sure that dates are aligned for easy reading."
2852 (format "%-9s %2d %s %4d"
2853 (calendar-day-name date)
2854 (cadr date) ; day
2855 (calendar-month-name (car date)) ; month
2856 (nth 2 date))) ; year
2857
2858 (defcustom org-agenda-include-diary nil
2859 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2860 :group 'org-agenda-daily/weekly
2861 :type 'boolean)
2862
2863 (defcustom org-agenda-include-all-todo nil
2864 "Set means weekly/daily agenda will always contain all TODO entries.
2865 The TODO entries will be listed at the top of the agenda, before
2866 the entries for specific days."
2867 :group 'org-agenda-daily/weekly
2868 :type 'boolean)
2869
2870 (defcustom org-agenda-repeating-timestamp-show-all t
2871 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2872 When nil, only one occurence is shown, either today or the
2873 nearest into the future."
2874 :group 'org-agenda-daily/weekly
2875 :type 'boolean)
2876
2877 (defcustom org-deadline-warning-days 14
2878 "No. of days before expiration during which a deadline becomes active.
2879 This variable governs the display in sparse trees and in the agenda.
2880 When 0 or negative, it means use this number (the absolute value of it)
2881 even if a deadline has a different individual lead time specified."
2882 :group 'org-time
2883 :group 'org-agenda-daily/weekly
2884 :type 'number)
2885
2886 (defcustom org-scheduled-past-days 10000
2887 "No. of days to continue listing scheduled items that are not marked DONE.
2888 When an item is scheduled on a date, it shows up in the agenda on this
2889 day and will be listed until it is marked done for the number of days
2890 given here."
2891 :group 'org-agenda-daily/weekly
2892 :type 'number)
2893
2894 (defgroup org-agenda-time-grid nil
2895 "Options concerning the time grid in the Org-mode Agenda."
2896 :tag "Org Agenda Time Grid"
2897 :group 'org-agenda)
2898
2899 (defcustom org-agenda-use-time-grid t
2900 "Non-nil means, show a time grid in the agenda schedule.
2901 A time grid is a set of lines for specific times (like every two hours between
2902 8:00 and 20:00). The items scheduled for a day at specific times are
2903 sorted in between these lines.
2904 For details about when the grid will be shown, and what it will look like, see
2905 the variable `org-agenda-time-grid'."
2906 :group 'org-agenda-time-grid
2907 :type 'boolean)
2908
2909 (defcustom org-agenda-time-grid
2910 '((daily today require-timed)
2911 "----------------"
2912 (800 1000 1200 1400 1600 1800 2000))
2913
2914 "The settings for time grid for agenda display.
2915 This is a list of three items. The first item is again a list. It contains
2916 symbols specifying conditions when the grid should be displayed:
2917
2918 daily if the agenda shows a single day
2919 weekly if the agenda shows an entire week
2920 today show grid on current date, independent of daily/weekly display
2921 require-timed show grid only if at least one item has a time specification
2922
2923 The second item is a string which will be places behing the grid time.
2924
2925 The third item is a list of integers, indicating the times that should have
2926 a grid line."
2927 :group 'org-agenda-time-grid
2928 :type
2929 '(list
2930 (set :greedy t :tag "Grid Display Options"
2931 (const :tag "Show grid in single day agenda display" daily)
2932 (const :tag "Show grid in weekly agenda display" weekly)
2933 (const :tag "Always show grid for today" today)
2934 (const :tag "Show grid only if any timed entries are present"
2935 require-timed)
2936 (const :tag "Skip grid times already present in an entry"
2937 remove-match))
2938 (string :tag "Grid String")
2939 (repeat :tag "Grid Times" (integer :tag "Time"))))
2940
2941 (defgroup org-agenda-sorting nil
2942 "Options concerning sorting in the Org-mode Agenda."
2943 :tag "Org Agenda Sorting"
2944 :group 'org-agenda)
2945
2946 (defcustom org-agenda-sorting-strategy
2947 '((agenda time-up category-keep priority-down)
2948 (todo category-keep priority-down)
2949 (tags category-keep priority-down)
2950 (search category-keep))
2951 "Sorting structure for the agenda items of a single day.
2952 This is a list of symbols which will be used in sequence to determine
2953 if an entry should be listed before another entry. The following
2954 symbols are recognized:
2955
2956 time-up Put entries with time-of-day indications first, early first
2957 time-down Put entries with time-of-day indications first, late first
2958 category-keep Keep the default order of categories, corresponding to the
2959 sequence in `org-agenda-files'.
2960 category-up Sort alphabetically by category, A-Z.
2961 category-down Sort alphabetically by category, Z-A.
2962 tag-up Sort alphabetically by last tag, A-Z.
2963 tag-down Sort alphabetically by last tag, Z-A.
2964 priority-up Sort numerically by priority, high priority last.
2965 priority-down Sort numerically by priority, high priority first.
2966
2967 The different possibilities will be tried in sequence, and testing stops
2968 if one comparison returns a \"not-equal\". For example, the default
2969 '(time-up category-keep priority-down)
2970 means: Pull out all entries having a specified time of day and sort them,
2971 in order to make a time schedule for the current day the first thing in the
2972 agenda listing for the day. Of the entries without a time indication, keep
2973 the grouped in categories, don't sort the categories, but keep them in
2974 the sequence given in `org-agenda-files'. Within each category sort by
2975 priority.
2976
2977 Leaving out `category-keep' would mean that items will be sorted across
2978 categories by priority.
2979
2980 Instead of a single list, this can also be a set of list for specific
2981 contents, with a context symbol in the car of the list, any of
2982 `agenda', `todo', `tags' for the corresponding agenda views."
2983 :group 'org-agenda-sorting
2984 :type `(choice
2985 (repeat :tag "General" ,org-sorting-choice)
2986 (list :tag "Individually"
2987 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2988 (repeat ,org-sorting-choice))
2989 (cons (const :tag "Strategy for TODO lists" todo)
2990 (repeat ,org-sorting-choice))
2991 (cons (const :tag "Strategy for Tags matches" tags)
2992 (repeat ,org-sorting-choice)))))
2993
2994 (defcustom org-sort-agenda-notime-is-late t
2995 "Non-nil means, items without time are considered late.
2996 This is only relevant for sorting. When t, items which have no explicit
2997 time like 15:30 will be considered as 99:01, i.e. later than any items which
2998 do have a time. When nil, the default time is before 0:00. You can use this
2999 option to decide if the schedule for today should come before or after timeless
3000 agenda entries."
3001 :group 'org-agenda-sorting
3002 :type 'boolean)
3003
3004 (defgroup org-agenda-line-format nil
3005 "Options concerning the entry prefix in the Org-mode agenda display."
3006 :tag "Org Agenda Line Format"
3007 :group 'org-agenda)
3008
3009 (defcustom org-agenda-prefix-format
3010 '((agenda . " %-12:c%?-12t% s")
3011 (timeline . " % s")
3012 (todo . " %-12:c")
3013 (tags . " %-12:c")
3014 (search . " %-12:c"))
3015 "Format specifications for the prefix of items in the agenda views.
3016 An alist with four entries, for the different agenda types. The keys to the
3017 sublists are `agenda', `timeline', `todo', and `tags'. The values
3018 are format strings.
3019 This format works similar to a printf format, with the following meaning:
3020
3021 %c the category of the item, \"Diary\" for entries from the diary, or
3022 as given by the CATEGORY keyword or derived from the file name.
3023 %T the *last* tag of the item. Last because inherited tags come
3024 first in the list.
3025 %t the time-of-day specification if one applies to the entry, in the
3026 format HH:MM
3027 %s Scheduling/Deadline information, a short string
3028
3029 All specifiers work basically like the standard `%s' of printf, but may
3030 contain two additional characters: A question mark just after the `%' and
3031 a whitespace/punctuation character just before the final letter.
3032
3033 If the first character after `%' is a question mark, the entire field
3034 will only be included if the corresponding value applies to the
3035 current entry. This is useful for fields which should have fixed
3036 width when present, but zero width when absent. For example,
3037 \"%?-12t\" will result in a 12 character time field if a time of the
3038 day is specified, but will completely disappear in entries which do
3039 not contain a time.
3040
3041 If there is punctuation or whitespace character just before the final
3042 format letter, this character will be appended to the field value if
3043 the value is not empty. For example, the format \"%-12:c\" leads to
3044 \"Diary: \" if the category is \"Diary\". If the category were be
3045 empty, no additional colon would be interted.
3046
3047 The default value of this option is \" %-12:c%?-12t% s\", meaning:
3048 - Indent the line with two space characters
3049 - Give the category in a 12 chars wide field, padded with whitespace on
3050 the right (because of `-'). Append a colon if there is a category
3051 (because of `:').
3052 - If there is a time-of-day, put it into a 12 chars wide field. If no
3053 time, don't put in an empty field, just skip it (because of '?').
3054 - Finally, put the scheduling information and append a whitespace.
3055
3056 As another example, if you don't want the time-of-day of entries in
3057 the prefix, you could use:
3058
3059 (setq org-agenda-prefix-format \" %-11:c% s\")
3060
3061 See also the variables `org-agenda-remove-times-when-in-prefix' and
3062 `org-agenda-remove-tags'."
3063 :type '(choice
3064 (string :tag "General format")
3065 (list :greedy t :tag "View dependent"
3066 (cons (const agenda) (string :tag "Format"))
3067 (cons (const timeline) (string :tag "Format"))
3068 (cons (const todo) (string :tag "Format"))
3069 (cons (const tags) (string :tag "Format"))
3070 (cons (const search) (string :tag "Format"))))
3071 :group 'org-agenda-line-format)
3072
3073 (defvar org-prefix-format-compiled nil
3074 "The compiled version of the most recently used prefix format.
3075 See the variable `org-agenda-prefix-format'.")
3076
3077 (defcustom org-agenda-todo-keyword-format "%-1s"
3078 "Format for the TODO keyword in agenda lines.
3079 Set this to something like \"%-12s\" if you want all TODO keywords
3080 to occupy a fixed space in the agenda display."
3081 :group 'org-agenda-line-format
3082 :type 'string)
3083
3084 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
3085 "Text preceeding scheduled items in the agenda view.
3086 This is a list with two strings. The first applies when the item is
3087 scheduled on the current day. The second applies when it has been scheduled
3088 previously, it may contain a %d to capture how many days ago the item was
3089 scheduled."
3090 :group 'org-agenda-line-format
3091 :type '(list
3092 (string :tag "Scheduled today ")
3093 (string :tag "Scheduled previously")))
3094
3095 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
3096 "Text preceeding deadline items in the agenda view.
3097 This is a list with two strings. The first applies when the item has its
3098 deadline on the current day. The second applies when it is in the past or
3099 in the future, it may contain %d to capture how many days away the deadline
3100 is (was)."
3101 :group 'org-agenda-line-format
3102 :type '(list
3103 (string :tag "Deadline today ")
3104 (string :tag "Deadline relative")))
3105
3106 (defcustom org-agenda-remove-times-when-in-prefix t
3107 "Non-nil means, remove duplicate time specifications in agenda items.
3108 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
3109 time-of-day specification in a headline or diary entry is extracted and
3110 placed into the prefix. If this option is non-nil, the original specification
3111 \(a timestamp or -range, or just a plain time(range) specification like
3112 11:30-4pm) will be removed for agenda display. This makes the agenda less
3113 cluttered.
3114 The option can be t or nil. It may also be the symbol `beg', indicating
3115 that the time should only be removed what it is located at the beginning of
3116 the headline/diary entry."
3117 :group 'org-agenda-line-format
3118 :type '(choice
3119 (const :tag "Always" t)
3120 (const :tag "Never" nil)
3121 (const :tag "When at beginning of entry" beg)))
3122
3123
3124 (defcustom org-agenda-default-appointment-duration nil
3125 "Default duration for appointments that only have a starting time.
3126 When nil, no duration is specified in such cases.
3127 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
3128 :group 'org-agenda-line-format
3129 :type '(choice
3130 (integer :tag "Minutes")
3131 (const :tag "No default duration")))
3132
3133
3134 (defcustom org-agenda-remove-tags nil
3135 "Non-nil means, remove the tags from the headline copy in the agenda.
3136 When this is the symbol `prefix', only remove tags when
3137 `org-agenda-prefix-format' contains a `%T' specifier."
3138 :group 'org-agenda-line-format
3139 :type '(choice
3140 (const :tag "Always" t)
3141 (const :tag "Never" nil)
3142 (const :tag "When prefix format contains %T" prefix)))
3143
3144 (if (fboundp 'defvaralias)
3145 (defvaralias 'org-agenda-remove-tags-when-in-prefix
3146 'org-agenda-remove-tags))
3147
3148 (defcustom org-agenda-tags-column -80
3149 "Shift tags in agenda items to this column.
3150 If this number is positive, it specifies the column. If it is negative,
3151 it means that the tags should be flushright to that column. For example,
3152 -80 works well for a normal 80 character screen."
3153 :group 'org-agenda-line-format
3154 :type 'integer)
3155
3156 (if (fboundp 'defvaralias)
3157 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
3158
3159 (defcustom org-agenda-fontify-priorities t
3160 "Non-nil means, highlight low and high priorities in agenda.
3161 When t, the highest priority entries are bold, lowest priority italic.
3162 This may also be an association list of priority faces. The face may be
3163 a names face, or a list like `(:background \"Red\")'."
3164 :group 'org-agenda-line-format
3165 :type '(choice
3166 (const :tag "Never" nil)
3167 (const :tag "Defaults" t)
3168 (repeat :tag "Specify"
3169 (list (character :tag "Priority" :value ?A)
3170 (sexp :tag "face")))))
3171
3172 (defgroup org-latex nil
3173 "Options for embedding LaTeX code into Org-mode."
3174 :tag "Org LaTeX"
3175 :group 'org)
3176
3177 (defcustom org-format-latex-options
3178 '(:foreground default :background default :scale 1.0
3179 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3180 :matchers ("begin" "$" "$$" "\\(" "\\["))
3181 "Options for creating images from LaTeX fragments.
3182 This is a property list with the following properties:
3183 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
3184 `default' means use the forground of the default face.
3185 :background the background color, or \"Transparent\".
3186 `default' means use the background of the default face.
3187 :scale a scaling factor for the size of the images
3188 :html-foreground, :html-background, :html-scale
3189 The same numbers for HTML export.
3190 :matchers a list indicating which matchers should be used to
3191 find LaTeX fragments. Valid members of this list are:
3192 \"begin\" find environments
3193 \"$\" find math expressions surrounded by $...$
3194 \"$$\" find math expressions surrounded by $$....$$
3195 \"\\(\" find math expressions surrounded by \\(...\\)
3196 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3197 :group 'org-latex
3198 :type 'plist)
3199
3200 (defcustom org-format-latex-header "\\documentclass{article}
3201 \\usepackage{fullpage} % do not remove
3202 \\usepackage{amssymb}
3203 \\usepackage[usenames]{color}
3204 \\usepackage{amsmath}
3205 \\usepackage{latexsym}
3206 \\usepackage[mathscr]{eucal}
3207 \\pagestyle{empty} % do not remove"
3208 "The document header used for processing LaTeX fragments."
3209 :group 'org-latex
3210 :type 'string)
3211
3212 (defgroup org-export nil
3213 "Options for exporting org-listings."
3214 :tag "Org Export"
3215 :group 'org)
3216
3217 (defgroup org-export-general nil
3218 "General options for exporting Org-mode files."
3219 :tag "Org Export General"
3220 :group 'org-export)
3221
3222 ;; FIXME
3223 (defvar org-export-publishing-directory nil)
3224
3225 (defcustom org-export-with-special-strings t
3226 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3227 When this option is turned on, these strings will be exported as:
3228
3229 Org HTML LaTeX
3230 -----+----------+--------
3231 \\- &shy; \\-
3232 -- &ndash; --
3233 --- &mdash; ---
3234 ... &hellip; \ldots
3235
3236 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3237 :group 'org-export-translation
3238 :type 'boolean)
3239
3240 (defcustom org-export-language-setup
3241 '(("en" "Author" "Date" "Table of Contents")
3242 ("cs" "Autor" "Datum" "Obsah")
3243 ("da" "Ophavsmand" "Dato" "Indhold")
3244 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3245 ("es" "Autor" "Fecha" "\xcdndice")
3246 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3247 ("it" "Autore" "Data" "Indice")
3248 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3249 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3250 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3251 "Terms used in export text, translated to different languages.
3252 Use the variable `org-export-default-language' to set the language,
3253 or use the +OPTION lines for a per-file setting."
3254 :group 'org-export-general
3255 :type '(repeat
3256 (list
3257 (string :tag "HTML language tag")
3258 (string :tag "Author")
3259 (string :tag "Date")
3260 (string :tag "Table of Contents"))))
3261
3262 (defcustom org-export-default-language "en"
3263 "The default language of HTML export, as a string.
3264 This should have an association in `org-export-language-setup'."
3265 :group 'org-export-general
3266 :type 'string)
3267
3268 (defcustom org-export-skip-text-before-1st-heading t
3269 "Non-nil means, skip all text before the first headline when exporting.
3270 When nil, that text is exported as well."
3271 :group 'org-export-general
3272 :type 'boolean)
3273
3274 (defcustom org-export-headline-levels 3
3275 "The last level which is still exported as a headline.
3276 Inferior levels will produce itemize lists when exported.
3277 Note that a numeric prefix argument to an exporter function overrides
3278 this setting.
3279
3280 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3281 :group 'org-export-general
3282 :type 'number)
3283
3284 (defcustom org-export-with-section-numbers t
3285 "Non-nil means, add section numbers to headlines when exporting.
3286
3287 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3288 :group 'org-export-general
3289 :type 'boolean)
3290
3291 (defcustom org-export-with-toc t
3292 "Non-nil means, create a table of contents in exported files.
3293 The TOC contains headlines with levels up to`org-export-headline-levels'.
3294 When an integer, include levels up to N in the toc, this may then be
3295 different from `org-export-headline-levels', but it will not be allowed
3296 to be larger than the number of headline levels.
3297 When nil, no table of contents is made.
3298
3299 Headlines which contain any TODO items will be marked with \"(*)\" in
3300 ASCII export, and with red color in HTML output, if the option
3301 `org-export-mark-todo-in-toc' is set.
3302
3303 In HTML output, the TOC will be clickable.
3304
3305 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3306 or \"toc:3\"."
3307 :group 'org-export-general
3308 :type '(choice
3309 (const :tag "No Table of Contents" nil)
3310 (const :tag "Full Table of Contents" t)
3311 (integer :tag "TOC to level")))
3312
3313 (defcustom org-export-mark-todo-in-toc nil
3314 "Non-nil means, mark TOC lines that contain any open TODO items."
3315 :group 'org-export-general
3316 :type 'boolean)
3317
3318 (defcustom org-export-preserve-breaks nil
3319 "Non-nil means, preserve all line breaks when exporting.
3320 Normally, in HTML output paragraphs will be reformatted. In ASCII
3321 export, line breaks will always be preserved, regardless of this variable.
3322
3323 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3324 :group 'org-export-general
3325 :type 'boolean)
3326
3327 (defcustom org-export-with-archived-trees 'headline
3328 "Whether subtrees with the ARCHIVE tag should be exported.
3329 This can have three different values
3330 nil Do not export, pretend this tree is not present
3331 t Do export the entire tree
3332 headline Only export the headline, but skip the tree below it."
3333 :group 'org-export-general
3334 :group 'org-archive
3335 :type '(choice
3336 (const :tag "not at all" nil)
3337 (const :tag "headline only" 'headline)
3338 (const :tag "entirely" t)))
3339
3340 (defcustom org-export-author-info t
3341 "Non-nil means, insert author name and email into the exported file.
3342
3343 This option can also be set with the +OPTIONS line,
3344 e.g. \"author-info:nil\"."
3345 :group 'org-export-general
3346 :type 'boolean)
3347
3348 (defcustom org-export-time-stamp-file t
3349 "Non-nil means, insert a time stamp into the exported file.
3350 The time stamp shows when the file was created.
3351
3352 This option can also be set with the +OPTIONS line,
3353 e.g. \"timestamp:nil\"."
3354 :group 'org-export-general
3355 :type 'boolean)
3356
3357 (defcustom org-export-with-timestamps t
3358 "If nil, do not export time stamps and associated keywords."
3359 :group 'org-export-general
3360 :type 'boolean)
3361
3362 (defcustom org-export-remove-timestamps-from-toc t
3363 "If nil, remove timestamps from the table of contents entries."
3364 :group 'org-export-general
3365 :type 'boolean)
3366
3367 (defcustom org-export-with-tags 'not-in-toc
3368 "If nil, do not export tags, just remove them from headlines.
3369 If this is the symbol `not-in-toc', tags will be removed from table of
3370 contents entries, but still be shown in the headlines of the document.
3371
3372 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3373 :group 'org-export-general
3374 :type '(choice
3375 (const :tag "Off" nil)
3376 (const :tag "Not in TOC" not-in-toc)
3377 (const :tag "On" t)))
3378
3379 (defcustom org-export-with-drawers nil
3380 "Non-nil means, export with drawers like the property drawer.
3381 When t, all drawers are exported. This may also be a list of
3382 drawer names to export."
3383 :group 'org-export-general
3384 :type '(choice
3385 (const :tag "All drawers" t)
3386 (const :tag "None" nil)
3387 (repeat :tag "Selected drawers"
3388 (string :tag "Drawer name"))))
3389
3390 (defgroup org-export-translation nil
3391 "Options for translating special ascii sequences for the export backends."
3392 :tag "Org Export Translation"
3393 :group 'org-export)
3394
3395 (defcustom org-export-with-emphasize t
3396 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3397 If the export target supports emphasizing text, the word will be
3398 typeset in bold, italic, or underlined, respectively. Works only for
3399 single words, but you can say: I *really* *mean* *this*.
3400 Not all export backends support this.
3401
3402 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3403 :group 'org-export-translation
3404 :type 'boolean)
3405
3406 (defcustom org-export-with-footnotes t
3407 "If nil, export [1] as a footnote marker.
3408 Lines starting with [1] will be formatted as footnotes.
3409
3410 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3411 :group 'org-export-translation
3412 :type 'boolean)
3413
3414 (defcustom org-export-with-sub-superscripts t
3415 "Non-nil means, interpret \"_\" and \"^\" for export.
3416 When this option is turned on, you can use TeX-like syntax for sub- and
3417 superscripts. Several characters after \"_\" or \"^\" will be
3418 considered as a single item - so grouping with {} is normally not
3419 needed. For example, the following things will be parsed as single
3420 sub- or superscripts.
3421
3422 10^24 or 10^tau several digits will be considered 1 item.
3423 10^-12 or 10^-tau a leading sign with digits or a word
3424 x^2-y^3 will be read as x^2 - y^3, because items are
3425 terminated by almost any nonword/nondigit char.
3426 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3427
3428 Still, ambiguity is possible - so when in doubt use {} to enclose the
3429 sub/superscript. If you set this variable to the symbol `{}',
3430 the braces are *required* in order to trigger interpretations as
3431 sub/superscript. This can be helpful in documents that need \"_\"
3432 frequently in plain text.
3433
3434 Not all export backends support this, but HTML does.
3435
3436 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3437 :group 'org-export-translation
3438 :type '(choice
3439 (const :tag "Always interpret" t)
3440 (const :tag "Only with braces" {})
3441 (const :tag "Never interpret" nil)))
3442
3443 (defcustom org-export-with-special-strings t
3444 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3445 When this option is turned on, these strings will be exported as:
3446
3447 \\- : &shy;
3448 -- : &ndash;
3449 --- : &mdash;
3450
3451 Not all export backends support this, but HTML does.
3452
3453 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3454 :group 'org-export-translation
3455 :type 'boolean)
3456
3457 (defcustom org-export-with-TeX-macros t
3458 "Non-nil means, interpret simple TeX-like macros when exporting.
3459 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3460 No only real TeX macros will work here, but the standard HTML entities
3461 for math can be used as macro names as well. For a list of supported
3462 names in HTML export, see the constant `org-html-entities'.
3463 Not all export backends support this.
3464
3465 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3466 :group 'org-export-translation
3467 :group 'org-export-latex
3468 :type 'boolean)
3469
3470 (defcustom org-export-with-LaTeX-fragments nil
3471 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3472 When set, the exporter will find LaTeX environments if the \\begin line is
3473 the first non-white thing on a line. It will also find the math delimiters
3474 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3475 display math.
3476
3477 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3478 :group 'org-export-translation
3479 :group 'org-export-latex
3480 :type 'boolean)
3481
3482 (defcustom org-export-with-fixed-width t
3483 "Non-nil means, lines starting with \":\" will be in fixed width font.
3484 This can be used to have pre-formatted text, fragments of code etc. For
3485 example:
3486 : ;; Some Lisp examples
3487 : (while (defc cnt)
3488 : (ding))
3489 will be looking just like this in also HTML. See also the QUOTE keyword.
3490 Not all export backends support this.
3491
3492 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3493 :group 'org-export-translation
3494 :type 'boolean)
3495
3496 (defcustom org-match-sexp-depth 3
3497 "Number of stacked braces for sub/superscript matching.
3498 This has to be set before loading org.el to be effective."
3499 :group 'org-export-translation
3500 :type 'integer)
3501
3502 (defgroup org-export-tables nil
3503 "Options for exporting tables in Org-mode."
3504 :tag "Org Export Tables"
3505 :group 'org-export)
3506
3507 (defcustom org-export-with-tables t
3508 "If non-nil, lines starting with \"|\" define a table.
3509 For example:
3510
3511 | Name | Address | Birthday |
3512 |-------------+----------+-----------|
3513 | Arthur Dent | England | 29.2.2100 |
3514
3515 Not all export backends support this.
3516
3517 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3518 :group 'org-export-tables
3519 :type 'boolean)
3520
3521 (defcustom org-export-highlight-first-table-line t
3522 "Non-nil means, highlight the first table line.
3523 In HTML export, this means use <th> instead of <td>.
3524 In tables created with table.el, this applies to the first table line.
3525 In Org-mode tables, all lines before the first horizontal separator
3526 line will be formatted with <th> tags."
3527 :group 'org-export-tables
3528 :type 'boolean)
3529
3530 (defcustom org-export-table-remove-special-lines t
3531 "Remove special lines and marking characters in calculating tables.
3532 This removes the special marking character column from tables that are set
3533 up for spreadsheet calculations. It also removes the entire lines
3534 marked with `!', `_', or `^'. The lines with `$' are kept, because
3535 the values of constants may be useful to have."
3536 :group 'org-export-tables
3537 :type 'boolean)
3538
3539 (defcustom org-export-prefer-native-exporter-for-tables nil
3540 "Non-nil means, always export tables created with table.el natively.
3541 Natively means, use the HTML code generator in table.el.
3542 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3543 the table does not use row- or column-spanning). This has the
3544 advantage, that the automatic HTML conversions for math symbols and
3545 sub/superscripts can be applied. Org-mode's HTML generator is also
3546 much faster."
3547 :group 'org-export-tables
3548 :type 'boolean)
3549
3550 (defgroup org-export-ascii nil
3551 "Options specific for ASCII export of Org-mode files."
3552 :tag "Org Export ASCII"
3553 :group 'org-export)
3554
3555 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3556 "Characters for underlining headings in ASCII export.
3557 In the given sequence, these characters will be used for level 1, 2, ..."
3558 :group 'org-export-ascii
3559 :type '(repeat character))
3560
3561 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3562 "Bullet characters for headlines converted to lists in ASCII export.
3563 The first character is used for the first lest level generated in this
3564 way, and so on. If there are more levels than characters given here,
3565 the list will be repeated.
3566 Note that plain lists will keep the same bullets as the have in the
3567 Org-mode file."
3568 :group 'org-export-ascii
3569 :type '(repeat character))
3570
3571 (defgroup org-export-xml nil
3572 "Options specific for XML export of Org-mode files."
3573 :tag "Org Export XML"
3574 :group 'org-export)
3575
3576 (defgroup org-export-html nil
3577 "Options specific for HTML export of Org-mode files."
3578 :tag "Org Export HTML"
3579 :group 'org-export)
3580
3581 (defcustom org-export-html-coding-system nil
3582 ""
3583 :group 'org-export-html
3584 :type 'coding-system)
3585
3586 (defcustom org-export-html-extension "html"
3587 "The extension for exported HTML files."
3588 :group 'org-export-html
3589 :type 'string)
3590
3591 (defcustom org-export-html-style
3592 "<style type=\"text/css\">
3593 html {
3594 font-family: Times, serif;
3595 font-size: 12pt;
3596 }
3597 .title { text-align: center; }
3598 .todo { color: red; }
3599 .done { color: green; }
3600 .timestamp { color: grey }
3601 .timestamp-kwd { color: CadetBlue }
3602 .tag { background-color:lightblue; font-weight:normal }
3603 .target { background-color: lavender; }
3604 pre {
3605 border: 1pt solid #AEBDCC;
3606 background-color: #F3F5F7;
3607 padding: 5pt;
3608 font-family: courier, monospace;
3609 }
3610 table { border-collapse: collapse; }
3611 td, th {
3612 vertical-align: top;
3613 <!--border: 1pt solid #ADB9CC;-->
3614 }
3615 </style>"
3616 "The default style specification for exported HTML files.
3617 Since there are different ways of setting style information, this variable
3618 needs to contain the full HTML structure to provide a style, including the
3619 surrounding HTML tags. The style specifications should include definitions
3620 for new classes todo, done, title, and deadline. For example, valid values
3621 would be:
3622
3623 <style type=\"text/css\">
3624 p { font-weight: normal; color: gray; }
3625 h1 { color: black; }
3626 .title { text-align: center; }
3627 .todo, .deadline { color: red; }
3628 .done { color: green; }
3629 </style>
3630
3631 or, if you want to keep the style in a file,
3632
3633 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3634
3635 As the value of this option simply gets inserted into the HTML <head> header,
3636 you can \"misuse\" it to add arbitrary text to the header."
3637 :group 'org-export-html
3638 :type 'string)
3639
3640
3641 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3642 "Format for typesetting the document title in HTML export."
3643 :group 'org-export-html
3644 :type 'string)
3645
3646 (defcustom org-export-html-toplevel-hlevel 2
3647 "The <H> level for level 1 headings in HTML export."
3648 :group 'org-export-html
3649 :type 'string)
3650
3651 (defcustom org-export-html-link-org-files-as-html t
3652 "Non-nil means, make file links to `file.org' point to `file.html'.
3653 When org-mode is exporting an org-mode file to HTML, links to
3654 non-html files are directly put into a href tag in HTML.
3655 However, links to other Org-mode files (recognized by the
3656 extension `.org.) should become links to the corresponding html
3657 file, assuming that the linked org-mode file will also be
3658 converted to HTML.
3659 When nil, the links still point to the plain `.org' file."
3660 :group 'org-export-html
3661 :type 'boolean)
3662
3663 (defcustom org-export-html-inline-images 'maybe
3664 "Non-nil means, inline images into exported HTML pages.
3665 This is done using an <img> tag. When nil, an anchor with href is used to
3666 link to the image. If this option is `maybe', then images in links with
3667 an empty description will be inlined, while images with a description will
3668 be linked only."
3669 :group 'org-export-html
3670 :type '(choice (const :tag "Never" nil)
3671 (const :tag "Always" t)
3672 (const :tag "When there is no description" maybe)))
3673
3674 ;; FIXME: rename
3675 (defcustom org-export-html-expand t
3676 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3677 When nil, these tags will be exported as plain text and therefore
3678 not be interpreted by a browser.
3679
3680 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3681 :group 'org-export-html
3682 :type 'boolean)
3683
3684 (defcustom org-export-html-table-tag
3685 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3686 "The HTML tag that is used to start a table.
3687 This must be a <table> tag, but you may change the options like
3688 borders and spacing."
3689 :group 'org-export-html
3690 :type 'string)
3691
3692 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3693 "The opening tag for table header fields.
3694 This is customizable so that alignment options can be specified."
3695 :group 'org-export-tables
3696 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3697
3698 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3699 "The opening tag for table data fields.
3700 This is customizable so that alignment options can be specified."
3701 :group 'org-export-tables
3702 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3703
3704 (defcustom org-export-html-with-timestamp nil
3705 "If non-nil, write `org-export-html-html-helper-timestamp'
3706 into the exported HTML text. Otherwise, the buffer will just be saved
3707 to a file."
3708 :group 'org-export-html
3709 :type 'boolean)
3710
3711 (defcustom org-export-html-html-helper-timestamp
3712 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3713 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3714 :group 'org-export-html
3715 :type 'string)
3716
3717 (defgroup org-export-icalendar nil
3718 "Options specific for iCalendar export of Org-mode files."
3719 :tag "Org Export iCalendar"
3720 :group 'org-export)
3721
3722 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3723 "The file name for the iCalendar file covering all agenda files.
3724 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3725 The file name should be absolute, the file will be overwritten without warning."
3726 :group 'org-export-icalendar
3727 :type 'file)
3728
3729 (defcustom org-icalendar-include-todo nil
3730 "Non-nil means, export to iCalendar files should also cover TODO items."
3731 :group 'org-export-icalendar
3732 :type '(choice
3733 (const :tag "None" nil)
3734 (const :tag "Unfinished" t)
3735 (const :tag "All" all)))
3736
3737 (defcustom org-icalendar-include-sexps t
3738 "Non-nil means, export to iCalendar files should also cover sexp entries.
3739 These are entries like in the diary, but directly in an Org-mode file."
3740 :group 'org-export-icalendar
3741 :type 'boolean)
3742
3743 (defcustom org-icalendar-include-body 100
3744 "Amount of text below headline to be included in iCalendar export.
3745 This is a number of characters that should maximally be included.
3746 Properties, scheduling and clocking lines will always be removed.
3747 The text will be inserted into the DESCRIPTION field."
3748 :group 'org-export-icalendar
3749 :type '(choice
3750 (const :tag "Nothing" nil)
3751 (const :tag "Everything" t)
3752 (integer :tag "Max characters")))
3753
3754 (defcustom org-icalendar-combined-name "OrgMode"
3755 "Calendar name for the combined iCalendar representing all agenda files."
3756 :group 'org-export-icalendar
3757 :type 'string)
3758
3759 (defgroup org-font-lock nil
3760 "Font-lock settings for highlighting in Org-mode."
3761 :tag "Org Font Lock"
3762 :group 'org)
3763
3764 (defcustom org-level-color-stars-only nil
3765 "Non-nil means fontify only the stars in each headline.
3766 When nil, the entire headline is fontified.
3767 Changing it requires restart of `font-lock-mode' to become effective
3768 also in regions already fontified."
3769 :group 'org-font-lock
3770 :type 'boolean)
3771
3772 (defcustom org-hide-leading-stars nil
3773 "Non-nil means, hide the first N-1 stars in a headline.
3774 This works by using the face `org-hide' for these stars. This
3775 face is white for a light background, and black for a dark
3776 background. You may have to customize the face `org-hide' to
3777 make this work.
3778 Changing it requires restart of `font-lock-mode' to become effective
3779 also in regions already fontified.
3780 You may also set this on a per-file basis by adding one of the following
3781 lines to the buffer:
3782
3783 #+STARTUP: hidestars
3784 #+STARTUP: showstars"
3785 :group 'org-font-lock
3786 :type 'boolean)
3787
3788 (defcustom org-fontify-done-headline nil
3789 "Non-nil means, change the face of a headline if it is marked DONE.
3790 Normally, only the TODO/DONE keyword indicates the state of a headline.
3791 When this is non-nil, the headline after the keyword is set to the
3792 `org-headline-done' as an additional indication."
3793 :group 'org-font-lock
3794 :type 'boolean)
3795
3796 (defcustom org-fontify-emphasized-text t
3797 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3798 Changing this variable requires a restart of Emacs to take effect."
3799 :group 'org-font-lock
3800 :type 'boolean)
3801
3802 (defcustom org-highlight-latex-fragments-and-specials nil
3803 "Non-nil means, fontify what is treated specially by the exporters."
3804 :group 'org-font-lock
3805 :type 'boolean)
3806
3807 (defcustom org-hide-emphasis-markers nil
3808 "Non-nil mean font-lock should hide the emphasis marker characters."
3809 :group 'org-font-lock
3810 :type 'boolean)
3811
3812 (defvar org-emph-re nil
3813 "Regular expression for matching emphasis.")
3814 (defvar org-verbatim-re nil
3815 "Regular expression for matching verbatim text.")
3816 (defvar org-emphasis-regexp-components) ; defined just below
3817 (defvar org-emphasis-alist) ; defined just below
3818 (defun org-set-emph-re (var val)
3819 "Set variable and compute the emphasis regular expression."
3820 (set var val)
3821 (when (and (boundp 'org-emphasis-alist)
3822 (boundp 'org-emphasis-regexp-components)
3823 org-emphasis-alist org-emphasis-regexp-components)
3824 (let* ((e org-emphasis-regexp-components)
3825 (pre (car e))
3826 (post (nth 1 e))
3827 (border (nth 2 e))
3828 (body (nth 3 e))
3829 (nl (nth 4 e))
3830 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3831 (body1 (concat body "*?"))
3832 (markers (mapconcat 'car org-emphasis-alist ""))
3833 (vmarkers (mapconcat
3834 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3835 org-emphasis-alist "")))
3836 ;; make sure special characters appear at the right position in the class
3837 (if (string-match "\\^" markers)
3838 (setq markers (concat (replace-match "" t t markers) "^")))
3839 (if (string-match "-" markers)
3840 (setq markers (concat (replace-match "" t t markers) "-")))
3841 (if (string-match "\\^" vmarkers)
3842 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3843 (if (string-match "-" vmarkers)
3844 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3845 (if (> nl 0)
3846 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3847 (int-to-string nl) "\\}")))
3848 ;; Make the regexp
3849 (setq org-emph-re
3850 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3851 "\\("
3852 "\\([" markers "]\\)"
3853 "\\("
3854 "[^" border "]\\|"
3855 "[^" border (if (and nil stacked) markers) "]"
3856 body1
3857 "[^" border (if (and nil stacked) markers) "]"
3858 "\\)"
3859 "\\3\\)"
3860 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3861 (setq org-verbatim-re
3862 (concat "\\([" pre "]\\|^\\)"
3863 "\\("
3864 "\\([" vmarkers "]\\)"
3865 "\\("
3866 "[^" border "]\\|"
3867 "[^" border "]"
3868 body1
3869 "[^" border "]"
3870 "\\)"
3871 "\\3\\)"
3872 "\\([" post "]\\|$\\)")))))
3873
3874 (defcustom org-emphasis-regexp-components
3875 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3876 "Components used to build the regular expression for emphasis.
3877 This is a list with 6 entries. Terminology: In an emphasis string
3878 like \" *strong word* \", we call the initial space PREMATCH, the final
3879 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3880 and \"trong wor\" is the body. The different components in this variable
3881 specify what is allowed/forbidden in each part:
3882
3883 pre Chars allowed as prematch. Beginning of line will be allowed too.
3884 post Chars allowed as postmatch. End of line will be allowed too.
3885 border The chars *forbidden* as border characters.
3886 body-regexp A regexp like \".\" to match a body character. Don't use
3887 non-shy groups here, and don't allow newline here.
3888 newline The maximum number of newlines allowed in an emphasis exp.
3889
3890 Use customize to modify this, or restart Emacs after changing it."
3891 :group 'org-font-lock
3892 :set 'org-set-emph-re
3893 :type '(list
3894 (sexp :tag "Allowed chars in pre ")
3895 (sexp :tag "Allowed chars in post ")
3896 (sexp :tag "Forbidden chars in border ")
3897 (sexp :tag "Regexp for body ")
3898 (integer :tag "number of newlines allowed")
3899 (option (boolean :tag "Stacking (DISABLED) "))))
3900
3901 (defcustom org-emphasis-alist
3902 '(("*" bold "<b>" "</b>")
3903 ("/" italic "<i>" "</i>")
3904 ("_" underline "<u>" "</u>")
3905 ("=" org-code "<code>" "</code>" verbatim)
3906 ("~" org-verbatim "" "" verbatim)
3907 ("+" (:strike-through t) "<del>" "</del>")
3908 )
3909 "Special syntax for emphasized text.
3910 Text starting and ending with a special character will be emphasized, for
3911 example *bold*, _underlined_ and /italic/. This variable sets the marker
3912 characters, the face to be used by font-lock for highlighting in Org-mode
3913 Emacs buffers, and the HTML tags to be used for this.
3914 Use customize to modify this, or restart Emacs after changing it."
3915 :group 'org-font-lock
3916 :set 'org-set-emph-re
3917 :type '(repeat
3918 (list
3919 (string :tag "Marker character")
3920 (choice
3921 (face :tag "Font-lock-face")
3922 (plist :tag "Face property list"))
3923 (string :tag "HTML start tag")
3924 (string :tag "HTML end tag")
3925 (option (const verbatim)))))
3926
3927 ;;; The faces
3928
3929 (defgroup org-faces nil
3930 "Faces in Org-mode."
3931 :tag "Org Faces"
3932 :group 'org-font-lock)
3933
3934 (defun org-compatible-face (inherits specs)
3935 "Make a compatible face specification.
3936 If INHERITS is an existing face and if the Emacs version supports it,
3937 just inherit the face. If not, use SPECS to define the face.
3938 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3939 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3940 to the top of the list. The `min-colors' attribute will be removed from
3941 any other entries, and any resulting duplicates will be removed entirely."
3942 (cond
3943 ((and inherits (facep inherits)
3944 (not (featurep 'xemacs)) (> emacs-major-version 22))
3945 ;; In Emacs 23, we use inheritance where possible.
3946 ;; We only do this in Emacs 23, because only there the outline
3947 ;; faces have been changed to the original org-mode-level-faces.
3948 (list (list t :inherit inherits)))
3949 ((or (featurep 'xemacs) (< emacs-major-version 22))
3950 ;; These do not understand the `min-colors' attribute.
3951 (let (r e a)
3952 (while (setq e (pop specs))
3953 (cond
3954 ((memq (car e) '(t default)) (push e r))
3955 ((setq a (member '(min-colors 8) (car e)))
3956 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3957 (cdr e)))))
3958 ((setq a (assq 'min-colors (car e)))
3959 (setq e (cons (delq a (car e)) (cdr e)))
3960 (or (assoc (car e) r) (push e r)))
3961 (t (or (assoc (car e) r) (push e r)))))
3962 (nreverse r)))
3963 (t specs)))
3964 (put 'org-compatible-face 'lisp-indent-function 1)
3965
3966 (defface org-hide
3967 '((((background light)) (:foreground "white"))
3968 (((background dark)) (:foreground "black")))
3969 "Face used to hide leading stars in headlines.
3970 The forground color of this face should be equal to the background
3971 color of the frame."
3972 :group 'org-faces)
3973
3974 (defface org-level-1 ;; font-lock-function-name-face
3975 (org-compatible-face 'outline-1
3976 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3977 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3978 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3979 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3980 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3981 (t (:bold t))))
3982 "Face used for level 1 headlines."
3983 :group 'org-faces)
3984
3985 (defface org-level-2 ;; font-lock-variable-name-face
3986 (org-compatible-face 'outline-2
3987 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3988 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3989 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3990 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3991 (t (:bold t))))
3992 "Face used for level 2 headlines."
3993 :group 'org-faces)
3994
3995 (defface org-level-3 ;; font-lock-keyword-face
3996 (org-compatible-face 'outline-3
3997 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3998 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3999 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
4000 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
4001 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
4002 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
4003 (t (:bold t))))
4004 "Face used for level 3 headlines."
4005 :group 'org-faces)
4006
4007 (defface org-level-4 ;; font-lock-comment-face
4008 (org-compatible-face 'outline-4
4009 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4010 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4011 (((class color) (min-colors 16) (background light)) (:foreground "red"))
4012 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
4013 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4014 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4015 (t (:bold t))))
4016 "Face used for level 4 headlines."
4017 :group 'org-faces)
4018
4019 (defface org-level-5 ;; font-lock-type-face
4020 (org-compatible-face 'outline-5
4021 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
4022 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
4023 (((class color) (min-colors 8)) (:foreground "green"))))
4024 "Face used for level 5 headlines."
4025 :group 'org-faces)
4026
4027 (defface org-level-6 ;; font-lock-constant-face
4028 (org-compatible-face 'outline-6
4029 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
4030 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
4031 (((class color) (min-colors 8)) (:foreground "magenta"))))
4032 "Face used for level 6 headlines."
4033 :group 'org-faces)
4034
4035 (defface org-level-7 ;; font-lock-builtin-face
4036 (org-compatible-face 'outline-7
4037 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
4038 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
4039 (((class color) (min-colors 8)) (:foreground "blue"))))
4040 "Face used for level 7 headlines."
4041 :group 'org-faces)
4042
4043 (defface org-level-8 ;; font-lock-string-face
4044 (org-compatible-face 'outline-8
4045 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4046 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4047 (((class color) (min-colors 8)) (:foreground "green"))))
4048 "Face used for level 8 headlines."
4049 :group 'org-faces)
4050
4051 (defface org-special-keyword ;; font-lock-string-face
4052 (org-compatible-face nil
4053 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4054 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4055 (t (:italic t))))
4056 "Face used for special keywords."
4057 :group 'org-faces)
4058
4059 (defface org-drawer ;; font-lock-function-name-face
4060 (org-compatible-face nil
4061 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4062 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4063 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4064 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4065 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4066 (t (:bold t))))
4067 "Face used for drawers."
4068 :group 'org-faces)
4069
4070 (defface org-property-value nil
4071 "Face used for the value of a property."
4072 :group 'org-faces)
4073
4074 (defface org-column
4075 (org-compatible-face nil
4076 '((((class color) (min-colors 16) (background light))
4077 (:background "grey90"))
4078 (((class color) (min-colors 16) (background dark))
4079 (:background "grey30"))
4080 (((class color) (min-colors 8))
4081 (:background "cyan" :foreground "black"))
4082 (t (:inverse-video t))))
4083 "Face for column display of entry properties."
4084 :group 'org-faces)
4085
4086 (when (fboundp 'set-face-attribute)
4087 ;; Make sure that a fixed-width face is used when we have a column table.
4088 (set-face-attribute 'org-column nil
4089 :height (face-attribute 'default :height)
4090 :family (face-attribute 'default :family)))
4091
4092 (defface org-warning
4093 (org-compatible-face 'font-lock-warning-face
4094 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4095 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4096 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4097 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4098 (t (:bold t))))
4099 "Face for deadlines and TODO keywords."
4100 :group 'org-faces)
4101
4102 (defface org-archived ; similar to shadow
4103 (org-compatible-face 'shadow
4104 '((((class color grayscale) (min-colors 88) (background light))
4105 (:foreground "grey50"))
4106 (((class color grayscale) (min-colors 88) (background dark))
4107 (:foreground "grey70"))
4108 (((class color) (min-colors 8) (background light))
4109 (:foreground "green"))
4110 (((class color) (min-colors 8) (background dark))
4111 (:foreground "yellow"))))
4112 "Face for headline with the ARCHIVE tag."
4113 :group 'org-faces)
4114
4115 (defface org-link
4116 '((((class color) (background light)) (:foreground "Purple" :underline t))
4117 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4118 (t (:underline t)))
4119 "Face for links."
4120 :group 'org-faces)
4121
4122 (defface org-ellipsis
4123 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
4124 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
4125 (t (:strike-through t)))
4126 "Face for the ellipsis in folded text."
4127 :group 'org-faces)
4128
4129 (defface org-target
4130 '((((class color) (background light)) (:underline t))
4131 (((class color) (background dark)) (:underline t))
4132 (t (:underline t)))
4133 "Face for links."
4134 :group 'org-faces)
4135
4136 (defface org-date
4137 '((((class color) (background light)) (:foreground "Purple" :underline t))
4138 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4139 (t (:underline t)))
4140 "Face for links."
4141 :group 'org-faces)
4142
4143 (defface org-sexp-date
4144 '((((class color) (background light)) (:foreground "Purple"))
4145 (((class color) (background dark)) (:foreground "Cyan"))
4146 (t (:underline t)))
4147 "Face for links."
4148 :group 'org-faces)
4149
4150 (defface org-tag
4151 '((t (:bold t)))
4152 "Face for tags."
4153 :group 'org-faces)
4154
4155 (defface org-todo ; font-lock-warning-face
4156 (org-compatible-face nil
4157 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4158 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4159 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4160 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4161 (t (:inverse-video t :bold t))))
4162 "Face for TODO keywords."
4163 :group 'org-faces)
4164
4165 (defface org-done ;; font-lock-type-face
4166 (org-compatible-face nil
4167 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
4168 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
4169 (((class color) (min-colors 8)) (:foreground "green"))
4170 (t (:bold t))))
4171 "Face used for todo keywords that indicate DONE items."
4172 :group 'org-faces)
4173
4174 (defface org-headline-done ;; font-lock-string-face
4175 (org-compatible-face nil
4176 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4177 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4178 (((class color) (min-colors 8) (background light)) (:bold nil))))
4179 "Face used to indicate that a headline is DONE.
4180 This face is only used if `org-fontify-done-headline' is set. If applies
4181 to the part of the headline after the DONE keyword."
4182 :group 'org-faces)
4183
4184 (defcustom org-todo-keyword-faces nil
4185 "Faces for specific TODO keywords.
4186 This is a list of cons cells, with TODO keywords in the car
4187 and faces in the cdr. The face can be a symbol, or a property
4188 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
4189 :group 'org-faces
4190 :group 'org-todo
4191 :type '(repeat
4192 (cons
4193 (string :tag "keyword")
4194 (sexp :tag "face"))))
4195
4196 (defface org-table ;; font-lock-function-name-face
4197 (org-compatible-face nil
4198 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4199 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4200 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4201 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4202 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4203 (((class color) (min-colors 8) (background dark)))))
4204 "Face used for tables."
4205 :group 'org-faces)
4206
4207 (defface org-formula
4208 (org-compatible-face nil
4209 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4210 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4211 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4212 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4213 (t (:bold t :italic t))))
4214 "Face for formulas."
4215 :group 'org-faces)
4216
4217 (defface org-code
4218 (org-compatible-face nil
4219 '((((class color grayscale) (min-colors 88) (background light))
4220 (:foreground "grey50"))
4221 (((class color grayscale) (min-colors 88) (background dark))
4222 (:foreground "grey70"))
4223 (((class color) (min-colors 8) (background light))
4224 (:foreground "green"))
4225 (((class color) (min-colors 8) (background dark))
4226 (:foreground "yellow"))))
4227 "Face for fixed-with text like code snippets."
4228 :group 'org-faces
4229 :version "22.1")
4230
4231 (defface org-verbatim
4232 (org-compatible-face nil
4233 '((((class color grayscale) (min-colors 88) (background light))
4234 (:foreground "grey50" :underline t))
4235 (((class color grayscale) (min-colors 88) (background dark))
4236 (:foreground "grey70" :underline t))
4237 (((class color) (min-colors 8) (background light))
4238 (:foreground "green" :underline t))
4239 (((class color) (min-colors 8) (background dark))
4240 (:foreground "yellow" :underline t))))
4241 "Face for fixed-with text like code snippets."
4242 :group 'org-faces
4243 :version "22.1")
4244
4245 (defface org-agenda-structure ;; font-lock-function-name-face
4246 (org-compatible-face nil
4247 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4248 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4249 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4250 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4251 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4252 (t (:bold t))))
4253 "Face used in agenda for captions and dates."
4254 :group 'org-faces)
4255
4256 (defface org-scheduled-today
4257 (org-compatible-face nil
4258 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4259 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4260 (((class color) (min-colors 8)) (:foreground "green"))
4261 (t (:bold t :italic t))))
4262 "Face for items scheduled for a certain day."
4263 :group 'org-faces)
4264
4265 (defface org-scheduled-previously
4266 (org-compatible-face nil
4267 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4268 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4269 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4270 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4271 (t (:bold t))))
4272 "Face for items scheduled previously, and not yet done."
4273 :group 'org-faces)
4274
4275 (defface org-upcoming-deadline
4276 (org-compatible-face nil
4277 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4278 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4279 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4280 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4281 (t (:bold t))))
4282 "Face for items scheduled previously, and not yet done."
4283 :group 'org-faces)
4284
4285 (defcustom org-agenda-deadline-faces
4286 '((1.0 . org-warning)
4287 (0.5 . org-upcoming-deadline)
4288 (0.0 . default))
4289 "Faces for showing deadlines in the agenda.
4290 This is a list of cons cells. The cdr of each cell is a face to be used,
4291 and it can also just be like '(:foreground \"yellow\").
4292 Each car is a fraction of the head-warning time that must have passed for
4293 this the face in the cdr to be used for display. The numbers must be
4294 given in descending order. The head-warning time is normally taken
4295 from `org-deadline-warning-days', but can also be specified in the deadline
4296 timestamp itself, like this:
4297
4298 DEADLINE: <2007-08-13 Mon -8d>
4299
4300 You may use d for days, w for weeks, m for months and y for years. Months
4301 and years will only be treated in an approximate fashion (30.4 days for a
4302 month and 365.24 days for a year)."
4303 :group 'org-faces
4304 :group 'org-agenda-daily/weekly
4305 :type '(repeat
4306 (cons
4307 (number :tag "Fraction of head-warning time passed")
4308 (sexp :tag "Face"))))
4309
4310 ;; FIXME: this is not a good face yet.
4311 (defface org-agenda-restriction-lock
4312 (org-compatible-face nil
4313 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4314 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4315 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4316 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4317 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4318 (t (:inverse-video t))))
4319 "Face for showing the agenda restriction lock."
4320 :group 'org-faces)
4321
4322 (defface org-time-grid ;; font-lock-variable-name-face
4323 (org-compatible-face nil
4324 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4325 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4326 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4327 "Face used for time grids."
4328 :group 'org-faces)
4329
4330 (defconst org-level-faces
4331 '(org-level-1 org-level-2 org-level-3 org-level-4
4332 org-level-5 org-level-6 org-level-7 org-level-8
4333 ))
4334
4335 (defcustom org-n-level-faces (length org-level-faces)
4336 "The number of different faces to be used for headlines.
4337 Org-mode defines 8 different headline faces, so this can be at most 8.
4338 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4339 :type 'number
4340 :group 'org-faces)
4341
4342 ;;; Variables from ther packages declared here to avoid compiler warnings
4343
4344 ;; XEmacs only
4345 (defvar outline-mode-menu-heading)
4346 (defvar outline-mode-menu-show)
4347 (defvar outline-mode-menu-hide)
4348 (defvar zmacs-regions) ; XEmacs regions
4349
4350 ;; Emacs only
4351 (defvar mark-active)
4352
4353 ;; Various packages
4354 ;; FIXME: get the argument lists for the UNKNOWN stuff
4355 (defvar calc-embedded-close-formula)
4356 (defvar calc-embedded-open-formula)
4357 (defvar calendar-mode-map)
4358 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4359 (defvar font-lock-unfontify-region-function)
4360 (defvar gnus-other-frame-object)
4361 (defvar gnus-group-name)
4362 (defvar gnus-article-current)
4363 (defvar Info-current-file)
4364 (defvar Info-current-node)
4365 (defvar mh-progs)
4366 (defvar mh-current-folder)
4367 (defvar mh-show-folder-buffer)
4368 (defvar mh-index-folder)
4369 (defvar mh-searcher)
4370
4371 (defvar remember-save-after-remembering)
4372 (defvar remember-data-file)
4373 (defvar remember-register)
4374 (defvar remember-buffer)
4375 (defvar remember-handler-functions)
4376 (defvar remember-annotation-functions)
4377 (defvar rmail-current-message)
4378 (defvar texmathp-why)
4379 (defvar vm-message-pointer)
4380 (defvar vm-folder-directory)
4381 (defvar w3m-current-url)
4382 (defvar w3m-current-title)
4383 ;; backward compatibility to old version of wl
4384 (defvar wl-summary-buffer-elmo-folder)
4385 (defvar wl-summary-buffer-folder-name)
4386
4387 (defvar org-latex-regexps)
4388 (defvar constants-unit-system)
4389
4390 ;;; Variables for pre-computed regular expressions, all buffer local
4391
4392 (defvar org-drawer-regexp nil
4393 "Matches first line of a hidden block.")
4394 (make-variable-buffer-local 'org-drawer-regexp)
4395 (defvar org-todo-regexp nil
4396 "Matches any of the TODO state keywords.")
4397 (make-variable-buffer-local 'org-todo-regexp)
4398 (defvar org-not-done-regexp nil
4399 "Matches any of the TODO state keywords except the last one.")
4400 (make-variable-buffer-local 'org-not-done-regexp)
4401 (defvar org-todo-line-regexp nil
4402 "Matches a headline and puts TODO state into group 2 if present.")
4403 (make-variable-buffer-local 'org-todo-line-regexp)
4404 (defvar org-complex-heading-regexp nil
4405 "Matches a headline and puts everything into groups:
4406 group 1: the stars
4407 group 2: The todo keyword, maybe
4408 group 3: Priority cookie
4409 group 4: True headline
4410 group 5: Tags")
4411 (make-variable-buffer-local 'org-complex-heading-regexp)
4412 (defvar org-todo-line-tags-regexp nil
4413 "Matches a headline and puts TODO state into group 2 if present.
4414 Also put tags into group 4 if tags are present.")
4415 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4416 (defvar org-nl-done-regexp nil
4417 "Matches newline followed by a headline with the DONE keyword.")
4418 (make-variable-buffer-local 'org-nl-done-regexp)
4419 (defvar org-looking-at-done-regexp nil
4420 "Matches the DONE keyword a point.")
4421 (make-variable-buffer-local 'org-looking-at-done-regexp)
4422 (defvar org-ds-keyword-length 12
4423 "Maximum length of the Deadline and SCHEDULED keywords.")
4424 (make-variable-buffer-local 'org-ds-keyword-length)
4425 (defvar org-deadline-regexp nil
4426 "Matches the DEADLINE keyword.")
4427 (make-variable-buffer-local 'org-deadline-regexp)
4428 (defvar org-deadline-time-regexp nil
4429 "Matches the DEADLINE keyword together with a time stamp.")
4430 (make-variable-buffer-local 'org-deadline-time-regexp)
4431 (defvar org-deadline-line-regexp nil
4432 "Matches the DEADLINE keyword and the rest of the line.")
4433 (make-variable-buffer-local 'org-deadline-line-regexp)
4434 (defvar org-scheduled-regexp nil
4435 "Matches the SCHEDULED keyword.")
4436 (make-variable-buffer-local 'org-scheduled-regexp)
4437 (defvar org-scheduled-time-regexp nil
4438 "Matches the SCHEDULED keyword together with a time stamp.")
4439 (make-variable-buffer-local 'org-scheduled-time-regexp)
4440 (defvar org-closed-time-regexp nil
4441 "Matches the CLOSED keyword together with a time stamp.")
4442 (make-variable-buffer-local 'org-closed-time-regexp)
4443
4444 (defvar org-keyword-time-regexp nil
4445 "Matches any of the 4 keywords, together with the time stamp.")
4446 (make-variable-buffer-local 'org-keyword-time-regexp)
4447 (defvar org-keyword-time-not-clock-regexp nil
4448 "Matches any of the 3 keywords, together with the time stamp.")
4449 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4450 (defvar org-maybe-keyword-time-regexp nil
4451 "Matches a timestamp, possibly preceeded by a keyword.")
4452 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4453 (defvar org-planning-or-clock-line-re nil
4454 "Matches a line with planning or clock info.")
4455 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4456
4457 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4458 rear-nonsticky t mouse-map t fontified t)
4459 "Properties to remove when a string without properties is wanted.")
4460
4461 (defsubst org-match-string-no-properties (num &optional string)
4462 (if (featurep 'xemacs)
4463 (let ((s (match-string num string)))
4464 (remove-text-properties 0 (length s) org-rm-props s)
4465 s)
4466 (match-string-no-properties num string)))
4467
4468 (defsubst org-no-properties (s)
4469 (if (fboundp 'set-text-properties)
4470 (set-text-properties 0 (length s) nil s)
4471 (remove-text-properties 0 (length s) org-rm-props s))
4472 s)
4473
4474 (defsubst org-get-alist-option (option key)
4475 (cond ((eq key t) t)
4476 ((eq option t) t)
4477 ((assoc key option) (cdr (assoc key option)))
4478 (t (cdr (assq 'default option)))))
4479
4480 (defsubst org-inhibit-invisibility ()
4481 "Modified `buffer-invisibility-spec' for Emacs 21.
4482 Some ops with invisible text do not work correctly on Emacs 21. For these
4483 we turn off invisibility temporarily. Use this in a `let' form."
4484 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4485
4486 (defsubst org-set-local (var value)
4487 "Make VAR local in current buffer and set it to VALUE."
4488 (set (make-variable-buffer-local var) value))
4489
4490 (defsubst org-mode-p ()
4491 "Check if the current buffer is in Org-mode."
4492 (eq major-mode 'org-mode))
4493
4494 (defsubst org-last (list)
4495 "Return the last element of LIST."
4496 (car (last list)))
4497
4498 (defun org-let (list &rest body)
4499 (eval (cons 'let (cons list body))))
4500 (put 'org-let 'lisp-indent-function 1)
4501
4502 (defun org-let2 (list1 list2 &rest body)
4503 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4504 (put 'org-let2 'lisp-indent-function 2)
4505 (defconst org-startup-options
4506 '(("fold" org-startup-folded t)
4507 ("overview" org-startup-folded t)
4508 ("nofold" org-startup-folded nil)
4509 ("showall" org-startup-folded nil)
4510 ("content" org-startup-folded content)
4511 ("hidestars" org-hide-leading-stars t)
4512 ("showstars" org-hide-leading-stars nil)
4513 ("odd" org-odd-levels-only t)
4514 ("oddeven" org-odd-levels-only nil)
4515 ("align" org-startup-align-all-tables t)
4516 ("noalign" org-startup-align-all-tables nil)
4517 ("customtime" org-display-custom-times t)
4518 ("logdone" org-log-done time)
4519 ("lognotedone" org-log-done note)
4520 ("nologdone" org-log-done nil)
4521 ("lognoteclock-out" org-log-note-clock-out t)
4522 ("nolognoteclock-out" org-log-note-clock-out nil)
4523 ("logrepeat" org-log-repeat state)
4524 ("lognoterepeat" org-log-repeat note)
4525 ("nologrepeat" org-log-repeat nil)
4526 ("constcgs" constants-unit-system cgs)
4527 ("constSI" constants-unit-system SI))
4528 "Variable associated with STARTUP options for org-mode.
4529 Each element is a list of three items: The startup options as written
4530 in the #+STARTUP line, the corresponding variable, and the value to
4531 set this variable to if the option is found. An optional forth element PUSH
4532 means to push this value onto the list in the variable.")
4533
4534 (defun org-set-regexps-and-options ()
4535 "Precompute regular expressions for current buffer."
4536 (when (org-mode-p)
4537 (org-set-local 'org-todo-kwd-alist nil)
4538 (org-set-local 'org-todo-key-alist nil)
4539 (org-set-local 'org-todo-key-trigger nil)
4540 (org-set-local 'org-todo-keywords-1 nil)
4541 (org-set-local 'org-done-keywords nil)
4542 (org-set-local 'org-todo-heads nil)
4543 (org-set-local 'org-todo-sets nil)
4544 (org-set-local 'org-todo-log-states nil)
4545 (let ((re (org-make-options-regexp
4546 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4547 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4548 "CONSTANTS" "PROPERTY" "DRAWERS")))
4549 (splitre "[ \t]+")
4550 kwds kws0 kwsa key log value cat arch tags const links hw dws
4551 tail sep kws1 prio props drawers)
4552 (save-excursion
4553 (save-restriction
4554 (widen)
4555 (goto-char (point-min))
4556 (while (re-search-forward re nil t)
4557 (setq key (match-string 1) value (org-match-string-no-properties 2))
4558 (cond
4559 ((equal key "CATEGORY")
4560 (if (string-match "[ \t]+$" value)
4561 (setq value (replace-match "" t t value)))
4562 (setq cat value))
4563 ((member key '("SEQ_TODO" "TODO"))
4564 (push (cons 'sequence (org-split-string value splitre)) kwds))
4565 ((equal key "TYP_TODO")
4566 (push (cons 'type (org-split-string value splitre)) kwds))
4567 ((equal key "TAGS")
4568 (setq tags (append tags (org-split-string value splitre))))
4569 ((equal key "COLUMNS")
4570 (org-set-local 'org-columns-default-format value))
4571 ((equal key "LINK")
4572 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4573 (push (cons (match-string 1 value)
4574 (org-trim (match-string 2 value)))
4575 links)))
4576 ((equal key "PRIORITIES")
4577 (setq prio (org-split-string value " +")))
4578 ((equal key "PROPERTY")
4579 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4580 (push (cons (match-string 1 value) (match-string 2 value))
4581 props)))
4582 ((equal key "DRAWERS")
4583 (setq drawers (org-split-string value splitre)))
4584 ((equal key "CONSTANTS")
4585 (setq const (append const (org-split-string value splitre))))
4586 ((equal key "STARTUP")
4587 (let ((opts (org-split-string value splitre))
4588 l var val)
4589 (while (setq l (pop opts))
4590 (when (setq l (assoc l org-startup-options))
4591 (setq var (nth 1 l) val (nth 2 l))
4592 (if (not (nth 3 l))
4593 (set (make-local-variable var) val)
4594 (if (not (listp (symbol-value var)))
4595 (set (make-local-variable var) nil))
4596 (set (make-local-variable var) (symbol-value var))
4597 (add-to-list var val))))))
4598 ((equal key "ARCHIVE")
4599 (string-match " *$" value)
4600 (setq arch (replace-match "" t t value))
4601 (remove-text-properties 0 (length arch)
4602 '(face t fontified t) arch)))
4603 )))
4604 (when cat
4605 (org-set-local 'org-category (intern cat))
4606 (push (cons "CATEGORY" cat) props))
4607 (when prio
4608 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4609 (setq prio (mapcar 'string-to-char prio))
4610 (org-set-local 'org-highest-priority (nth 0 prio))
4611 (org-set-local 'org-lowest-priority (nth 1 prio))
4612 (org-set-local 'org-default-priority (nth 2 prio)))
4613 (and props (org-set-local 'org-local-properties (nreverse props)))
4614 (and drawers (org-set-local 'org-drawers drawers))
4615 (and arch (org-set-local 'org-archive-location arch))
4616 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4617 ;; Process the TODO keywords
4618 (unless kwds
4619 ;; Use the global values as if they had been given locally.
4620 (setq kwds (default-value 'org-todo-keywords))
4621 (if (stringp (car kwds))
4622 (setq kwds (list (cons org-todo-interpretation
4623 (default-value 'org-todo-keywords)))))
4624 (setq kwds (reverse kwds)))
4625 (setq kwds (nreverse kwds))
4626 (let (inter kws kw)
4627 (while (setq kws (pop kwds))
4628 (setq inter (pop kws) sep (member "|" kws)
4629 kws0 (delete "|" (copy-sequence kws))
4630 kwsa nil
4631 kws1 (mapcar
4632 (lambda (x)
4633 ;; 1 2
4634 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4635 (progn
4636 (setq kw (match-string 1 x)
4637 key (and (match-end 2) (match-string 2 x))
4638 log (org-extract-log-state-settings x))
4639 (push (cons kw (and key (string-to-char key))) kwsa)
4640 (and log (push log org-todo-log-states))
4641 kw)
4642 (error "Invalid TODO keyword %s" x)))
4643 kws0)
4644 kwsa (if kwsa (append '((:startgroup))
4645 (nreverse kwsa)
4646 '((:endgroup))))
4647 hw (car kws1)
4648 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4649 tail (list inter hw (car dws) (org-last dws)))
4650 (add-to-list 'org-todo-heads hw 'append)
4651 (push kws1 org-todo-sets)
4652 (setq org-done-keywords (append org-done-keywords dws nil))
4653 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4654 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4655 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4656 (setq org-todo-sets (nreverse org-todo-sets)
4657 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4658 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4659 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4660 ;; Process the constants
4661 (when const
4662 (let (e cst)
4663 (while (setq e (pop const))
4664 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4665 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4666 (setq org-table-formula-constants-local cst)))
4667
4668 ;; Process the tags.
4669 (when tags
4670 (let (e tgs)
4671 (while (setq e (pop tags))
4672 (cond
4673 ((equal e "{") (push '(:startgroup) tgs))
4674 ((equal e "}") (push '(:endgroup) tgs))
4675 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4676 (push (cons (match-string 1 e)
4677 (string-to-char (match-string 2 e)))
4678 tgs))
4679 (t (push (list e) tgs))))
4680 (org-set-local 'org-tag-alist nil)
4681 (while (setq e (pop tgs))
4682 (or (and (stringp (car e))
4683 (assoc (car e) org-tag-alist))
4684 (push e org-tag-alist))))))
4685
4686 ;; Compute the regular expressions and other local variables
4687 (if (not org-done-keywords)
4688 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4689 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4690 (length org-scheduled-string)))
4691 org-drawer-regexp
4692 (concat "^[ \t]*:\\("
4693 (mapconcat 'regexp-quote org-drawers "\\|")
4694 "\\):[ \t]*$")
4695 org-not-done-keywords
4696 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4697 org-todo-regexp
4698 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4699 "\\|") "\\)\\>")
4700 org-not-done-regexp
4701 (concat "\\<\\("
4702 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4703 "\\)\\>")
4704 org-todo-line-regexp
4705 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4706 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4707 "\\)\\>\\)?[ \t]*\\(.*\\)")
4708 org-complex-heading-regexp
4709 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4710 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4711 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4712 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4713 org-nl-done-regexp
4714 (concat "\n\\*+[ \t]+"
4715 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4716 "\\)" "\\>")
4717 org-todo-line-tags-regexp
4718 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4719 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4720 (org-re
4721 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4722 org-looking-at-done-regexp
4723 (concat "^" "\\(?:"
4724 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4725 "\\>")
4726 org-deadline-regexp (concat "\\<" org-deadline-string)
4727 org-deadline-time-regexp
4728 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4729 org-deadline-line-regexp
4730 (concat "\\<\\(" org-deadline-string "\\).*")
4731 org-scheduled-regexp
4732 (concat "\\<" org-scheduled-string)
4733 org-scheduled-time-regexp
4734 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4735 org-closed-time-regexp
4736 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4737 org-keyword-time-regexp
4738 (concat "\\<\\(" org-scheduled-string
4739 "\\|" org-deadline-string
4740 "\\|" org-closed-string
4741 "\\|" org-clock-string "\\)"
4742 " *[[<]\\([^]>]+\\)[]>]")
4743 org-keyword-time-not-clock-regexp
4744 (concat "\\<\\(" org-scheduled-string
4745 "\\|" org-deadline-string
4746 "\\|" org-closed-string
4747 "\\)"
4748 " *[[<]\\([^]>]+\\)[]>]")
4749 org-maybe-keyword-time-regexp
4750 (concat "\\(\\<\\(" org-scheduled-string
4751 "\\|" org-deadline-string
4752 "\\|" org-closed-string
4753 "\\|" org-clock-string "\\)\\)?"
4754 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4755 org-planning-or-clock-line-re
4756 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4757 "\\|" org-deadline-string
4758 "\\|" org-closed-string "\\|" org-clock-string
4759 "\\)\\>\\)")
4760 )
4761 (org-compute-latex-and-specials-regexp)
4762 (org-set-font-lock-defaults)))
4763
4764 (defun org-extract-log-state-settings (x)
4765 "Extract the log state setting from a TODO keyword string.
4766 This will extract info from a string like \"WAIT(w@/!)\"."
4767 (let (kw key log1 log2)
4768 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4769 (setq kw (match-string 1 x)
4770 key (and (match-end 2) (match-string 2 x))
4771 log1 (and (match-end 3) (match-string 3 x))
4772 log2 (and (match-end 4) (match-string 4 x)))
4773 (and (or log1 log2)
4774 (list kw
4775 (and log1 (if (equal log1 "!") 'time 'note))
4776 (and log2 (if (equal log2 "!") 'time 'note)))))))
4777
4778 (defun org-remove-keyword-keys (list)
4779 "Remove a pair of parenthesis at the end of each string in LIST."
4780 (mapcar (lambda (x)
4781 (if (string-match "(.*)$" x)
4782 (substring x 0 (match-beginning 0))
4783 x))
4784 list))
4785
4786 ;; FIXME: this could be done much better, using second characters etc.
4787 (defun org-assign-fast-keys (alist)
4788 "Assign fast keys to a keyword-key alist.
4789 Respect keys that are already there."
4790 (let (new e k c c1 c2 (char ?a))
4791 (while (setq e (pop alist))
4792 (cond
4793 ((equal e '(:startgroup)) (push e new))
4794 ((equal e '(:endgroup)) (push e new))
4795 (t
4796 (setq k (car e) c2 nil)
4797 (if (cdr e)
4798 (setq c (cdr e))
4799 ;; automatically assign a character.
4800 (setq c1 (string-to-char
4801 (downcase (substring
4802 k (if (= (string-to-char k) ?@) 1 0)))))
4803 (if (or (rassoc c1 new) (rassoc c1 alist))
4804 (while (or (rassoc char new) (rassoc char alist))
4805 (setq char (1+ char)))
4806 (setq c2 c1))
4807 (setq c (or c2 char)))
4808 (push (cons k c) new))))
4809 (nreverse new)))
4810
4811 ;;; Some variables ujsed in various places
4812
4813 (defvar org-window-configuration nil
4814 "Used in various places to store a window configuration.")
4815 (defvar org-finish-function nil
4816 "Function to be called when `C-c C-c' is used.
4817 This is for getting out of special buffers like remember.")
4818
4819
4820 ;; FIXME: Occasionally check by commenting these, to make sure
4821 ;; no other functions uses these, forgetting to let-bind them.
4822 (defvar entry)
4823 (defvar state)
4824 (defvar last-state)
4825 (defvar date)
4826 (defvar description)
4827
4828 ;; Defined somewhere in this file, but used before definition.
4829 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4830 (defvar org-agenda-buffer-name)
4831 (defvar org-agenda-undo-list)
4832 (defvar org-agenda-pending-undo-list)
4833 (defvar org-agenda-overriding-header)
4834 (defvar orgtbl-mode)
4835 (defvar org-html-entities)
4836 (defvar org-struct-menu)
4837 (defvar org-org-menu)
4838 (defvar org-tbl-menu)
4839 (defvar org-agenda-keymap)
4840
4841 ;;;; Emacs/XEmacs compatibility
4842
4843 ;; Overlay compatibility functions
4844 (defun org-make-overlay (beg end &optional buffer)
4845 (if (featurep 'xemacs)
4846 (make-extent beg end buffer)
4847 (make-overlay beg end buffer)))
4848 (defun org-delete-overlay (ovl)
4849 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4850 (defun org-detach-overlay (ovl)
4851 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4852 (defun org-move-overlay (ovl beg end &optional buffer)
4853 (if (featurep 'xemacs)
4854 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4855 (move-overlay ovl beg end buffer)))
4856 (defun org-overlay-put (ovl prop value)
4857 (if (featurep 'xemacs)
4858 (set-extent-property ovl prop value)
4859 (overlay-put ovl prop value)))
4860 (defun org-overlay-display (ovl text &optional face evap)
4861 "Make overlay OVL display TEXT with face FACE."
4862 (if (featurep 'xemacs)
4863 (let ((gl (make-glyph text)))
4864 (and face (set-glyph-face gl face))
4865 (set-extent-property ovl 'invisible t)
4866 (set-extent-property ovl 'end-glyph gl))
4867 (overlay-put ovl 'display text)
4868 (if face (overlay-put ovl 'face face))
4869 (if evap (overlay-put ovl 'evaporate t))))
4870 (defun org-overlay-before-string (ovl text &optional face evap)
4871 "Make overlay OVL display TEXT with face FACE."
4872 (if (featurep 'xemacs)
4873 (let ((gl (make-glyph text)))
4874 (and face (set-glyph-face gl face))
4875 (set-extent-property ovl 'begin-glyph gl))
4876 (if face (org-add-props text nil 'face face))
4877 (overlay-put ovl 'before-string text)
4878 (if evap (overlay-put ovl 'evaporate t))))
4879 (defun org-overlay-get (ovl prop)
4880 (if (featurep 'xemacs)
4881 (extent-property ovl prop)
4882 (overlay-get ovl prop)))
4883 (defun org-overlays-at (pos)
4884 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4885 (defun org-overlays-in (&optional start end)
4886 (if (featurep 'xemacs)
4887 (extent-list nil start end)
4888 (overlays-in start end)))
4889 (defun org-overlay-start (o)
4890 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4891 (defun org-overlay-end (o)
4892 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4893 (defun org-find-overlays (prop &optional pos delete)
4894 "Find all overlays specifying PROP at POS or point.
4895 If DELETE is non-nil, delete all those overlays."
4896 (let ((overlays (org-overlays-at (or pos (point))))
4897 ov found)
4898 (while (setq ov (pop overlays))
4899 (if (org-overlay-get ov prop)
4900 (if delete (org-delete-overlay ov) (push ov found))))
4901 found))
4902
4903 ;; Region compatibility
4904
4905 (defun org-add-hook (hook function &optional append local)
4906 "Add-hook, compatible with both Emacsen."
4907 (if (and local (featurep 'xemacs))
4908 (add-local-hook hook function append)
4909 (add-hook hook function append local)))
4910
4911 (defvar org-ignore-region nil
4912 "To temporarily disable the active region.")
4913
4914 (defun org-region-active-p ()
4915 "Is `transient-mark-mode' on and the region active?
4916 Works on both Emacs and XEmacs."
4917 (if org-ignore-region
4918 nil
4919 (if (featurep 'xemacs)
4920 (and zmacs-regions (region-active-p))
4921 (if (fboundp 'use-region-p)
4922 (use-region-p)
4923 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4924
4925 ;; Invisibility compatibility
4926
4927 (defun org-add-to-invisibility-spec (arg)
4928 "Add elements to `buffer-invisibility-spec'.
4929 See documentation for `buffer-invisibility-spec' for the kind of elements
4930 that can be added."
4931 (cond
4932 ((fboundp 'add-to-invisibility-spec)
4933 (add-to-invisibility-spec arg))
4934 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4935 (setq buffer-invisibility-spec (list arg)))
4936 (t
4937 (setq buffer-invisibility-spec
4938 (cons arg buffer-invisibility-spec)))))
4939
4940 (defun org-remove-from-invisibility-spec (arg)
4941 "Remove elements from `buffer-invisibility-spec'."
4942 (if (fboundp 'remove-from-invisibility-spec)
4943 (remove-from-invisibility-spec arg)
4944 (if (consp buffer-invisibility-spec)
4945 (setq buffer-invisibility-spec
4946 (delete arg buffer-invisibility-spec)))))
4947
4948 (defun org-in-invisibility-spec-p (arg)
4949 "Is ARG a member of `buffer-invisibility-spec'?"
4950 (if (consp buffer-invisibility-spec)
4951 (member arg buffer-invisibility-spec)
4952 nil))
4953
4954 ;;;; Define the Org-mode
4955
4956 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4957 (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."))
4958
4959
4960 ;; We use a before-change function to check if a table might need
4961 ;; an update.
4962 (defvar org-table-may-need-update t
4963 "Indicates that a table might need an update.
4964 This variable is set by `org-before-change-function'.
4965 `org-table-align' sets it back to nil.")
4966 (defvar org-mode-map)
4967 (defvar org-mode-hook nil)
4968 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4969 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4970 (defvar org-table-buffer-is-an nil)
4971 (defconst org-outline-regexp "\\*+ ")
4972
4973 ;;;###autoload
4974 (define-derived-mode org-mode outline-mode "Org"
4975 "Outline-based notes management and organizer, alias
4976 \"Carsten's outline-mode for keeping track of everything.\"
4977
4978 Org-mode develops organizational tasks around a NOTES file which
4979 contains information about projects as plain text. Org-mode is
4980 implemented on top of outline-mode, which is ideal to keep the content
4981 of large files well structured. It supports ToDo items, deadlines and
4982 time stamps, which magically appear in the diary listing of the Emacs
4983 calendar. Tables are easily created with a built-in table editor.
4984 Plain text URL-like links connect to websites, emails (VM), Usenet
4985 messages (Gnus), BBDB entries, and any files related to the project.
4986 For printing and sharing of notes, an Org-mode file (or a part of it)
4987 can be exported as a structured ASCII or HTML file.
4988
4989 The following commands are available:
4990
4991 \\{org-mode-map}"
4992
4993 ;; Get rid of Outline menus, they are not needed
4994 ;; Need to do this here because define-derived-mode sets up
4995 ;; the keymap so late. Still, it is a waste to call this each time
4996 ;; we switch another buffer into org-mode.
4997 (if (featurep 'xemacs)
4998 (when (boundp 'outline-mode-menu-heading)
4999 ;; Assume this is Greg's port, it used easymenu
5000 (easy-menu-remove outline-mode-menu-heading)
5001 (easy-menu-remove outline-mode-menu-show)
5002 (easy-menu-remove outline-mode-menu-hide))
5003 (define-key org-mode-map [menu-bar headings] 'undefined)
5004 (define-key org-mode-map [menu-bar hide] 'undefined)
5005 (define-key org-mode-map [menu-bar show] 'undefined))
5006
5007 (easy-menu-add org-org-menu)
5008 (easy-menu-add org-tbl-menu)
5009 (org-install-agenda-files-menu)
5010 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
5011 (org-add-to-invisibility-spec '(org-cwidth))
5012 (when (featurep 'xemacs)
5013 (org-set-local 'line-move-ignore-invisible t))
5014 (org-set-local 'outline-regexp org-outline-regexp)
5015 (org-set-local 'outline-level 'org-outline-level)
5016 (when (and org-ellipsis
5017 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5018 (fboundp 'make-glyph-code))
5019 (unless org-display-table
5020 (setq org-display-table (make-display-table)))
5021 (set-display-table-slot
5022 org-display-table 4
5023 (vconcat (mapcar
5024 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5025 org-ellipsis)))
5026 (if (stringp org-ellipsis) org-ellipsis "..."))))
5027 (setq buffer-display-table org-display-table))
5028 (org-set-regexps-and-options)
5029 ;; Calc embedded
5030 (org-set-local 'calc-embedded-open-mode "# ")
5031 (modify-syntax-entry ?# "<")
5032 (modify-syntax-entry ?@ "w")
5033 (if org-startup-truncated (setq truncate-lines t))
5034 (org-set-local 'font-lock-unfontify-region-function
5035 'org-unfontify-region)
5036 ;; Activate before-change-function
5037 (org-set-local 'org-table-may-need-update t)
5038 (org-add-hook 'before-change-functions 'org-before-change-function nil
5039 'local)
5040 ;; Check for running clock before killing a buffer
5041 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5042 ;; Paragraphs and auto-filling
5043 (org-set-autofill-regexps)
5044 (setq indent-line-function 'org-indent-line-function)
5045 (org-update-radio-target-regexp)
5046
5047 ;; Comment characters
5048 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
5049 (org-set-local 'comment-padding " ")
5050
5051 ;; Align options lines
5052 (org-set-local
5053 'align-mode-rules-list
5054 '((org-in-buffer-settings
5055 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5056 (modes . '(org-mode)))))
5057
5058 ;; Imenu
5059 (org-set-local 'imenu-create-index-function
5060 'org-imenu-get-tree)
5061
5062 ;; Make isearch reveal context
5063 (if (or (featurep 'xemacs)
5064 (not (boundp 'outline-isearch-open-invisible-function)))
5065 ;; Emacs 21 and XEmacs make use of the hook
5066 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5067 ;; Emacs 22 deals with this through a special variable
5068 (org-set-local 'outline-isearch-open-invisible-function
5069 (lambda (&rest ignore) (org-show-context 'isearch))))
5070
5071 ;; If empty file that did not turn on org-mode automatically, make it to.
5072 (if (and org-insert-mode-line-in-empty-file
5073 (interactive-p)
5074 (= (point-min) (point-max)))
5075 (insert "# -*- mode: org -*-\n\n"))
5076
5077 (unless org-inhibit-startup
5078 (when org-startup-align-all-tables
5079 (let ((bmp (buffer-modified-p)))
5080 (org-table-map-tables 'org-table-align)
5081 (set-buffer-modified-p bmp)))
5082 (org-cycle-hide-drawers 'all)
5083 (cond
5084 ((eq org-startup-folded t)
5085 (org-cycle '(4)))
5086 ((eq org-startup-folded 'content)
5087 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5088 (org-cycle '(4)) (org-cycle '(4)))))))
5089
5090 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5091
5092 (defsubst org-call-with-arg (command arg)
5093 "Call COMMAND interactively, but pretend prefix are was ARG."
5094 (let ((current-prefix-arg arg)) (call-interactively command)))
5095
5096 (defsubst org-current-line (&optional pos)
5097 (save-excursion
5098 (and pos (goto-char pos))
5099 ;; works also in narrowed buffer, because we start at 1, not point-min
5100 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
5101
5102 (defun org-current-time ()
5103 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5104 (if (> (car org-time-stamp-rounding-minutes) 1)
5105 (let ((r (car org-time-stamp-rounding-minutes))
5106 (time (decode-time)))
5107 (apply 'encode-time
5108 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5109 (nthcdr 2 time))))
5110 (current-time)))
5111
5112 (defun org-add-props (string plist &rest props)
5113 "Add text properties to entire string, from beginning to end.
5114 PLIST may be a list of properties, PROPS are individual properties and values
5115 that will be added to PLIST. Returns the string that was modified."
5116 (add-text-properties
5117 0 (length string) (if props (append plist props) plist) string)
5118 string)
5119 (put 'org-add-props 'lisp-indent-function 2)
5120
5121
5122 ;;;; Font-Lock stuff, including the activators
5123
5124 (defvar org-mouse-map (make-sparse-keymap))
5125 (org-defkey org-mouse-map
5126 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5127 (org-defkey org-mouse-map
5128 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5129 (when org-mouse-1-follows-link
5130 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5131 (when org-tab-follows-link
5132 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5133 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5134 (when org-return-follows-link
5135 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5136 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5137
5138 (require 'font-lock)
5139
5140 (defconst org-non-link-chars "]\t\n\r<>")
5141 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5142 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5143 (defvar org-link-re-with-space nil
5144 "Matches a link with spaces, optional angular brackets around it.")
5145 (defvar org-link-re-with-space2 nil
5146 "Matches a link with spaces, optional angular brackets around it.")
5147 (defvar org-angle-link-re nil
5148 "Matches link with angular brackets, spaces are allowed.")
5149 (defvar org-plain-link-re nil
5150 "Matches plain link, without spaces.")
5151 (defvar org-bracket-link-regexp nil
5152 "Matches a link in double brackets.")
5153 (defvar org-bracket-link-analytic-regexp nil
5154 "Regular expression used to analyze links.
5155 Here is what the match groups contain after a match:
5156 1: http:
5157 2: http
5158 3: path
5159 4: [desc]
5160 5: desc")
5161 (defvar org-any-link-re nil
5162 "Regular expression matching any link.")
5163
5164 (defun org-make-link-regexps ()
5165 "Update the link regular expressions.
5166 This should be called after the variable `org-link-types' has changed."
5167 (setq org-link-re-with-space
5168 (concat
5169 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5170 "\\([^" org-non-link-chars " ]"
5171 "[^" org-non-link-chars "]*"
5172 "[^" org-non-link-chars " ]\\)>?")
5173 org-link-re-with-space2
5174 (concat
5175 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5176 "\\([^" org-non-link-chars " ]"
5177 "[^]\t\n\r]*"
5178 "[^" org-non-link-chars " ]\\)>?")
5179 org-angle-link-re
5180 (concat
5181 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5182 "\\([^" org-non-link-chars " ]"
5183 "[^" org-non-link-chars "]*"
5184 "\\)>")
5185 org-plain-link-re
5186 (concat
5187 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5188 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5189 org-bracket-link-regexp
5190 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5191 org-bracket-link-analytic-regexp
5192 (concat
5193 "\\[\\["
5194 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5195 "\\([^]]+\\)"
5196 "\\]"
5197 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5198 "\\]")
5199 org-any-link-re
5200 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5201 org-angle-link-re "\\)\\|\\("
5202 org-plain-link-re "\\)")))
5203
5204 (org-make-link-regexps)
5205
5206 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5207 "Regular expression for fast time stamp matching.")
5208 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5209 "Regular expression for fast time stamp matching.")
5210 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5211 "Regular expression matching time strings for analysis.
5212 This one does not require the space after the date, so it can be used
5213 on a string that terminates immediately after the date.")
5214 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5215 "Regular expression matching time strings for analysis.")
5216 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5217 "Regular expression matching time stamps, with groups.")
5218 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5219 "Regular expression matching time stamps (also [..]), with groups.")
5220 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5221 "Regular expression matching a time stamp range.")
5222 (defconst org-tr-regexp-both
5223 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5224 "Regular expression matching a time stamp range.")
5225 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5226 org-ts-regexp "\\)?")
5227 "Regular expression matching a time stamp or time stamp range.")
5228 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5229 org-ts-regexp-both "\\)?")
5230 "Regular expression matching a time stamp or time stamp range.
5231 The time stamps may be either active or inactive.")
5232
5233 (defvar org-emph-face nil)
5234
5235 (defun org-do-emphasis-faces (limit)
5236 "Run through the buffer and add overlays to links."
5237 (let (rtn)
5238 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5239 (if (not (= (char-after (match-beginning 3))
5240 (char-after (match-beginning 4))))
5241 (progn
5242 (setq rtn t)
5243 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5244 'face
5245 (nth 1 (assoc (match-string 3)
5246 org-emphasis-alist)))
5247 (add-text-properties (match-beginning 2) (match-end 2)
5248 '(font-lock-multiline t))
5249 (when org-hide-emphasis-markers
5250 (add-text-properties (match-end 4) (match-beginning 5)
5251 '(invisible org-link))
5252 (add-text-properties (match-beginning 3) (match-end 3)
5253 '(invisible org-link)))))
5254 (backward-char 1))
5255 rtn))
5256
5257 (defun org-emphasize (&optional char)
5258 "Insert or change an emphasis, i.e. a font like bold or italic.
5259 If there is an active region, change that region to a new emphasis.
5260 If there is no region, just insert the marker characters and position
5261 the cursor between them.
5262 CHAR should be either the marker character, or the first character of the
5263 HTML tag associated with that emphasis. If CHAR is a space, the means
5264 to remove the emphasis of the selected region.
5265 If char is not given (for example in an interactive call) it
5266 will be prompted for."
5267 (interactive)
5268 (let ((eal org-emphasis-alist) e det
5269 (erc org-emphasis-regexp-components)
5270 (prompt "")
5271 (string "") beg end move tag c s)
5272 (if (org-region-active-p)
5273 (setq beg (region-beginning) end (region-end)
5274 string (buffer-substring beg end))
5275 (setq move t))
5276
5277 (while (setq e (pop eal))
5278 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5279 c (aref tag 0))
5280 (push (cons c (string-to-char (car e))) det)
5281 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5282 (substring tag 1)))))
5283 (unless char
5284 (message "%s" (concat "Emphasis marker or tag:" prompt))
5285 (setq char (read-char-exclusive)))
5286 (setq char (or (cdr (assoc char det)) char))
5287 (if (equal char ?\ )
5288 (setq s "" move nil)
5289 (unless (assoc (char-to-string char) org-emphasis-alist)
5290 (error "No such emphasis marker: \"%c\"" char))
5291 (setq s (char-to-string char)))
5292 (while (and (> (length string) 1)
5293 (equal (substring string 0 1) (substring string -1))
5294 (assoc (substring string 0 1) org-emphasis-alist))
5295 (setq string (substring string 1 -1)))
5296 (setq string (concat s string s))
5297 (if beg (delete-region beg end))
5298 (unless (or (bolp)
5299 (string-match (concat "[" (nth 0 erc) "\n]")
5300 (char-to-string (char-before (point)))))
5301 (insert " "))
5302 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5303 (char-to-string (char-after (point))))
5304 (insert " ") (backward-char 1))
5305 (insert string)
5306 (and move (backward-char 1))))
5307
5308 (defconst org-nonsticky-props
5309 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5310
5311
5312 (defun org-activate-plain-links (limit)
5313 "Run through the buffer and add overlays to links."
5314 (catch 'exit
5315 (let (f)
5316 (while (re-search-forward org-plain-link-re limit t)
5317 (setq f (get-text-property (match-beginning 0) 'face))
5318 (if (or (eq f 'org-tag)
5319 (and (listp f) (memq 'org-tag f)))
5320 nil
5321 (add-text-properties (match-beginning 0) (match-end 0)
5322 (list 'mouse-face 'highlight
5323 'rear-nonsticky org-nonsticky-props
5324 'keymap org-mouse-map
5325 ))
5326 (throw 'exit t))))))
5327
5328 (defun org-activate-code (limit)
5329 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5330 (unless (get-text-property (match-beginning 1) 'face)
5331 (remove-text-properties (match-beginning 0) (match-end 0)
5332 '(display t invisible t intangible t))
5333 t)))
5334
5335 (defun org-activate-angle-links (limit)
5336 "Run through the buffer and add overlays to links."
5337 (if (re-search-forward org-angle-link-re limit t)
5338 (progn
5339 (add-text-properties (match-beginning 0) (match-end 0)
5340 (list 'mouse-face 'highlight
5341 'rear-nonsticky org-nonsticky-props
5342 'keymap org-mouse-map
5343 ))
5344 t)))
5345
5346 (defmacro org-maybe-intangible (props)
5347 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5348 In emacs 21, invisible text is not avoided by the command loop, so the
5349 intangible property is needed to make sure point skips this text.
5350 In Emacs 22, this is not necessary. The intangible text property has
5351 led to problems with flyspell. These problems are fixed in flyspell.el,
5352 but we still avoid setting the property in Emacs 22 and later.
5353 We use a macro so that the test can happen at compilation time."
5354 (if (< emacs-major-version 22)
5355 `(append '(intangible t) ,props)
5356 props))
5357
5358 (defun org-activate-bracket-links (limit)
5359 "Run through the buffer and add overlays to bracketed links."
5360 (if (re-search-forward org-bracket-link-regexp limit t)
5361 (let* ((help (concat "LINK: "
5362 (org-match-string-no-properties 1)))
5363 ;; FIXME: above we should remove the escapes.
5364 ;; but that requires another match, protecting match data,
5365 ;; a lot of overhead for font-lock.
5366 (ip (org-maybe-intangible
5367 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5368 'keymap org-mouse-map 'mouse-face 'highlight
5369 'font-lock-multiline t 'help-echo help)))
5370 (vp (list 'rear-nonsticky org-nonsticky-props
5371 'keymap org-mouse-map 'mouse-face 'highlight
5372 ' font-lock-multiline t 'help-echo help)))
5373 ;; We need to remove the invisible property here. Table narrowing
5374 ;; may have made some of this invisible.
5375 (remove-text-properties (match-beginning 0) (match-end 0)
5376 '(invisible nil))
5377 (if (match-end 3)
5378 (progn
5379 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5380 (add-text-properties (match-beginning 3) (match-end 3) vp)
5381 (add-text-properties (match-end 3) (match-end 0) ip))
5382 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5383 (add-text-properties (match-beginning 1) (match-end 1) vp)
5384 (add-text-properties (match-end 1) (match-end 0) ip))
5385 t)))
5386
5387 (defun org-activate-dates (limit)
5388 "Run through the buffer and add overlays to dates."
5389 (if (re-search-forward org-tsr-regexp-both limit t)
5390 (progn
5391 (add-text-properties (match-beginning 0) (match-end 0)
5392 (list 'mouse-face 'highlight
5393 'rear-nonsticky org-nonsticky-props
5394 'keymap org-mouse-map))
5395 (when org-display-custom-times
5396 (if (match-end 3)
5397 (org-display-custom-time (match-beginning 3) (match-end 3)))
5398 (org-display-custom-time (match-beginning 1) (match-end 1)))
5399 t)))
5400
5401 (defvar org-target-link-regexp nil
5402 "Regular expression matching radio targets in plain text.")
5403 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5404 "Regular expression matching a link target.")
5405 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5406 "Regular expression matching a radio target.")
5407 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5408 "Regular expression matching any target.")
5409
5410 (defun org-activate-target-links (limit)
5411 "Run through the buffer and add overlays to target matches."
5412 (when org-target-link-regexp
5413 (let ((case-fold-search t))
5414 (if (re-search-forward org-target-link-regexp limit t)
5415 (progn
5416 (add-text-properties (match-beginning 0) (match-end 0)
5417 (list 'mouse-face 'highlight
5418 'rear-nonsticky org-nonsticky-props
5419 'keymap org-mouse-map
5420 'help-echo "Radio target link"
5421 'org-linked-text t))
5422 t)))))
5423
5424 (defun org-update-radio-target-regexp ()
5425 "Find all radio targets in this file and update the regular expression."
5426 (interactive)
5427 (when (memq 'radio org-activate-links)
5428 (setq org-target-link-regexp
5429 (org-make-target-link-regexp (org-all-targets 'radio)))
5430 (org-restart-font-lock)))
5431
5432 (defun org-hide-wide-columns (limit)
5433 (let (s e)
5434 (setq s (text-property-any (point) (or limit (point-max))
5435 'org-cwidth t))
5436 (when s
5437 (setq e (next-single-property-change s 'org-cwidth))
5438 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5439 (goto-char e)
5440 t)))
5441
5442 (defvar org-latex-and-specials-regexp nil
5443 "Regular expression for highlighting export special stuff.")
5444 (defvar org-match-substring-regexp)
5445 (defvar org-match-substring-with-braces-regexp)
5446 (defvar org-export-html-special-string-regexps)
5447
5448 (defun org-compute-latex-and-specials-regexp ()
5449 "Compute regular expression for stuff treated specially by exporters."
5450 (if (not org-highlight-latex-fragments-and-specials)
5451 (org-set-local 'org-latex-and-specials-regexp nil)
5452 (let*
5453 ((matchers (plist-get org-format-latex-options :matchers))
5454 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5455 org-latex-regexps)))
5456 (options (org-combine-plists (org-default-export-plist)
5457 (org-infile-export-plist)))
5458 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5459 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5460 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5461 (org-export-html-expand (plist-get options :expand-quoted-html))
5462 (org-export-with-special-strings (plist-get options :special-strings))
5463 (re-sub
5464 (cond
5465 ((equal org-export-with-sub-superscripts '{})
5466 (list org-match-substring-with-braces-regexp))
5467 (org-export-with-sub-superscripts
5468 (list org-match-substring-regexp))
5469 (t nil)))
5470 (re-latex
5471 (if org-export-with-LaTeX-fragments
5472 (mapcar (lambda (x) (nth 1 x)) latexs)))
5473 (re-macros
5474 (if org-export-with-TeX-macros
5475 (list (concat "\\\\"
5476 (regexp-opt
5477 (append (mapcar 'car org-html-entities)
5478 (if (boundp 'org-latex-entities)
5479 org-latex-entities nil))
5480 'words))) ; FIXME
5481 ))
5482 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5483 (re-special (if org-export-with-special-strings
5484 (mapcar (lambda (x) (car x))
5485 org-export-html-special-string-regexps)))
5486 (re-rest
5487 (delq nil
5488 (list
5489 (if org-export-html-expand "@<[^>\n]+>")
5490 ))))
5491 (org-set-local
5492 'org-latex-and-specials-regexp
5493 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5494 re-rest) "\\|")))))
5495
5496 (defface org-latex-and-export-specials
5497 (let ((font (cond ((assq :inherit custom-face-attributes)
5498 '(:inherit underline))
5499 (t '(:underline t)))))
5500 `((((class grayscale) (background light))
5501 (:foreground "DimGray" ,@font))
5502 (((class grayscale) (background dark))
5503 (:foreground "LightGray" ,@font))
5504 (((class color) (background light))
5505 (:foreground "SaddleBrown"))
5506 (((class color) (background dark))
5507 (:foreground "burlywood"))
5508 (t (,@font))))
5509 "Face used to highlight math latex and other special exporter stuff."
5510 :group 'org-faces)
5511
5512 (defun org-do-latex-and-special-faces (limit)
5513 "Run through the buffer and add overlays to links."
5514 (when org-latex-and-specials-regexp
5515 (let (rtn d)
5516 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5517 limit t))
5518 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5519 'face))
5520 '(org-code org-verbatim underline)))
5521 (progn
5522 (setq rtn t
5523 d (cond ((member (char-after (1+ (match-beginning 0)))
5524 '(?_ ?^)) 1)
5525 (t 0)))
5526 (font-lock-prepend-text-property
5527 (+ d (match-beginning 0)) (match-end 0)
5528 'face 'org-latex-and-export-specials)
5529 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5530 '(font-lock-multiline t)))))
5531 rtn)))
5532
5533 (defun org-restart-font-lock ()
5534 "Restart font-lock-mode, to force refontification."
5535 (when (and (boundp 'font-lock-mode) font-lock-mode)
5536 (font-lock-mode -1)
5537 (font-lock-mode 1)))
5538
5539 (defun org-all-targets (&optional radio)
5540 "Return a list of all targets in this file.
5541 With optional argument RADIO, only find radio targets."
5542 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5543 rtn)
5544 (save-excursion
5545 (goto-char (point-min))
5546 (while (re-search-forward re nil t)
5547 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5548 rtn)))
5549
5550 (defun org-make-target-link-regexp (targets)
5551 "Make regular expression matching all strings in TARGETS.
5552 The regular expression finds the targets also if there is a line break
5553 between words."
5554 (and targets
5555 (concat
5556 "\\<\\("
5557 (mapconcat
5558 (lambda (x)
5559 (while (string-match " +" x)
5560 (setq x (replace-match "\\s-+" t t x)))
5561 x)
5562 targets
5563 "\\|")
5564 "\\)\\>")))
5565
5566 (defun org-activate-tags (limit)
5567 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5568 (progn
5569 (add-text-properties (match-beginning 1) (match-end 1)
5570 (list 'mouse-face 'highlight
5571 'rear-nonsticky org-nonsticky-props
5572 'keymap org-mouse-map))
5573 t)))
5574
5575 (defun org-outline-level ()
5576 (save-excursion
5577 (looking-at outline-regexp)
5578 (if (match-beginning 1)
5579 (+ (org-get-string-indentation (match-string 1)) 1000)
5580 (1- (- (match-end 0) (match-beginning 0))))))
5581
5582 (defvar org-font-lock-keywords nil)
5583
5584 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5585 "Regular expression matching a property line.")
5586
5587 (defun org-set-font-lock-defaults ()
5588 (let* ((em org-fontify-emphasized-text)
5589 (lk org-activate-links)
5590 (org-font-lock-extra-keywords
5591 (list
5592 ;; Headlines
5593 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5594 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5595 ;; Table lines
5596 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5597 (1 'org-table t))
5598 ;; Table internals
5599 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5600 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5601 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5602 ;; Drawers
5603 (list org-drawer-regexp '(0 'org-special-keyword t))
5604 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5605 ;; Properties
5606 (list org-property-re
5607 '(1 'org-special-keyword t)
5608 '(3 'org-property-value t))
5609 (if org-format-transports-properties-p
5610 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5611 ;; Links
5612 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5613 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5614 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5615 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5616 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5617 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5618 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5619 '(org-hide-wide-columns (0 nil append))
5620 ;; TODO lines
5621 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5622 '(1 (org-get-todo-face 1) t))
5623 ;; DONE
5624 (if org-fontify-done-headline
5625 (list (concat "^[*]+ +\\<\\("
5626 (mapconcat 'regexp-quote org-done-keywords "\\|")
5627 "\\)\\(.*\\)")
5628 '(2 'org-headline-done t))
5629 nil)
5630 ;; Priorities
5631 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5632 ;; Special keywords
5633 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5634 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5635 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5636 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5637 ;; Emphasis
5638 (if em
5639 (if (featurep 'xemacs)
5640 '(org-do-emphasis-faces (0 nil append))
5641 '(org-do-emphasis-faces)))
5642 ;; Checkboxes
5643 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5644 2 'bold prepend)
5645 (if org-provide-checkbox-statistics
5646 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5647 (0 (org-get-checkbox-statistics-face) t)))
5648 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5649 '(1 'org-archived prepend))
5650 ;; Specials
5651 '(org-do-latex-and-special-faces)
5652 ;; Code
5653 '(org-activate-code (1 'org-code t))
5654 ;; COMMENT
5655 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5656 "\\|" org-quote-string "\\)\\>")
5657 '(1 'org-special-keyword t))
5658 '("^#.*" (0 'font-lock-comment-face t))
5659 )))
5660 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5661 ;; Now set the full font-lock-keywords
5662 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5663 (org-set-local 'font-lock-defaults
5664 '(org-font-lock-keywords t nil nil backward-paragraph))
5665 (kill-local-variable 'font-lock-keywords) nil))
5666
5667 (defvar org-m nil)
5668 (defvar org-l nil)
5669 (defvar org-f nil)
5670 (defun org-get-level-face (n)
5671 "Get the right face for match N in font-lock matching of healdines."
5672 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5673 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5674 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5675 (cond
5676 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5677 ((eq n 2) org-f)
5678 (t (if org-level-color-stars-only nil org-f))))
5679
5680 (defun org-get-todo-face (kwd)
5681 "Get the right face for a TODO keyword KWD.
5682 If KWD is a number, get the corresponding match group."
5683 (if (numberp kwd) (setq kwd (match-string kwd)))
5684 (or (cdr (assoc kwd org-todo-keyword-faces))
5685 (and (member kwd org-done-keywords) 'org-done)
5686 'org-todo))
5687
5688 (defun org-unfontify-region (beg end &optional maybe_loudly)
5689 "Remove fontification and activation overlays from links."
5690 (font-lock-default-unfontify-region beg end)
5691 (let* ((buffer-undo-list t)
5692 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5693 (inhibit-modification-hooks t)
5694 deactivate-mark buffer-file-name buffer-file-truename)
5695 (remove-text-properties beg end
5696 '(mouse-face t keymap t org-linked-text t
5697 invisible t intangible t))))
5698
5699 ;;;; Visibility cycling, including org-goto and indirect buffer
5700
5701 ;;; Cycling
5702
5703 (defvar org-cycle-global-status nil)
5704 (make-variable-buffer-local 'org-cycle-global-status)
5705 (defvar org-cycle-subtree-status nil)
5706 (make-variable-buffer-local 'org-cycle-subtree-status)
5707
5708 ;;;###autoload
5709 (defun org-cycle (&optional arg)
5710 "Visibility cycling for Org-mode.
5711
5712 - When this function is called with a prefix argument, rotate the entire
5713 buffer through 3 states (global cycling)
5714 1. OVERVIEW: Show only top-level headlines.
5715 2. CONTENTS: Show all headlines of all levels, but no body text.
5716 3. SHOW ALL: Show everything.
5717
5718 - When point is at the beginning of a headline, rotate the subtree started
5719 by this line through 3 different states (local cycling)
5720 1. FOLDED: Only the main headline is shown.
5721 2. CHILDREN: The main headline and the direct children are shown.
5722 From this state, you can move to one of the children
5723 and zoom in further.
5724 3. SUBTREE: Show the entire subtree, including body text.
5725
5726 - When there is a numeric prefix, go up to a heading with level ARG, do
5727 a `show-subtree' and return to the previous cursor position. If ARG
5728 is negative, go up that many levels.
5729
5730 - When point is not at the beginning of a headline, execute
5731 `indent-relative', like TAB normally does. See the option
5732 `org-cycle-emulate-tab' for details.
5733
5734 - Special case: if point is at the beginning of the buffer and there is
5735 no headline in line 1, this function will act as if called with prefix arg.
5736 But only if also the variable `org-cycle-global-at-bob' is t."
5737 (interactive "P")
5738 (let* ((outline-regexp
5739 (if (and (org-mode-p) org-cycle-include-plain-lists)
5740 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5741 outline-regexp))
5742 (bob-special (and org-cycle-global-at-bob (bobp)
5743 (not (looking-at outline-regexp))))
5744 (org-cycle-hook
5745 (if bob-special
5746 (delq 'org-optimize-window-after-visibility-change
5747 (copy-sequence org-cycle-hook))
5748 org-cycle-hook))
5749 (pos (point)))
5750
5751 (if (or bob-special (equal arg '(4)))
5752 ;; special case: use global cycling
5753 (setq arg t))
5754
5755 (cond
5756
5757 ((org-at-table-p 'any)
5758 ;; Enter the table or move to the next field in the table
5759 (or (org-table-recognize-table.el)
5760 (progn
5761 (if arg (org-table-edit-field t)
5762 (org-table-justify-field-maybe)
5763 (call-interactively 'org-table-next-field)))))
5764
5765 ((eq arg t) ;; Global cycling
5766
5767 (cond
5768 ((and (eq last-command this-command)
5769 (eq org-cycle-global-status 'overview))
5770 ;; We just created the overview - now do table of contents
5771 ;; This can be slow in very large buffers, so indicate action
5772 (message "CONTENTS...")
5773 (org-content)
5774 (message "CONTENTS...done")
5775 (setq org-cycle-global-status 'contents)
5776 (run-hook-with-args 'org-cycle-hook 'contents))
5777
5778 ((and (eq last-command this-command)
5779 (eq org-cycle-global-status 'contents))
5780 ;; We just showed the table of contents - now show everything
5781 (show-all)
5782 (message "SHOW ALL")
5783 (setq org-cycle-global-status 'all)
5784 (run-hook-with-args 'org-cycle-hook 'all))
5785
5786 (t
5787 ;; Default action: go to overview
5788 (org-overview)
5789 (message "OVERVIEW")
5790 (setq org-cycle-global-status 'overview)
5791 (run-hook-with-args 'org-cycle-hook 'overview))))
5792
5793 ((and org-drawers org-drawer-regexp
5794 (save-excursion
5795 (beginning-of-line 1)
5796 (looking-at org-drawer-regexp)))
5797 ;; Toggle block visibility
5798 (org-flag-drawer
5799 (not (get-char-property (match-end 0) 'invisible))))
5800
5801 ((integerp arg)
5802 ;; Show-subtree, ARG levels up from here.
5803 (save-excursion
5804 (org-back-to-heading)
5805 (outline-up-heading (if (< arg 0) (- arg)
5806 (- (funcall outline-level) arg)))
5807 (org-show-subtree)))
5808
5809 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5810 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5811 ;; At a heading: rotate between three different views
5812 (org-back-to-heading)
5813 (let ((goal-column 0) eoh eol eos)
5814 ;; First, some boundaries
5815 (save-excursion
5816 (org-back-to-heading)
5817 (save-excursion
5818 (beginning-of-line 2)
5819 (while (and (not (eobp)) ;; this is like `next-line'
5820 (get-char-property (1- (point)) 'invisible))
5821 (beginning-of-line 2)) (setq eol (point)))
5822 (outline-end-of-heading) (setq eoh (point))
5823 (org-end-of-subtree t)
5824 (unless (eobp)
5825 (skip-chars-forward " \t\n")
5826 (beginning-of-line 1) ; in case this is an item
5827 )
5828 (setq eos (1- (point))))
5829 ;; Find out what to do next and set `this-command'
5830 (cond
5831 ((= eos eoh)
5832 ;; Nothing is hidden behind this heading
5833 (message "EMPTY ENTRY")
5834 (setq org-cycle-subtree-status nil)
5835 (save-excursion
5836 (goto-char eos)
5837 (outline-next-heading)
5838 (if (org-invisible-p) (org-flag-heading nil))))
5839 ((or (>= eol eos)
5840 (not (string-match "\\S-" (buffer-substring eol eos))))
5841 ;; Entire subtree is hidden in one line: open it
5842 (org-show-entry)
5843 (show-children)
5844 (message "CHILDREN")
5845 (save-excursion
5846 (goto-char eos)
5847 (outline-next-heading)
5848 (if (org-invisible-p) (org-flag-heading nil)))
5849 (setq org-cycle-subtree-status 'children)
5850 (run-hook-with-args 'org-cycle-hook 'children))
5851 ((and (eq last-command this-command)
5852 (eq org-cycle-subtree-status 'children))
5853 ;; We just showed the children, now show everything.
5854 (org-show-subtree)
5855 (message "SUBTREE")
5856 (setq org-cycle-subtree-status 'subtree)
5857 (run-hook-with-args 'org-cycle-hook 'subtree))
5858 (t
5859 ;; Default action: hide the subtree.
5860 (hide-subtree)
5861 (message "FOLDED")
5862 (setq org-cycle-subtree-status 'folded)
5863 (run-hook-with-args 'org-cycle-hook 'folded)))))
5864
5865 ;; TAB emulation
5866 (buffer-read-only (org-back-to-heading))
5867
5868 ((org-try-cdlatex-tab))
5869
5870 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5871 (or (not (bolp))
5872 (not (looking-at outline-regexp))))
5873 (call-interactively (global-key-binding "\t")))
5874
5875 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5876 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5877 (or (and (eq org-cycle-emulate-tab 'white)
5878 (= (match-end 0) (point-at-eol)))
5879 (and (eq org-cycle-emulate-tab 'whitestart)
5880 (>= (match-end 0) pos))))
5881 t
5882 (eq org-cycle-emulate-tab t))
5883 ; (if (and (looking-at "[ \n\r\t]")
5884 ; (string-match "^[ \t]*$" (buffer-substring
5885 ; (point-at-bol) (point))))
5886 ; (progn
5887 ; (beginning-of-line 1)
5888 ; (and (looking-at "[ \t]+") (replace-match ""))))
5889 (call-interactively (global-key-binding "\t")))
5890
5891 (t (save-excursion
5892 (org-back-to-heading)
5893 (org-cycle))))))
5894
5895 ;;;###autoload
5896 (defun org-global-cycle (&optional arg)
5897 "Cycle the global visibility. For details see `org-cycle'."
5898 (interactive "P")
5899 (let ((org-cycle-include-plain-lists
5900 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5901 (if (integerp arg)
5902 (progn
5903 (show-all)
5904 (hide-sublevels arg)
5905 (setq org-cycle-global-status 'contents))
5906 (org-cycle '(4)))))
5907
5908 (defun org-overview ()
5909 "Switch to overview mode, shoing only top-level headlines.
5910 Really, this shows all headlines with level equal or greater than the level
5911 of the first headline in the buffer. This is important, because if the
5912 first headline is not level one, then (hide-sublevels 1) gives confusing
5913 results."
5914 (interactive)
5915 (let ((level (save-excursion
5916 (goto-char (point-min))
5917 (if (re-search-forward (concat "^" outline-regexp) nil t)
5918 (progn
5919 (goto-char (match-beginning 0))
5920 (funcall outline-level))))))
5921 (and level (hide-sublevels level))))
5922
5923 (defun org-content (&optional arg)
5924 "Show all headlines in the buffer, like a table of contents.
5925 With numerical argument N, show content up to level N."
5926 (interactive "P")
5927 (save-excursion
5928 ;; Visit all headings and show their offspring
5929 (and (integerp arg) (org-overview))
5930 (goto-char (point-max))
5931 (catch 'exit
5932 (while (and (progn (condition-case nil
5933 (outline-previous-visible-heading 1)
5934 (error (goto-char (point-min))))
5935 t)
5936 (looking-at outline-regexp))
5937 (if (integerp arg)
5938 (show-children (1- arg))
5939 (show-branches))
5940 (if (bobp) (throw 'exit nil))))))
5941
5942
5943 (defun org-optimize-window-after-visibility-change (state)
5944 "Adjust the window after a change in outline visibility.
5945 This function is the default value of the hook `org-cycle-hook'."
5946 (when (get-buffer-window (current-buffer))
5947 (cond
5948 ; ((eq state 'overview) (org-first-headline-recenter 1))
5949 ; ((eq state 'overview) (org-beginning-of-line))
5950 ((eq state 'content) nil)
5951 ((eq state 'all) nil)
5952 ((eq state 'folded) nil)
5953 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5954 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5955
5956 (defun org-compact-display-after-subtree-move ()
5957 (let (beg end)
5958 (save-excursion
5959 (if (org-up-heading-safe)
5960 (progn
5961 (hide-subtree)
5962 (show-entry)
5963 (show-children)
5964 (org-cycle-show-empty-lines 'children)
5965 (org-cycle-hide-drawers 'children))
5966 (org-overview)))))
5967
5968 (defun org-cycle-show-empty-lines (state)
5969 "Show empty lines above all visible headlines.
5970 The region to be covered depends on STATE when called through
5971 `org-cycle-hook'. Lisp program can use t for STATE to get the
5972 entire buffer covered. Note that an empty line is only shown if there
5973 are at least `org-cycle-separator-lines' empty lines before the headeline."
5974 (when (> org-cycle-separator-lines 0)
5975 (save-excursion
5976 (let* ((n org-cycle-separator-lines)
5977 (re (cond
5978 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5979 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5980 (t (let ((ns (number-to-string (- n 2))))
5981 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5982 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5983 beg end)
5984 (cond
5985 ((memq state '(overview contents t))
5986 (setq beg (point-min) end (point-max)))
5987 ((memq state '(children folded))
5988 (setq beg (point) end (progn (org-end-of-subtree t t)
5989 (beginning-of-line 2)
5990 (point)))))
5991 (when beg
5992 (goto-char beg)
5993 (while (re-search-forward re end t)
5994 (if (not (get-char-property (match-end 1) 'invisible))
5995 (outline-flag-region
5996 (match-beginning 1) (match-end 1) nil)))))))
5997 ;; Never hide empty lines at the end of the file.
5998 (save-excursion
5999 (goto-char (point-max))
6000 (outline-previous-heading)
6001 (outline-end-of-heading)
6002 (if (and (looking-at "[ \t\n]+")
6003 (= (match-end 0) (point-max)))
6004 (outline-flag-region (point) (match-end 0) nil))))
6005
6006 (defun org-subtree-end-visible-p ()
6007 "Is the end of the current subtree visible?"
6008 (pos-visible-in-window-p
6009 (save-excursion (org-end-of-subtree t) (point))))
6010
6011 (defun org-first-headline-recenter (&optional N)
6012 "Move cursor to the first headline and recenter the headline.
6013 Optional argument N means, put the headline into the Nth line of the window."
6014 (goto-char (point-min))
6015 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6016 (beginning-of-line)
6017 (recenter (prefix-numeric-value N))))
6018
6019 ;;; Org-goto
6020
6021 (defvar org-goto-window-configuration nil)
6022 (defvar org-goto-marker nil)
6023 (defvar org-goto-map
6024 (let ((map (make-sparse-keymap)))
6025 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6026 (while (setq cmd (pop cmds))
6027 (substitute-key-definition cmd cmd map global-map)))
6028 (suppress-keymap map)
6029 (org-defkey map "\C-m" 'org-goto-ret)
6030 (org-defkey map [(return)] 'org-goto-ret)
6031 (org-defkey map [(left)] 'org-goto-left)
6032 (org-defkey map [(right)] 'org-goto-right)
6033 (org-defkey map [(control ?g)] 'org-goto-quit)
6034 (org-defkey map "\C-i" 'org-cycle)
6035 (org-defkey map [(tab)] 'org-cycle)
6036 (org-defkey map [(down)] 'outline-next-visible-heading)
6037 (org-defkey map [(up)] 'outline-previous-visible-heading)
6038 (if org-goto-auto-isearch
6039 (if (fboundp 'define-key-after)
6040 (define-key-after map [t] 'org-goto-local-auto-isearch)
6041 nil)
6042 (org-defkey map "q" 'org-goto-quit)
6043 (org-defkey map "n" 'outline-next-visible-heading)
6044 (org-defkey map "p" 'outline-previous-visible-heading)
6045 (org-defkey map "f" 'outline-forward-same-level)
6046 (org-defkey map "b" 'outline-backward-same-level)
6047 (org-defkey map "u" 'outline-up-heading))
6048 (org-defkey map "/" 'org-occur)
6049 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6050 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6051 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6052 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6053 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6054 map))
6055
6056 (defconst org-goto-help
6057 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6058 RET=jump to location [Q]uit and return to previous location
6059 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6060
6061 (defvar org-goto-start-pos) ; dynamically scoped parameter
6062
6063 (defun org-goto (&optional alternative-interface)
6064 "Look up a different location in the current file, keeping current visibility.
6065
6066 When you want look-up or go to a different location in a document, the
6067 fastest way is often to fold the entire buffer and then dive into the tree.
6068 This method has the disadvantage, that the previous location will be folded,
6069 which may not be what you want.
6070
6071 This command works around this by showing a copy of the current buffer
6072 in an indirect buffer, in overview mode. You can dive into the tree in
6073 that copy, use org-occur and incremental search to find a location.
6074 When pressing RET or `Q', the command returns to the original buffer in
6075 which the visibility is still unchanged. After RET is will also jump to
6076 the location selected in the indirect buffer and expose the
6077 the headline hierarchy above."
6078 (interactive "P")
6079 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
6080 (org-refile-use-outline-path t)
6081 (interface
6082 (if (not alternative-interface)
6083 org-goto-interface
6084 (if (eq org-goto-interface 'outline)
6085 'outline-path-completion
6086 'outline)))
6087 (org-goto-start-pos (point))
6088 (selected-point
6089 (if (eq interface 'outline)
6090 (car (org-get-location (current-buffer) org-goto-help))
6091 (nth 3 (org-refile-get-location "Goto: ")))))
6092 (if selected-point
6093 (progn
6094 (org-mark-ring-push org-goto-start-pos)
6095 (goto-char selected-point)
6096 (if (or (org-invisible-p) (org-invisible-p2))
6097 (org-show-context 'org-goto)))
6098 (message "Quit"))))
6099
6100 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6101 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6102 (defvar org-goto-local-auto-isearch-map) ; defined below
6103
6104 (defun org-get-location (buf help)
6105 "Let the user select a location in the Org-mode buffer BUF.
6106 This function uses a recursive edit. It returns the selected position
6107 or nil."
6108 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6109 (isearch-hide-immediately nil)
6110 (isearch-search-fun-function
6111 (lambda () 'org-goto-local-search-forward-headings))
6112 (org-goto-selected-point org-goto-exit-command))
6113 (save-excursion
6114 (save-window-excursion
6115 (delete-other-windows)
6116 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6117 (switch-to-buffer
6118 (condition-case nil
6119 (make-indirect-buffer (current-buffer) "*org-goto*")
6120 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6121 (with-output-to-temp-buffer "*Help*"
6122 (princ help))
6123 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6124 (setq buffer-read-only nil)
6125 (let ((org-startup-truncated t)
6126 (org-startup-folded nil)
6127 (org-startup-align-all-tables nil))
6128 (org-mode)
6129 (org-overview))
6130 (setq buffer-read-only t)
6131 (if (and (boundp 'org-goto-start-pos)
6132 (integer-or-marker-p org-goto-start-pos))
6133 (let ((org-show-hierarchy-above t)
6134 (org-show-siblings t)
6135 (org-show-following-heading t))
6136 (goto-char org-goto-start-pos)
6137 (and (org-invisible-p) (org-show-context)))
6138 (goto-char (point-min)))
6139 (org-beginning-of-line)
6140 (message "Select location and press RET")
6141 (use-local-map org-goto-map)
6142 (recursive-edit)
6143 ))
6144 (kill-buffer "*org-goto*")
6145 (cons org-goto-selected-point org-goto-exit-command)))
6146
6147 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6148 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6149 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6150 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6151
6152 (defun org-goto-local-search-forward-headings (string bound noerror)
6153 "Search and make sure that anu matches are in headlines."
6154 (catch 'return
6155 (while (search-forward string bound noerror)
6156 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6157 (and (member :headline context)
6158 (not (member :tags context))))
6159 (throw 'return (point))))))
6160
6161 (defun org-goto-local-auto-isearch ()
6162 "Start isearch."
6163 (interactive)
6164 (goto-char (point-min))
6165 (let ((keys (this-command-keys)))
6166 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6167 (isearch-mode t)
6168 (isearch-process-search-char (string-to-char keys)))))
6169
6170 (defun org-goto-ret (&optional arg)
6171 "Finish `org-goto' by going to the new location."
6172 (interactive "P")
6173 (setq org-goto-selected-point (point)
6174 org-goto-exit-command 'return)
6175 (throw 'exit nil))
6176
6177 (defun org-goto-left ()
6178 "Finish `org-goto' by going to the new location."
6179 (interactive)
6180 (if (org-on-heading-p)
6181 (progn
6182 (beginning-of-line 1)
6183 (setq org-goto-selected-point (point)
6184 org-goto-exit-command 'left)
6185 (throw 'exit nil))
6186 (error "Not on a heading")))
6187
6188 (defun org-goto-right ()
6189 "Finish `org-goto' by going to the new location."
6190 (interactive)
6191 (if (org-on-heading-p)
6192 (progn
6193 (setq org-goto-selected-point (point)
6194 org-goto-exit-command 'right)
6195 (throw 'exit nil))
6196 (error "Not on a heading")))
6197
6198 (defun org-goto-quit ()
6199 "Finish `org-goto' without cursor motion."
6200 (interactive)
6201 (setq org-goto-selected-point nil)
6202 (setq org-goto-exit-command 'quit)
6203 (throw 'exit nil))
6204
6205 ;;; Indirect buffer display of subtrees
6206
6207 (defvar org-indirect-dedicated-frame nil
6208 "This is the frame being used for indirect tree display.")
6209 (defvar org-last-indirect-buffer nil)
6210
6211 (defun org-tree-to-indirect-buffer (&optional arg)
6212 "Create indirect buffer and narrow it to current subtree.
6213 With numerical prefix ARG, go up to this level and then take that tree.
6214 If ARG is negative, go up that many levels.
6215 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6216 indirect buffer previously made with this command, to avoid proliferation of
6217 indirect buffers. However, when you call the command with a `C-u' prefix, or
6218 when `org-indirect-buffer-display' is `new-frame', the last buffer
6219 is kept so that you can work with several indirect buffers at the same time.
6220 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6221 requests that a new frame be made for the new buffer, so that the dedicated
6222 frame is not changed."
6223 (interactive "P")
6224 (let ((cbuf (current-buffer))
6225 (cwin (selected-window))
6226 (pos (point))
6227 beg end level heading ibuf)
6228 (save-excursion
6229 (org-back-to-heading t)
6230 (when (numberp arg)
6231 (setq level (org-outline-level))
6232 (if (< arg 0) (setq arg (+ level arg)))
6233 (while (> (setq level (org-outline-level)) arg)
6234 (outline-up-heading 1 t)))
6235 (setq beg (point)
6236 heading (org-get-heading))
6237 (org-end-of-subtree t) (setq end (point)))
6238 (if (and (buffer-live-p org-last-indirect-buffer)
6239 (not (eq org-indirect-buffer-display 'new-frame))
6240 (not arg))
6241 (kill-buffer org-last-indirect-buffer))
6242 (setq ibuf (org-get-indirect-buffer cbuf)
6243 org-last-indirect-buffer ibuf)
6244 (cond
6245 ((or (eq org-indirect-buffer-display 'new-frame)
6246 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6247 (select-frame (make-frame))
6248 (delete-other-windows)
6249 (switch-to-buffer ibuf)
6250 (org-set-frame-title heading))
6251 ((eq org-indirect-buffer-display 'dedicated-frame)
6252 (raise-frame
6253 (select-frame (or (and org-indirect-dedicated-frame
6254 (frame-live-p org-indirect-dedicated-frame)
6255 org-indirect-dedicated-frame)
6256 (setq org-indirect-dedicated-frame (make-frame)))))
6257 (delete-other-windows)
6258 (switch-to-buffer ibuf)
6259 (org-set-frame-title (concat "Indirect: " heading)))
6260 ((eq org-indirect-buffer-display 'current-window)
6261 (switch-to-buffer ibuf))
6262 ((eq org-indirect-buffer-display 'other-window)
6263 (pop-to-buffer ibuf))
6264 (t (error "Invalid value.")))
6265 (if (featurep 'xemacs)
6266 (save-excursion (org-mode) (turn-on-font-lock)))
6267 (narrow-to-region beg end)
6268 (show-all)
6269 (goto-char pos)
6270 (and (window-live-p cwin) (select-window cwin))))
6271
6272 (defun org-get-indirect-buffer (&optional buffer)
6273 (setq buffer (or buffer (current-buffer)))
6274 (let ((n 1) (base (buffer-name buffer)) bname)
6275 (while (buffer-live-p
6276 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6277 (setq n (1+ n)))
6278 (condition-case nil
6279 (make-indirect-buffer buffer bname 'clone)
6280 (error (make-indirect-buffer buffer bname)))))
6281
6282 (defun org-set-frame-title (title)
6283 "Set the title of the current frame to the string TITLE."
6284 ;; FIXME: how to name a single frame in XEmacs???
6285 (unless (featurep 'xemacs)
6286 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6287
6288 ;;;; Structure editing
6289
6290 ;;; Inserting headlines
6291
6292 (defun org-insert-heading (&optional force-heading)
6293 "Insert a new heading or item with same depth at point.
6294 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6295 If point is at the beginning of a headline, insert a sibling before the
6296 current headline. If point is not at the beginning, do not split the line,
6297 but create the new hedline after the current line."
6298 (interactive "P")
6299 (if (= (buffer-size) 0)
6300 (insert "\n* ")
6301 (when (or force-heading (not (org-insert-item)))
6302 (let* ((head (save-excursion
6303 (condition-case nil
6304 (progn
6305 (org-back-to-heading)
6306 (match-string 0))
6307 (error "*"))))
6308 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6309 pos)
6310 (cond
6311 ((and (org-on-heading-p) (bolp)
6312 (or (bobp)
6313 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6314 ;; insert before the current line
6315 (open-line (if blank 2 1)))
6316 ((and (bolp)
6317 (or (bobp)
6318 (save-excursion
6319 (backward-char 1) (not (org-invisible-p)))))
6320 ;; insert right here
6321 nil)
6322 (t
6323 ; ;; in the middle of the line
6324 ; (org-show-entry)
6325 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
6326 ; (if (and
6327 ; (org-on-heading-p)
6328 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6329 ; ;; protect the tags
6330 ;; (let ((tags (match-string 2)) pos)
6331 ; (delete-region (match-beginning 1) (match-end 1))
6332 ; (setq pos (point-at-bol))
6333 ; (newline (if blank 2 1))
6334 ; (save-excursion
6335 ; (goto-char pos)
6336 ; (end-of-line 1)
6337 ; (insert " " tags)
6338 ; (org-set-tags nil 'align)))
6339 ; (newline (if blank 2 1)))
6340 ; (newline (if blank 2 1))))
6341
6342
6343 ;; in the middle of the line
6344 (org-show-entry)
6345 (let ((split
6346 (org-get-alist-option org-M-RET-may-split-line 'headline))
6347 tags pos)
6348 (if (org-on-heading-p)
6349 (progn
6350 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6351 (setq tags (and (match-end 2) (match-string 2)))
6352 (and (match-end 1)
6353 (delete-region (match-beginning 1) (match-end 1)))
6354 (setq pos (point-at-bol))
6355 (or split (end-of-line 1))
6356 (delete-horizontal-space)
6357 (newline (if blank 2 1))
6358 (when tags
6359 (save-excursion
6360 (goto-char pos)
6361 (end-of-line 1)
6362 (insert " " tags)
6363 (org-set-tags nil 'align))))
6364 (or split (end-of-line 1))
6365 (newline (if blank 2 1))))))
6366 (insert head) (just-one-space)
6367 (setq pos (point))
6368 (end-of-line 1)
6369 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6370 (run-hooks 'org-insert-heading-hook)))))
6371
6372 (defun org-insert-heading-after-current ()
6373 "Insert a new heading with same level as current, after current subtree."
6374 (interactive)
6375 (org-back-to-heading)
6376 (org-insert-heading)
6377 (org-move-subtree-down)
6378 (end-of-line 1))
6379
6380 (defun org-insert-todo-heading (arg)
6381 "Insert a new heading with the same level and TODO state as current heading.
6382 If the heading has no TODO state, or if the state is DONE, use the first
6383 state (TODO by default). Also with prefix arg, force first state."
6384 (interactive "P")
6385 (when (not (org-insert-item 'checkbox))
6386 (org-insert-heading)
6387 (save-excursion
6388 (org-back-to-heading)
6389 (outline-previous-heading)
6390 (looking-at org-todo-line-regexp))
6391 (if (or arg
6392 (not (match-beginning 2))
6393 (member (match-string 2) org-done-keywords))
6394 (insert (car org-todo-keywords-1) " ")
6395 (insert (match-string 2) " "))))
6396
6397 (defun org-insert-subheading (arg)
6398 "Insert a new subheading and demote it.
6399 Works for outline headings and for plain lists alike."
6400 (interactive "P")
6401 (org-insert-heading arg)
6402 (cond
6403 ((org-on-heading-p) (org-do-demote))
6404 ((org-at-item-p) (org-indent-item 1))))
6405
6406 (defun org-insert-todo-subheading (arg)
6407 "Insert a new subheading with TODO keyword or checkbox and demote it.
6408 Works for outline headings and for plain lists alike."
6409 (interactive "P")
6410 (org-insert-todo-heading arg)
6411 (cond
6412 ((org-on-heading-p) (org-do-demote))
6413 ((org-at-item-p) (org-indent-item 1))))
6414
6415 ;;; Promotion and Demotion
6416
6417 (defun org-promote-subtree ()
6418 "Promote the entire subtree.
6419 See also `org-promote'."
6420 (interactive)
6421 (save-excursion
6422 (org-map-tree 'org-promote))
6423 (org-fix-position-after-promote))
6424
6425 (defun org-demote-subtree ()
6426 "Demote the entire subtree. See `org-demote'.
6427 See also `org-promote'."
6428 (interactive)
6429 (save-excursion
6430 (org-map-tree 'org-demote))
6431 (org-fix-position-after-promote))
6432
6433
6434 (defun org-do-promote ()
6435 "Promote the current heading higher up the tree.
6436 If the region is active in `transient-mark-mode', promote all headings
6437 in the region."
6438 (interactive)
6439 (save-excursion
6440 (if (org-region-active-p)
6441 (org-map-region 'org-promote (region-beginning) (region-end))
6442 (org-promote)))
6443 (org-fix-position-after-promote))
6444
6445 (defun org-do-demote ()
6446 "Demote the current heading lower down the tree.
6447 If the region is active in `transient-mark-mode', demote all headings
6448 in the region."
6449 (interactive)
6450 (save-excursion
6451 (if (org-region-active-p)
6452 (org-map-region 'org-demote (region-beginning) (region-end))
6453 (org-demote)))
6454 (org-fix-position-after-promote))
6455
6456 (defun org-fix-position-after-promote ()
6457 "Make sure that after pro/demotion cursor position is right."
6458 (let ((pos (point)))
6459 (when (save-excursion
6460 (beginning-of-line 1)
6461 (looking-at org-todo-line-regexp)
6462 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6463 (cond ((eobp) (insert " "))
6464 ((eolp) (insert " "))
6465 ((equal (char-after) ?\ ) (forward-char 1))))))
6466
6467 (defun org-reduced-level (l)
6468 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6469
6470 (defun org-get-valid-level (level &optional change)
6471 "Rectify a level change under the influence of `org-odd-levels-only'
6472 LEVEL is a current level, CHANGE is by how much the level should be
6473 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6474 even level numbers will become the next higher odd number."
6475 (if org-odd-levels-only
6476 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6477 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6478 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6479 (max 1 (+ level change))))
6480
6481 (define-obsolete-function-alias 'org-get-legal-level
6482 'org-get-valid-level "23.1")
6483
6484 (defun org-promote ()
6485 "Promote the current heading higher up the tree.
6486 If the region is active in `transient-mark-mode', promote all headings
6487 in the region."
6488 (org-back-to-heading t)
6489 (let* ((level (save-match-data (funcall outline-level)))
6490 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6491 (diff (abs (- level (length up-head) -1))))
6492 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6493 (replace-match up-head nil t)
6494 ;; Fixup tag positioning
6495 (and org-auto-align-tags (org-set-tags nil t))
6496 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6497
6498 (defun org-demote ()
6499 "Demote the current heading lower down the tree.
6500 If the region is active in `transient-mark-mode', demote all headings
6501 in the region."
6502 (org-back-to-heading t)
6503 (let* ((level (save-match-data (funcall outline-level)))
6504 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6505 (diff (abs (- level (length down-head) -1))))
6506 (replace-match down-head nil t)
6507 ;; Fixup tag positioning
6508 (and org-auto-align-tags (org-set-tags nil t))
6509 (if org-adapt-indentation (org-fixup-indentation diff))))
6510
6511 (defun org-map-tree (fun)
6512 "Call FUN for every heading underneath the current one."
6513 (org-back-to-heading)
6514 (let ((level (funcall outline-level)))
6515 (save-excursion
6516 (funcall fun)
6517 (while (and (progn
6518 (outline-next-heading)
6519 (> (funcall outline-level) level))
6520 (not (eobp)))
6521 (funcall fun)))))
6522
6523 (defun org-map-region (fun beg end)
6524 "Call FUN for every heading between BEG and END."
6525 (let ((org-ignore-region t))
6526 (save-excursion
6527 (setq end (copy-marker end))
6528 (goto-char beg)
6529 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6530 (< (point) end))
6531 (funcall fun))
6532 (while (and (progn
6533 (outline-next-heading)
6534 (< (point) end))
6535 (not (eobp)))
6536 (funcall fun)))))
6537
6538 (defun org-fixup-indentation (diff)
6539 "Change the indentation in the current entry by DIFF
6540 However, if any line in the current entry has no indentation, or if it
6541 would end up with no indentation after the change, nothing at all is done."
6542 (save-excursion
6543 (let ((end (save-excursion (outline-next-heading)
6544 (point-marker)))
6545 (prohibit (if (> diff 0)
6546 "^\\S-"
6547 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6548 col)
6549 (unless (save-excursion (end-of-line 1)
6550 (re-search-forward prohibit end t))
6551 (while (and (< (point) end)
6552 (re-search-forward "^[ \t]+" end t))
6553 (goto-char (match-end 0))
6554 (setq col (current-column))
6555 (if (< diff 0) (replace-match ""))
6556 (indent-to (+ diff col))))
6557 (move-marker end nil))))
6558
6559 (defun org-convert-to-odd-levels ()
6560 "Convert an org-mode file with all levels allowed to one with odd levels.
6561 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6562 level 5 etc."
6563 (interactive)
6564 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6565 (let ((org-odd-levels-only nil) n)
6566 (save-excursion
6567 (goto-char (point-min))
6568 (while (re-search-forward "^\\*\\*+ " nil t)
6569 (setq n (- (length (match-string 0)) 2))
6570 (while (>= (setq n (1- n)) 0)
6571 (org-demote))
6572 (end-of-line 1))))))
6573
6574
6575 (defun org-convert-to-oddeven-levels ()
6576 "Convert an org-mode file with only odd levels to one with odd and even levels.
6577 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6578 section with an even level, conversion would destroy the structure of the file. An error
6579 is signaled in this case."
6580 (interactive)
6581 (goto-char (point-min))
6582 ;; First check if there are no even levels
6583 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6584 (org-show-context t)
6585 (error "Not all levels are odd in this file. Conversion not possible."))
6586 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6587 (let ((org-odd-levels-only nil) n)
6588 (save-excursion
6589 (goto-char (point-min))
6590 (while (re-search-forward "^\\*\\*+ " nil t)
6591 (setq n (/ (1- (length (match-string 0))) 2))
6592 (while (>= (setq n (1- n)) 0)
6593 (org-promote))
6594 (end-of-line 1))))))
6595
6596 (defun org-tr-level (n)
6597 "Make N odd if required."
6598 (if org-odd-levels-only (1+ (/ n 2)) n))
6599
6600 ;;; Vertical tree motion, cutting and pasting of subtrees
6601
6602 (defun org-move-subtree-up (&optional arg)
6603 "Move the current subtree up past ARG headlines of the same level."
6604 (interactive "p")
6605 (org-move-subtree-down (- (prefix-numeric-value arg))))
6606
6607 (defun org-move-subtree-down (&optional arg)
6608 "Move the current subtree down past ARG headlines of the same level."
6609 (interactive "p")
6610 (setq arg (prefix-numeric-value arg))
6611 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6612 'outline-get-last-sibling))
6613 (ins-point (make-marker))
6614 (cnt (abs arg))
6615 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6616 ;; Select the tree
6617 (org-back-to-heading)
6618 (setq beg0 (point))
6619 (save-excursion
6620 (setq ne-beg (org-back-over-empty-lines))
6621 (setq beg (point)))
6622 (save-match-data
6623 (save-excursion (outline-end-of-heading)
6624 (setq folded (org-invisible-p)))
6625 (outline-end-of-subtree))
6626 (outline-next-heading)
6627 (setq ne-end (org-back-over-empty-lines))
6628 (setq end (point))
6629 (goto-char beg0)
6630 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6631 ;; include less whitespace
6632 (save-excursion
6633 (goto-char beg)
6634 (forward-line (- ne-beg ne-end))
6635 (setq beg (point))))
6636 ;; Find insertion point, with error handling
6637 (while (> cnt 0)
6638 (or (and (funcall movfunc) (looking-at outline-regexp))
6639 (progn (goto-char beg0)
6640 (error "Cannot move past superior level or buffer limit")))
6641 (setq cnt (1- cnt)))
6642 (if (> arg 0)
6643 ;; Moving forward - still need to move over subtree
6644 (progn (org-end-of-subtree t t)
6645 (save-excursion
6646 (org-back-over-empty-lines)
6647 (or (bolp) (newline)))))
6648 (setq ne-ins (org-back-over-empty-lines))
6649 (move-marker ins-point (point))
6650 (setq txt (buffer-substring beg end))
6651 (delete-region beg end)
6652 (outline-flag-region (1- beg) beg nil)
6653 (outline-flag-region (1- (point)) (point) nil)
6654 (insert txt)
6655 (or (bolp) (insert "\n"))
6656 (setq ins-end (point))
6657 (goto-char ins-point)
6658 (org-skip-whitespace)
6659 (when (and (< arg 0)
6660 (org-first-sibling-p)
6661 (> ne-ins ne-beg))
6662 ;; Move whitespace back to beginning
6663 (save-excursion
6664 (goto-char ins-end)
6665 (let ((kill-whole-line t))
6666 (kill-line (- ne-ins ne-beg)) (point)))
6667 (insert (make-string (- ne-ins ne-beg) ?\n)))
6668 (move-marker ins-point nil)
6669 (org-compact-display-after-subtree-move)
6670 (unless folded
6671 (org-show-entry)
6672 (show-children)
6673 (org-cycle-hide-drawers 'children))))
6674
6675 (defvar org-subtree-clip ""
6676 "Clipboard for cut and paste of subtrees.
6677 This is actually only a copy of the kill, because we use the normal kill
6678 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6679
6680 (defvar org-subtree-clip-folded nil
6681 "Was the last copied subtree folded?
6682 This is used to fold the tree back after pasting.")
6683
6684 (defun org-cut-subtree (&optional n)
6685 "Cut the current subtree into the clipboard.
6686 With prefix arg N, cut this many sequential subtrees.
6687 This is a short-hand for marking the subtree and then cutting it."
6688 (interactive "p")
6689 (org-copy-subtree n 'cut))
6690
6691 (defun org-copy-subtree (&optional n cut)
6692 "Cut the current subtree into the clipboard.
6693 With prefix arg N, cut this many sequential subtrees.
6694 This is a short-hand for marking the subtree and then copying it.
6695 If CUT is non-nil, actually cut the subtree."
6696 (interactive "p")
6697 (let (beg end folded (beg0 (point)))
6698 (if (interactive-p)
6699 (org-back-to-heading nil) ; take what looks like a subtree
6700 (org-back-to-heading t)) ; take what is really there
6701 (org-back-over-empty-lines)
6702 (setq beg (point))
6703 (skip-chars-forward " \t\r\n")
6704 (save-match-data
6705 (save-excursion (outline-end-of-heading)
6706 (setq folded (org-invisible-p)))
6707 (condition-case nil
6708 (outline-forward-same-level (1- n))
6709 (error nil))
6710 (org-end-of-subtree t t))
6711 (org-back-over-empty-lines)
6712 (setq end (point))
6713 (goto-char beg0)
6714 (when (> end beg)
6715 (setq org-subtree-clip-folded folded)
6716 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6717 (setq org-subtree-clip (current-kill 0))
6718 (message "%s: Subtree(s) with %d characters"
6719 (if cut "Cut" "Copied")
6720 (length org-subtree-clip)))))
6721
6722 (defun org-paste-subtree (&optional level tree)
6723 "Paste the clipboard as a subtree, with modification of headline level.
6724 The entire subtree is promoted or demoted in order to match a new headline
6725 level. By default, the new level is derived from the visible headings
6726 before and after the insertion point, and taken to be the inferior headline
6727 level of the two. So if the previous visible heading is level 3 and the
6728 next is level 4 (or vice versa), level 4 will be used for insertion.
6729 This makes sure that the subtree remains an independent subtree and does
6730 not swallow low level entries.
6731
6732 You can also force a different level, either by using a numeric prefix
6733 argument, or by inserting the heading marker by hand. For example, if the
6734 cursor is after \"*****\", then the tree will be shifted to level 5.
6735
6736 If you want to insert the tree as is, just use \\[yank].
6737
6738 If optional TREE is given, use this text instead of the kill ring."
6739 (interactive "P")
6740 (unless (org-kill-is-subtree-p tree)
6741 (error "%s"
6742 (substitute-command-keys
6743 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6744 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6745 (^re (concat "^\\(" outline-regexp "\\)"))
6746 (re (concat "\\(" outline-regexp "\\)"))
6747 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6748
6749 (old-level (if (string-match ^re txt)
6750 (- (match-end 0) (match-beginning 0) 1)
6751 -1))
6752 (force-level (cond (level (prefix-numeric-value level))
6753 ((string-match
6754 ^re_ (buffer-substring (point-at-bol) (point)))
6755 (- (match-end 1) (match-beginning 1)))
6756 (t nil)))
6757 (previous-level (save-excursion
6758 (condition-case nil
6759 (progn
6760 (outline-previous-visible-heading 1)
6761 (if (looking-at re)
6762 (- (match-end 0) (match-beginning 0) 1)
6763 1))
6764 (error 1))))
6765 (next-level (save-excursion
6766 (condition-case nil
6767 (progn
6768 (or (looking-at outline-regexp)
6769 (outline-next-visible-heading 1))
6770 (if (looking-at re)
6771 (- (match-end 0) (match-beginning 0) 1)
6772 1))
6773 (error 1))))
6774 (new-level (or force-level (max previous-level next-level)))
6775 (shift (if (or (= old-level -1)
6776 (= new-level -1)
6777 (= old-level new-level))
6778 0
6779 (- new-level old-level)))
6780 (delta (if (> shift 0) -1 1))
6781 (func (if (> shift 0) 'org-demote 'org-promote))
6782 (org-odd-levels-only nil)
6783 beg end)
6784 ;; Remove the forced level indicator
6785 (if force-level
6786 (delete-region (point-at-bol) (point)))
6787 ;; Paste
6788 (beginning-of-line 1)
6789 (org-back-over-empty-lines) ;; FIXME: correct fix????
6790 (setq beg (point))
6791 (insert-before-markers txt) ;; FIXME: correct fix????
6792 (unless (string-match "\n\\'" txt) (insert "\n"))
6793 (setq end (point))
6794 (goto-char beg)
6795 (skip-chars-forward " \t\n\r")
6796 (setq beg (point))
6797 ;; Shift if necessary
6798 (unless (= shift 0)
6799 (save-restriction
6800 (narrow-to-region beg end)
6801 (while (not (= shift 0))
6802 (org-map-region func (point-min) (point-max))
6803 (setq shift (+ delta shift)))
6804 (goto-char (point-min))))
6805 (when (interactive-p)
6806 (message "Clipboard pasted as level %d subtree" new-level))
6807 (if (and kill-ring
6808 (eq org-subtree-clip (current-kill 0))
6809 org-subtree-clip-folded)
6810 ;; The tree was folded before it was killed/copied
6811 (hide-subtree))))
6812
6813 (defun org-kill-is-subtree-p (&optional txt)
6814 "Check if the current kill is an outline subtree, or a set of trees.
6815 Returns nil if kill does not start with a headline, or if the first
6816 headline level is not the largest headline level in the tree.
6817 So this will actually accept several entries of equal levels as well,
6818 which is OK for `org-paste-subtree'.
6819 If optional TXT is given, check this string instead of the current kill."
6820 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6821 (start-level (and kill
6822 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6823 org-outline-regexp "\\)")
6824 kill)
6825 (- (match-end 2) (match-beginning 2) 1)))
6826 (re (concat "^" org-outline-regexp))
6827 (start (1+ (match-beginning 2))))
6828 (if (not start-level)
6829 (progn
6830 nil) ;; does not even start with a heading
6831 (catch 'exit
6832 (while (setq start (string-match re kill (1+ start)))
6833 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6834 (throw 'exit nil)))
6835 t))))
6836
6837 (defun org-narrow-to-subtree ()
6838 "Narrow buffer to the current subtree."
6839 (interactive)
6840 (save-excursion
6841 (save-match-data
6842 (narrow-to-region
6843 (progn (org-back-to-heading) (point))
6844 (progn (org-end-of-subtree t t) (point))))))
6845
6846
6847 ;;; Outline Sorting
6848
6849 (defun org-sort (with-case)
6850 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6851 Optional argument WITH-CASE means sort case-sensitively."
6852 (interactive "P")
6853 (if (org-at-table-p)
6854 (org-call-with-arg 'org-table-sort-lines with-case)
6855 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6856
6857 (defvar org-priority-regexp) ; defined later in the file
6858
6859 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6860 "Sort entries on a certain level of an outline tree.
6861 If there is an active region, the entries in the region are sorted.
6862 Else, if the cursor is before the first entry, sort the top-level items.
6863 Else, the children of the entry at point are sorted.
6864
6865 Sorting can be alphabetically, numerically, and by date/time as given by
6866 the first time stamp in the entry. The command prompts for the sorting
6867 type unless it has been given to the function through the SORTING-TYPE
6868 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6869 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6870 called with point at the beginning of the record. It must return either
6871 a string or a number that should serve as the sorting key for that record.
6872
6873 Comparing entries ignores case by default. However, with an optional argument
6874 WITH-CASE, the sorting considers case as well."
6875 (interactive "P")
6876 (let ((case-func (if with-case 'identity 'downcase))
6877 start beg end stars re re2
6878 txt what tmp plain-list-p)
6879 ;; Find beginning and end of region to sort
6880 (cond
6881 ((org-region-active-p)
6882 ;; we will sort the region
6883 (setq end (region-end)
6884 what "region")
6885 (goto-char (region-beginning))
6886 (if (not (org-on-heading-p)) (outline-next-heading))
6887 (setq start (point)))
6888 ((org-at-item-p)
6889 ;; we will sort this plain list
6890 (org-beginning-of-item-list) (setq start (point))
6891 (org-end-of-item-list) (setq end (point))
6892 (goto-char start)
6893 (setq plain-list-p t
6894 what "plain list"))
6895 ((or (org-on-heading-p)
6896 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6897 ;; we will sort the children of the current headline
6898 (org-back-to-heading)
6899 (setq start (point)
6900 end (progn (org-end-of-subtree t t)
6901 (org-back-over-empty-lines)
6902 (point))
6903 what "children")
6904 (goto-char start)
6905 (show-subtree)
6906 (outline-next-heading))
6907 (t
6908 ;; we will sort the top-level entries in this file
6909 (goto-char (point-min))
6910 (or (org-on-heading-p) (outline-next-heading))
6911 (setq start (point) end (point-max) what "top-level")
6912 (goto-char start)
6913 (show-all)))
6914
6915 (setq beg (point))
6916 (if (>= beg end) (error "Nothing to sort"))
6917
6918 (unless plain-list-p
6919 (looking-at "\\(\\*+\\)")
6920 (setq stars (match-string 1)
6921 re (concat "^" (regexp-quote stars) " +")
6922 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6923 txt (buffer-substring beg end))
6924 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6925 (if (and (not (equal stars "*")) (string-match re2 txt))
6926 (error "Region to sort contains a level above the first entry")))
6927
6928 (unless sorting-type
6929 (message
6930 (if plain-list-p
6931 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6932 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6933 what)
6934 (setq sorting-type (read-char-exclusive))
6935
6936 (and (= (downcase sorting-type) ?f)
6937 (setq getkey-func
6938 (completing-read "Sort using function: "
6939 obarray 'fboundp t nil nil))
6940 (setq getkey-func (intern getkey-func)))
6941
6942 (and (= (downcase sorting-type) ?r)
6943 (setq property
6944 (completing-read "Property: "
6945 (mapcar 'list (org-buffer-property-keys t))
6946 nil t))))
6947
6948 (message "Sorting entries...")
6949
6950 (save-restriction
6951 (narrow-to-region start end)
6952
6953 (let ((dcst (downcase sorting-type))
6954 (now (current-time)))
6955 (sort-subr
6956 (/= dcst sorting-type)
6957 ;; This function moves to the beginning character of the "record" to
6958 ;; be sorted.
6959 (if plain-list-p
6960 (lambda nil
6961 (if (org-at-item-p) t (goto-char (point-max))))
6962 (lambda nil
6963 (if (re-search-forward re nil t)
6964 (goto-char (match-beginning 0))
6965 (goto-char (point-max)))))
6966 ;; This function moves to the last character of the "record" being
6967 ;; sorted.
6968 (if plain-list-p
6969 'org-end-of-item
6970 (lambda nil
6971 (save-match-data
6972 (condition-case nil
6973 (outline-forward-same-level 1)
6974 (error
6975 (goto-char (point-max)))))))
6976
6977 ;; This function returns the value that gets sorted against.
6978 (if plain-list-p
6979 (lambda nil
6980 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6981 (cond
6982 ((= dcst ?n)
6983 (string-to-number (buffer-substring (match-end 0)
6984 (point-at-eol))))
6985 ((= dcst ?a)
6986 (buffer-substring (match-end 0) (point-at-eol)))
6987 ((= dcst ?t)
6988 (if (re-search-forward org-ts-regexp
6989 (point-at-eol) t)
6990 (org-time-string-to-time (match-string 0))
6991 now))
6992 ((= dcst ?f)
6993 (if getkey-func
6994 (progn
6995 (setq tmp (funcall getkey-func))
6996 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6997 tmp)
6998 (error "Invalid key function `%s'" getkey-func)))
6999 (t (error "Invalid sorting type `%c'" sorting-type)))))
7000 (lambda nil
7001 (cond
7002 ((= dcst ?n)
7003 (if (looking-at outline-regexp)
7004 (string-to-number (buffer-substring (match-end 0)
7005 (point-at-eol)))
7006 nil))
7007 ((= dcst ?a)
7008 (funcall case-func (buffer-substring (point-at-bol)
7009 (point-at-eol))))
7010 ((= dcst ?t)
7011 (if (re-search-forward org-ts-regexp
7012 (save-excursion
7013 (forward-line 2)
7014 (point)) t)
7015 (org-time-string-to-time (match-string 0))
7016 now))
7017 ((= dcst ?p)
7018 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7019 (string-to-char (match-string 2))
7020 org-default-priority))
7021 ((= dcst ?r)
7022 (or (org-entry-get nil property) ""))
7023 ((= dcst ?f)
7024 (if getkey-func
7025 (progn
7026 (setq tmp (funcall getkey-func))
7027 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7028 tmp)
7029 (error "Invalid key function `%s'" getkey-func)))
7030 (t (error "Invalid sorting type `%c'" sorting-type)))))
7031 nil
7032 (cond
7033 ((= dcst ?a) 'string<)
7034 ((= dcst ?t) 'time-less-p)
7035 (t nil)))))
7036 (message "Sorting entries...done")))
7037
7038 (defun org-do-sort (table what &optional with-case sorting-type)
7039 "Sort TABLE of WHAT according to SORTING-TYPE.
7040 The user will be prompted for the SORTING-TYPE if the call to this
7041 function does not specify it. WHAT is only for the prompt, to indicate
7042 what is being sorted. The sorting key will be extracted from
7043 the car of the elements of the table.
7044 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7045 (unless sorting-type
7046 (message
7047 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7048 what)
7049 (setq sorting-type (read-char-exclusive)))
7050 (let ((dcst (downcase sorting-type))
7051 extractfun comparefun)
7052 ;; Define the appropriate functions
7053 (cond
7054 ((= dcst ?n)
7055 (setq extractfun 'string-to-number
7056 comparefun (if (= dcst sorting-type) '< '>)))
7057 ((= dcst ?a)
7058 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7059 (lambda(x) (downcase (org-sort-remove-invisible x))))
7060 comparefun (if (= dcst sorting-type)
7061 'string<
7062 (lambda (a b) (and (not (string< a b))
7063 (not (string= a b)))))))
7064 ((= dcst ?t)
7065 (setq extractfun
7066 (lambda (x)
7067 (if (string-match org-ts-regexp x)
7068 (time-to-seconds
7069 (org-time-string-to-time (match-string 0 x)))
7070 0))
7071 comparefun (if (= dcst sorting-type) '< '>)))
7072 (t (error "Invalid sorting type `%c'" sorting-type)))
7073
7074 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7075 table)
7076 (lambda (a b) (funcall comparefun (car a) (car b))))))
7077
7078 ;;;; Plain list items, including checkboxes
7079
7080 ;;; Plain list items
7081
7082 (defun org-at-item-p ()
7083 "Is point in a line starting a hand-formatted item?"
7084 (let ((llt org-plain-list-ordered-item-terminator))
7085 (save-excursion
7086 (goto-char (point-at-bol))
7087 (looking-at
7088 (cond
7089 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7090 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7091 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7092 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7093
7094 (defun org-in-item-p ()
7095 "It the cursor inside a plain list item.
7096 Does not have to be the first line."
7097 (save-excursion
7098 (condition-case nil
7099 (progn
7100 (org-beginning-of-item)
7101 (org-at-item-p)
7102 t)
7103 (error nil))))
7104
7105 (defun org-insert-item (&optional checkbox)
7106 "Insert a new item at the current level.
7107 Return t when things worked, nil when we are not in an item."
7108 (when (save-excursion
7109 (condition-case nil
7110 (progn
7111 (org-beginning-of-item)
7112 (org-at-item-p)
7113 (if (org-invisible-p) (error "Invisible item"))
7114 t)
7115 (error nil)))
7116 (let* ((bul (match-string 0))
7117 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7118 (match-end 0)))
7119 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7120 pos)
7121 (cond
7122 ((and (org-at-item-p) (<= (point) eow))
7123 ;; before the bullet
7124 (beginning-of-line 1)
7125 (open-line (if blank 2 1)))
7126 ((<= (point) eow)
7127 (beginning-of-line 1))
7128 (t
7129 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7130 (end-of-line 1)
7131 (delete-horizontal-space))
7132 (newline (if blank 2 1))))
7133 (insert bul (if checkbox "[ ]" ""))
7134 (just-one-space)
7135 (setq pos (point))
7136 (end-of-line 1)
7137 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7138 (org-maybe-renumber-ordered-list)
7139 (and checkbox (org-update-checkbox-count-maybe))
7140 t))
7141
7142 ;;; Checkboxes
7143
7144 (defun org-at-item-checkbox-p ()
7145 "Is point at a line starting a plain-list item with a checklet?"
7146 (and (org-at-item-p)
7147 (save-excursion
7148 (goto-char (match-end 0))
7149 (skip-chars-forward " \t")
7150 (looking-at "\\[[- X]\\]"))))
7151
7152 (defun org-toggle-checkbox (&optional arg)
7153 "Toggle the checkbox in the current line."
7154 (interactive "P")
7155 (catch 'exit
7156 (let (beg end status (firstnew 'unknown))
7157 (cond
7158 ((org-region-active-p)
7159 (setq beg (region-beginning) end (region-end)))
7160 ((org-on-heading-p)
7161 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7162 ((org-at-item-checkbox-p)
7163 (let ((pos (point)))
7164 (replace-match
7165 (cond (arg "[-]")
7166 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7167 (t "[ ]"))
7168 t t)
7169 (goto-char pos))
7170 (throw 'exit t))
7171 (t (error "Not at a checkbox or heading, and no active region")))
7172 (save-excursion
7173 (goto-char beg)
7174 (while (< (point) end)
7175 (when (org-at-item-checkbox-p)
7176 (setq status (equal (match-string 0) "[X]"))
7177 (when (eq firstnew 'unknown)
7178 (setq firstnew (not status)))
7179 (replace-match
7180 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7181 (beginning-of-line 2)))))
7182 (org-update-checkbox-count-maybe))
7183
7184 (defun org-update-checkbox-count-maybe ()
7185 "Update checkbox statistics unless turned off by user."
7186 (when org-provide-checkbox-statistics
7187 (org-update-checkbox-count)))
7188
7189 (defun org-update-checkbox-count (&optional all)
7190 "Update the checkbox statistics in the current section.
7191 This will find all statistic cookies like [57%] and [6/12] and update them
7192 with the current numbers. With optional prefix argument ALL, do this for
7193 the whole buffer."
7194 (interactive "P")
7195 (save-excursion
7196 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7197 (beg (condition-case nil
7198 (progn (outline-back-to-heading) (point))
7199 (error (point-min))))
7200 (end (move-marker (make-marker)
7201 (progn (outline-next-heading) (point))))
7202 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7203 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7204 (re-find (concat re "\\|" re-box))
7205 beg-cookie end-cookie is-percent c-on c-off lim
7206 eline curr-ind next-ind continue-from startsearch
7207 (cstat 0)
7208 )
7209 (when all
7210 (goto-char (point-min))
7211 (outline-next-heading)
7212 (setq beg (point) end (point-max)))
7213 (goto-char end)
7214 ;; find each statistic cookie
7215 (while (re-search-backward re-find beg t)
7216 (setq beg-cookie (match-beginning 1)
7217 end-cookie (match-end 1)
7218 cstat (+ cstat (if end-cookie 1 0))
7219 startsearch (point-at-eol)
7220 continue-from (point-at-bol)
7221 is-percent (match-beginning 2)
7222 lim (cond
7223 ((org-on-heading-p) (outline-next-heading) (point))
7224 ((org-at-item-p) (org-end-of-item) (point))
7225 (t nil))
7226 c-on 0
7227 c-off 0)
7228 (when lim
7229 ;; find first checkbox for this cookie and gather
7230 ;; statistics from all that are at this indentation level
7231 (goto-char startsearch)
7232 (if (re-search-forward re-box lim t)
7233 (progn
7234 (org-beginning-of-item)
7235 (setq curr-ind (org-get-indentation))
7236 (setq next-ind curr-ind)
7237 (while (= curr-ind next-ind)
7238 (save-excursion (end-of-line) (setq eline (point)))
7239 (if (re-search-forward re-box eline t)
7240 (if (member (match-string 2) '("[ ]" "[-]"))
7241 (setq c-off (1+ c-off))
7242 (setq c-on (1+ c-on))
7243 )
7244 )
7245 (org-end-of-item)
7246 (setq next-ind (org-get-indentation))
7247 )))
7248 (goto-char continue-from)
7249 ;; update cookie
7250 (when end-cookie
7251 (delete-region beg-cookie end-cookie)
7252 (goto-char beg-cookie)
7253 (insert
7254 (if is-percent
7255 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7256 (format "[%d/%d]" c-on (+ c-on c-off)))))
7257 ;; update items checkbox if it has one
7258 (when (org-at-item-p)
7259 (org-beginning-of-item)
7260 (when (and (> (+ c-on c-off) 0)
7261 (re-search-forward re-box (point-at-eol) t))
7262 (setq beg-cookie (match-beginning 2)
7263 end-cookie (match-end 2))
7264 (delete-region beg-cookie end-cookie)
7265 (goto-char beg-cookie)
7266 (cond ((= c-off 0) (insert "[X]"))
7267 ((= c-on 0) (insert "[ ]"))
7268 (t (insert "[-]")))
7269 )))
7270 (goto-char continue-from))
7271 (when (interactive-p)
7272 (message "Checkbox satistics updated %s (%d places)"
7273 (if all "in entire file" "in current outline entry") cstat)))))
7274
7275 (defun org-get-checkbox-statistics-face ()
7276 "Select the face for checkbox statistics.
7277 The face will be `org-done' when all relevant boxes are checked. Otherwise
7278 it will be `org-todo'."
7279 (if (match-end 1)
7280 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7281 (if (and (> (match-end 2) (match-beginning 2))
7282 (equal (match-string 2) (match-string 3)))
7283 'org-done
7284 'org-todo)))
7285
7286 (defun org-get-indentation (&optional line)
7287 "Get the indentation of the current line, interpreting tabs.
7288 When LINE is given, assume it represents a line and compute its indentation."
7289 (if line
7290 (if (string-match "^ *" (org-remove-tabs line))
7291 (match-end 0))
7292 (save-excursion
7293 (beginning-of-line 1)
7294 (skip-chars-forward " \t")
7295 (current-column))))
7296
7297 (defun org-remove-tabs (s &optional width)
7298 "Replace tabulators in S with spaces.
7299 Assumes that s is a single line, starting in column 0."
7300 (setq width (or width tab-width))
7301 (while (string-match "\t" s)
7302 (setq s (replace-match
7303 (make-string
7304 (- (* width (/ (+ (match-beginning 0) width) width))
7305 (match-beginning 0)) ?\ )
7306 t t s)))
7307 s)
7308
7309 (defun org-fix-indentation (line ind)
7310 "Fix indentation in LINE.
7311 IND is a cons cell with target and minimum indentation.
7312 If the current indenation in LINE is smaller than the minimum,
7313 leave it alone. If it is larger than ind, set it to the target."
7314 (let* ((l (org-remove-tabs line))
7315 (i (org-get-indentation l))
7316 (i1 (car ind)) (i2 (cdr ind)))
7317 (if (>= i i2) (setq l (substring line i2)))
7318 (if (> i1 0)
7319 (concat (make-string i1 ?\ ) l)
7320 l)))
7321
7322 (defcustom org-empty-line-terminates-plain-lists nil
7323 "Non-nil means, an empty line ends all plain list levels.
7324 When nil, empty lines are part of the preceeding item."
7325 :group 'org-plain-lists
7326 :type 'boolean)
7327
7328 (defun org-beginning-of-item ()
7329 "Go to the beginning of the current hand-formatted item.
7330 If the cursor is not in an item, throw an error."
7331 (interactive)
7332 (let ((pos (point))
7333 (limit (save-excursion
7334 (condition-case nil
7335 (progn
7336 (org-back-to-heading)
7337 (beginning-of-line 2) (point))
7338 (error (point-min)))))
7339 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7340 ind ind1)
7341 (if (org-at-item-p)
7342 (beginning-of-line 1)
7343 (beginning-of-line 1)
7344 (skip-chars-forward " \t")
7345 (setq ind (current-column))
7346 (if (catch 'exit
7347 (while t
7348 (beginning-of-line 0)
7349 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7350
7351 (if (looking-at "[ \t]*$")
7352 (setq ind1 ind-empty)
7353 (skip-chars-forward " \t")
7354 (setq ind1 (current-column)))
7355 (if (< ind1 ind)
7356 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7357 nil
7358 (goto-char pos)
7359 (error "Not in an item")))))
7360
7361 (defun org-end-of-item ()
7362 "Go to the end of the current hand-formatted item.
7363 If the cursor is not in an item, throw an error."
7364 (interactive)
7365 (let* ((pos (point))
7366 ind1
7367 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7368 (limit (save-excursion (outline-next-heading) (point)))
7369 (ind (save-excursion
7370 (org-beginning-of-item)
7371 (skip-chars-forward " \t")
7372 (current-column)))
7373 (end (catch 'exit
7374 (while t
7375 (beginning-of-line 2)
7376 (if (eobp) (throw 'exit (point)))
7377 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7378 (if (looking-at "[ \t]*$")
7379 (setq ind1 ind-empty)
7380 (skip-chars-forward " \t")
7381 (setq ind1 (current-column)))
7382 (if (<= ind1 ind)
7383 (throw 'exit (point-at-bol)))))))
7384 (if end
7385 (goto-char end)
7386 (goto-char pos)
7387 (error "Not in an item"))))
7388
7389 (defun org-next-item ()
7390 "Move to the beginning of the next item in the current plain list.
7391 Error if not at a plain list, or if this is the last item in the list."
7392 (interactive)
7393 (let (ind ind1 (pos (point)))
7394 (org-beginning-of-item)
7395 (setq ind (org-get-indentation))
7396 (org-end-of-item)
7397 (setq ind1 (org-get-indentation))
7398 (unless (and (org-at-item-p) (= ind ind1))
7399 (goto-char pos)
7400 (error "On last item"))))
7401
7402 (defun org-previous-item ()
7403 "Move to the beginning of the previous item in the current plain list.
7404 Error if not at a plain list, or if this is the first item in the list."
7405 (interactive)
7406 (let (beg ind ind1 (pos (point)))
7407 (org-beginning-of-item)
7408 (setq beg (point))
7409 (setq ind (org-get-indentation))
7410 (goto-char beg)
7411 (catch 'exit
7412 (while t
7413 (beginning-of-line 0)
7414 (if (looking-at "[ \t]*$")
7415 nil
7416 (if (<= (setq ind1 (org-get-indentation)) ind)
7417 (throw 'exit t)))))
7418 (condition-case nil
7419 (if (or (not (org-at-item-p))
7420 (< ind1 (1- ind)))
7421 (error "")
7422 (org-beginning-of-item))
7423 (error (goto-char pos)
7424 (error "On first item")))))
7425
7426 (defun org-first-list-item-p ()
7427 "Is this heading the item in a plain list?"
7428 (unless (org-at-item-p)
7429 (error "Not at a plain list item"))
7430 (org-beginning-of-item)
7431 (= (point) (save-excursion (org-beginning-of-item-list))))
7432
7433 (defun org-move-item-down ()
7434 "Move the plain list item at point down, i.e. swap with following item.
7435 Subitems (items with larger indentation) are considered part of the item,
7436 so this really moves item trees."
7437 (interactive)
7438 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7439 (org-beginning-of-item)
7440 (setq beg0 (point))
7441 (save-excursion
7442 (setq ne-beg (org-back-over-empty-lines))
7443 (setq beg (point)))
7444 (goto-char beg0)
7445 (setq ind (org-get-indentation))
7446 (org-end-of-item)
7447 (setq end0 (point))
7448 (setq ind1 (org-get-indentation))
7449 (setq ne-end (org-back-over-empty-lines))
7450 (setq end (point))
7451 (goto-char beg0)
7452 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7453 ;; include less whitespace
7454 (save-excursion
7455 (goto-char beg)
7456 (forward-line (- ne-beg ne-end))
7457 (setq beg (point))))
7458 (goto-char end0)
7459 (if (and (org-at-item-p) (= ind ind1))
7460 (progn
7461 (org-end-of-item)
7462 (org-back-over-empty-lines)
7463 (setq txt (buffer-substring beg end))
7464 (save-excursion
7465 (delete-region beg end))
7466 (setq pos (point))
7467 (insert txt)
7468 (goto-char pos) (org-skip-whitespace)
7469 (org-maybe-renumber-ordered-list))
7470 (goto-char pos)
7471 (error "Cannot move this item further down"))))
7472
7473 (defun org-move-item-up (arg)
7474 "Move the plain list item at point up, i.e. swap with previous item.
7475 Subitems (items with larger indentation) are considered part of the item,
7476 so this really moves item trees."
7477 (interactive "p")
7478 (let (beg beg0 end ind ind1 (pos (point)) txt
7479 ne-beg ne-ins ins-end)
7480 (org-beginning-of-item)
7481 (setq beg0 (point))
7482 (setq ind (org-get-indentation))
7483 (save-excursion
7484 (setq ne-beg (org-back-over-empty-lines))
7485 (setq beg (point)))
7486 (goto-char beg0)
7487 (org-end-of-item)
7488 (setq end (point))
7489 (goto-char beg0)
7490 (catch 'exit
7491 (while t
7492 (beginning-of-line 0)
7493 (if (looking-at "[ \t]*$")
7494 (if org-empty-line-terminates-plain-lists
7495 (progn
7496 (goto-char pos)
7497 (error "Cannot move this item further up"))
7498 nil)
7499 (if (<= (setq ind1 (org-get-indentation)) ind)
7500 (throw 'exit t)))))
7501 (condition-case nil
7502 (org-beginning-of-item)
7503 (error (goto-char beg)
7504 (error "Cannot move this item further up")))
7505 (setq ind1 (org-get-indentation))
7506 (if (and (org-at-item-p) (= ind ind1))
7507 (progn
7508 (setq ne-ins (org-back-over-empty-lines))
7509 (setq txt (buffer-substring beg end))
7510 (save-excursion
7511 (delete-region beg end))
7512 (setq pos (point))
7513 (insert txt)
7514 (setq ins-end (point))
7515 (goto-char pos) (org-skip-whitespace)
7516
7517 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7518 ;; Move whitespace back to beginning
7519 (save-excursion
7520 (goto-char ins-end)
7521 (let ((kill-whole-line t))
7522 (kill-line (- ne-ins ne-beg)) (point)))
7523 (insert (make-string (- ne-ins ne-beg) ?\n)))
7524
7525 (org-maybe-renumber-ordered-list))
7526 (goto-char pos)
7527 (error "Cannot move this item further up"))))
7528
7529 (defun org-maybe-renumber-ordered-list ()
7530 "Renumber the ordered list at point if setup allows it.
7531 This tests the user option `org-auto-renumber-ordered-lists' before
7532 doing the renumbering."
7533 (interactive)
7534 (when (and org-auto-renumber-ordered-lists
7535 (org-at-item-p))
7536 (if (match-beginning 3)
7537 (org-renumber-ordered-list 1)
7538 (org-fix-bullet-type))))
7539
7540 (defun org-maybe-renumber-ordered-list-safe ()
7541 (condition-case nil
7542 (save-excursion
7543 (org-maybe-renumber-ordered-list))
7544 (error nil)))
7545
7546 (defun org-cycle-list-bullet (&optional which)
7547 "Cycle through the different itemize/enumerate bullets.
7548 This cycle the entire list level through the sequence:
7549
7550 `-' -> `+' -> `*' -> `1.' -> `1)'
7551
7552 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7553 0 meand `-', 1 means `+' etc."
7554 (interactive "P")
7555 (org-preserve-lc
7556 (org-beginning-of-item-list)
7557 (org-at-item-p)
7558 (beginning-of-line 1)
7559 (let ((current (match-string 0))
7560 (prevp (eq which 'previous))
7561 new)
7562 (setq new (cond
7563 ((and (numberp which)
7564 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7565 ((string-match "-" current) (if prevp "1)" "+"))
7566 ((string-match "\\+" current)
7567 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7568 ((string-match "\\*" current) (if prevp "+" "1."))
7569 ((string-match "\\." current) (if prevp "*" "1)"))
7570 ((string-match ")" current) (if prevp "1." "-"))
7571 (t (error "This should not happen"))))
7572 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7573 (org-fix-bullet-type)
7574 (org-maybe-renumber-ordered-list))))
7575
7576 (defun org-get-string-indentation (s)
7577 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7578 (let ((n -1) (i 0) (w tab-width) c)
7579 (catch 'exit
7580 (while (< (setq n (1+ n)) (length s))
7581 (setq c (aref s n))
7582 (cond ((= c ?\ ) (setq i (1+ i)))
7583 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7584 (t (throw 'exit t)))))
7585 i))
7586
7587 (defun org-renumber-ordered-list (arg)
7588 "Renumber an ordered plain list.
7589 Cursor needs to be in the first line of an item, the line that starts
7590 with something like \"1.\" or \"2)\"."
7591 (interactive "p")
7592 (unless (and (org-at-item-p)
7593 (match-beginning 3))
7594 (error "This is not an ordered list"))
7595 (let ((line (org-current-line))
7596 (col (current-column))
7597 (ind (org-get-string-indentation
7598 (buffer-substring (point-at-bol) (match-beginning 3))))
7599 ;; (term (substring (match-string 3) -1))
7600 ind1 (n (1- arg))
7601 fmt)
7602 ;; find where this list begins
7603 (org-beginning-of-item-list)
7604 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7605 (setq fmt (concat "%d" (match-string 1)))
7606 (beginning-of-line 0)
7607 ;; walk forward and replace these numbers
7608 (catch 'exit
7609 (while t
7610 (catch 'next
7611 (beginning-of-line 2)
7612 (if (eobp) (throw 'exit nil))
7613 (if (looking-at "[ \t]*$") (throw 'next nil))
7614 (skip-chars-forward " \t") (setq ind1 (current-column))
7615 (if (> ind1 ind) (throw 'next t))
7616 (if (< ind1 ind) (throw 'exit t))
7617 (if (not (org-at-item-p)) (throw 'exit nil))
7618 (delete-region (match-beginning 2) (match-end 2))
7619 (goto-char (match-beginning 2))
7620 (insert (format fmt (setq n (1+ n)))))))
7621 (goto-line line)
7622 (move-to-column col)))
7623
7624 (defun org-fix-bullet-type ()
7625 "Make sure all items in this list have the same bullet as the firsst item."
7626 (interactive)
7627 (unless (org-at-item-p) (error "This is not a list"))
7628 (let ((line (org-current-line))
7629 (col (current-column))
7630 (ind (current-indentation))
7631 ind1 bullet)
7632 ;; find where this list begins
7633 (org-beginning-of-item-list)
7634 (beginning-of-line 1)
7635 ;; find out what the bullet type is
7636 (looking-at "[ \t]*\\(\\S-+\\)")
7637 (setq bullet (match-string 1))
7638 ;; walk forward and replace these numbers
7639 (beginning-of-line 0)
7640 (catch 'exit
7641 (while t
7642 (catch 'next
7643 (beginning-of-line 2)
7644 (if (eobp) (throw 'exit nil))
7645 (if (looking-at "[ \t]*$") (throw 'next nil))
7646 (skip-chars-forward " \t") (setq ind1 (current-column))
7647 (if (> ind1 ind) (throw 'next t))
7648 (if (< ind1 ind) (throw 'exit t))
7649 (if (not (org-at-item-p)) (throw 'exit nil))
7650 (skip-chars-forward " \t")
7651 (looking-at "\\S-+")
7652 (replace-match bullet))))
7653 (goto-line line)
7654 (move-to-column col)
7655 (if (string-match "[0-9]" bullet)
7656 (org-renumber-ordered-list 1))))
7657
7658 (defun org-beginning-of-item-list ()
7659 "Go to the beginning of the current item list.
7660 I.e. to the first item in this list."
7661 (interactive)
7662 (org-beginning-of-item)
7663 (let ((pos (point-at-bol))
7664 (ind (org-get-indentation))
7665 ind1)
7666 ;; find where this list begins
7667 (catch 'exit
7668 (while t
7669 (catch 'next
7670 (beginning-of-line 0)
7671 (if (looking-at "[ \t]*$")
7672 (throw (if (bobp) 'exit 'next) t))
7673 (skip-chars-forward " \t") (setq ind1 (current-column))
7674 (if (or (< ind1 ind)
7675 (and (= ind1 ind)
7676 (not (org-at-item-p)))
7677 (bobp))
7678 (throw 'exit t)
7679 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7680 (goto-char pos)))
7681
7682
7683 (defun org-end-of-item-list ()
7684 "Go to the end of the current item list.
7685 I.e. to the text after the last item."
7686 (interactive)
7687 (org-beginning-of-item)
7688 (let ((pos (point-at-bol))
7689 (ind (org-get-indentation))
7690 ind1)
7691 ;; find where this list begins
7692 (catch 'exit
7693 (while t
7694 (catch 'next
7695 (beginning-of-line 2)
7696 (if (looking-at "[ \t]*$")
7697 (throw (if (eobp) 'exit 'next) t))
7698 (skip-chars-forward " \t") (setq ind1 (current-column))
7699 (if (or (< ind1 ind)
7700 (and (= ind1 ind)
7701 (not (org-at-item-p)))
7702 (eobp))
7703 (progn
7704 (setq pos (point-at-bol))
7705 (throw 'exit t))))))
7706 (goto-char pos)))
7707
7708
7709 (defvar org-last-indent-begin-marker (make-marker))
7710 (defvar org-last-indent-end-marker (make-marker))
7711
7712 (defun org-outdent-item (arg)
7713 "Outdent a local list item."
7714 (interactive "p")
7715 (org-indent-item (- arg)))
7716
7717 (defun org-indent-item (arg)
7718 "Indent a local list item."
7719 (interactive "p")
7720 (unless (org-at-item-p)
7721 (error "Not on an item"))
7722 (save-excursion
7723 (let (beg end ind ind1 tmp delta ind-down ind-up)
7724 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7725 (setq beg org-last-indent-begin-marker
7726 end org-last-indent-end-marker)
7727 (org-beginning-of-item)
7728 (setq beg (move-marker org-last-indent-begin-marker (point)))
7729 (org-end-of-item)
7730 (setq end (move-marker org-last-indent-end-marker (point))))
7731 (goto-char beg)
7732 (setq tmp (org-item-indent-positions)
7733 ind (car tmp)
7734 ind-down (nth 2 tmp)
7735 ind-up (nth 1 tmp)
7736 delta (if (> arg 0)
7737 (if ind-down (- ind-down ind) 2)
7738 (if ind-up (- ind-up ind) -2)))
7739 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7740 (while (< (point) end)
7741 (beginning-of-line 1)
7742 (skip-chars-forward " \t") (setq ind1 (current-column))
7743 (delete-region (point-at-bol) (point))
7744 (or (eolp) (indent-to-column (+ ind1 delta)))
7745 (beginning-of-line 2))))
7746 (org-fix-bullet-type)
7747 (org-maybe-renumber-ordered-list-safe)
7748 (save-excursion
7749 (beginning-of-line 0)
7750 (condition-case nil (org-beginning-of-item) (error nil))
7751 (org-maybe-renumber-ordered-list-safe)))
7752
7753 (defun org-item-indent-positions ()
7754 "Return indentation for plain list items.
7755 This returns a list with three values: The current indentation, the
7756 parent indentation and the indentation a child should habe.
7757 Assumes cursor in item line."
7758 (let* ((bolpos (point-at-bol))
7759 (ind (org-get-indentation))
7760 ind-down ind-up pos)
7761 (save-excursion
7762 (org-beginning-of-item-list)
7763 (skip-chars-backward "\n\r \t")
7764 (when (org-in-item-p)
7765 (org-beginning-of-item)
7766 (setq ind-up (org-get-indentation))))
7767 (setq pos (point))
7768 (save-excursion
7769 (cond
7770 ((and (condition-case nil (progn (org-previous-item) t)
7771 (error nil))
7772 (or (forward-char 1) t)
7773 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7774 (setq ind-down (org-get-indentation)))
7775 ((and (goto-char pos)
7776 (org-at-item-p))
7777 (goto-char (match-end 0))
7778 (skip-chars-forward " \t")
7779 (setq ind-down (current-column)))))
7780 (list ind ind-up ind-down)))
7781
7782 ;;; The orgstruct minor mode
7783
7784 ;; Define a minor mode which can be used in other modes in order to
7785 ;; integrate the org-mode structure editing commands.
7786
7787 ;; This is really a hack, because the org-mode structure commands use
7788 ;; keys which normally belong to the major mode. Here is how it
7789 ;; works: The minor mode defines all the keys necessary to operate the
7790 ;; structure commands, but wraps the commands into a function which
7791 ;; tests if the cursor is currently at a headline or a plain list
7792 ;; item. If that is the case, the structure command is used,
7793 ;; temporarily setting many Org-mode variables like regular
7794 ;; expressions for filling etc. However, when any of those keys is
7795 ;; used at a different location, function uses `key-binding' to look
7796 ;; up if the key has an associated command in another currently active
7797 ;; keymap (minor modes, major mode, global), and executes that
7798 ;; command. There might be problems if any of the keys is otherwise
7799 ;; used as a prefix key.
7800
7801 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7802 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7803 ;; addresses this by checking explicitly for both bindings.
7804
7805 (defvar orgstruct-mode-map (make-sparse-keymap)
7806 "Keymap for the minor `orgstruct-mode'.")
7807
7808 (defvar org-local-vars nil
7809 "List of local variables, for use by `orgstruct-mode'")
7810
7811 ;;;###autoload
7812 (define-minor-mode orgstruct-mode
7813 "Toggle the minor more `orgstruct-mode'.
7814 This mode is for using Org-mode structure commands in other modes.
7815 The following key behave as if Org-mode was active, if the cursor
7816 is on a headline, or on a plain list item (both in the definition
7817 of Org-mode).
7818
7819 M-up Move entry/item up
7820 M-down Move entry/item down
7821 M-left Promote
7822 M-right Demote
7823 M-S-up Move entry/item up
7824 M-S-down Move entry/item down
7825 M-S-left Promote subtree
7826 M-S-right Demote subtree
7827 M-q Fill paragraph and items like in Org-mode
7828 C-c ^ Sort entries
7829 C-c - Cycle list bullet
7830 TAB Cycle item visibility
7831 M-RET Insert new heading/item
7832 S-M-RET Insert new TODO heading / Chekbox item
7833 C-c C-c Set tags / toggle checkbox"
7834 nil " OrgStruct" nil
7835 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7836
7837 ;;;###autoload
7838 (defun turn-on-orgstruct ()
7839 "Unconditionally turn on `orgstruct-mode'."
7840 (orgstruct-mode 1))
7841
7842 ;;;###autoload
7843 (defun turn-on-orgstruct++ ()
7844 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7845 In addition to setting orgstruct-mode, this also exports all indentation and
7846 autofilling variables from org-mode into the buffer. Note that turning
7847 off orgstruct-mode will *not* remove these additional settings."
7848 (orgstruct-mode 1)
7849 (let (var val)
7850 (mapc
7851 (lambda (x)
7852 (when (string-match
7853 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7854 (symbol-name (car x)))
7855 (setq var (car x) val (nth 1 x))
7856 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7857 org-local-vars)))
7858
7859 (defun orgstruct-error ()
7860 "Error when there is no default binding for a structure key."
7861 (interactive)
7862 (error "This key has no function outside structure elements"))
7863
7864 (defun orgstruct-setup ()
7865 "Setup orgstruct keymaps."
7866 (let ((nfunc 0)
7867 (bindings
7868 (list
7869 '([(meta up)] org-metaup)
7870 '([(meta down)] org-metadown)
7871 '([(meta left)] org-metaleft)
7872 '([(meta right)] org-metaright)
7873 '([(meta shift up)] org-shiftmetaup)
7874 '([(meta shift down)] org-shiftmetadown)
7875 '([(meta shift left)] org-shiftmetaleft)
7876 '([(meta shift right)] org-shiftmetaright)
7877 '([(shift up)] org-shiftup)
7878 '([(shift down)] org-shiftdown)
7879 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7880 '("\M-q" fill-paragraph)
7881 '("\C-c^" org-sort)
7882 '("\C-c-" org-cycle-list-bullet)))
7883 elt key fun cmd)
7884 (while (setq elt (pop bindings))
7885 (setq nfunc (1+ nfunc))
7886 (setq key (org-key (car elt))
7887 fun (nth 1 elt)
7888 cmd (orgstruct-make-binding fun nfunc key))
7889 (org-defkey orgstruct-mode-map key cmd))
7890
7891 ;; Special treatment needed for TAB and RET
7892 (org-defkey orgstruct-mode-map [(tab)]
7893 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7894 (org-defkey orgstruct-mode-map "\C-i"
7895 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7896
7897 (org-defkey orgstruct-mode-map "\M-\C-m"
7898 (orgstruct-make-binding 'org-insert-heading 105
7899 "\M-\C-m" [(meta return)]))
7900 (org-defkey orgstruct-mode-map [(meta return)]
7901 (orgstruct-make-binding 'org-insert-heading 106
7902 [(meta return)] "\M-\C-m"))
7903
7904 (org-defkey orgstruct-mode-map [(shift meta return)]
7905 (orgstruct-make-binding 'org-insert-todo-heading 107
7906 [(meta return)] "\M-\C-m"))
7907
7908 (unless org-local-vars
7909 (setq org-local-vars (org-get-local-variables)))
7910
7911 t))
7912
7913 (defun orgstruct-make-binding (fun n &rest keys)
7914 "Create a function for binding in the structure minor mode.
7915 FUN is the command to call inside a table. N is used to create a unique
7916 command name. KEYS are keys that should be checked in for a command
7917 to execute outside of tables."
7918 (eval
7919 (list 'defun
7920 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7921 '(arg)
7922 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7923 "Outside of structure, run the binding of `"
7924 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7925 "'.")
7926 '(interactive "p")
7927 (list 'if
7928 '(org-context-p 'headline 'item)
7929 (list 'org-run-like-in-org-mode (list 'quote fun))
7930 (list 'let '(orgstruct-mode)
7931 (list 'call-interactively
7932 (append '(or)
7933 (mapcar (lambda (k)
7934 (list 'key-binding k))
7935 keys)
7936 '('orgstruct-error))))))))
7937
7938 (defun org-context-p (&rest contexts)
7939 "Check if local context is and of CONTEXTS.
7940 Possible values in the list of contexts are `table', `headline', and `item'."
7941 (let ((pos (point)))
7942 (goto-char (point-at-bol))
7943 (prog1 (or (and (memq 'table contexts)
7944 (looking-at "[ \t]*|"))
7945 (and (memq 'headline contexts)
7946 (looking-at "\\*+"))
7947 (and (memq 'item contexts)
7948 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7949 (goto-char pos))))
7950
7951 (defun org-get-local-variables ()
7952 "Return a list of all local variables in an org-mode buffer."
7953 (let (varlist)
7954 (with-current-buffer (get-buffer-create "*Org tmp*")
7955 (erase-buffer)
7956 (org-mode)
7957 (setq varlist (buffer-local-variables)))
7958 (kill-buffer "*Org tmp*")
7959 (delq nil
7960 (mapcar
7961 (lambda (x)
7962 (setq x
7963 (if (symbolp x)
7964 (list x)
7965 (list (car x) (list 'quote (cdr x)))))
7966 (if (string-match
7967 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7968 (symbol-name (car x)))
7969 x nil))
7970 varlist))))
7971
7972 ;;;###autoload
7973 (defun org-run-like-in-org-mode (cmd)
7974 (unless org-local-vars
7975 (setq org-local-vars (org-get-local-variables)))
7976 (eval (list 'let org-local-vars
7977 (list 'call-interactively (list 'quote cmd)))))
7978
7979 ;;;; Archiving
7980
7981 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7982
7983 (defun org-archive-subtree (&optional find-done)
7984 "Move the current subtree to the archive.
7985 The archive can be a certain top-level heading in the current file, or in
7986 a different file. The tree will be moved to that location, the subtree
7987 heading be marked DONE, and the current time will be added.
7988
7989 When called with prefix argument FIND-DONE, find whole trees without any
7990 open TODO items and archive them (after getting confirmation from the user).
7991 If the cursor is not at a headline when this comand is called, try all level
7992 1 trees. If the cursor is on a headline, only try the direct children of
7993 this heading."
7994 (interactive "P")
7995 (if find-done
7996 (org-archive-all-done)
7997 ;; Save all relevant TODO keyword-relatex variables
7998
7999 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
8000 (tr-org-todo-keywords-1 org-todo-keywords-1)
8001 (tr-org-todo-kwd-alist org-todo-kwd-alist)
8002 (tr-org-done-keywords org-done-keywords)
8003 (tr-org-todo-regexp org-todo-regexp)
8004 (tr-org-todo-line-regexp org-todo-line-regexp)
8005 (tr-org-odd-levels-only org-odd-levels-only)
8006 (this-buffer (current-buffer))
8007 (org-archive-location org-archive-location)
8008 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
8009 ;; start of variables that will be used for saving context
8010 ;; The compiler complains about them - keep them anyway!
8011 (file (abbreviate-file-name (buffer-file-name)))
8012 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
8013 (time (format-time-string
8014 (substring (cdr org-time-stamp-formats) 1 -1)
8015 (current-time)))
8016 afile heading buffer level newfile-p
8017 category todo priority
8018 ;; start of variables that will be used for savind context
8019 ltags itags prop)
8020
8021 ;; Try to find a local archive location
8022 (save-excursion
8023 (save-restriction
8024 (widen)
8025 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
8026 (if (and prop (string-match "\\S-" prop))
8027 (setq org-archive-location prop)
8028 (if (or (re-search-backward re nil t)
8029 (re-search-forward re nil t))
8030 (setq org-archive-location (match-string 1))))))
8031
8032 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
8033 (progn
8034 (setq afile (format (match-string 1 org-archive-location)
8035 (file-name-nondirectory buffer-file-name))
8036 heading (match-string 2 org-archive-location)))
8037 (error "Invalid `org-archive-location'"))
8038 (if (> (length afile) 0)
8039 (setq newfile-p (not (file-exists-p afile))
8040 buffer (find-file-noselect afile))
8041 (setq buffer (current-buffer)))
8042 (unless buffer
8043 (error "Cannot access file \"%s\"" afile))
8044 (if (and (> (length heading) 0)
8045 (string-match "^\\*+" heading))
8046 (setq level (match-end 0))
8047 (setq heading nil level 0))
8048 (save-excursion
8049 (org-back-to-heading t)
8050 ;; Get context information that will be lost by moving the tree
8051 (org-refresh-category-properties)
8052 (setq category (org-get-category)
8053 todo (and (looking-at org-todo-line-regexp)
8054 (match-string 2))
8055 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
8056 ltags (org-get-tags)
8057 itags (org-delete-all ltags (org-get-tags-at)))
8058 (setq ltags (mapconcat 'identity ltags " ")
8059 itags (mapconcat 'identity itags " "))
8060 ;; We first only copy, in case something goes wrong
8061 ;; we need to protect this-command, to avoid kill-region sets it,
8062 ;; which would lead to duplication of subtrees
8063 (let (this-command) (org-copy-subtree))
8064 (set-buffer buffer)
8065 ;; Enforce org-mode for the archive buffer
8066 (if (not (org-mode-p))
8067 ;; Force the mode for future visits.
8068 (let ((org-insert-mode-line-in-empty-file t)
8069 (org-inhibit-startup t))
8070 (call-interactively 'org-mode)))
8071 (when newfile-p
8072 (goto-char (point-max))
8073 (insert (format "\nArchived entries from file %s\n\n"
8074 (buffer-file-name this-buffer))))
8075 ;; Force the TODO keywords of the original buffer
8076 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
8077 (org-todo-keywords-1 tr-org-todo-keywords-1)
8078 (org-todo-kwd-alist tr-org-todo-kwd-alist)
8079 (org-done-keywords tr-org-done-keywords)
8080 (org-todo-regexp tr-org-todo-regexp)
8081 (org-todo-line-regexp tr-org-todo-line-regexp)
8082 (org-odd-levels-only
8083 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8084 org-odd-levels-only
8085 tr-org-odd-levels-only)))
8086 (goto-char (point-min))
8087 (show-all)
8088 (if heading
8089 (progn
8090 (if (re-search-forward
8091 (concat "^" (regexp-quote heading)
8092 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8093 nil t)
8094 (goto-char (match-end 0))
8095 ;; Heading not found, just insert it at the end
8096 (goto-char (point-max))
8097 (or (bolp) (insert "\n"))
8098 (insert "\n" heading "\n")
8099 (end-of-line 0))
8100 ;; Make the subtree visible
8101 (show-subtree)
8102 (org-end-of-subtree t)
8103 (skip-chars-backward " \t\r\n")
8104 (and (looking-at "[ \t\r\n]*")
8105 (replace-match "\n\n")))
8106 ;; No specific heading, just go to end of file.
8107 (goto-char (point-max)) (insert "\n"))
8108 ;; Paste
8109 (org-paste-subtree (org-get-valid-level level 1))
8110
8111 ;; Mark the entry as done
8112 (when (and org-archive-mark-done
8113 (looking-at org-todo-line-regexp)
8114 (or (not (match-end 2))
8115 (not (member (match-string 2) org-done-keywords))))
8116 (let (org-log-done org-todo-log-states)
8117 (org-todo
8118 (car (or (member org-archive-mark-done org-done-keywords)
8119 org-done-keywords)))))
8120
8121 ;; Add the context info
8122 (when org-archive-save-context-info
8123 (let ((l org-archive-save-context-info) e n v)
8124 (while (setq e (pop l))
8125 (when (and (setq v (symbol-value e))
8126 (stringp v) (string-match "\\S-" v))
8127 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8128 (org-entry-put (point) n v)))))
8129
8130 ;; Save and kill the buffer, if it is not the same buffer.
8131 (if (not (eq this-buffer buffer))
8132 (progn (save-buffer) (kill-buffer buffer)))))
8133 ;; Here we are back in the original buffer. Everything seems to have
8134 ;; worked. So now cut the tree and finish up.
8135 (let (this-command) (org-cut-subtree))
8136 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8137 (message "Subtree archived %s"
8138 (if (eq this-buffer buffer)
8139 (concat "under heading: " heading)
8140 (concat "in file: " (abbreviate-file-name afile)))))))
8141
8142 (defun org-refresh-category-properties ()
8143 "Refresh category text properties in teh buffer."
8144 (let ((def-cat (cond
8145 ((null org-category)
8146 (if buffer-file-name
8147 (file-name-sans-extension
8148 (file-name-nondirectory buffer-file-name))
8149 "???"))
8150 ((symbolp org-category) (symbol-name org-category))
8151 (t org-category)))
8152 beg end cat pos optionp)
8153 (org-unmodified
8154 (save-excursion
8155 (save-restriction
8156 (widen)
8157 (goto-char (point-min))
8158 (put-text-property (point) (point-max) 'org-category def-cat)
8159 (while (re-search-forward
8160 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8161 (setq pos (match-end 0)
8162 optionp (equal (char-after (match-beginning 0)) ?#)
8163 cat (org-trim (match-string 2)))
8164 (if optionp
8165 (setq beg (point-at-bol) end (point-max))
8166 (org-back-to-heading t)
8167 (setq beg (point) end (org-end-of-subtree t t)))
8168 (put-text-property beg end 'org-category cat)
8169 (goto-char pos)))))))
8170
8171 (defun org-archive-all-done (&optional tag)
8172 "Archive sublevels of the current tree without open TODO items.
8173 If the cursor is not on a headline, try all level 1 trees. If
8174 it is on a headline, try all direct children.
8175 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8176 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8177 (rea (concat ".*:" org-archive-tag ":"))
8178 (begm (make-marker))
8179 (endm (make-marker))
8180 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8181 "Move subtree to archive (no open TODO items)? "))
8182 beg end (cntarch 0))
8183 (if (org-on-heading-p)
8184 (progn
8185 (setq re1 (concat "^" (regexp-quote
8186 (make-string
8187 (1+ (- (match-end 0) (match-beginning 0) 1))
8188 ?*))
8189 " "))
8190 (move-marker begm (point))
8191 (move-marker endm (org-end-of-subtree t)))
8192 (setq re1 "^* ")
8193 (move-marker begm (point-min))
8194 (move-marker endm (point-max)))
8195 (save-excursion
8196 (goto-char begm)
8197 (while (re-search-forward re1 endm t)
8198 (setq beg (match-beginning 0)
8199 end (save-excursion (org-end-of-subtree t) (point)))
8200 (goto-char beg)
8201 (if (re-search-forward re end t)
8202 (goto-char end)
8203 (goto-char beg)
8204 (if (and (or (not tag) (not (looking-at rea)))
8205 (y-or-n-p question))
8206 (progn
8207 (if tag
8208 (org-toggle-tag org-archive-tag 'on)
8209 (org-archive-subtree))
8210 (setq cntarch (1+ cntarch)))
8211 (goto-char end)))))
8212 (message "%d trees archived" cntarch)))
8213
8214 (defun org-cycle-hide-drawers (state)
8215 "Re-hide all drawers after a visibility state change."
8216 (when (and (org-mode-p)
8217 (not (memq state '(overview folded))))
8218 (save-excursion
8219 (let* ((globalp (memq state '(contents all)))
8220 (beg (if globalp (point-min) (point)))
8221 (end (if globalp (point-max) (org-end-of-subtree t))))
8222 (goto-char beg)
8223 (while (re-search-forward org-drawer-regexp end t)
8224 (org-flag-drawer t))))))
8225
8226 (defun org-flag-drawer (flag)
8227 (save-excursion
8228 (beginning-of-line 1)
8229 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8230 (let ((b (match-end 0))
8231 (outline-regexp org-outline-regexp))
8232 (if (re-search-forward
8233 "^[ \t]*:END:"
8234 (save-excursion (outline-next-heading) (point)) t)
8235 (outline-flag-region b (point-at-eol) flag)
8236 (error ":END: line missing"))))))
8237
8238 (defun org-cycle-hide-archived-subtrees (state)
8239 "Re-hide all archived subtrees after a visibility state change."
8240 (when (and (not org-cycle-open-archived-trees)
8241 (not (memq state '(overview folded))))
8242 (save-excursion
8243 (let* ((globalp (memq state '(contents all)))
8244 (beg (if globalp (point-min) (point)))
8245 (end (if globalp (point-max) (org-end-of-subtree t))))
8246 (org-hide-archived-subtrees beg end)
8247 (goto-char beg)
8248 (if (looking-at (concat ".*:" org-archive-tag ":"))
8249 (message "%s" (substitute-command-keys
8250 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8251
8252 (defun org-force-cycle-archived ()
8253 "Cycle subtree even if it is archived."
8254 (interactive)
8255 (setq this-command 'org-cycle)
8256 (let ((org-cycle-open-archived-trees t))
8257 (call-interactively 'org-cycle)))
8258
8259 (defun org-hide-archived-subtrees (beg end)
8260 "Re-hide all archived subtrees after a visibility state change."
8261 (save-excursion
8262 (let* ((re (concat ":" org-archive-tag ":")))
8263 (goto-char beg)
8264 (while (re-search-forward re end t)
8265 (and (org-on-heading-p) (hide-subtree))
8266 (org-end-of-subtree t)))))
8267
8268 (defun org-toggle-tag (tag &optional onoff)
8269 "Toggle the tag TAG for the current line.
8270 If ONOFF is `on' or `off', don't toggle but set to this state."
8271 (unless (org-on-heading-p t) (error "Not on headling"))
8272 (let (res current)
8273 (save-excursion
8274 (beginning-of-line)
8275 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8276 (point-at-eol) t)
8277 (progn
8278 (setq current (match-string 1))
8279 (replace-match ""))
8280 (setq current ""))
8281 (setq current (nreverse (org-split-string current ":")))
8282 (cond
8283 ((eq onoff 'on)
8284 (setq res t)
8285 (or (member tag current) (push tag current)))
8286 ((eq onoff 'off)
8287 (or (not (member tag current)) (setq current (delete tag current))))
8288 (t (if (member tag current)
8289 (setq current (delete tag current))
8290 (setq res t)
8291 (push tag current))))
8292 (end-of-line 1)
8293 (if current
8294 (progn
8295 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8296 (org-set-tags nil t))
8297 (delete-horizontal-space))
8298 (run-hooks 'org-after-tags-change-hook))
8299 res))
8300
8301 (defun org-toggle-archive-tag (&optional arg)
8302 "Toggle the archive tag for the current headline.
8303 With prefix ARG, check all children of current headline and offer tagging
8304 the children that do not contain any open TODO items."
8305 (interactive "P")
8306 (if arg
8307 (org-archive-all-done 'tag)
8308 (let (set)
8309 (save-excursion
8310 (org-back-to-heading t)
8311 (setq set (org-toggle-tag org-archive-tag))
8312 (when set (hide-subtree)))
8313 (and set (beginning-of-line 1))
8314 (message "Subtree %s" (if set "archived" "unarchived")))))
8315
8316
8317 ;;;; Tables
8318
8319 ;;; The table editor
8320
8321 ;; Watch out: Here we are talking about two different kind of tables.
8322 ;; Most of the code is for the tables created with the Org-mode table editor.
8323 ;; Sometimes, we talk about tables created and edited with the table.el
8324 ;; Emacs package. We call the former org-type tables, and the latter
8325 ;; table.el-type tables.
8326
8327 (defun org-before-change-function (beg end)
8328 "Every change indicates that a table might need an update."
8329 (setq org-table-may-need-update t))
8330
8331 (defconst org-table-line-regexp "^[ \t]*|"
8332 "Detects an org-type table line.")
8333 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8334 "Detects an org-type table line.")
8335 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8336 "Detects a table line marked for automatic recalculation.")
8337 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8338 "Detects a table line marked for automatic recalculation.")
8339 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8340 "Detects a table line marked for automatic recalculation.")
8341 (defconst org-table-hline-regexp "^[ \t]*|-"
8342 "Detects an org-type table hline.")
8343 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8344 "Detects a table-type table hline.")
8345 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8346 "Detects an org-type or table-type table.")
8347 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8348 "Searching from within a table (any type) this finds the first line
8349 outside the table.")
8350 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8351 "Searching from within a table (any type) this finds the first line
8352 outside the table.")
8353
8354 (defvar org-table-last-highlighted-reference nil)
8355 (defvar org-table-formula-history nil)
8356
8357 (defvar org-table-column-names nil
8358 "Alist with column names, derived from the `!' line.")
8359 (defvar org-table-column-name-regexp nil
8360 "Regular expression matching the current column names.")
8361 (defvar org-table-local-parameters nil
8362 "Alist with parameter names, derived from the `$' line.")
8363 (defvar org-table-named-field-locations nil
8364 "Alist with locations of named fields.")
8365
8366 (defvar org-table-current-line-types nil
8367 "Table row types, non-nil only for the duration of a comand.")
8368 (defvar org-table-current-begin-line nil
8369 "Table begin line, non-nil only for the duration of a comand.")
8370 (defvar org-table-current-begin-pos nil
8371 "Table begin position, non-nil only for the duration of a comand.")
8372 (defvar org-table-dlines nil
8373 "Vector of data line line numbers in the current table.")
8374 (defvar org-table-hlines nil
8375 "Vector of hline line numbers in the current table.")
8376
8377 (defconst org-table-range-regexp
8378 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8379 ;; 1 2 3 4 5
8380 "Regular expression for matching ranges in formulas.")
8381
8382 (defconst org-table-range-regexp2
8383 (concat
8384 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8385 "\\.\\."
8386 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8387 "Match a range for reference display.")
8388
8389 (defconst org-table-translate-regexp
8390 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8391 "Match a reference that needs translation, for reference display.")
8392
8393 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8394
8395 (defun org-table-create-with-table.el ()
8396 "Use the table.el package to insert a new table.
8397 If there is already a table at point, convert between Org-mode tables
8398 and table.el tables."
8399 (interactive)
8400 (require 'table)
8401 (cond
8402 ((org-at-table.el-p)
8403 (if (y-or-n-p "Convert table to Org-mode table? ")
8404 (org-table-convert)))
8405 ((org-at-table-p)
8406 (if (y-or-n-p "Convert table to table.el table? ")
8407 (org-table-convert)))
8408 (t (call-interactively 'table-insert))))
8409
8410 (defun org-table-create-or-convert-from-region (arg)
8411 "Convert region to table, or create an empty table.
8412 If there is an active region, convert it to a table, using the function
8413 `org-table-convert-region'. See the documentation of that function
8414 to learn how the prefix argument is interpreted to determine the field
8415 separator.
8416 If there is no such region, create an empty table with `org-table-create'."
8417 (interactive "P")
8418 (if (org-region-active-p)
8419 (org-table-convert-region (region-beginning) (region-end) arg)
8420 (org-table-create arg)))
8421
8422 (defun org-table-create (&optional size)
8423 "Query for a size and insert a table skeleton.
8424 SIZE is a string Columns x Rows like for example \"3x2\"."
8425 (interactive "P")
8426 (unless size
8427 (setq size (read-string
8428 (concat "Table size Columns x Rows [e.g. "
8429 org-table-default-size "]: ")
8430 "" nil org-table-default-size)))
8431
8432 (let* ((pos (point))
8433 (indent (make-string (current-column) ?\ ))
8434 (split (org-split-string size " *x *"))
8435 (rows (string-to-number (nth 1 split)))
8436 (columns (string-to-number (car split)))
8437 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8438 "\n")))
8439 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8440 (point-at-bol) (point)))
8441 (beginning-of-line 1)
8442 (newline))
8443 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8444 (dotimes (i rows) (insert line))
8445 (goto-char pos)
8446 (if (> rows 1)
8447 ;; Insert a hline after the first row.
8448 (progn
8449 (end-of-line 1)
8450 (insert "\n|-")
8451 (goto-char pos)))
8452 (org-table-align)))
8453
8454 (defun org-table-convert-region (beg0 end0 &optional separator)
8455 "Convert region to a table.
8456 The region goes from BEG0 to END0, but these borders will be moved
8457 slightly, to make sure a beginning of line in the first line is included.
8458
8459 SEPARATOR specifies the field separator in the lines. It can have the
8460 following values:
8461
8462 '(4) Use the comma as a field separator
8463 '(16) Use a TAB as field separator
8464 integer When a number, use that many spaces as field separator
8465 nil When nil, the command tries to be smart and figure out the
8466 separator in the following way:
8467 - when each line contains a TAB, assume TAB-separated material
8468 - when each line contains a comme, assume CSV material
8469 - else, assume one or more SPACE charcters as separator."
8470 (interactive "rP")
8471 (let* ((beg (min beg0 end0))
8472 (end (max beg0 end0))
8473 re)
8474 (goto-char beg)
8475 (beginning-of-line 1)
8476 (setq beg (move-marker (make-marker) (point)))
8477 (goto-char end)
8478 (if (bolp) (backward-char 1) (end-of-line 1))
8479 (setq end (move-marker (make-marker) (point)))
8480 ;; Get the right field separator
8481 (unless separator
8482 (goto-char beg)
8483 (setq separator
8484 (cond
8485 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8486 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8487 (t 1))))
8488 (setq re (cond
8489 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8490 ((equal separator '(16)) "^\\|\t")
8491 ((integerp separator)
8492 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8493 (t (error "This should not happen"))))
8494 (goto-char beg)
8495 (while (re-search-forward re end t)
8496 (replace-match "| " t t))
8497 (goto-char beg)
8498 (insert " ")
8499 (org-table-align)))
8500
8501 (defun org-table-import (file arg)
8502 "Import FILE as a table.
8503 The file is assumed to be tab-separated. Such files can be produced by most
8504 spreadsheet and database applications. If no tabs (at least one per line)
8505 are found, lines will be split on whitespace into fields."
8506 (interactive "f\nP")
8507 (or (bolp) (newline))
8508 (let ((beg (point))
8509 (pm (point-max)))
8510 (insert-file-contents file)
8511 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8512
8513 (defun org-table-export ()
8514 "Export table as a tab-separated file.
8515 Such a file can be imported into a spreadsheet program like Excel."
8516 (interactive)
8517 (let* ((beg (org-table-begin))
8518 (end (org-table-end))
8519 (table (buffer-substring beg end))
8520 (file (read-file-name "Export table to: "))
8521 buf)
8522 (unless (or (not (file-exists-p file))
8523 (y-or-n-p (format "Overwrite file %s? " file)))
8524 (error "Abort"))
8525 (with-current-buffer (find-file-noselect file)
8526 (setq buf (current-buffer))
8527 (erase-buffer)
8528 (fundamental-mode)
8529 (insert table)
8530 (goto-char (point-min))
8531 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8532 (replace-match "" t t)
8533 (end-of-line 1))
8534 (goto-char (point-min))
8535 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8536 (replace-match "" t t)
8537 (goto-char (min (1+ (point)) (point-max))))
8538 (goto-char (point-min))
8539 (while (re-search-forward "^-[-+]*$" nil t)
8540 (replace-match "")
8541 (if (looking-at "\n")
8542 (delete-char 1)))
8543 (goto-char (point-min))
8544 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8545 (replace-match "\t" t t))
8546 (save-buffer))
8547 (kill-buffer buf)))
8548
8549 (defvar org-table-aligned-begin-marker (make-marker)
8550 "Marker at the beginning of the table last aligned.
8551 Used to check if cursor still is in that table, to minimize realignment.")
8552 (defvar org-table-aligned-end-marker (make-marker)
8553 "Marker at the end of the table last aligned.
8554 Used to check if cursor still is in that table, to minimize realignment.")
8555 (defvar org-table-last-alignment nil
8556 "List of flags for flushright alignment, from the last re-alignment.
8557 This is being used to correctly align a single field after TAB or RET.")
8558 (defvar org-table-last-column-widths nil
8559 "List of max width of fields in each column.
8560 This is being used to correctly align a single field after TAB or RET.")
8561 (defvar org-table-overlay-coordinates nil
8562 "Overlay coordinates after each align of a table.")
8563 (make-variable-buffer-local 'org-table-overlay-coordinates)
8564
8565 (defvar org-last-recalc-line nil)
8566 (defconst org-narrow-column-arrow "=>"
8567 "Used as display property in narrowed table columns.")
8568
8569 (defun org-table-align ()
8570 "Align the table at point by aligning all vertical bars."
8571 (interactive)
8572 (let* (
8573 ;; Limits of table
8574 (beg (org-table-begin))
8575 (end (org-table-end))
8576 ;; Current cursor position
8577 (linepos (org-current-line))
8578 (colpos (org-table-current-column))
8579 (winstart (window-start))
8580 (winstartline (org-current-line (min winstart (1- (point-max)))))
8581 lines (new "") lengths l typenums ty fields maxfields i
8582 column
8583 (indent "") cnt frac
8584 rfmt hfmt
8585 (spaces '(1 . 1))
8586 (sp1 (car spaces))
8587 (sp2 (cdr spaces))
8588 (rfmt1 (concat
8589 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8590 (hfmt1 (concat
8591 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8592 emptystrings links dates emph narrow fmax f1 len c e)
8593 (untabify beg end)
8594 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8595 ;; Check if we have links or dates
8596 (goto-char beg)
8597 (setq links (re-search-forward org-bracket-link-regexp end t))
8598 (goto-char beg)
8599 (setq emph (and org-hide-emphasis-markers
8600 (re-search-forward org-emph-re end t)))
8601 (goto-char beg)
8602 (setq dates (and org-display-custom-times
8603 (re-search-forward org-ts-regexp-both end t)))
8604 ;; Make sure the link properties are right
8605 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8606 ;; Make sure the date properties are right
8607 (when dates (goto-char beg) (while (org-activate-dates end)))
8608 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8609
8610 ;; Check if we are narrowing any columns
8611 (goto-char beg)
8612 (setq narrow (and org-format-transports-properties-p
8613 (re-search-forward "<[0-9]+>" end t)))
8614 ;; Get the rows
8615 (setq lines (org-split-string
8616 (buffer-substring beg end) "\n"))
8617 ;; Store the indentation of the first line
8618 (if (string-match "^ *" (car lines))
8619 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8620 ;; Mark the hlines by setting the corresponding element to nil
8621 ;; At the same time, we remove trailing space.
8622 (setq lines (mapcar (lambda (l)
8623 (if (string-match "^ *|-" l)
8624 nil
8625 (if (string-match "[ \t]+$" l)
8626 (substring l 0 (match-beginning 0))
8627 l)))
8628 lines))
8629 ;; Get the data fields by splitting the lines.
8630 (setq fields (mapcar
8631 (lambda (l)
8632 (org-split-string l " *| *"))
8633 (delq nil (copy-sequence lines))))
8634 ;; How many fields in the longest line?
8635 (condition-case nil
8636 (setq maxfields (apply 'max (mapcar 'length fields)))
8637 (error
8638 (kill-region beg end)
8639 (org-table-create org-table-default-size)
8640 (error "Empty table - created default table")))
8641 ;; A list of empty strings to fill any short rows on output
8642 (setq emptystrings (make-list maxfields ""))
8643 ;; Check for special formatting.
8644 (setq i -1)
8645 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8646 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8647 ;; Check if there is an explicit width specified
8648 (when narrow
8649 (setq c column fmax nil)
8650 (while c
8651 (setq e (pop c))
8652 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8653 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8654 ;; Find fields that are wider than fmax, and shorten them
8655 (when fmax
8656 (loop for xx in column do
8657 (when (and (stringp xx)
8658 (> (org-string-width xx) fmax))
8659 (org-add-props xx nil
8660 'help-echo
8661 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8662 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8663 (unless (> f1 1)
8664 (error "Cannot narrow field starting with wide link \"%s\""
8665 (match-string 0 xx)))
8666 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8667 (add-text-properties (- f1 2) f1
8668 (list 'display org-narrow-column-arrow)
8669 xx)))))
8670 ;; Get the maximum width for each column
8671 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8672 ;; Get the fraction of numbers, to decide about alignment of the column
8673 (setq cnt 0 frac 0.0)
8674 (loop for x in column do
8675 (if (equal x "")
8676 nil
8677 (setq frac ( / (+ (* frac cnt)
8678 (if (string-match org-table-number-regexp x) 1 0))
8679 (setq cnt (1+ cnt))))))
8680 (push (>= frac org-table-number-fraction) typenums))
8681 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8682
8683 ;; Store the alignment of this table, for later editing of single fields
8684 (setq org-table-last-alignment typenums
8685 org-table-last-column-widths lengths)
8686
8687 ;; With invisible characters, `format' does not get the field width right
8688 ;; So we need to make these fields wide by hand.
8689 (when (or links emph)
8690 (loop for i from 0 upto (1- maxfields) do
8691 (setq len (nth i lengths))
8692 (loop for j from 0 upto (1- (length fields)) do
8693 (setq c (nthcdr i (car (nthcdr j fields))))
8694 (if (and (stringp (car c))
8695 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8696 ; (string-match org-bracket-link-regexp (car c))
8697 (< (org-string-width (car c)) len))
8698 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8699
8700 ;; Compute the formats needed for output of the table
8701 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8702 (while (setq l (pop lengths))
8703 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8704 (setq rfmt (concat rfmt (format rfmt1 ty l))
8705 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8706 (setq rfmt (concat rfmt "\n")
8707 hfmt (concat (substring hfmt 0 -1) "|\n"))
8708
8709 (setq new (mapconcat
8710 (lambda (l)
8711 (if l (apply 'format rfmt
8712 (append (pop fields) emptystrings))
8713 hfmt))
8714 lines ""))
8715 ;; Replace the old one
8716 (delete-region beg end)
8717 (move-marker end nil)
8718 (move-marker org-table-aligned-begin-marker (point))
8719 (insert new)
8720 (move-marker org-table-aligned-end-marker (point))
8721 (when (and orgtbl-mode (not (org-mode-p)))
8722 (goto-char org-table-aligned-begin-marker)
8723 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8724 ;; Try to move to the old location
8725 (goto-line winstartline)
8726 (setq winstart (point-at-bol))
8727 (goto-line linepos)
8728 (set-window-start (selected-window) winstart 'noforce)
8729 (org-table-goto-column colpos)
8730 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8731 (setq org-table-may-need-update nil)
8732 ))
8733
8734 (defun org-string-width (s)
8735 "Compute width of string, ignoring invisible characters.
8736 This ignores character with invisibility property `org-link', and also
8737 characters with property `org-cwidth', because these will become invisible
8738 upon the next fontification round."
8739 (let (b l)
8740 (when (or (eq t buffer-invisibility-spec)
8741 (assq 'org-link buffer-invisibility-spec))
8742 (while (setq b (text-property-any 0 (length s)
8743 'invisible 'org-link s))
8744 (setq s (concat (substring s 0 b)
8745 (substring s (or (next-single-property-change
8746 b 'invisible s) (length s)))))))
8747 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8748 (setq s (concat (substring s 0 b)
8749 (substring s (or (next-single-property-change
8750 b 'org-cwidth s) (length s))))))
8751 (setq l (string-width s) b -1)
8752 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8753 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8754 l))
8755
8756 (defun org-table-begin (&optional table-type)
8757 "Find the beginning of the table and return its position.
8758 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8759 (save-excursion
8760 (if (not (re-search-backward
8761 (if table-type org-table-any-border-regexp
8762 org-table-border-regexp)
8763 nil t))
8764 (progn (goto-char (point-min)) (point))
8765 (goto-char (match-beginning 0))
8766 (beginning-of-line 2)
8767 (point))))
8768
8769 (defun org-table-end (&optional table-type)
8770 "Find the end of the table and return its position.
8771 With argument TABLE-TYPE, go to the end of a table.el-type table."
8772 (save-excursion
8773 (if (not (re-search-forward
8774 (if table-type org-table-any-border-regexp
8775 org-table-border-regexp)
8776 nil t))
8777 (goto-char (point-max))
8778 (goto-char (match-beginning 0)))
8779 (point-marker)))
8780
8781 (defun org-table-justify-field-maybe (&optional new)
8782 "Justify the current field, text to left, number to right.
8783 Optional argument NEW may specify text to replace the current field content."
8784 (cond
8785 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8786 ((org-at-table-hline-p))
8787 ((and (not new)
8788 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8789 (current-buffer)))
8790 (< (point) org-table-aligned-begin-marker)
8791 (>= (point) org-table-aligned-end-marker)))
8792 ;; This is not the same table, force a full re-align
8793 (setq org-table-may-need-update t))
8794 (t ;; realign the current field, based on previous full realign
8795 (let* ((pos (point)) s
8796 (col (org-table-current-column))
8797 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8798 l f n o e)
8799 (when (> col 0)
8800 (skip-chars-backward "^|\n")
8801 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8802 (progn
8803 (setq s (match-string 1)
8804 o (match-string 0)
8805 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8806 e (not (= (match-beginning 2) (match-end 2))))
8807 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8808 l (if e "|" (setq org-table-may-need-update t) ""))
8809 n (format f s))
8810 (if new
8811 (if (<= (length new) l) ;; FIXME: length -> str-width?
8812 (setq n (format f new))
8813 (setq n (concat new "|") org-table-may-need-update t)))
8814 (or (equal n o)
8815 (let (org-table-may-need-update)
8816 (replace-match n t t))))
8817 (setq org-table-may-need-update t))
8818 (goto-char pos))))))
8819
8820 (defun org-table-next-field ()
8821 "Go to the next field in the current table, creating new lines as needed.
8822 Before doing so, re-align the table if necessary."
8823 (interactive)
8824 (org-table-maybe-eval-formula)
8825 (org-table-maybe-recalculate-line)
8826 (if (and org-table-automatic-realign
8827 org-table-may-need-update)
8828 (org-table-align))
8829 (let ((end (org-table-end)))
8830 (if (org-at-table-hline-p)
8831 (end-of-line 1))
8832 (condition-case nil
8833 (progn
8834 (re-search-forward "|" end)
8835 (if (looking-at "[ \t]*$")
8836 (re-search-forward "|" end))
8837 (if (and (looking-at "-")
8838 org-table-tab-jumps-over-hlines
8839 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8840 (goto-char (match-beginning 1)))
8841 (if (looking-at "-")
8842 (progn
8843 (beginning-of-line 0)
8844 (org-table-insert-row 'below))
8845 (if (looking-at " ") (forward-char 1))))
8846 (error
8847 (org-table-insert-row 'below)))))
8848
8849 (defun org-table-previous-field ()
8850 "Go to the previous field in the table.
8851 Before doing so, re-align the table if necessary."
8852 (interactive)
8853 (org-table-justify-field-maybe)
8854 (org-table-maybe-recalculate-line)
8855 (if (and org-table-automatic-realign
8856 org-table-may-need-update)
8857 (org-table-align))
8858 (if (org-at-table-hline-p)
8859 (end-of-line 1))
8860 (re-search-backward "|" (org-table-begin))
8861 (re-search-backward "|" (org-table-begin))
8862 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8863 (re-search-backward "|" (org-table-begin)))
8864 (if (looking-at "| ?")
8865 (goto-char (match-end 0))))
8866
8867 (defun org-table-next-row ()
8868 "Go to the next row (same column) in the current table.
8869 Before doing so, re-align the table if necessary."
8870 (interactive)
8871 (org-table-maybe-eval-formula)
8872 (org-table-maybe-recalculate-line)
8873 (if (or (looking-at "[ \t]*$")
8874 (save-excursion (skip-chars-backward " \t") (bolp)))
8875 (newline)
8876 (if (and org-table-automatic-realign
8877 org-table-may-need-update)
8878 (org-table-align))
8879 (let ((col (org-table-current-column)))
8880 (beginning-of-line 2)
8881 (if (or (not (org-at-table-p))
8882 (org-at-table-hline-p))
8883 (progn
8884 (beginning-of-line 0)
8885 (org-table-insert-row 'below)))
8886 (org-table-goto-column col)
8887 (skip-chars-backward "^|\n\r")
8888 (if (looking-at " ") (forward-char 1)))))
8889
8890 (defun org-table-copy-down (n)
8891 "Copy a field down in the current column.
8892 If the field at the cursor is empty, copy into it the content of the nearest
8893 non-empty field above. With argument N, use the Nth non-empty field.
8894 If the current field is not empty, it is copied down to the next row, and
8895 the cursor is moved with it. Therefore, repeating this command causes the
8896 column to be filled row-by-row.
8897 If the variable `org-table-copy-increment' is non-nil and the field is an
8898 integer or a timestamp, it will be incremented while copying. In the case of
8899 a timestamp, if the cursor is on the year, change the year. If it is on the
8900 month or the day, change that. Point will stay on the current date field
8901 in order to easily repeat the interval."
8902 (interactive "p")
8903 (let* ((colpos (org-table-current-column))
8904 (col (current-column))
8905 (field (org-table-get-field))
8906 (non-empty (string-match "[^ \t]" field))
8907 (beg (org-table-begin))
8908 txt)
8909 (org-table-check-inside-data-field)
8910 (if non-empty
8911 (progn
8912 (setq txt (org-trim field))
8913 (org-table-next-row)
8914 (org-table-blank-field))
8915 (save-excursion
8916 (setq txt
8917 (catch 'exit
8918 (while (progn (beginning-of-line 1)
8919 (re-search-backward org-table-dataline-regexp
8920 beg t))
8921 (org-table-goto-column colpos t)
8922 (if (and (looking-at
8923 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8924 (= (setq n (1- n)) 0))
8925 (throw 'exit (match-string 1))))))))
8926 (if txt
8927 (progn
8928 (if (and org-table-copy-increment
8929 (string-match "^[0-9]+$" txt))
8930 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8931 (insert txt)
8932 (move-to-column col)
8933 (if (and org-table-copy-increment (org-at-timestamp-p t))
8934 (org-timestamp-up 1)
8935 (org-table-maybe-recalculate-line))
8936 (org-table-align)
8937 (move-to-column col))
8938 (error "No non-empty field found"))))
8939
8940 (defun org-table-check-inside-data-field ()
8941 "Is point inside a table data field?
8942 I.e. not on a hline or before the first or after the last column?
8943 This actually throws an error, so it aborts the current command."
8944 (if (or (not (org-at-table-p))
8945 (= (org-table-current-column) 0)
8946 (org-at-table-hline-p)
8947 (looking-at "[ \t]*$"))
8948 (error "Not in table data field")))
8949
8950 (defvar org-table-clip nil
8951 "Clipboard for table regions.")
8952
8953 (defun org-table-blank-field ()
8954 "Blank the current table field or active region."
8955 (interactive)
8956 (org-table-check-inside-data-field)
8957 (if (and (interactive-p) (org-region-active-p))
8958 (let (org-table-clip)
8959 (org-table-cut-region (region-beginning) (region-end)))
8960 (skip-chars-backward "^|")
8961 (backward-char 1)
8962 (if (looking-at "|[^|\n]+")
8963 (let* ((pos (match-beginning 0))
8964 (match (match-string 0))
8965 (len (org-string-width match)))
8966 (replace-match (concat "|" (make-string (1- len) ?\ )))
8967 (goto-char (+ 2 pos))
8968 (substring match 1)))))
8969
8970 (defun org-table-get-field (&optional n replace)
8971 "Return the value of the field in column N of current row.
8972 N defaults to current field.
8973 If REPLACE is a string, replace field with this value. The return value
8974 is always the old value."
8975 (and n (org-table-goto-column n))
8976 (skip-chars-backward "^|\n")
8977 (backward-char 1)
8978 (if (looking-at "|[^|\r\n]*")
8979 (let* ((pos (match-beginning 0))
8980 (val (buffer-substring (1+ pos) (match-end 0))))
8981 (if replace
8982 (replace-match (concat "|" replace) t t))
8983 (goto-char (min (point-at-eol) (+ 2 pos)))
8984 val)
8985 (forward-char 1) ""))
8986
8987 (defun org-table-field-info (arg)
8988 "Show info about the current field, and highlight any reference at point."
8989 (interactive "P")
8990 (org-table-get-specials)
8991 (save-excursion
8992 (let* ((pos (point))
8993 (col (org-table-current-column))
8994 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8995 (name (car (rassoc (list (org-current-line) col)
8996 org-table-named-field-locations)))
8997 (eql (org-table-get-stored-formulas))
8998 (dline (org-table-current-dline))
8999 (ref (format "@%d$%d" dline col))
9000 (ref1 (org-table-convert-refs-to-an ref))
9001 (fequation (or (assoc name eql) (assoc ref eql)))
9002 (cequation (assoc (int-to-string col) eql))
9003 (eqn (or fequation cequation)))
9004 (goto-char pos)
9005 (condition-case nil
9006 (org-table-show-reference 'local)
9007 (error nil))
9008 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
9009 dline col
9010 (if cname (concat " or $" cname) "")
9011 dline col ref1
9012 (if name (concat " or $" name) "")
9013 ;; FIXME: formula info not correct if special table line
9014 (if eqn
9015 (concat ", formula: "
9016 (org-table-formula-to-user
9017 (concat
9018 (if (string-match "^[$@]"(car eqn)) "" "$")
9019 (car eqn) "=" (cdr eqn))))
9020 "")))))
9021
9022 (defun org-table-current-column ()
9023 "Find out which column we are in.
9024 When called interactively, column is also displayed in echo area."
9025 (interactive)
9026 (if (interactive-p) (org-table-check-inside-data-field))
9027 (save-excursion
9028 (let ((cnt 0) (pos (point)))
9029 (beginning-of-line 1)
9030 (while (search-forward "|" pos t)
9031 (setq cnt (1+ cnt)))
9032 (if (interactive-p) (message "This is table column %d" cnt))
9033 cnt)))
9034
9035 (defun org-table-current-dline ()
9036 "Find out what table data line we are in.
9037 Only datalins count for this."
9038 (interactive)
9039 (if (interactive-p) (org-table-check-inside-data-field))
9040 (save-excursion
9041 (let ((cnt 0) (pos (point)))
9042 (goto-char (org-table-begin))
9043 (while (<= (point) pos)
9044 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
9045 (beginning-of-line 2))
9046 (if (interactive-p) (message "This is table line %d" cnt))
9047 cnt)))
9048
9049 (defun org-table-goto-column (n &optional on-delim force)
9050 "Move the cursor to the Nth column in the current table line.
9051 With optional argument ON-DELIM, stop with point before the left delimiter
9052 of the field.
9053 If there are less than N fields, just go to after the last delimiter.
9054 However, when FORCE is non-nil, create new columns if necessary."
9055 (interactive "p")
9056 (let ((pos (point-at-eol)))
9057 (beginning-of-line 1)
9058 (when (> n 0)
9059 (while (and (> (setq n (1- n)) -1)
9060 (or (search-forward "|" pos t)
9061 (and force
9062 (progn (end-of-line 1)
9063 (skip-chars-backward "^|")
9064 (insert " | "))))))
9065 ; (backward-char 2) t)))))
9066 (when (and force (not (looking-at ".*|")))
9067 (save-excursion (end-of-line 1) (insert " | ")))
9068 (if on-delim
9069 (backward-char 1)
9070 (if (looking-at " ") (forward-char 1))))))
9071
9072 (defun org-at-table-p (&optional table-type)
9073 "Return t if the cursor is inside an org-type table.
9074 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9075 (if org-enable-table-editor
9076 (save-excursion
9077 (beginning-of-line 1)
9078 (looking-at (if table-type org-table-any-line-regexp
9079 org-table-line-regexp)))
9080 nil))
9081
9082 (defun org-at-table.el-p ()
9083 "Return t if and only if we are at a table.el table."
9084 (and (org-at-table-p 'any)
9085 (save-excursion
9086 (goto-char (org-table-begin 'any))
9087 (looking-at org-table1-hline-regexp))))
9088
9089 (defun org-table-recognize-table.el ()
9090 "If there is a table.el table nearby, recognize it and move into it."
9091 (if org-table-tab-recognizes-table.el
9092 (if (org-at-table.el-p)
9093 (progn
9094 (beginning-of-line 1)
9095 (if (looking-at org-table-dataline-regexp)
9096 nil
9097 (if (looking-at org-table1-hline-regexp)
9098 (progn
9099 (beginning-of-line 2)
9100 (if (looking-at org-table-any-border-regexp)
9101 (beginning-of-line -1)))))
9102 (if (re-search-forward "|" (org-table-end t) t)
9103 (progn
9104 (require 'table)
9105 (if (table--at-cell-p (point))
9106 t
9107 (message "recognizing table.el table...")
9108 (table-recognize-table)
9109 (message "recognizing table.el table...done")))
9110 (error "This should not happen..."))
9111 t)
9112 nil)
9113 nil))
9114
9115 (defun org-at-table-hline-p ()
9116 "Return t if the cursor is inside a hline in a table."
9117 (if org-enable-table-editor
9118 (save-excursion
9119 (beginning-of-line 1)
9120 (looking-at org-table-hline-regexp))
9121 nil))
9122
9123 (defun org-table-insert-column ()
9124 "Insert a new column into the table."
9125 (interactive)
9126 (if (not (org-at-table-p))
9127 (error "Not at a table"))
9128 (org-table-find-dataline)
9129 (let* ((col (max 1 (org-table-current-column)))
9130 (beg (org-table-begin))
9131 (end (org-table-end))
9132 ;; Current cursor position
9133 (linepos (org-current-line))
9134 (colpos col))
9135 (goto-char beg)
9136 (while (< (point) end)
9137 (if (org-at-table-hline-p)
9138 nil
9139 (org-table-goto-column col t)
9140 (insert "| "))
9141 (beginning-of-line 2))
9142 (move-marker end nil)
9143 (goto-line linepos)
9144 (org-table-goto-column colpos)
9145 (org-table-align)
9146 (org-table-fix-formulas "$" nil (1- col) 1)))
9147
9148 (defun org-table-find-dataline ()
9149 "Find a dataline in the current table, which is needed for column commands."
9150 (if (and (org-at-table-p)
9151 (not (org-at-table-hline-p)))
9152 t
9153 (let ((col (current-column))
9154 (end (org-table-end)))
9155 (move-to-column col)
9156 (while (and (< (point) end)
9157 (or (not (= (current-column) col))
9158 (org-at-table-hline-p)))
9159 (beginning-of-line 2)
9160 (move-to-column col))
9161 (if (and (org-at-table-p)
9162 (not (org-at-table-hline-p)))
9163 t
9164 (error
9165 "Please position cursor in a data line for column operations")))))
9166
9167 (defun org-table-delete-column ()
9168 "Delete a column from the table."
9169 (interactive)
9170 (if (not (org-at-table-p))
9171 (error "Not at a table"))
9172 (org-table-find-dataline)
9173 (org-table-check-inside-data-field)
9174 (let* ((col (org-table-current-column))
9175 (beg (org-table-begin))
9176 (end (org-table-end))
9177 ;; Current cursor position
9178 (linepos (org-current-line))
9179 (colpos col))
9180 (goto-char beg)
9181 (while (< (point) end)
9182 (if (org-at-table-hline-p)
9183 nil
9184 (org-table-goto-column col t)
9185 (and (looking-at "|[^|\n]+|")
9186 (replace-match "|")))
9187 (beginning-of-line 2))
9188 (move-marker end nil)
9189 (goto-line linepos)
9190 (org-table-goto-column colpos)
9191 (org-table-align)
9192 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9193 col -1 col)))
9194
9195 (defun org-table-move-column-right ()
9196 "Move column to the right."
9197 (interactive)
9198 (org-table-move-column nil))
9199 (defun org-table-move-column-left ()
9200 "Move column to the left."
9201 (interactive)
9202 (org-table-move-column 'left))
9203
9204 (defun org-table-move-column (&optional left)
9205 "Move the current column to the right. With arg LEFT, move to the left."
9206 (interactive "P")
9207 (if (not (org-at-table-p))
9208 (error "Not at a table"))
9209 (org-table-find-dataline)
9210 (org-table-check-inside-data-field)
9211 (let* ((col (org-table-current-column))
9212 (col1 (if left (1- col) col))
9213 (beg (org-table-begin))
9214 (end (org-table-end))
9215 ;; Current cursor position
9216 (linepos (org-current-line))
9217 (colpos (if left (1- col) (1+ col))))
9218 (if (and left (= col 1))
9219 (error "Cannot move column further left"))
9220 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9221 (error "Cannot move column further right"))
9222 (goto-char beg)
9223 (while (< (point) end)
9224 (if (org-at-table-hline-p)
9225 nil
9226 (org-table-goto-column col1 t)
9227 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9228 (replace-match "|\\2|\\1|")))
9229 (beginning-of-line 2))
9230 (move-marker end nil)
9231 (goto-line linepos)
9232 (org-table-goto-column colpos)
9233 (org-table-align)
9234 (org-table-fix-formulas
9235 "$" (list (cons (number-to-string col) (number-to-string colpos))
9236 (cons (number-to-string colpos) (number-to-string col))))))
9237
9238 (defun org-table-move-row-down ()
9239 "Move table row down."
9240 (interactive)
9241 (org-table-move-row nil))
9242 (defun org-table-move-row-up ()
9243 "Move table row up."
9244 (interactive)
9245 (org-table-move-row 'up))
9246
9247 (defun org-table-move-row (&optional up)
9248 "Move the current table line down. With arg UP, move it up."
9249 (interactive "P")
9250 (let* ((col (current-column))
9251 (pos (point))
9252 (hline1p (save-excursion (beginning-of-line 1)
9253 (looking-at org-table-hline-regexp)))
9254 (dline1 (org-table-current-dline))
9255 (dline2 (+ dline1 (if up -1 1)))
9256 (tonew (if up 0 2))
9257 txt hline2p)
9258 (beginning-of-line tonew)
9259 (unless (org-at-table-p)
9260 (goto-char pos)
9261 (error "Cannot move row further"))
9262 (setq hline2p (looking-at org-table-hline-regexp))
9263 (goto-char pos)
9264 (beginning-of-line 1)
9265 (setq pos (point))
9266 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9267 (delete-region (point) (1+ (point-at-eol)))
9268 (beginning-of-line tonew)
9269 (insert txt)
9270 (beginning-of-line 0)
9271 (move-to-column col)
9272 (unless (or hline1p hline2p)
9273 (org-table-fix-formulas
9274 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9275 (cons (number-to-string dline2) (number-to-string dline1)))))))
9276
9277 (defun org-table-insert-row (&optional arg)
9278 "Insert a new row above the current line into the table.
9279 With prefix ARG, insert below the current line."
9280 (interactive "P")
9281 (if (not (org-at-table-p))
9282 (error "Not at a table"))
9283 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9284 (new (org-table-clean-line line)))
9285 ;; Fix the first field if necessary
9286 (if (string-match "^[ \t]*| *[#$] *|" line)
9287 (setq new (replace-match (match-string 0 line) t t new)))
9288 (beginning-of-line (if arg 2 1))
9289 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9290 (beginning-of-line 0)
9291 (re-search-forward "| ?" (point-at-eol) t)
9292 (and (or org-table-may-need-update org-table-overlay-coordinates)
9293 (org-table-align))
9294 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9295
9296 (defun org-table-insert-hline (&optional above)
9297 "Insert a horizontal-line below the current line into the table.
9298 With prefix ABOVE, insert above the current line."
9299 (interactive "P")
9300 (if (not (org-at-table-p))
9301 (error "Not at a table"))
9302 (let ((line (org-table-clean-line
9303 (buffer-substring (point-at-bol) (point-at-eol))))
9304 (col (current-column)))
9305 (while (string-match "|\\( +\\)|" line)
9306 (setq line (replace-match
9307 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9308 ?-) "|") t t line)))
9309 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9310 (beginning-of-line (if above 1 2))
9311 (insert line "\n")
9312 (beginning-of-line (if above 1 -1))
9313 (move-to-column col)
9314 (and org-table-overlay-coordinates (org-table-align))))
9315
9316 (defun org-table-hline-and-move (&optional same-column)
9317 "Insert a hline and move to the row below that line."
9318 (interactive "P")
9319 (let ((col (org-table-current-column)))
9320 (org-table-maybe-eval-formula)
9321 (org-table-maybe-recalculate-line)
9322 (org-table-insert-hline)
9323 (end-of-line 2)
9324 (if (looking-at "\n[ \t]*|-")
9325 (progn (insert "\n|") (org-table-align))
9326 (org-table-next-field))
9327 (if same-column (org-table-goto-column col))))
9328
9329 (defun org-table-clean-line (s)
9330 "Convert a table line S into a string with only \"|\" and space.
9331 In particular, this does handle wide and invisible characters."
9332 (if (string-match "^[ \t]*|-" s)
9333 ;; It's a hline, just map the characters
9334 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9335 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9336 (setq s (replace-match
9337 (concat "|" (make-string (org-string-width (match-string 1 s))
9338 ?\ ) "|")
9339 t t s)))
9340 s))
9341
9342 (defun org-table-kill-row ()
9343 "Delete the current row or horizontal line from the table."
9344 (interactive)
9345 (if (not (org-at-table-p))
9346 (error "Not at a table"))
9347 (let ((col (current-column))
9348 (dline (org-table-current-dline)))
9349 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9350 (if (not (org-at-table-p)) (beginning-of-line 0))
9351 (move-to-column col)
9352 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9353 dline -1 dline)))
9354
9355 (defun org-table-sort-lines (with-case &optional sorting-type)
9356 "Sort table lines according to the column at point.
9357
9358 The position of point indicates the column to be used for
9359 sorting, and the range of lines is the range between the nearest
9360 horizontal separator lines, or the entire table of no such lines
9361 exist. If point is before the first column, you will be prompted
9362 for the sorting column. If there is an active region, the mark
9363 specifies the first line and the sorting column, while point
9364 should be in the last line to be included into the sorting.
9365
9366 The command then prompts for the sorting type which can be
9367 alphabetically, numerically, or by time (as given in a time stamp
9368 in the field). Sorting in reverse order is also possible.
9369
9370 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9371
9372 If SORTING-TYPE is specified when this function is called from a Lisp
9373 program, no prompting will take place. SORTING-TYPE must be a character,
9374 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9375 should be done in reverse order."
9376 (interactive "P")
9377 (let* ((thisline (org-current-line))
9378 (thiscol (org-table-current-column))
9379 beg end bcol ecol tend tbeg column lns pos)
9380 (when (equal thiscol 0)
9381 (if (interactive-p)
9382 (setq thiscol
9383 (string-to-number
9384 (read-string "Use column N for sorting: ")))
9385 (setq thiscol 1))
9386 (org-table-goto-column thiscol))
9387 (org-table-check-inside-data-field)
9388 (if (org-region-active-p)
9389 (progn
9390 (setq beg (region-beginning) end (region-end))
9391 (goto-char beg)
9392 (setq column (org-table-current-column)
9393 beg (point-at-bol))
9394 (goto-char end)
9395 (setq end (point-at-bol 2)))
9396 (setq column (org-table-current-column)
9397 pos (point)
9398 tbeg (org-table-begin)
9399 tend (org-table-end))
9400 (if (re-search-backward org-table-hline-regexp tbeg t)
9401 (setq beg (point-at-bol 2))
9402 (goto-char tbeg)
9403 (setq beg (point-at-bol 1)))
9404 (goto-char pos)
9405 (if (re-search-forward org-table-hline-regexp tend t)
9406 (setq end (point-at-bol 1))
9407 (goto-char tend)
9408 (setq end (point-at-bol))))
9409 (setq beg (move-marker (make-marker) beg)
9410 end (move-marker (make-marker) end))
9411 (untabify beg end)
9412 (goto-char beg)
9413 (org-table-goto-column column)
9414 (skip-chars-backward "^|")
9415 (setq bcol (current-column))
9416 (org-table-goto-column (1+ column))
9417 (skip-chars-backward "^|")
9418 (setq ecol (1- (current-column)))
9419 (org-table-goto-column column)
9420 (setq lns (mapcar (lambda(x) (cons
9421 (org-sort-remove-invisible
9422 (nth (1- column)
9423 (org-split-string x "[ \t]*|[ \t]*")))
9424 x))
9425 (org-split-string (buffer-substring beg end) "\n")))
9426 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9427 (delete-region beg end)
9428 (move-marker beg nil)
9429 (move-marker end nil)
9430 (insert (mapconcat 'cdr lns "\n") "\n")
9431 (goto-line thisline)
9432 (org-table-goto-column thiscol)
9433 (message "%d lines sorted, based on column %d" (length lns) column)))
9434
9435 ;; FIXME: maybe we will not need this? Table sorting is broken....
9436 (defun org-sort-remove-invisible (s)
9437 (remove-text-properties 0 (length s) org-rm-props s)
9438 (while (string-match org-bracket-link-regexp s)
9439 (setq s (replace-match (if (match-end 2)
9440 (match-string 3 s)
9441 (match-string 1 s)) t t s)))
9442 s)
9443
9444 (defun org-table-cut-region (beg end)
9445 "Copy region in table to the clipboard and blank all relevant fields."
9446 (interactive "r")
9447 (org-table-copy-region beg end 'cut))
9448
9449 (defun org-table-copy-region (beg end &optional cut)
9450 "Copy rectangular region in table to clipboard.
9451 A special clipboard is used which can only be accessed
9452 with `org-table-paste-rectangle'."
9453 (interactive "rP")
9454 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9455 region cols
9456 (rpl (if cut " " nil)))
9457 (goto-char beg)
9458 (org-table-check-inside-data-field)
9459 (setq l01 (org-current-line)
9460 c01 (org-table-current-column))
9461 (goto-char end)
9462 (org-table-check-inside-data-field)
9463 (setq l02 (org-current-line)
9464 c02 (org-table-current-column))
9465 (setq l1 (min l01 l02) l2 (max l01 l02)
9466 c1 (min c01 c02) c2 (max c01 c02))
9467 (catch 'exit
9468 (while t
9469 (catch 'nextline
9470 (if (> l1 l2) (throw 'exit t))
9471 (goto-line l1)
9472 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9473 (setq cols nil ic1 c1 ic2 c2)
9474 (while (< ic1 (1+ ic2))
9475 (push (org-table-get-field ic1 rpl) cols)
9476 (setq ic1 (1+ ic1)))
9477 (push (nreverse cols) region)
9478 (setq l1 (1+ l1)))))
9479 (setq org-table-clip (nreverse region))
9480 (if cut (org-table-align))
9481 org-table-clip))
9482
9483 (defun org-table-paste-rectangle ()
9484 "Paste a rectangular region into a table.
9485 The upper right corner ends up in the current field. All involved fields
9486 will be overwritten. If the rectangle does not fit into the present table,
9487 the table is enlarged as needed. The process ignores horizontal separator
9488 lines."
9489 (interactive)
9490 (unless (and org-table-clip (listp org-table-clip))
9491 (error "First cut/copy a region to paste!"))
9492 (org-table-check-inside-data-field)
9493 (let* ((clip org-table-clip)
9494 (line (org-current-line))
9495 (col (org-table-current-column))
9496 (org-enable-table-editor t)
9497 (org-table-automatic-realign nil)
9498 c cols field)
9499 (while (setq cols (pop clip))
9500 (while (org-at-table-hline-p) (beginning-of-line 2))
9501 (if (not (org-at-table-p))
9502 (progn (end-of-line 0) (org-table-next-field)))
9503 (setq c col)
9504 (while (setq field (pop cols))
9505 (org-table-goto-column c nil 'force)
9506 (org-table-get-field nil field)
9507 (setq c (1+ c)))
9508 (beginning-of-line 2))
9509 (goto-line line)
9510 (org-table-goto-column col)
9511 (org-table-align)))
9512
9513 (defun org-table-convert ()
9514 "Convert from `org-mode' table to table.el and back.
9515 Obviously, this only works within limits. When an Org-mode table is
9516 converted to table.el, all horizontal separator lines get lost, because
9517 table.el uses these as cell boundaries and has no notion of horizontal lines.
9518 A table.el table can be converted to an Org-mode table only if it does not
9519 do row or column spanning. Multiline cells will become multiple cells.
9520 Beware, Org-mode does not test if the table can be successfully converted - it
9521 blindly applies a recipe that works for simple tables."
9522 (interactive)
9523 (require 'table)
9524 (if (org-at-table.el-p)
9525 ;; convert to Org-mode table
9526 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9527 (end (move-marker (make-marker) (org-table-end t))))
9528 (table-unrecognize-region beg end)
9529 (goto-char beg)
9530 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9531 (replace-match ""))
9532 (goto-char beg))
9533 (if (org-at-table-p)
9534 ;; convert to table.el table
9535 (let ((beg (move-marker (make-marker) (org-table-begin)))
9536 (end (move-marker (make-marker) (org-table-end))))
9537 ;; first, get rid of all horizontal lines
9538 (goto-char beg)
9539 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9540 (replace-match ""))
9541 ;; insert a hline before first
9542 (goto-char beg)
9543 (org-table-insert-hline 'above)
9544 (beginning-of-line -1)
9545 ;; insert a hline after each line
9546 (while (progn (beginning-of-line 3) (< (point) end))
9547 (org-table-insert-hline))
9548 (goto-char beg)
9549 (setq end (move-marker end (org-table-end)))
9550 ;; replace "+" at beginning and ending of hlines
9551 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9552 (replace-match "\\1+-"))
9553 (goto-char beg)
9554 (while (re-search-forward "-|[ \t]*$" end t)
9555 (replace-match "-+"))
9556 (goto-char beg)))))
9557
9558 (defun org-table-wrap-region (arg)
9559 "Wrap several fields in a column like a paragraph.
9560 This is useful if you'd like to spread the contents of a field over several
9561 lines, in order to keep the table compact.
9562
9563 If there is an active region, and both point and mark are in the same column,
9564 the text in the column is wrapped to minimum width for the given number of
9565 lines. Generally, this makes the table more compact. A prefix ARG may be
9566 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9567 formats the selected text to two lines. If the region was longer than two
9568 lines, the remaining lines remain empty. A negative prefix argument reduces
9569 the current number of lines by that amount. The wrapped text is pasted back
9570 into the table. If you formatted it to more lines than it was before, fields
9571 further down in the table get overwritten - so you might need to make space in
9572 the table first.
9573
9574 If there is no region, the current field is split at the cursor position and
9575 the text fragment to the right of the cursor is prepended to the field one
9576 line down.
9577
9578 If there is no region, but you specify a prefix ARG, the current field gets
9579 blank, and the content is appended to the field above."
9580 (interactive "P")
9581 (org-table-check-inside-data-field)
9582 (if (org-region-active-p)
9583 ;; There is a region: fill as a paragraph
9584 (let* ((beg (region-beginning))
9585 (cline (save-excursion (goto-char beg) (org-current-line)))
9586 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9587 nlines)
9588 (org-table-cut-region (region-beginning) (region-end))
9589 (if (> (length (car org-table-clip)) 1)
9590 (error "Region must be limited to single column"))
9591 (setq nlines (if arg
9592 (if (< arg 1)
9593 (+ (length org-table-clip) arg)
9594 arg)
9595 (length org-table-clip)))
9596 (setq org-table-clip
9597 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9598 nil nlines)))
9599 (goto-line cline)
9600 (org-table-goto-column ccol)
9601 (org-table-paste-rectangle))
9602 ;; No region, split the current field at point
9603 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9604 (skip-chars-forward "^\r\n|"))
9605 (if arg
9606 ;; combine with field above
9607 (let ((s (org-table-blank-field))
9608 (col (org-table-current-column)))
9609 (beginning-of-line 0)
9610 (while (org-at-table-hline-p) (beginning-of-line 0))
9611 (org-table-goto-column col)
9612 (skip-chars-forward "^|")
9613 (skip-chars-backward " ")
9614 (insert " " (org-trim s))
9615 (org-table-align))
9616 ;; split field
9617 (if (looking-at "\\([^|]+\\)+|")
9618 (let ((s (match-string 1)))
9619 (replace-match " |")
9620 (goto-char (match-beginning 0))
9621 (org-table-next-row)
9622 (insert (org-trim s) " ")
9623 (org-table-align))
9624 (org-table-next-row)))))
9625
9626 (defvar org-field-marker nil)
9627
9628 (defun org-table-edit-field (arg)
9629 "Edit table field in a different window.
9630 This is mainly useful for fields that contain hidden parts.
9631 When called with a \\[universal-argument] prefix, just make the full field visible so that
9632 it can be edited in place."
9633 (interactive "P")
9634 (if arg
9635 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9636 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9637 (remove-text-properties b e '(org-cwidth t invisible t
9638 display t intangible t))
9639 (if (and (boundp 'font-lock-mode) font-lock-mode)
9640 (font-lock-fontify-block)))
9641 (let ((pos (move-marker (make-marker) (point)))
9642 (field (org-table-get-field))
9643 (cw (current-window-configuration))
9644 p)
9645 (org-switch-to-buffer-other-window "*Org tmp*")
9646 (erase-buffer)
9647 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9648 (let ((org-inhibit-startup t)) (org-mode))
9649 (goto-char (setq p (point-max)))
9650 (insert (org-trim field))
9651 (remove-text-properties p (point-max)
9652 '(invisible t org-cwidth t display t
9653 intangible t))
9654 (goto-char p)
9655 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9656 (org-set-local 'org-window-configuration cw)
9657 (org-set-local 'org-field-marker pos)
9658 (message "Edit and finish with C-c C-c"))))
9659
9660 (defun org-table-finish-edit-field ()
9661 "Finish editing a table data field.
9662 Remove all newline characters, insert the result into the table, realign
9663 the table and kill the editing buffer."
9664 (let ((pos org-field-marker)
9665 (cw org-window-configuration)
9666 (cb (current-buffer))
9667 text)
9668 (goto-char (point-min))
9669 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9670 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9671 (replace-match " "))
9672 (setq text (org-trim (buffer-string)))
9673 (set-window-configuration cw)
9674 (kill-buffer cb)
9675 (select-window (get-buffer-window (marker-buffer pos)))
9676 (goto-char pos)
9677 (move-marker pos nil)
9678 (org-table-check-inside-data-field)
9679 (org-table-get-field nil text)
9680 (org-table-align)
9681 (message "New field value inserted")))
9682
9683 (defun org-trim (s)
9684 "Remove whitespace at beginning and end of string."
9685 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9686 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9687 s)
9688
9689 (defun org-wrap (string &optional width lines)
9690 "Wrap string to either a number of lines, or a width in characters.
9691 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9692 that costs. If there is a word longer than WIDTH, the text is actually
9693 wrapped to the length of that word.
9694 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9695 many lines, whatever width that takes.
9696 The return value is a list of lines, without newlines at the end."
9697 (let* ((words (org-split-string string "[ \t\n]+"))
9698 (maxword (apply 'max (mapcar 'org-string-width words)))
9699 w ll)
9700 (cond (width
9701 (org-do-wrap words (max maxword width)))
9702 (lines
9703 (setq w maxword)
9704 (setq ll (org-do-wrap words maxword))
9705 (if (<= (length ll) lines)
9706 ll
9707 (setq ll words)
9708 (while (> (length ll) lines)
9709 (setq w (1+ w))
9710 (setq ll (org-do-wrap words w)))
9711 ll))
9712 (t (error "Cannot wrap this")))))
9713
9714
9715 (defun org-do-wrap (words width)
9716 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9717 (let (lines line)
9718 (while words
9719 (setq line (pop words))
9720 (while (and words (< (+ (length line) (length (car words))) width))
9721 (setq line (concat line " " (pop words))))
9722 (setq lines (push line lines)))
9723 (nreverse lines)))
9724
9725 (defun org-split-string (string &optional separators)
9726 "Splits STRING into substrings at SEPARATORS.
9727 No empty strings are returned if there are matches at the beginning
9728 and end of string."
9729 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9730 (start 0)
9731 notfirst
9732 (list nil))
9733 (while (and (string-match rexp string
9734 (if (and notfirst
9735 (= start (match-beginning 0))
9736 (< start (length string)))
9737 (1+ start) start))
9738 (< (match-beginning 0) (length string)))
9739 (setq notfirst t)
9740 (or (eq (match-beginning 0) 0)
9741 (and (eq (match-beginning 0) (match-end 0))
9742 (eq (match-beginning 0) start))
9743 (setq list
9744 (cons (substring string start (match-beginning 0))
9745 list)))
9746 (setq start (match-end 0)))
9747 (or (eq start (length string))
9748 (setq list
9749 (cons (substring string start)
9750 list)))
9751 (nreverse list)))
9752
9753 (defun org-table-map-tables (function)
9754 "Apply FUNCTION to the start of all tables in the buffer."
9755 (save-excursion
9756 (save-restriction
9757 (widen)
9758 (goto-char (point-min))
9759 (while (re-search-forward org-table-any-line-regexp nil t)
9760 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9761 (beginning-of-line 1)
9762 (if (looking-at org-table-line-regexp)
9763 (save-excursion (funcall function)))
9764 (re-search-forward org-table-any-border-regexp nil 1))))
9765 (message "Mapping tables: done"))
9766
9767 (defvar org-timecnt) ; dynamically scoped parameter
9768
9769 (defun org-table-sum (&optional beg end nlast)
9770 "Sum numbers in region of current table column.
9771 The result will be displayed in the echo area, and will be available
9772 as kill to be inserted with \\[yank].
9773
9774 If there is an active region, it is interpreted as a rectangle and all
9775 numbers in that rectangle will be summed. If there is no active
9776 region and point is located in a table column, sum all numbers in that
9777 column.
9778
9779 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9780 numbers are assumed to be times as well (in decimal hours) and the
9781 numbers are added as such.
9782
9783 If NLAST is a number, only the NLAST fields will actually be summed."
9784 (interactive)
9785 (save-excursion
9786 (let (col (org-timecnt 0) diff h m s org-table-clip)
9787 (cond
9788 ((and beg end)) ; beg and end given explicitly
9789 ((org-region-active-p)
9790 (setq beg (region-beginning) end (region-end)))
9791 (t
9792 (setq col (org-table-current-column))
9793 (goto-char (org-table-begin))
9794 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9795 (error "No table data"))
9796 (org-table-goto-column col)
9797 (setq beg (point))
9798 (goto-char (org-table-end))
9799 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9800 (error "No table data"))
9801 (org-table-goto-column col)
9802 (setq end (point))))
9803 (let* ((items (apply 'append (org-table-copy-region beg end)))
9804 (items1 (cond ((not nlast) items)
9805 ((>= nlast (length items)) items)
9806 (t (setq items (reverse items))
9807 (setcdr (nthcdr (1- nlast) items) nil)
9808 (nreverse items))))
9809 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9810 items1)))
9811 (res (apply '+ numbers))
9812 (sres (if (= org-timecnt 0)
9813 (format "%g" res)
9814 (setq diff (* 3600 res)
9815 h (floor (/ diff 3600)) diff (mod diff 3600)
9816 m (floor (/ diff 60)) diff (mod diff 60)
9817 s diff)
9818 (format "%d:%02d:%02d" h m s))))
9819 (kill-new sres)
9820 (if (interactive-p)
9821 (message "%s"
9822 (substitute-command-keys
9823 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9824 (length numbers) sres))))
9825 sres))))
9826
9827 (defun org-table-get-number-for-summing (s)
9828 (let (n)
9829 (if (string-match "^ *|? *" s)
9830 (setq s (replace-match "" nil nil s)))
9831 (if (string-match " *|? *$" s)
9832 (setq s (replace-match "" nil nil s)))
9833 (setq n (string-to-number s))
9834 (cond
9835 ((and (string-match "0" s)
9836 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9837 ((string-match "\\`[ \t]+\\'" s) nil)
9838 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9839 (let ((h (string-to-number (or (match-string 1 s) "0")))
9840 (m (string-to-number (or (match-string 2 s) "0")))
9841 (s (string-to-number (or (match-string 4 s) "0"))))
9842 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9843 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9844 ((equal n 0) nil)
9845 (t n))))
9846
9847 (defun org-table-current-field-formula (&optional key noerror)
9848 "Return the formula active for the current field.
9849 Assumes that specials are in place.
9850 If KEY is given, return the key to this formula.
9851 Otherwise return the formula preceeded with \"=\" or \":=\"."
9852 (let* ((name (car (rassoc (list (org-current-line)
9853 (org-table-current-column))
9854 org-table-named-field-locations)))
9855 (col (org-table-current-column))
9856 (scol (int-to-string col))
9857 (ref (format "@%d$%d" (org-table-current-dline) col))
9858 (stored-list (org-table-get-stored-formulas noerror))
9859 (ass (or (assoc name stored-list)
9860 (assoc ref stored-list)
9861 (assoc scol stored-list))))
9862 (if key
9863 (car ass)
9864 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9865 (cdr ass))))))
9866
9867 (defun org-table-get-formula (&optional equation named)
9868 "Read a formula from the minibuffer, offer stored formula as default.
9869 When NAMED is non-nil, look for a named equation."
9870 (let* ((stored-list (org-table-get-stored-formulas))
9871 (name (car (rassoc (list (org-current-line)
9872 (org-table-current-column))
9873 org-table-named-field-locations)))
9874 (ref (format "@%d$%d" (org-table-current-dline)
9875 (org-table-current-column)))
9876 (refass (assoc ref stored-list))
9877 (scol (if named
9878 (if name name ref)
9879 (int-to-string (org-table-current-column))))
9880 (dummy (and (or name refass) (not named)
9881 (not (y-or-n-p "Replace field formula with column formula? " ))
9882 (error "Abort")))
9883 (name (or name ref))
9884 (org-table-may-need-update nil)
9885 (stored (cdr (assoc scol stored-list)))
9886 (eq (cond
9887 ((and stored equation (string-match "^ *=? *$" equation))
9888 stored)
9889 ((stringp equation)
9890 equation)
9891 (t (org-table-formula-from-user
9892 (read-string
9893 (org-table-formula-to-user
9894 (format "%s formula %s%s="
9895 (if named "Field" "Column")
9896 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9897 scol))
9898 (if stored (org-table-formula-to-user stored) "")
9899 'org-table-formula-history
9900 )))))
9901 mustsave)
9902 (when (not (string-match "\\S-" eq))
9903 ;; remove formula
9904 (setq stored-list (delq (assoc scol stored-list) stored-list))
9905 (org-table-store-formulas stored-list)
9906 (error "Formula removed"))
9907 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9908 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9909 (if (and name (not named))
9910 ;; We set the column equation, delete the named one.
9911 (setq stored-list (delq (assoc name stored-list) stored-list)
9912 mustsave t))
9913 (if stored
9914 (setcdr (assoc scol stored-list) eq)
9915 (setq stored-list (cons (cons scol eq) stored-list)))
9916 (if (or mustsave (not (equal stored eq)))
9917 (org-table-store-formulas stored-list))
9918 eq))
9919
9920 (defun org-table-store-formulas (alist)
9921 "Store the list of formulas below the current table."
9922 (setq alist (sort alist 'org-table-formula-less-p))
9923 (save-excursion
9924 (goto-char (org-table-end))
9925 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9926 (progn
9927 ;; don't overwrite TBLFM, we might use text properties to store stuff
9928 (goto-char (match-beginning 2))
9929 (delete-region (match-beginning 2) (match-end 0)))
9930 (insert "#+TBLFM:"))
9931 (insert " "
9932 (mapconcat (lambda (x)
9933 (concat
9934 (if (equal (string-to-char (car x)) ?@) "" "$")
9935 (car x) "=" (cdr x)))
9936 alist "::")
9937 "\n")))
9938
9939 (defsubst org-table-formula-make-cmp-string (a)
9940 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9941 (concat
9942 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9943 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9944 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9945
9946 (defun org-table-formula-less-p (a b)
9947 "Compare two formulas for sorting."
9948 (let ((as (org-table-formula-make-cmp-string (car a)))
9949 (bs (org-table-formula-make-cmp-string (car b))))
9950 (and as bs (string< as bs))))
9951
9952 (defun org-table-get-stored-formulas (&optional noerror)
9953 "Return an alist with the stored formulas directly after current table."
9954 (interactive)
9955 (let (scol eq eq-alist strings string seen)
9956 (save-excursion
9957 (goto-char (org-table-end))
9958 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9959 (setq strings (org-split-string (match-string 2) " *:: *"))
9960 (while (setq string (pop strings))
9961 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9962 (setq scol (if (match-end 2)
9963 (match-string 2 string)
9964 (match-string 1 string))
9965 eq (match-string 3 string)
9966 eq-alist (cons (cons scol eq) eq-alist))
9967 (if (member scol seen)
9968 (if noerror
9969 (progn
9970 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9971 (ding)
9972 (sit-for 2))
9973 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9974 (push scol seen))))))
9975 (nreverse eq-alist)))
9976
9977 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9978 "Modify the equations after the table structure has been edited.
9979 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9980 For all numbers larger than LIMIT, shift them by DELTA."
9981 (save-excursion
9982 (goto-char (org-table-end))
9983 (when (looking-at "#\\+TBLFM:")
9984 (let ((re (concat key "\\([0-9]+\\)"))
9985 (re2
9986 (when remove
9987 (if (equal key "$")
9988 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9989 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9990 s n a)
9991 (when remove
9992 (while (re-search-forward re2 (point-at-eol) t)
9993 (replace-match "")))
9994 (while (re-search-forward re (point-at-eol) t)
9995 (setq s (match-string 1) n (string-to-number s))
9996 (cond
9997 ((setq a (assoc s replace))
9998 (replace-match (concat key (cdr a)) t t))
9999 ((and limit (> n limit))
10000 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
10001
10002 (defun org-table-get-specials ()
10003 "Get the column names and local parameters for this table."
10004 (save-excursion
10005 (let ((beg (org-table-begin)) (end (org-table-end))
10006 names name fields fields1 field cnt
10007 c v l line col types dlines hlines)
10008 (setq org-table-column-names nil
10009 org-table-local-parameters nil
10010 org-table-named-field-locations nil
10011 org-table-current-begin-line nil
10012 org-table-current-begin-pos nil
10013 org-table-current-line-types nil)
10014 (goto-char beg)
10015 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10016 (setq names (org-split-string (match-string 1) " *| *")
10017 cnt 1)
10018 (while (setq name (pop names))
10019 (setq cnt (1+ cnt))
10020 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10021 (push (cons name (int-to-string cnt)) org-table-column-names))))
10022 (setq org-table-column-names (nreverse org-table-column-names))
10023 (setq org-table-column-name-regexp
10024 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10025 (goto-char beg)
10026 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10027 (setq fields (org-split-string (match-string 1) " *| *"))
10028 (while (setq field (pop fields))
10029 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10030 (push (cons (match-string 1 field) (match-string 2 field))
10031 org-table-local-parameters))))
10032 (goto-char beg)
10033 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10034 (setq c (match-string 1)
10035 fields (org-split-string (match-string 2) " *| *"))
10036 (save-excursion
10037 (beginning-of-line (if (equal c "_") 2 0))
10038 (setq line (org-current-line) col 1)
10039 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10040 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10041 (while (and fields1 (setq field (pop fields)))
10042 (setq v (pop fields1) col (1+ col))
10043 (when (and (stringp field) (stringp v)
10044 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10045 (push (cons field v) org-table-local-parameters)
10046 (push (list field line col) org-table-named-field-locations))))
10047 ;; Analyse the line types
10048 (goto-char beg)
10049 (setq org-table-current-begin-line (org-current-line)
10050 org-table-current-begin-pos (point)
10051 l org-table-current-begin-line)
10052 (while (looking-at "[ \t]*|\\(-\\)?")
10053 (push (if (match-end 1) 'hline 'dline) types)
10054 (if (match-end 1) (push l hlines) (push l dlines))
10055 (beginning-of-line 2)
10056 (setq l (1+ l)))
10057 (setq org-table-current-line-types (apply 'vector (nreverse types))
10058 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
10059 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
10060
10061 (defun org-table-maybe-eval-formula ()
10062 "Check if the current field starts with \"=\" or \":=\".
10063 If yes, store the formula and apply it."
10064 ;; We already know we are in a table. Get field will only return a formula
10065 ;; when appropriate. It might return a separator line, but no problem.
10066 (when org-table-formula-evaluate-inline
10067 (let* ((field (org-trim (or (org-table-get-field) "")))
10068 named eq)
10069 (when (string-match "^:?=\\(.*\\)" field)
10070 (setq named (equal (string-to-char field) ?:)
10071 eq (match-string 1 field))
10072 (if (or (fboundp 'calc-eval)
10073 (equal (substring eq 0 (min 2 (length eq))) "'("))
10074 (org-table-eval-formula (if named '(4) nil)
10075 (org-table-formula-from-user eq))
10076 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10077
10078 (defvar org-recalc-commands nil
10079 "List of commands triggering the recalculation of a line.
10080 Will be filled automatically during use.")
10081
10082 (defvar org-recalc-marks
10083 '((" " . "Unmarked: no special line, no automatic recalculation")
10084 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10085 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10086 ("!" . "Column name definition line. Reference in formula as $name.")
10087 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10088 ("_" . "Names for values in row below this one.")
10089 ("^" . "Names for values in row above this one.")))
10090
10091 (defun org-table-rotate-recalc-marks (&optional newchar)
10092 "Rotate the recalculation mark in the first column.
10093 If in any row, the first field is not consistent with a mark,
10094 insert a new column for the markers.
10095 When there is an active region, change all the lines in the region,
10096 after prompting for the marking character.
10097 After each change, a message will be displayed indicating the meaning
10098 of the new mark."
10099 (interactive)
10100 (unless (org-at-table-p) (error "Not at a table"))
10101 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10102 (beg (org-table-begin))
10103 (end (org-table-end))
10104 (l (org-current-line))
10105 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10106 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10107 (have-col
10108 (save-excursion
10109 (goto-char beg)
10110 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10111 (col (org-table-current-column))
10112 (forcenew (car (assoc newchar org-recalc-marks)))
10113 epos new)
10114 (when l1
10115 (message "Change region to what mark? Type # * ! $ or SPC: ")
10116 (setq newchar (char-to-string (read-char-exclusive))
10117 forcenew (car (assoc newchar org-recalc-marks))))
10118 (if (and newchar (not forcenew))
10119 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10120 newchar))
10121 (if l1 (goto-line l1))
10122 (save-excursion
10123 (beginning-of-line 1)
10124 (unless (looking-at org-table-dataline-regexp)
10125 (error "Not at a table data line")))
10126 (unless have-col
10127 (org-table-goto-column 1)
10128 (org-table-insert-column)
10129 (org-table-goto-column (1+ col)))
10130 (setq epos (point-at-eol))
10131 (save-excursion
10132 (beginning-of-line 1)
10133 (org-table-get-field
10134 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10135 (concat " "
10136 (setq new (or forcenew
10137 (cadr (member (match-string 1) marks))))
10138 " ")
10139 " # ")))
10140 (if (and l1 l2)
10141 (progn
10142 (goto-line l1)
10143 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10144 (and (looking-at org-table-dataline-regexp)
10145 (org-table-get-field 1 (concat " " new " "))))
10146 (goto-line l1)))
10147 (if (not (= epos (point-at-eol))) (org-table-align))
10148 (goto-line l)
10149 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10150
10151 (defun org-table-maybe-recalculate-line ()
10152 "Recompute the current line if marked for it, and if we haven't just done it."
10153 (interactive)
10154 (and org-table-allow-automatic-line-recalculation
10155 (not (and (memq last-command org-recalc-commands)
10156 (equal org-last-recalc-line (org-current-line))))
10157 (save-excursion (beginning-of-line 1)
10158 (looking-at org-table-auto-recalculate-regexp))
10159 (org-table-recalculate) t))
10160
10161 (defvar org-table-formula-debug nil
10162 "Non-nil means, debug table formulas.
10163 When nil, simply write \"#ERROR\" in corrupted fields.")
10164 (make-variable-buffer-local 'org-table-formula-debug)
10165
10166 (defvar modes)
10167 (defsubst org-set-calc-mode (var &optional value)
10168 (if (stringp var)
10169 (setq var (assoc var '(("D" calc-angle-mode deg)
10170 ("R" calc-angle-mode rad)
10171 ("F" calc-prefer-frac t)
10172 ("S" calc-symbolic-mode t)))
10173 value (nth 2 var) var (nth 1 var)))
10174 (if (memq var modes)
10175 (setcar (cdr (memq var modes)) value)
10176 (cons var (cons value modes)))
10177 modes)
10178
10179 (defun org-table-eval-formula (&optional arg equation
10180 suppress-align suppress-const
10181 suppress-store suppress-analysis)
10182 "Replace the table field value at the cursor by the result of a calculation.
10183
10184 This function makes use of Dave Gillespie's Calc package, in my view the
10185 most exciting program ever written for GNU Emacs. So you need to have Calc
10186 installed in order to use this function.
10187
10188 In a table, this command replaces the value in the current field with the
10189 result of a formula. It also installs the formula as the \"current\" column
10190 formula, by storing it in a special line below the table. When called
10191 with a `C-u' prefix, the current field must ba a named field, and the
10192 formula is installed as valid in only this specific field.
10193
10194 When called with two `C-u' prefixes, insert the active equation
10195 for the field back into the current field, so that it can be
10196 edited there. This is useful in order to use \\[org-table-show-reference]
10197 to check the referenced fields.
10198
10199 When called, the command first prompts for a formula, which is read in
10200 the minibuffer. Previously entered formulas are available through the
10201 history list, and the last used formula is offered as a default.
10202 These stored formulas are adapted correctly when moving, inserting, or
10203 deleting columns with the corresponding commands.
10204
10205 The formula can be any algebraic expression understood by the Calc package.
10206 For details, see the Org-mode manual.
10207
10208 This function can also be called from Lisp programs and offers
10209 additional arguments: EQUATION can be the formula to apply. If this
10210 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10211 used to speed-up recursive calls by by-passing unnecessary aligns.
10212 SUPPRESS-CONST suppresses the interpretation of constants in the
10213 formula, assuming that this has been done already outside the function.
10214 SUPPRESS-STORE means the formula should not be stored, either because
10215 it is already stored, or because it is a modified equation that should
10216 not overwrite the stored one."
10217 (interactive "P")
10218 (org-table-check-inside-data-field)
10219 (or suppress-analysis (org-table-get-specials))
10220 (if (equal arg '(16))
10221 (let ((eq (org-table-current-field-formula)))
10222 (or eq (error "No equation active for current field"))
10223 (org-table-get-field nil eq)
10224 (org-table-align)
10225 (setq org-table-may-need-update t))
10226 (let* (fields
10227 (ndown (if (integerp arg) arg 1))
10228 (org-table-automatic-realign nil)
10229 (case-fold-search nil)
10230 (down (> ndown 1))
10231 (formula (if (and equation suppress-store)
10232 equation
10233 (org-table-get-formula equation (equal arg '(4)))))
10234 (n0 (org-table-current-column))
10235 (modes (copy-sequence org-calc-default-modes))
10236 (numbers nil) ; was a variable, now fixed default
10237 (keep-empty nil)
10238 n form form0 bw fmt x ev orig c lispp literal)
10239 ;; Parse the format string. Since we have a lot of modes, this is
10240 ;; a lot of work. However, I think calc still uses most of the time.
10241 (if (string-match ";" formula)
10242 (let ((tmp (org-split-string formula ";")))
10243 (setq formula (car tmp)
10244 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10245 (nth 1 tmp)))
10246 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10247 (setq c (string-to-char (match-string 1 fmt))
10248 n (string-to-number (match-string 2 fmt)))
10249 (if (= c ?p)
10250 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10251 (setq modes (org-set-calc-mode
10252 'calc-float-format
10253 (list (cdr (assoc c '((?n . float) (?f . fix)
10254 (?s . sci) (?e . eng))))
10255 n))))
10256 (setq fmt (replace-match "" t t fmt)))
10257 (if (string-match "[NT]" fmt)
10258 (setq numbers (equal (match-string 0 fmt) "N")
10259 fmt (replace-match "" t t fmt)))
10260 (if (string-match "L" fmt)
10261 (setq literal t
10262 fmt (replace-match "" t t fmt)))
10263 (if (string-match "E" fmt)
10264 (setq keep-empty t
10265 fmt (replace-match "" t t fmt)))
10266 (while (string-match "[DRFS]" fmt)
10267 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10268 (setq fmt (replace-match "" t t fmt)))
10269 (unless (string-match "\\S-" fmt)
10270 (setq fmt nil))))
10271 (if (and (not suppress-const) org-table-formula-use-constants)
10272 (setq formula (org-table-formula-substitute-names formula)))
10273 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10274 (while (> ndown 0)
10275 (setq fields (org-split-string
10276 (org-no-properties
10277 (buffer-substring (point-at-bol) (point-at-eol)))
10278 " *| *"))
10279 (if (eq numbers t)
10280 (setq fields (mapcar
10281 (lambda (x) (number-to-string (string-to-number x)))
10282 fields)))
10283 (setq ndown (1- ndown))
10284 (setq form (copy-sequence formula)
10285 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10286 (if (and lispp literal) (setq lispp 'literal))
10287 ;; Check for old vertical references
10288 (setq form (org-rewrite-old-row-references form))
10289 ;; Insert complex ranges
10290 (while (string-match org-table-range-regexp form)
10291 (setq form
10292 (replace-match
10293 (save-match-data
10294 (org-table-make-reference
10295 (org-table-get-range (match-string 0 form) nil n0)
10296 keep-empty numbers lispp))
10297 t t form)))
10298 ;; Insert simple ranges
10299 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10300 (setq form
10301 (replace-match
10302 (save-match-data
10303 (org-table-make-reference
10304 (org-sublist
10305 fields (string-to-number (match-string 1 form))
10306 (string-to-number (match-string 2 form)))
10307 keep-empty numbers lispp))
10308 t t form)))
10309 (setq form0 form)
10310 ;; Insert the references to fields in same row
10311 (while (string-match "\\$\\([0-9]+\\)" form)
10312 (setq n (string-to-number (match-string 1 form))
10313 x (nth (1- (if (= n 0) n0 n)) fields))
10314 (unless x (error "Invalid field specifier \"%s\""
10315 (match-string 0 form)))
10316 (setq form (replace-match
10317 (save-match-data
10318 (org-table-make-reference x nil numbers lispp))
10319 t t form)))
10320
10321 (if lispp
10322 (setq ev (condition-case nil
10323 (eval (eval (read form)))
10324 (error "#ERROR"))
10325 ev (if (numberp ev) (number-to-string ev) ev))
10326 (or (fboundp 'calc-eval)
10327 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10328 (setq ev (calc-eval (cons form modes)
10329 (if numbers 'num))))
10330
10331 (when org-table-formula-debug
10332 (with-output-to-temp-buffer "*Substitution History*"
10333 (princ (format "Substitution history of formula
10334 Orig: %s
10335 $xyz-> %s
10336 @r$c-> %s
10337 $1-> %s\n" orig formula form0 form))
10338 (if (listp ev)
10339 (princ (format " %s^\nError: %s"
10340 (make-string (car ev) ?\-) (nth 1 ev)))
10341 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10342 ev (or fmt "NONE")
10343 (if fmt (format fmt (string-to-number ev)) ev)))))
10344 (setq bw (get-buffer-window "*Substitution History*"))
10345 (shrink-window-if-larger-than-buffer bw)
10346 (unless (and (interactive-p) (not ndown))
10347 (unless (let (inhibit-redisplay)
10348 (y-or-n-p "Debugging Formula. Continue to next? "))
10349 (org-table-align)
10350 (error "Abort"))
10351 (delete-window bw)
10352 (message "")))
10353 (if (listp ev) (setq fmt nil ev "#ERROR"))
10354 (org-table-justify-field-maybe
10355 (if fmt (format fmt (string-to-number ev)) ev))
10356 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10357 (call-interactively 'org-return)
10358 (setq ndown 0)))
10359 (and down (org-table-maybe-recalculate-line))
10360 (or suppress-align (and org-table-may-need-update
10361 (org-table-align))))))
10362
10363 (defun org-table-put-field-property (prop value)
10364 (save-excursion
10365 (put-text-property (progn (skip-chars-backward "^|") (point))
10366 (progn (skip-chars-forward "^|") (point))
10367 prop value)))
10368
10369 (defun org-table-get-range (desc &optional tbeg col highlight)
10370 "Get a calc vector from a column, accorting to descriptor DESC.
10371 Optional arguments TBEG and COL can give the beginning of the table and
10372 the current column, to avoid unnecessary parsing.
10373 HIGHLIGHT means, just highlight the range."
10374 (if (not (equal (string-to-char desc) ?@))
10375 (setq desc (concat "@" desc)))
10376 (save-excursion
10377 (or tbeg (setq tbeg (org-table-begin)))
10378 (or col (setq col (org-table-current-column)))
10379 (let ((thisline (org-current-line))
10380 beg end c1 c2 r1 r2 rangep tmp)
10381 (unless (string-match org-table-range-regexp desc)
10382 (error "Invalid table range specifier `%s'" desc))
10383 (setq rangep (match-end 3)
10384 r1 (and (match-end 1) (match-string 1 desc))
10385 r2 (and (match-end 4) (match-string 4 desc))
10386 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10387 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10388
10389 (and c1 (setq c1 (+ (string-to-number c1)
10390 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10391 (and c2 (setq c2 (+ (string-to-number c2)
10392 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10393 (if (equal r1 "") (setq r1 nil))
10394 (if (equal r2 "") (setq r2 nil))
10395 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10396 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10397 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10398 (if (not r1) (setq r1 thisline))
10399 (if (not r2) (setq r2 thisline))
10400 (if (not c1) (setq c1 col))
10401 (if (not c2) (setq c2 col))
10402 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10403 ;; just one field
10404 (progn
10405 (goto-line r1)
10406 (while (not (looking-at org-table-dataline-regexp))
10407 (beginning-of-line 2))
10408 (prog1 (org-trim (org-table-get-field c1))
10409 (if highlight (org-table-highlight-rectangle (point) (point)))))
10410 ;; A range, return a vector
10411 ;; First sort the numbers to get a regular ractangle
10412 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10413 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10414 (goto-line r1)
10415 (while (not (looking-at org-table-dataline-regexp))
10416 (beginning-of-line 2))
10417 (org-table-goto-column c1)
10418 (setq beg (point))
10419 (goto-line r2)
10420 (while (not (looking-at org-table-dataline-regexp))
10421 (beginning-of-line 0))
10422 (org-table-goto-column c2)
10423 (setq end (point))
10424 (if highlight
10425 (org-table-highlight-rectangle
10426 beg (progn (skip-chars-forward "^|\n") (point))))
10427 ;; return string representation of calc vector
10428 (mapcar 'org-trim
10429 (apply 'append (org-table-copy-region beg end)))))))
10430
10431 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10432 "Analyze descriptor DESC and retrieve the corresponding line number.
10433 The cursor is currently in line CLINE, the table begins in line BLINE,
10434 and TABLE is a vector with line types."
10435 (if (string-match "^[0-9]+$" desc)
10436 (aref org-table-dlines (string-to-number desc))
10437 (setq cline (or cline (org-current-line))
10438 bline (or bline org-table-current-begin-line)
10439 table (or table org-table-current-line-types))
10440 (if (or
10441 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10442 ;; 1 2 3 4 5 6
10443 (and (not (match-end 3)) (not (match-end 6)))
10444 (and (match-end 3) (match-end 6) (not (match-end 5))))
10445 (error "invalid row descriptor `%s'" desc))
10446 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10447 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10448 (odir (and (match-end 5) (match-string 5 desc)))
10449 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10450 (i (- cline bline))
10451 (rel (and (match-end 6)
10452 (or (and (match-end 1) (not (match-end 3)))
10453 (match-end 5)))))
10454 (if (and hn (not hdir))
10455 (progn
10456 (setq i 0 hdir "+")
10457 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10458 (if (and (not hn) on (not odir))
10459 (error "should never happen");;(aref org-table-dlines on)
10460 (if (and hn (> hn 0))
10461 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10462 (if on
10463 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10464 (+ bline i)))))
10465
10466 (defun org-find-row-type (table i type backwards relative n)
10467 (let ((l (length table)))
10468 (while (> n 0)
10469 (while (and (setq i (+ i (if backwards -1 1)))
10470 (>= i 0) (< i l)
10471 (not (eq (aref table i) type))
10472 (if (and relative (eq (aref table i) 'hline))
10473 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10474 t)))
10475 (setq n (1- n)))
10476 (if (or (< i 0) (>= i l))
10477 (error "Row descriptior leads outside table")
10478 i)))
10479
10480 (defun org-rewrite-old-row-references (s)
10481 (if (string-match "&[-+0-9I]" s)
10482 (error "Formula contains old &row reference, please rewrite using @-syntax")
10483 s))
10484
10485 (defun org-table-make-reference (elements keep-empty numbers lispp)
10486 "Convert list ELEMENTS to something appropriate to insert into formula.
10487 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10488 NUMBERS indicates that everything should be converted to numbers.
10489 LISPP means to return something appropriate for a Lisp list."
10490 (if (stringp elements) ; just a single val
10491 (if lispp
10492 (if (eq lispp 'literal)
10493 elements
10494 (prin1-to-string (if numbers (string-to-number elements) elements)))
10495 (if (equal elements "") (setq elements "0"))
10496 (if numbers (number-to-string (string-to-number elements)) elements))
10497 (unless keep-empty
10498 (setq elements
10499 (delq nil
10500 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10501 elements))))
10502 (setq elements (or elements '("0")))
10503 (if lispp
10504 (mapconcat
10505 (lambda (x)
10506 (if (eq lispp 'literal)
10507 x
10508 (prin1-to-string (if numbers (string-to-number x) x))))
10509 elements " ")
10510 (concat "[" (mapconcat
10511 (lambda (x)
10512 (if numbers (number-to-string (string-to-number x)) x))
10513 elements
10514 ",") "]"))))
10515
10516 (defun org-table-recalculate (&optional all noalign)
10517 "Recalculate the current table line by applying all stored formulas.
10518 With prefix arg ALL, do this for all lines in the table."
10519 (interactive "P")
10520 (or (memq this-command org-recalc-commands)
10521 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10522 (unless (org-at-table-p) (error "Not at a table"))
10523 (if (equal all '(16))
10524 (org-table-iterate)
10525 (org-table-get-specials)
10526 (let* ((eqlist (sort (org-table-get-stored-formulas)
10527 (lambda (a b) (string< (car a) (car b)))))
10528 (inhibit-redisplay (not debug-on-error))
10529 (line-re org-table-dataline-regexp)
10530 (thisline (org-current-line))
10531 (thiscol (org-table-current-column))
10532 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10533 ;; Insert constants in all formulas
10534 (setq eqlist
10535 (mapcar (lambda (x)
10536 (setcdr x (org-table-formula-substitute-names (cdr x)))
10537 x)
10538 eqlist))
10539 ;; Split the equation list
10540 (while (setq eq (pop eqlist))
10541 (if (<= (string-to-char (car eq)) ?9)
10542 (push eq eqlnum)
10543 (push eq eqlname)))
10544 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10545 (if all
10546 (progn
10547 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10548 (goto-char (setq beg (org-table-begin)))
10549 (if (re-search-forward org-table-calculate-mark-regexp end t)
10550 ;; This is a table with marked lines, compute selected lines
10551 (setq line-re org-table-recalculate-regexp)
10552 ;; Move forward to the first non-header line
10553 (if (and (re-search-forward org-table-dataline-regexp end t)
10554 (re-search-forward org-table-hline-regexp end t)
10555 (re-search-forward org-table-dataline-regexp end t))
10556 (setq beg (match-beginning 0))
10557 nil))) ;; just leave beg where it is
10558 (setq beg (point-at-bol)
10559 end (move-marker (make-marker) (1+ (point-at-eol)))))
10560 (goto-char beg)
10561 (and all (message "Re-applying formulas to full table..."))
10562
10563 ;; First find the named fields, and mark them untouchanble
10564 (remove-text-properties beg end '(org-untouchable t))
10565 (while (setq eq (pop eqlname))
10566 (setq name (car eq)
10567 a (assoc name org-table-named-field-locations))
10568 (and (not a)
10569 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10570 (setq a (list name
10571 (aref org-table-dlines
10572 (string-to-number (match-string 1 name)))
10573 (string-to-number (match-string 2 name)))))
10574 (when (and a (or all (equal (nth 1 a) thisline)))
10575 (message "Re-applying formula to field: %s" name)
10576 (goto-line (nth 1 a))
10577 (org-table-goto-column (nth 2 a))
10578 (push (append a (list (cdr eq))) eqlname1)
10579 (org-table-put-field-property :org-untouchable t)))
10580
10581 ;; Now evauluate the column formulas, but skip fields covered by
10582 ;; field formulas
10583 (goto-char beg)
10584 (while (re-search-forward line-re end t)
10585 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10586 ;; Unprotected line, recalculate
10587 (and all (message "Re-applying formulas to full table...(line %d)"
10588 (setq cnt (1+ cnt))))
10589 (setq org-last-recalc-line (org-current-line))
10590 (setq eql eqlnum)
10591 (while (setq entry (pop eql))
10592 (goto-line org-last-recalc-line)
10593 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10594 (unless (get-text-property (point) :org-untouchable)
10595 (org-table-eval-formula nil (cdr entry)
10596 'noalign 'nocst 'nostore 'noanalysis)))))
10597
10598 ;; Now evaluate the field formulas
10599 (while (setq eq (pop eqlname1))
10600 (message "Re-applying formula to field: %s" (car eq))
10601 (goto-line (nth 1 eq))
10602 (org-table-goto-column (nth 2 eq))
10603 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10604 'nostore 'noanalysis))
10605
10606 (goto-line thisline)
10607 (org-table-goto-column thiscol)
10608 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10609 (or noalign (and org-table-may-need-update (org-table-align))
10610 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10611
10612 ;; back to initial position
10613 (message "Re-applying formulas...done")
10614 (goto-line thisline)
10615 (org-table-goto-column thiscol)
10616 (or noalign (and org-table-may-need-update (org-table-align))
10617 (and all (message "Re-applying formulas...done"))))))
10618
10619 (defun org-table-iterate (&optional arg)
10620 "Recalculate the table until it does not change anymore."
10621 (interactive "P")
10622 (let ((imax (if arg (prefix-numeric-value arg) 10))
10623 (i 0)
10624 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10625 thistbl)
10626 (catch 'exit
10627 (while (< i imax)
10628 (setq i (1+ i))
10629 (org-table-recalculate 'all)
10630 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10631 (if (not (string= lasttbl thistbl))
10632 (setq lasttbl thistbl)
10633 (if (> i 1)
10634 (message "Convergence after %d iterations" i)
10635 (message "Table was already stable"))
10636 (throw 'exit t)))
10637 (error "No convergence after %d iterations" i))))
10638
10639 (defun org-table-formula-substitute-names (f)
10640 "Replace $const with values in string F."
10641 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10642 ;; First, check for column names
10643 (while (setq start (string-match org-table-column-name-regexp f start))
10644 (setq start (1+ start))
10645 (setq a (assoc (match-string 1 f) org-table-column-names))
10646 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10647 ;; Parameters and constants
10648 (setq start 0)
10649 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10650 (setq start (1+ start))
10651 (if (setq a (save-match-data
10652 (org-table-get-constant (match-string 1 f))))
10653 (setq f (replace-match
10654 (concat (if pp "(") a (if pp ")")) t t f))))
10655 (if org-table-formula-debug
10656 (put-text-property 0 (length f) :orig-formula f1 f))
10657 f))
10658
10659 (defun org-table-get-constant (const)
10660 "Find the value for a parameter or constant in a formula.
10661 Parameters get priority."
10662 (or (cdr (assoc const org-table-local-parameters))
10663 (cdr (assoc const org-table-formula-constants-local))
10664 (cdr (assoc const org-table-formula-constants))
10665 (and (fboundp 'constants-get) (constants-get const))
10666 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10667 (org-entry-get nil (substring const 5) 'inherit))
10668 "#UNDEFINED_NAME"))
10669
10670 (defvar org-table-fedit-map
10671 (let ((map (make-sparse-keymap)))
10672 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10673 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10674 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10675 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10676 (org-defkey map "\C-c?" 'org-table-show-reference)
10677 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10678 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10679 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10680 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10681 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10682 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10683 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10684 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10685 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10686 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10687 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10688 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10689 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10690 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10691 map))
10692
10693 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10694 '("Edit-Formulas"
10695 ["Finish and Install" org-table-fedit-finish t]
10696 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10697 ["Abort" org-table-fedit-abort t]
10698 "--"
10699 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10700 ["Complete Lisp Symbol" lisp-complete-symbol t]
10701 "--"
10702 "Shift Reference at Point"
10703 ["Up" org-table-fedit-ref-up t]
10704 ["Down" org-table-fedit-ref-down t]
10705 ["Left" org-table-fedit-ref-left t]
10706 ["Right" org-table-fedit-ref-right t]
10707 "-"
10708 "Change Test Row for Column Formulas"
10709 ["Up" org-table-fedit-line-up t]
10710 ["Down" org-table-fedit-line-down t]
10711 "--"
10712 ["Scroll Table Window" org-table-fedit-scroll t]
10713 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10714 ["Show Table Grid" org-table-fedit-toggle-coordinates
10715 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10716 org-table-overlay-coordinates)]
10717 "--"
10718 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10719 :style toggle :selected org-table-buffer-is-an]))
10720
10721 (defvar org-pos)
10722
10723 (defun org-table-edit-formulas ()
10724 "Edit the formulas of the current table in a separate buffer."
10725 (interactive)
10726 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10727 (beginning-of-line 0))
10728 (unless (org-at-table-p) (error "Not at a table"))
10729 (org-table-get-specials)
10730 (let ((key (org-table-current-field-formula 'key 'noerror))
10731 (eql (sort (org-table-get-stored-formulas 'noerror)
10732 'org-table-formula-less-p))
10733 (pos (move-marker (make-marker) (point)))
10734 (startline 1)
10735 (wc (current-window-configuration))
10736 (titles '((column . "# Column Formulas\n")
10737 (field . "# Field Formulas\n")
10738 (named . "# Named Field Formulas\n")))
10739 entry s type title)
10740 (org-switch-to-buffer-other-window "*Edit Formulas*")
10741 (erase-buffer)
10742 ;; Keep global-font-lock-mode from turning on font-lock-mode
10743 (let ((font-lock-global-modes '(not fundamental-mode)))
10744 (fundamental-mode))
10745 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10746 (org-set-local 'org-pos pos)
10747 (org-set-local 'org-window-configuration wc)
10748 (use-local-map org-table-fedit-map)
10749 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10750 (easy-menu-add org-table-fedit-menu)
10751 (setq startline (org-current-line))
10752 (while (setq entry (pop eql))
10753 (setq type (cond
10754 ((equal (string-to-char (car entry)) ?@) 'field)
10755 ((string-match "^[0-9]" (car entry)) 'column)
10756 (t 'named)))
10757 (when (setq title (assq type titles))
10758 (or (bobp) (insert "\n"))
10759 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10760 (setq titles (delq title titles)))
10761 (if (equal key (car entry)) (setq startline (org-current-line)))
10762 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10763 (car entry) " = " (cdr entry) "\n"))
10764 (remove-text-properties 0 (length s) '(face nil) s)
10765 (insert s))
10766 (if (eq org-table-use-standard-references t)
10767 (org-table-fedit-toggle-ref-type))
10768 (goto-line startline)
10769 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10770
10771 (defun org-table-fedit-post-command ()
10772 (when (not (memq this-command '(lisp-complete-symbol)))
10773 (let ((win (selected-window)))
10774 (save-excursion
10775 (condition-case nil
10776 (org-table-show-reference)
10777 (error nil))
10778 (select-window win)))))
10779
10780 (defun org-table-formula-to-user (s)
10781 "Convert a formula from internal to user representation."
10782 (if (eq org-table-use-standard-references t)
10783 (org-table-convert-refs-to-an s)
10784 s))
10785
10786 (defun org-table-formula-from-user (s)
10787 "Convert a formula from user to internal representation."
10788 (if org-table-use-standard-references
10789 (org-table-convert-refs-to-rc s)
10790 s))
10791
10792 (defun org-table-convert-refs-to-rc (s)
10793 "Convert spreadsheet references from AB7 to @7$28.
10794 Works for single references, but also for entire formulas and even the
10795 full TBLFM line."
10796 (let ((start 0))
10797 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10798 (cond
10799 ((match-end 3)
10800 ;; format match, just advance
10801 (setq start (match-end 0)))
10802 ((and (> (match-beginning 0) 0)
10803 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10804 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10805 ;; 3.e5 or something like this.
10806 (setq start (match-end 0)))
10807 (t
10808 (setq start (match-beginning 0)
10809 s (replace-match
10810 (if (equal (match-string 2 s) "&")
10811 (format "$%d" (org-letters-to-number (match-string 1 s)))
10812 (format "@%d$%d"
10813 (string-to-number (match-string 2 s))
10814 (org-letters-to-number (match-string 1 s))))
10815 t t s)))))
10816 s))
10817
10818 (defun org-table-convert-refs-to-an (s)
10819 "Convert spreadsheet references from to @7$28 to AB7.
10820 Works for single references, but also for entire formulas and even the
10821 full TBLFM line."
10822 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10823 (setq s (replace-match
10824 (format "%s%d"
10825 (org-number-to-letters
10826 (string-to-number (match-string 2 s)))
10827 (string-to-number (match-string 1 s)))
10828 t t s)))
10829 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10830 (setq s (replace-match (concat "\\1"
10831 (org-number-to-letters
10832 (string-to-number (match-string 2 s))) "&")
10833 t nil s)))
10834 s)
10835
10836 (defun org-letters-to-number (s)
10837 "Convert a base 26 number represented by letters into an integer.
10838 For example: AB -> 28."
10839 (let ((n 0))
10840 (setq s (upcase s))
10841 (while (> (length s) 0)
10842 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10843 s (substring s 1)))
10844 n))
10845
10846 (defun org-number-to-letters (n)
10847 "Convert an integer into a base 26 number represented by letters.
10848 For example: 28 -> AB."
10849 (let ((s ""))
10850 (while (> n 0)
10851 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10852 n (/ (1- n) 26)))
10853 s))
10854
10855 (defun org-table-fedit-convert-buffer (function)
10856 "Convert all references in this buffer, using FUNTION."
10857 (let ((line (org-current-line)))
10858 (goto-char (point-min))
10859 (while (not (eobp))
10860 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10861 (delete-region (point) (point-at-eol))
10862 (or (eobp) (forward-char 1)))
10863 (goto-line line)))
10864
10865 (defun org-table-fedit-toggle-ref-type ()
10866 "Convert all references in the buffer from B3 to @3$2 and back."
10867 (interactive)
10868 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10869 (org-table-fedit-convert-buffer
10870 (if org-table-buffer-is-an
10871 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10872 (message "Reference type switched to %s"
10873 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10874
10875 (defun org-table-fedit-ref-up ()
10876 "Shift the reference at point one row/hline up."
10877 (interactive)
10878 (org-table-fedit-shift-reference 'up))
10879 (defun org-table-fedit-ref-down ()
10880 "Shift the reference at point one row/hline down."
10881 (interactive)
10882 (org-table-fedit-shift-reference 'down))
10883 (defun org-table-fedit-ref-left ()
10884 "Shift the reference at point one field to the left."
10885 (interactive)
10886 (org-table-fedit-shift-reference 'left))
10887 (defun org-table-fedit-ref-right ()
10888 "Shift the reference at point one field to the right."
10889 (interactive)
10890 (org-table-fedit-shift-reference 'right))
10891
10892 (defun org-table-fedit-shift-reference (dir)
10893 (cond
10894 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10895 (if (memq dir '(left right))
10896 (org-rematch-and-replace 1 (eq dir 'left))
10897 (error "Cannot shift reference in this direction")))
10898 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10899 ;; A B3-like reference
10900 (if (memq dir '(up down))
10901 (org-rematch-and-replace 2 (eq dir 'up))
10902 (org-rematch-and-replace 1 (eq dir 'left))))
10903 ((org-at-regexp-p
10904 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10905 ;; An internal reference
10906 (if (memq dir '(up down))
10907 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10908 (org-rematch-and-replace 5 (eq dir 'left))))))
10909
10910 (defun org-rematch-and-replace (n &optional decr hline)
10911 "Re-match the group N, and replace it with the shifted refrence."
10912 (or (match-end n) (error "Cannot shift reference in this direction"))
10913 (goto-char (match-beginning n))
10914 (and (looking-at (regexp-quote (match-string n)))
10915 (replace-match (org-shift-refpart (match-string 0) decr hline)
10916 t t)))
10917
10918 (defun org-shift-refpart (ref &optional decr hline)
10919 "Shift a refrence part REF.
10920 If DECR is set, decrease the references row/column, else increase.
10921 If HLINE is set, this may be a hline reference, it certainly is not
10922 a translation reference."
10923 (save-match-data
10924 (let* ((sign (string-match "^[-+]" ref)) n)
10925
10926 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10927 (cond
10928 ((and hline (string-match "^I+" ref))
10929 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10930 (setq n (+ n (if decr -1 1)))
10931 (if (= n 0) (setq n (+ n (if decr -1 1))))
10932 (if sign
10933 (setq sign (if (< n 0) "-" "+") n (abs n))
10934 (setq n (max 1 n)))
10935 (concat sign (make-string n ?I)))
10936
10937 ((string-match "^[0-9]+" ref)
10938 (setq n (string-to-number (concat sign ref)))
10939 (setq n (+ n (if decr -1 1)))
10940 (if sign
10941 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10942 (number-to-string (max 1 n))))
10943
10944 ((string-match "^[a-zA-Z]+" ref)
10945 (org-number-to-letters
10946 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10947
10948 (t (error "Cannot shift reference"))))))
10949
10950 (defun org-table-fedit-toggle-coordinates ()
10951 "Toggle the display of coordinates in the refrenced table."
10952 (interactive)
10953 (let ((pos (marker-position org-pos)))
10954 (with-current-buffer (marker-buffer org-pos)
10955 (save-excursion
10956 (goto-char pos)
10957 (org-table-toggle-coordinate-overlays)))))
10958
10959 (defun org-table-fedit-finish (&optional arg)
10960 "Parse the buffer for formula definitions and install them.
10961 With prefix ARG, apply the new formulas to the table."
10962 (interactive "P")
10963 (org-table-remove-rectangle-highlight)
10964 (if org-table-use-standard-references
10965 (progn
10966 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10967 (setq org-table-buffer-is-an nil)))
10968 (let ((pos org-pos) eql var form)
10969 (goto-char (point-min))
10970 (while (re-search-forward
10971 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10972 nil t)
10973 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10974 form (match-string 3))
10975 (setq form (org-trim form))
10976 (when (not (equal form ""))
10977 (while (string-match "[ \t]*\n[ \t]*" form)
10978 (setq form (replace-match " " t t form)))
10979 (when (assoc var eql)
10980 (error "Double formulas for %s" var))
10981 (push (cons var form) eql)))
10982 (setq org-pos nil)
10983 (set-window-configuration org-window-configuration)
10984 (select-window (get-buffer-window (marker-buffer pos)))
10985 (goto-char pos)
10986 (unless (org-at-table-p)
10987 (error "Lost table position - cannot install formulae"))
10988 (org-table-store-formulas eql)
10989 (move-marker pos nil)
10990 (kill-buffer "*Edit Formulas*")
10991 (if arg
10992 (org-table-recalculate 'all)
10993 (message "New formulas installed - press C-u C-c C-c to apply."))))
10994
10995 (defun org-table-fedit-abort ()
10996 "Abort editing formulas, without installing the changes."
10997 (interactive)
10998 (org-table-remove-rectangle-highlight)
10999 (let ((pos org-pos))
11000 (set-window-configuration org-window-configuration)
11001 (select-window (get-buffer-window (marker-buffer pos)))
11002 (goto-char pos)
11003 (move-marker pos nil)
11004 (message "Formula editing aborted without installing changes")))
11005
11006 (defun org-table-fedit-lisp-indent ()
11007 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
11008 (interactive)
11009 (let ((pos (point)) beg end ind)
11010 (beginning-of-line 1)
11011 (cond
11012 ((looking-at "[ \t]")
11013 (goto-char pos)
11014 (call-interactively 'lisp-indent-line))
11015 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
11016 ((not (fboundp 'pp-buffer))
11017 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
11018 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
11019 (goto-char (- (match-end 0) 2))
11020 (setq beg (point))
11021 (setq ind (make-string (current-column) ?\ ))
11022 (condition-case nil (forward-sexp 1)
11023 (error
11024 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
11025 (setq end (point))
11026 (save-restriction
11027 (narrow-to-region beg end)
11028 (if (eq last-command this-command)
11029 (progn
11030 (goto-char (point-min))
11031 (setq this-command nil)
11032 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
11033 (replace-match " ")))
11034 (pp-buffer)
11035 (untabify (point-min) (point-max))
11036 (goto-char (1+ (point-min)))
11037 (while (re-search-forward "^." nil t)
11038 (beginning-of-line 1)
11039 (insert ind))
11040 (goto-char (point-max))
11041 (backward-delete-char 1)))
11042 (goto-char beg))
11043 (t nil))))
11044
11045 (defvar org-show-positions nil)
11046
11047 (defun org-table-show-reference (&optional local)
11048 "Show the location/value of the $ expression at point."
11049 (interactive)
11050 (org-table-remove-rectangle-highlight)
11051 (catch 'exit
11052 (let ((pos (if local (point) org-pos))
11053 (face2 'highlight)
11054 (org-inhibit-highlight-removal t)
11055 (win (selected-window))
11056 (org-show-positions nil)
11057 var name e what match dest)
11058 (if local (org-table-get-specials))
11059 (setq what (cond
11060 ((or (org-at-regexp-p org-table-range-regexp2)
11061 (org-at-regexp-p org-table-translate-regexp)
11062 (org-at-regexp-p org-table-range-regexp))
11063 (setq match
11064 (save-match-data
11065 (org-table-convert-refs-to-rc (match-string 0))))
11066 'range)
11067 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11068 ((org-at-regexp-p "\\$[0-9]+") 'column)
11069 ((not local) nil)
11070 (t (error "No reference at point")))
11071 match (and what (or match (match-string 0))))
11072 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11073 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11074 'secondary-selection))
11075 (org-add-hook 'before-change-functions
11076 'org-table-remove-rectangle-highlight)
11077 (if (eq what 'name) (setq var (substring match 1)))
11078 (when (eq what 'range)
11079 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11080 (setq match (org-table-formula-substitute-names match)))
11081 (unless local
11082 (save-excursion
11083 (end-of-line 1)
11084 (re-search-backward "^\\S-" nil t)
11085 (beginning-of-line 1)
11086 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11087 (setq dest
11088 (save-match-data
11089 (org-table-convert-refs-to-rc (match-string 1))))
11090 (org-table-add-rectangle-overlay
11091 (match-beginning 1) (match-end 1) face2))))
11092 (if (and (markerp pos) (marker-buffer pos))
11093 (if (get-buffer-window (marker-buffer pos))
11094 (select-window (get-buffer-window (marker-buffer pos)))
11095 (org-switch-to-buffer-other-window (get-buffer-window
11096 (marker-buffer pos)))))
11097 (goto-char pos)
11098 (org-table-force-dataline)
11099 (when dest
11100 (setq name (substring dest 1))
11101 (cond
11102 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11103 (setq e (assoc name org-table-named-field-locations))
11104 (goto-line (nth 1 e))
11105 (org-table-goto-column (nth 2 e)))
11106 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11107 (let ((l (string-to-number (match-string 1 dest)))
11108 (c (string-to-number (match-string 2 dest))))
11109 (goto-line (aref org-table-dlines l))
11110 (org-table-goto-column c)))
11111 (t (org-table-goto-column (string-to-number name))))
11112 (move-marker pos (point))
11113 (org-table-highlight-rectangle nil nil face2))
11114 (cond
11115 ((equal dest match))
11116 ((not match))
11117 ((eq what 'range)
11118 (condition-case nil
11119 (save-excursion
11120 (org-table-get-range match nil nil 'highlight))
11121 (error nil)))
11122 ((setq e (assoc var org-table-named-field-locations))
11123 (goto-line (nth 1 e))
11124 (org-table-goto-column (nth 2 e))
11125 (org-table-highlight-rectangle (point) (point))
11126 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11127 ((setq e (assoc var org-table-column-names))
11128 (org-table-goto-column (string-to-number (cdr e)))
11129 (org-table-highlight-rectangle (point) (point))
11130 (goto-char (org-table-begin))
11131 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11132 (org-table-end) t)
11133 (progn
11134 (goto-char (match-beginning 1))
11135 (org-table-highlight-rectangle)
11136 (message "Named column (column %s)" (cdr e)))
11137 (error "Column name not found")))
11138 ((eq what 'column)
11139 ;; column number
11140 (org-table-goto-column (string-to-number (substring match 1)))
11141 (org-table-highlight-rectangle (point) (point))
11142 (message "Column %s" (substring match 1)))
11143 ((setq e (assoc var org-table-local-parameters))
11144 (goto-char (org-table-begin))
11145 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11146 (progn
11147 (goto-char (match-beginning 1))
11148 (org-table-highlight-rectangle)
11149 (message "Local parameter."))
11150 (error "Parameter not found")))
11151 (t
11152 (cond
11153 ((not var) (error "No reference at point"))
11154 ((setq e (assoc var org-table-formula-constants-local))
11155 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11156 var (cdr e)))
11157 ((setq e (assoc var org-table-formula-constants))
11158 (message "Constant: $%s=%s in `org-table-formula-constants'."
11159 var (cdr e)))
11160 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11161 (message "Constant: $%s=%s, from `constants.el'%s."
11162 var e (format " (%s units)" constants-unit-system)))
11163 (t (error "Undefined name $%s" var)))))
11164 (goto-char pos)
11165 (when (and org-show-positions
11166 (not (memq this-command '(org-table-fedit-scroll
11167 org-table-fedit-scroll-down))))
11168 (push pos org-show-positions)
11169 (push org-table-current-begin-pos org-show-positions)
11170 (let ((min (apply 'min org-show-positions))
11171 (max (apply 'max org-show-positions)))
11172 (goto-char min) (recenter 0)
11173 (goto-char max)
11174 (or (pos-visible-in-window-p max) (recenter -1))))
11175 (select-window win))))
11176
11177 (defun org-table-force-dataline ()
11178 "Make sure the cursor is in a dataline in a table."
11179 (unless (save-excursion
11180 (beginning-of-line 1)
11181 (looking-at org-table-dataline-regexp))
11182 (let* ((re org-table-dataline-regexp)
11183 (p1 (save-excursion (re-search-forward re nil 'move)))
11184 (p2 (save-excursion (re-search-backward re nil 'move))))
11185 (cond ((and p1 p2)
11186 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11187 p1 p2)))
11188 ((or p1 p2) (goto-char (or p1 p2)))
11189 (t (error "No table dataline around here"))))))
11190
11191 (defun org-table-fedit-line-up ()
11192 "Move cursor one line up in the window showing the table."
11193 (interactive)
11194 (org-table-fedit-move 'previous-line))
11195
11196 (defun org-table-fedit-line-down ()
11197 "Move cursor one line down in the window showing the table."
11198 (interactive)
11199 (org-table-fedit-move 'next-line))
11200
11201 (defun org-table-fedit-move (command)
11202 "Move the cursor in the window shoinw the table.
11203 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11204 (let ((org-table-allow-automatic-line-recalculation nil)
11205 (pos org-pos) (win (selected-window)) p)
11206 (select-window (get-buffer-window (marker-buffer org-pos)))
11207 (setq p (point))
11208 (call-interactively command)
11209 (while (and (org-at-table-p)
11210 (org-at-table-hline-p))
11211 (call-interactively command))
11212 (or (org-at-table-p) (goto-char p))
11213 (move-marker pos (point))
11214 (select-window win)))
11215
11216 (defun org-table-fedit-scroll (N)
11217 (interactive "p")
11218 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11219 (scroll-other-window N)))
11220
11221 (defun org-table-fedit-scroll-down (N)
11222 (interactive "p")
11223 (org-table-fedit-scroll (- N)))
11224
11225 (defvar org-table-rectangle-overlays nil)
11226
11227 (defun org-table-add-rectangle-overlay (beg end &optional face)
11228 "Add a new overlay."
11229 (let ((ov (org-make-overlay beg end)))
11230 (org-overlay-put ov 'face (or face 'secondary-selection))
11231 (push ov org-table-rectangle-overlays)))
11232
11233 (defun org-table-highlight-rectangle (&optional beg end face)
11234 "Highlight rectangular region in a table."
11235 (setq beg (or beg (point)) end (or end (point)))
11236 (let ((b (min beg end))
11237 (e (max beg end))
11238 l1 c1 l2 c2 tmp)
11239 (and (boundp 'org-show-positions)
11240 (setq org-show-positions (cons b (cons e org-show-positions))))
11241 (goto-char (min beg end))
11242 (setq l1 (org-current-line)
11243 c1 (org-table-current-column))
11244 (goto-char (max beg end))
11245 (setq l2 (org-current-line)
11246 c2 (org-table-current-column))
11247 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11248 (goto-line l1)
11249 (beginning-of-line 1)
11250 (loop for line from l1 to l2 do
11251 (when (looking-at org-table-dataline-regexp)
11252 (org-table-goto-column c1)
11253 (skip-chars-backward "^|\n") (setq beg (point))
11254 (org-table-goto-column c2)
11255 (skip-chars-forward "^|\n") (setq end (point))
11256 (org-table-add-rectangle-overlay beg end face))
11257 (beginning-of-line 2))
11258 (goto-char b))
11259 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11260
11261 (defun org-table-remove-rectangle-highlight (&rest ignore)
11262 "Remove the rectangle overlays."
11263 (unless org-inhibit-highlight-removal
11264 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11265 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11266 (setq org-table-rectangle-overlays nil)))
11267
11268 (defvar org-table-coordinate-overlays nil
11269 "Collects the cooordinate grid overlays, so that they can be removed.")
11270 (make-variable-buffer-local 'org-table-coordinate-overlays)
11271
11272 (defun org-table-overlay-coordinates ()
11273 "Add overlays to the table at point, to show row/column coordinates."
11274 (interactive)
11275 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11276 (setq org-table-coordinate-overlays nil)
11277 (save-excursion
11278 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11279 (goto-char (org-table-begin))
11280 (while (org-at-table-p)
11281 (setq eol (point-at-eol))
11282 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11283 (push ov org-table-coordinate-overlays)
11284 (setq hline (looking-at org-table-hline-regexp))
11285 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11286 (format "%4d" (setq id (1+ id)))))
11287 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11288 (when hline
11289 (setq ic 0)
11290 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11291 (setq beg (1+ (match-beginning 0))
11292 ic (1+ ic)
11293 s1 (concat "$" (int-to-string ic))
11294 s2 (org-number-to-letters ic)
11295 str (if (eq org-table-use-standard-references t) s2 s1))
11296 (setq ov (org-make-overlay beg (+ beg (length str))))
11297 (push ov org-table-coordinate-overlays)
11298 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11299 (beginning-of-line 2)))))
11300
11301 (defun org-table-toggle-coordinate-overlays ()
11302 "Toggle the display of Row/Column numbers in tables."
11303 (interactive)
11304 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11305 (message "Row/Column number display turned %s"
11306 (if org-table-overlay-coordinates "on" "off"))
11307 (if (and (org-at-table-p) org-table-overlay-coordinates)
11308 (org-table-align))
11309 (unless org-table-overlay-coordinates
11310 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11311 (setq org-table-coordinate-overlays nil)))
11312
11313 (defun org-table-toggle-formula-debugger ()
11314 "Toggle the formula debugger in tables."
11315 (interactive)
11316 (setq org-table-formula-debug (not org-table-formula-debug))
11317 (message "Formula debugging has been turned %s"
11318 (if org-table-formula-debug "on" "off")))
11319
11320 ;;; The orgtbl minor mode
11321
11322 ;; Define a minor mode which can be used in other modes in order to
11323 ;; integrate the org-mode table editor.
11324
11325 ;; This is really a hack, because the org-mode table editor uses several
11326 ;; keys which normally belong to the major mode, for example the TAB and
11327 ;; RET keys. Here is how it works: The minor mode defines all the keys
11328 ;; necessary to operate the table editor, but wraps the commands into a
11329 ;; function which tests if the cursor is currently inside a table. If that
11330 ;; is the case, the table editor command is executed. However, when any of
11331 ;; those keys is used outside a table, the function uses `key-binding' to
11332 ;; look up if the key has an associated command in another currently active
11333 ;; keymap (minor modes, major mode, global), and executes that command.
11334 ;; There might be problems if any of the keys used by the table editor is
11335 ;; otherwise used as a prefix key.
11336
11337 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11338 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11339 ;; addresses this by checking explicitly for both bindings.
11340
11341 ;; The optimized version (see variable `orgtbl-optimized') takes over
11342 ;; all keys which are bound to `self-insert-command' in the *global map*.
11343 ;; Some modes bind other commands to simple characters, for example
11344 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11345 ;; active, this binding is ignored inside tables and replaced with a
11346 ;; modified self-insert.
11347
11348 (defvar orgtbl-mode nil
11349 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11350 table editor in arbitrary modes.")
11351 (make-variable-buffer-local 'orgtbl-mode)
11352
11353 (defvar orgtbl-mode-map (make-keymap)
11354 "Keymap for `orgtbl-mode'.")
11355
11356 ;;;###autoload
11357 (defun turn-on-orgtbl ()
11358 "Unconditionally turn on `orgtbl-mode'."
11359 (orgtbl-mode 1))
11360
11361 (defvar org-old-auto-fill-inhibit-regexp nil
11362 "Local variable used by `orgtbl-mode'")
11363
11364 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11365 "Matches a line belonging to an orgtbl.")
11366
11367 (defconst orgtbl-extra-font-lock-keywords
11368 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11369 0 (quote 'org-table) 'prepend))
11370 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11371
11372 ;;;###autoload
11373 (defun orgtbl-mode (&optional arg)
11374 "The `org-mode' table editor as a minor mode for use in other modes."
11375 (interactive)
11376 (if (org-mode-p)
11377 ;; Exit without error, in case some hook functions calls this
11378 ;; by accident in org-mode.
11379 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11380 (setq orgtbl-mode
11381 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11382 (if orgtbl-mode
11383 (progn
11384 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11385 ;; Make sure we are first in minor-mode-map-alist
11386 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11387 (and c (setq minor-mode-map-alist
11388 (cons c (delq c minor-mode-map-alist)))))
11389 (org-set-local (quote org-table-may-need-update) t)
11390 (org-add-hook 'before-change-functions 'org-before-change-function
11391 nil 'local)
11392 (org-set-local 'org-old-auto-fill-inhibit-regexp
11393 auto-fill-inhibit-regexp)
11394 (org-set-local 'auto-fill-inhibit-regexp
11395 (if auto-fill-inhibit-regexp
11396 (concat orgtbl-line-start-regexp "\\|"
11397 auto-fill-inhibit-regexp)
11398 orgtbl-line-start-regexp))
11399 (org-add-to-invisibility-spec '(org-cwidth))
11400 (when (fboundp 'font-lock-add-keywords)
11401 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11402 (org-restart-font-lock))
11403 (easy-menu-add orgtbl-mode-menu)
11404 (run-hooks 'orgtbl-mode-hook))
11405 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11406 (org-cleanup-narrow-column-properties)
11407 (org-remove-from-invisibility-spec '(org-cwidth))
11408 (remove-hook 'before-change-functions 'org-before-change-function t)
11409 (when (fboundp 'font-lock-remove-keywords)
11410 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11411 (org-restart-font-lock))
11412 (easy-menu-remove orgtbl-mode-menu)
11413 (force-mode-line-update 'all))))
11414
11415 (defun org-cleanup-narrow-column-properties ()
11416 "Remove all properties related to narrow-column invisibility."
11417 (let ((s 1))
11418 (while (setq s (text-property-any s (point-max)
11419 'display org-narrow-column-arrow))
11420 (remove-text-properties s (1+ s) '(display t)))
11421 (setq s 1)
11422 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11423 (remove-text-properties s (1+ s) '(org-cwidth t)))
11424 (setq s 1)
11425 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11426 (remove-text-properties s (1+ s) '(invisible t)))))
11427
11428 ;; Install it as a minor mode.
11429 (put 'orgtbl-mode :included t)
11430 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11431 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11432
11433 (defun orgtbl-make-binding (fun n &rest keys)
11434 "Create a function for binding in the table minor mode.
11435 FUN is the command to call inside a table. N is used to create a unique
11436 command name. KEYS are keys that should be checked in for a command
11437 to execute outside of tables."
11438 (eval
11439 (list 'defun
11440 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11441 '(arg)
11442 (concat "In tables, run `" (symbol-name fun) "'.\n"
11443 "Outside of tables, run the binding of `"
11444 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11445 "'.")
11446 '(interactive "p")
11447 (list 'if
11448 '(org-at-table-p)
11449 (list 'call-interactively (list 'quote fun))
11450 (list 'let '(orgtbl-mode)
11451 (list 'call-interactively
11452 (append '(or)
11453 (mapcar (lambda (k)
11454 (list 'key-binding k))
11455 keys)
11456 '('orgtbl-error))))))))
11457
11458 (defun orgtbl-error ()
11459 "Error when there is no default binding for a table key."
11460 (interactive)
11461 (error "This key has no function outside tables"))
11462
11463 (defun orgtbl-setup ()
11464 "Setup orgtbl keymaps."
11465 (let ((nfunc 0)
11466 (bindings
11467 (list
11468 '([(meta shift left)] org-table-delete-column)
11469 '([(meta left)] org-table-move-column-left)
11470 '([(meta right)] org-table-move-column-right)
11471 '([(meta shift right)] org-table-insert-column)
11472 '([(meta shift up)] org-table-kill-row)
11473 '([(meta shift down)] org-table-insert-row)
11474 '([(meta up)] org-table-move-row-up)
11475 '([(meta down)] org-table-move-row-down)
11476 '("\C-c\C-w" org-table-cut-region)
11477 '("\C-c\M-w" org-table-copy-region)
11478 '("\C-c\C-y" org-table-paste-rectangle)
11479 '("\C-c-" org-table-insert-hline)
11480 '("\C-c}" org-table-toggle-coordinate-overlays)
11481 '("\C-c{" org-table-toggle-formula-debugger)
11482 '("\C-m" org-table-next-row)
11483 '([(shift return)] org-table-copy-down)
11484 '("\C-c\C-q" org-table-wrap-region)
11485 '("\C-c?" org-table-field-info)
11486 '("\C-c " org-table-blank-field)
11487 '("\C-c+" org-table-sum)
11488 '("\C-c=" org-table-eval-formula)
11489 '("\C-c'" org-table-edit-formulas)
11490 '("\C-c`" org-table-edit-field)
11491 '("\C-c*" org-table-recalculate)
11492 '("\C-c|" org-table-create-or-convert-from-region)
11493 '("\C-c^" org-table-sort-lines)
11494 '([(control ?#)] org-table-rotate-recalc-marks)))
11495 elt key fun cmd)
11496 (while (setq elt (pop bindings))
11497 (setq nfunc (1+ nfunc))
11498 (setq key (org-key (car elt))
11499 fun (nth 1 elt)
11500 cmd (orgtbl-make-binding fun nfunc key))
11501 (org-defkey orgtbl-mode-map key cmd))
11502
11503 ;; Special treatment needed for TAB and RET
11504 (org-defkey orgtbl-mode-map [(return)]
11505 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11506 (org-defkey orgtbl-mode-map "\C-m"
11507 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11508
11509 (org-defkey orgtbl-mode-map [(tab)]
11510 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11511 (org-defkey orgtbl-mode-map "\C-i"
11512 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11513
11514 (org-defkey orgtbl-mode-map [(shift tab)]
11515 (orgtbl-make-binding 'org-table-previous-field 104
11516 [(shift tab)] [(tab)] "\C-i"))
11517
11518 (org-defkey orgtbl-mode-map "\M-\C-m"
11519 (orgtbl-make-binding 'org-table-wrap-region 105
11520 "\M-\C-m" [(meta return)]))
11521 (org-defkey orgtbl-mode-map [(meta return)]
11522 (orgtbl-make-binding 'org-table-wrap-region 106
11523 [(meta return)] "\M-\C-m"))
11524
11525 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11526 (when orgtbl-optimized
11527 ;; If the user wants maximum table support, we need to hijack
11528 ;; some standard editing functions
11529 (org-remap orgtbl-mode-map
11530 'self-insert-command 'orgtbl-self-insert-command
11531 'delete-char 'org-delete-char
11532 'delete-backward-char 'org-delete-backward-char)
11533 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11534 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11535 '("OrgTbl"
11536 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11537 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11538 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11539 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11540 "--"
11541 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11542 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11543 ["Copy Field from Above"
11544 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11545 "--"
11546 ("Column"
11547 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11548 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11549 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11550 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11551 ("Row"
11552 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11553 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11554 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11555 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11556 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
11557 "--"
11558 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11559 ("Rectangle"
11560 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11561 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11562 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11563 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11564 "--"
11565 ("Radio tables"
11566 ["Insert table template" orgtbl-insert-radio-table
11567 (assq major-mode orgtbl-radio-table-templates)]
11568 ["Comment/uncomment table" orgtbl-toggle-comment t])
11569 "--"
11570 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11571 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11572 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11573 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11574 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11575 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11576 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11577 ["Sum Column/Rectangle" org-table-sum
11578 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11579 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11580 ["Debug Formulas"
11581 org-table-toggle-formula-debugger :active (org-at-table-p)
11582 :keys "C-c {"
11583 :style toggle :selected org-table-formula-debug]
11584 ["Show Col/Row Numbers"
11585 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11586 :keys "C-c }"
11587 :style toggle :selected org-table-overlay-coordinates]
11588 ))
11589 t))
11590
11591 (defun orgtbl-ctrl-c-ctrl-c (arg)
11592 "If the cursor is inside a table, realign the table.
11593 It it is a table to be sent away to a receiver, do it.
11594 With prefix arg, also recompute table."
11595 (interactive "P")
11596 (let ((pos (point)) action)
11597 (save-excursion
11598 (beginning-of-line 1)
11599 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11600 ((looking-at "[ \t]*|") pos)
11601 ((looking-at "#\\+TBLFM:") 'recalc))))
11602 (cond
11603 ((integerp action)
11604 (goto-char action)
11605 (org-table-maybe-eval-formula)
11606 (if arg
11607 (call-interactively 'org-table-recalculate)
11608 (org-table-maybe-recalculate-line))
11609 (call-interactively 'org-table-align)
11610 (orgtbl-send-table 'maybe))
11611 ((eq action 'recalc)
11612 (save-excursion
11613 (beginning-of-line 1)
11614 (skip-chars-backward " \r\n\t")
11615 (if (org-at-table-p)
11616 (org-call-with-arg 'org-table-recalculate t))))
11617 (t (let (orgtbl-mode)
11618 (call-interactively (key-binding "\C-c\C-c")))))))
11619
11620 (defun orgtbl-tab (arg)
11621 "Justification and field motion for `orgtbl-mode'."
11622 (interactive "P")
11623 (if arg (org-table-edit-field t)
11624 (org-table-justify-field-maybe)
11625 (org-table-next-field)))
11626
11627 (defun orgtbl-ret ()
11628 "Justification and field motion for `orgtbl-mode'."
11629 (interactive)
11630 (org-table-justify-field-maybe)
11631 (org-table-next-row))
11632
11633 (defun orgtbl-self-insert-command (N)
11634 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11635 If the cursor is in a table looking at whitespace, the whitespace is
11636 overwritten, and the table is not marked as requiring realignment."
11637 (interactive "p")
11638 (if (and (org-at-table-p)
11639 (or
11640 (and org-table-auto-blank-field
11641 (member last-command
11642 '(orgtbl-hijacker-command-100
11643 orgtbl-hijacker-command-101
11644 orgtbl-hijacker-command-102
11645 orgtbl-hijacker-command-103
11646 orgtbl-hijacker-command-104
11647 orgtbl-hijacker-command-105))
11648 (org-table-blank-field))
11649 t)
11650 (eq N 1)
11651 (looking-at "[^|\n]* +|"))
11652 (let (org-table-may-need-update)
11653 (goto-char (1- (match-end 0)))
11654 (delete-backward-char 1)
11655 (goto-char (match-beginning 0))
11656 (self-insert-command N))
11657 (setq org-table-may-need-update t)
11658 (let (orgtbl-mode)
11659 (call-interactively (key-binding (vector last-input-event))))))
11660
11661 (defun org-force-self-insert (N)
11662 "Needed to enforce self-insert under remapping."
11663 (interactive "p")
11664 (self-insert-command N))
11665
11666 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11667 "Regula expression matching exponentials as produced by calc.")
11668
11669 (defvar org-table-clean-did-remove-column nil)
11670
11671 (defun orgtbl-export (table target)
11672 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11673 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11674 org-table-last-alignment org-table-last-column-widths
11675 maxcol column)
11676 (if (not (fboundp func))
11677 (error "Cannot export orgtbl table to %s" target))
11678 (setq lines (org-table-clean-before-export lines))
11679 (setq table
11680 (mapcar
11681 (lambda (x)
11682 (if (string-match org-table-hline-regexp x)
11683 'hline
11684 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11685 lines))
11686 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11687 table)))
11688 (loop for i from (1- maxcol) downto 0 do
11689 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11690 (setq column (delq nil column))
11691 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11692 (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))
11693 (funcall func table nil)))
11694
11695 (defun orgtbl-send-table (&optional maybe)
11696 "Send a tranformed version of this table to the receiver position.
11697 With argument MAYBE, fail quietly if no transformation is defined for
11698 this table."
11699 (interactive)
11700 (catch 'exit
11701 (unless (org-at-table-p) (error "Not at a table"))
11702 ;; when non-interactive, we assume align has just happened.
11703 (when (interactive-p) (org-table-align))
11704 (save-excursion
11705 (goto-char (org-table-begin))
11706 (beginning-of-line 0)
11707 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11708 (if maybe
11709 (throw 'exit nil)
11710 (error "Don't know how to transform this table."))))
11711 (let* ((name (match-string 1))
11712 beg
11713 (transform (intern (match-string 2)))
11714 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11715 (skip (plist-get params :skip))
11716 (skipcols (plist-get params :skipcols))
11717 (txt (buffer-substring-no-properties
11718 (org-table-begin) (org-table-end)))
11719 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11720 (lines (org-table-clean-before-export lines))
11721 (i0 (if org-table-clean-did-remove-column 2 1))
11722 (table (mapcar
11723 (lambda (x)
11724 (if (string-match org-table-hline-regexp x)
11725 'hline
11726 (org-remove-by-index
11727 (org-split-string (org-trim x) "\\s-*|\\s-*")
11728 skipcols i0)))
11729 lines))
11730 (fun (if (= i0 2) 'cdr 'identity))
11731 (org-table-last-alignment
11732 (org-remove-by-index (funcall fun org-table-last-alignment)
11733 skipcols i0))
11734 (org-table-last-column-widths
11735 (org-remove-by-index (funcall fun org-table-last-column-widths)
11736 skipcols i0)))
11737
11738 (unless (fboundp transform)
11739 (error "No such transformation function %s" transform))
11740 (setq txt (funcall transform table params))
11741 ;; Find the insertion place
11742 (save-excursion
11743 (goto-char (point-min))
11744 (unless (re-search-forward
11745 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11746 (error "Don't know where to insert translated table"))
11747 (goto-char (match-beginning 0))
11748 (beginning-of-line 2)
11749 (setq beg (point))
11750 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11751 (error "Cannot find end of insertion region"))
11752 (beginning-of-line 1)
11753 (delete-region beg (point))
11754 (goto-char beg)
11755 (insert txt "\n"))
11756 (message "Table converted and installed at receiver location"))))
11757
11758 (defun org-remove-by-index (list indices &optional i0)
11759 "Remove the elements in LIST with indices in INDICES.
11760 First element has index 0, or I0 if given."
11761 (if (not indices)
11762 list
11763 (if (integerp indices) (setq indices (list indices)))
11764 (setq i0 (1- (or i0 0)))
11765 (delq :rm (mapcar (lambda (x)
11766 (setq i0 (1+ i0))
11767 (if (memq i0 indices) :rm x))
11768 list))))
11769
11770 (defun orgtbl-toggle-comment ()
11771 "Comment or uncomment the orgtbl at point."
11772 (interactive)
11773 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11774 (re2 (concat "^" orgtbl-line-start-regexp))
11775 (commented (save-excursion (beginning-of-line 1)
11776 (cond ((looking-at re1) t)
11777 ((looking-at re2) nil)
11778 (t (error "Not at an org table")))))
11779 (re (if commented re1 re2))
11780 beg end)
11781 (save-excursion
11782 (beginning-of-line 1)
11783 (while (looking-at re) (beginning-of-line 0))
11784 (beginning-of-line 2)
11785 (setq beg (point))
11786 (while (looking-at re) (beginning-of-line 2))
11787 (setq end (point)))
11788 (comment-region beg end (if commented '(4) nil))))
11789
11790 (defun orgtbl-insert-radio-table ()
11791 "Insert a radio table template appropriate for this major mode."
11792 (interactive)
11793 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11794 (txt (nth 1 e))
11795 name pos)
11796 (unless e (error "No radio table setup defined for %s" major-mode))
11797 (setq name (read-string "Table name: "))
11798 (while (string-match "%n" txt)
11799 (setq txt (replace-match name t t txt)))
11800 (or (bolp) (insert "\n"))
11801 (setq pos (point))
11802 (insert txt)
11803 (goto-char pos)))
11804
11805 (defun org-get-param (params header i sym &optional hsym)
11806 "Get parameter value for symbol SYM.
11807 If this is a header line, actually get the value for the symbol with an
11808 additional \"h\" inserted after the colon.
11809 If the value is a protperty list, get the element for the current column.
11810 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11811 (let ((val (plist-get params sym)))
11812 (and hsym header (setq val (or (plist-get params hsym) val)))
11813 (if (consp val) (plist-get val i) val)))
11814
11815 (defun orgtbl-to-generic (table params)
11816 "Convert the orgtbl-mode TABLE to some other format.
11817 This generic routine can be used for many standard cases.
11818 TABLE is a list, each entry either the symbol `hline' for a horizontal
11819 separator line, or a list of fields for that line.
11820 PARAMS is a property list of parameters that can influence the conversion.
11821 For the generic converter, some parameters are obligatory: You need to
11822 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11823 :splice, you must have :tstart and :tend.
11824
11825 Valid parameters are
11826
11827 :tstart String to start the table. Ignored when :splice is t.
11828 :tend String to end the table. Ignored when :splice is t.
11829
11830 :splice When set to t, return only table body lines, don't wrap
11831 them into :tstart and :tend. Default is nil.
11832
11833 :hline String to be inserted on horizontal separation lines.
11834 May be nil to ignore hlines.
11835
11836 :lstart String to start a new table line.
11837 :lend String to end a table line
11838 :sep Separator between two fields
11839 :lfmt Format for entire line, with enough %s to capture all fields.
11840 If this is present, :lstart, :lend, and :sep are ignored.
11841 :fmt A format to be used to wrap the field, should contain
11842 %s for the original field value. For example, to wrap
11843 everything in dollars, you could use :fmt \"$%s$\".
11844 This may also be a property list with column numbers and
11845 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11846
11847 :hlstart :hlend :hlsep :hlfmt :hfmt
11848 Same as above, specific for the header lines in the table.
11849 All lines before the first hline are treated as header.
11850 If any of these is not present, the data line value is used.
11851
11852 :efmt Use this format to print numbers with exponentials.
11853 The format should have %s twice for inserting mantissa
11854 and exponent, for example \"%s\\\\times10^{%s}\". This
11855 may also be a property list with column numbers and
11856 formats. :fmt will still be applied after :efmt.
11857
11858 In addition to this, the parameters :skip and :skipcols are always handled
11859 directly by `orgtbl-send-table'. See manual."
11860 (interactive)
11861 (let* ((p params)
11862 (splicep (plist-get p :splice))
11863 (hline (plist-get p :hline))
11864 rtn line i fm efm lfmt h)
11865
11866 ;; Do we have a header?
11867 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11868 (setq h t))
11869
11870 ;; Put header
11871 (unless splicep
11872 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11873
11874 ;; Now loop over all lines
11875 (while (setq line (pop table))
11876 (if (eq line 'hline)
11877 ;; A horizontal separator line
11878 (progn (if hline (push hline rtn))
11879 (setq h nil)) ; no longer in header
11880 ;; A normal line. Convert the fields, push line onto the result list
11881 (setq i 0)
11882 (setq line
11883 (mapcar
11884 (lambda (f)
11885 (setq i (1+ i)
11886 fm (org-get-param p h i :fmt :hfmt)
11887 efm (org-get-param p h i :efmt))
11888 (if (and efm (string-match orgtbl-exp-regexp f))
11889 (setq f (format
11890 efm (match-string 1 f) (match-string 2 f))))
11891 (if fm (setq f (format fm f)))
11892 f)
11893 line))
11894 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11895 (push (apply 'format lfmt line) rtn)
11896 (push (concat
11897 (org-get-param p h i :lstart :hlstart)
11898 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11899 (org-get-param p h i :lend :hlend))
11900 rtn))))
11901
11902 (unless splicep
11903 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11904
11905 (mapconcat 'identity (nreverse rtn) "\n")))
11906
11907 (defun orgtbl-to-latex (table params)
11908 "Convert the orgtbl-mode TABLE to LaTeX.
11909 TABLE is a list, each entry either the symbol `hline' for a horizontal
11910 separator line, or a list of fields for that line.
11911 PARAMS is a property list of parameters that can influence the conversion.
11912 Supports all parameters from `orgtbl-to-generic'. Most important for
11913 LaTeX are:
11914
11915 :splice When set to t, return only table body lines, don't wrap
11916 them into a tabular environment. Default is nil.
11917
11918 :fmt A format to be used to wrap the field, should contain %s for the
11919 original field value. For example, to wrap everything in dollars,
11920 use :fmt \"$%s$\". This may also be a property list with column
11921 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11922
11923 :efmt Format for transforming numbers with exponentials. The format
11924 should have %s twice for inserting mantissa and exponent, for
11925 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11926 This may also be a property list with column numbers and formats.
11927
11928 The general parameters :skip and :skipcols have already been applied when
11929 this function is called."
11930 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11931 org-table-last-alignment ""))
11932 (params2
11933 (list
11934 :tstart (concat "\\begin{tabular}{" alignment "}")
11935 :tend "\\end{tabular}"
11936 :lstart "" :lend " \\\\" :sep " & "
11937 :efmt "%s\\,(%s)" :hline "\\hline")))
11938 (orgtbl-to-generic table (org-combine-plists params2 params))))
11939
11940 (defun orgtbl-to-html (table params)
11941 "Convert the orgtbl-mode TABLE to LaTeX.
11942 TABLE is a list, each entry either the symbol `hline' for a horizontal
11943 separator line, or a list of fields for that line.
11944 PARAMS is a property list of parameters that can influence the conversion.
11945 Currently this function recognizes the following parameters:
11946
11947 :splice When set to t, return only table body lines, don't wrap
11948 them into a <table> environment. Default is nil.
11949
11950 The general parameters :skip and :skipcols have already been applied when
11951 this function is called. The function does *not* use `orgtbl-to-generic',
11952 so you cannot specify parameters for it."
11953 (let* ((splicep (plist-get params :splice))
11954 html)
11955 ;; Just call the formatter we already have
11956 ;; We need to make text lines for it, so put the fields back together.
11957 (setq html (org-format-org-table-html
11958 (mapcar
11959 (lambda (x)
11960 (if (eq x 'hline)
11961 "|----+----|"
11962 (concat "| " (mapconcat 'identity x " | ") " |")))
11963 table)
11964 splicep))
11965 (if (string-match "\n+\\'" html)
11966 (setq html (replace-match "" t t html)))
11967 html))
11968
11969 (defun orgtbl-to-texinfo (table params)
11970 "Convert the orgtbl-mode TABLE to TeXInfo.
11971 TABLE is a list, each entry either the symbol `hline' for a horizontal
11972 separator line, or a list of fields for that line.
11973 PARAMS is a property list of parameters that can influence the conversion.
11974 Supports all parameters from `orgtbl-to-generic'. Most important for
11975 TeXInfo are:
11976
11977 :splice nil/t When set to t, return only table body lines, don't wrap
11978 them into a multitable environment. Default is nil.
11979
11980 :fmt fmt A format to be used to wrap the field, should contain
11981 %s for the original field value. For example, to wrap
11982 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11983 This may also be a property list with column numbers and
11984 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11985
11986 :cf \"f1 f2..\" The column fractions for the table. By default these
11987 are computed automatically from the width of the columns
11988 under org-mode.
11989
11990 The general parameters :skip and :skipcols have already been applied when
11991 this function is called."
11992 (let* ((total (float (apply '+ org-table-last-column-widths)))
11993 (colfrac (or (plist-get params :cf)
11994 (mapconcat
11995 (lambda (x) (format "%.3f" (/ (float x) total)))
11996 org-table-last-column-widths " ")))
11997 (params2
11998 (list
11999 :tstart (concat "@multitable @columnfractions " colfrac)
12000 :tend "@end multitable"
12001 :lstart "@item " :lend "" :sep " @tab "
12002 :hlstart "@headitem ")))
12003 (orgtbl-to-generic table (org-combine-plists params2 params))))
12004
12005 ;;;; Link Stuff
12006
12007 ;;; Link abbreviations
12008
12009 (defun org-link-expand-abbrev (link)
12010 "Apply replacements as defined in `org-link-abbrev-alist."
12011 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
12012 (let* ((key (match-string 1 link))
12013 (as (or (assoc key org-link-abbrev-alist-local)
12014 (assoc key org-link-abbrev-alist)))
12015 (tag (and (match-end 2) (match-string 3 link)))
12016 rpl)
12017 (if (not as)
12018 link
12019 (setq rpl (cdr as))
12020 (cond
12021 ((symbolp rpl) (funcall rpl tag))
12022 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
12023 (t (concat rpl tag)))))
12024 link))
12025
12026 ;;; Storing and inserting links
12027
12028 (defvar org-insert-link-history nil
12029 "Minibuffer history for links inserted with `org-insert-link'.")
12030
12031 (defvar org-stored-links nil
12032 "Contains the links stored with `org-store-link'.")
12033
12034 (defvar org-store-link-plist nil
12035 "Plist with info about the most recently link created with `org-store-link'.")
12036
12037 (defvar org-link-protocols nil
12038 "Link protocols added to Org-mode using `org-add-link-type'.")
12039
12040 (defvar org-store-link-functions nil
12041 "List of functions that are called to create and store a link.
12042 Each function will be called in turn until one returns a non-nil
12043 value. Each function should check if it is responsible for creating
12044 this link (for example by looking at the major mode).
12045 If not, it must exit and return nil.
12046 If yes, it should return a non-nil value after a calling
12047 `org-store-link-props' with a list of properties and values.
12048 Special properties are:
12049
12050 :type The link prefix. like \"http\". This must be given.
12051 :link The link, like \"http://www.astro.uva.nl/~dominik\".
12052 This is obligatory as well.
12053 :description Optional default description for the second pair
12054 of brackets in an Org-mode link. The user can still change
12055 this when inserting this link into an Org-mode buffer.
12056
12057 In addition to these, any additional properties can be specified
12058 and then used in remember templates.")
12059
12060 (defun org-add-link-type (type &optional follow publish)
12061 "Add TYPE to the list of `org-link-types'.
12062 Re-compute all regular expressions depending on `org-link-types'
12063 FOLLOW and PUBLISH are two functions. Both take the link path as
12064 an argument.
12065 FOLLOW should do whatever is necessary to follow the link, for example
12066 to find a file or display a mail message.
12067
12068 PUBLISH takes the path and retuns the string that should be used when
12069 this document is published. FIMXE: This is actually not yet implemented."
12070 (add-to-list 'org-link-types type t)
12071 (org-make-link-regexps)
12072 (add-to-list 'org-link-protocols
12073 (list type follow publish)))
12074
12075 (defun org-add-agenda-custom-command (entry)
12076 "Replace or add a command in `org-agenda-custom-commands'.
12077 This is mostly for hacking and trying a new command - once the command
12078 works you probably want to add it to `org-agenda-custom-commands' for good."
12079 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12080 (if ass
12081 (setcdr ass (cdr entry))
12082 (push entry org-agenda-custom-commands))))
12083
12084 ;;;###autoload
12085 (defun org-store-link (arg)
12086 "\\<org-mode-map>Store an org-link to the current location.
12087 This link is added to `org-stored-links' and can later be inserted
12088 into an org-buffer with \\[org-insert-link].
12089
12090 For some link types, a prefix arg is interpreted:
12091 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12092 For file links, arg negates `org-context-in-file-links'."
12093 (interactive "P")
12094 (require 'org-irc)
12095 (setq org-store-link-plist nil) ; reset
12096 (let (link cpltxt desc description search txt)
12097 (cond
12098
12099 ((run-hook-with-args-until-success 'org-store-link-functions)
12100 (setq link (plist-get org-store-link-plist :link)
12101 desc (or (plist-get org-store-link-plist :description) link)))
12102
12103 ((eq major-mode 'bbdb-mode)
12104 (let ((name (bbdb-record-name (bbdb-current-record)))
12105 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
12106 (setq cpltxt (concat "bbdb:" (or name company))
12107 link (org-make-link cpltxt))
12108 (org-store-link-props :type "bbdb" :name name :company company)))
12109
12110 ((eq major-mode 'Info-mode)
12111 (setq link (org-make-link "info:"
12112 (file-name-nondirectory Info-current-file)
12113 ":" Info-current-node))
12114 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
12115 ":" Info-current-node))
12116 (org-store-link-props :type "info" :file Info-current-file
12117 :node Info-current-node))
12118
12119 ((eq major-mode 'calendar-mode)
12120 (let ((cd (calendar-cursor-to-date)))
12121 (setq link
12122 (format-time-string
12123 (car org-time-stamp-formats)
12124 (apply 'encode-time
12125 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12126 nil nil nil))))
12127 (org-store-link-props :type "calendar" :date cd)))
12128
12129 ((or (eq major-mode 'vm-summary-mode)
12130 (eq major-mode 'vm-presentation-mode))
12131 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
12132 (vm-follow-summary-cursor)
12133 (save-excursion
12134 (vm-select-folder-buffer)
12135 (let* ((message (car vm-message-pointer))
12136 (folder buffer-file-name)
12137 (subject (vm-su-subject message))
12138 (to (vm-get-header-contents message "To"))
12139 (from (vm-get-header-contents message "From"))
12140 (message-id (vm-su-message-id message)))
12141 (org-store-link-props :type "vm" :from from :to to :subject subject
12142 :message-id message-id)
12143 (setq message-id (org-remove-angle-brackets message-id))
12144 (setq folder (abbreviate-file-name folder))
12145 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
12146 folder)
12147 (setq folder (replace-match "" t t folder)))
12148 (setq cpltxt (org-email-link-description))
12149 (setq link (org-make-link "vm:" folder "#" message-id)))))
12150
12151 ((eq major-mode 'wl-summary-mode)
12152 (let* ((msgnum (wl-summary-message-number))
12153 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
12154 msgnum 'message-id))
12155 (wl-message-entity
12156 (if (fboundp 'elmo-message-entity)
12157 (elmo-message-entity
12158 wl-summary-buffer-elmo-folder msgnum)
12159 (elmo-msgdb-overview-get-entity
12160 msgnum (wl-summary-buffer-msgdb))))
12161 (from (wl-summary-line-from))
12162 (to (car (elmo-message-entity-field wl-message-entity 'to)))
12163 (subject (let (wl-thr-indent-string wl-parent-message-entity)
12164 (wl-summary-line-subject))))
12165 (org-store-link-props :type "wl" :from from :to to
12166 :subject subject :message-id message-id)
12167 (setq message-id (org-remove-angle-brackets message-id))
12168 (setq cpltxt (org-email-link-description))
12169 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
12170 "#" message-id))))
12171
12172 ((or (equal major-mode 'mh-folder-mode)
12173 (equal major-mode 'mh-show-mode))
12174 (let ((from (org-mhe-get-header "From:"))
12175 (to (org-mhe-get-header "To:"))
12176 (message-id (org-mhe-get-header "Message-Id:"))
12177 (subject (org-mhe-get-header "Subject:")))
12178 (org-store-link-props :type "mh" :from from :to to
12179 :subject subject :message-id message-id)
12180 (setq cpltxt (org-email-link-description))
12181 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
12182 (org-remove-angle-brackets message-id)))))
12183
12184 ((or (eq major-mode 'rmail-mode)
12185 (eq major-mode 'rmail-summary-mode))
12186 (save-window-excursion
12187 (save-restriction
12188 (when (eq major-mode 'rmail-summary-mode)
12189 (rmail-show-message rmail-current-message))
12190 (rmail-narrow-to-non-pruned-header)
12191 (let ((folder buffer-file-name)
12192 (message-id (mail-fetch-field "message-id"))
12193 (from (mail-fetch-field "from"))
12194 (to (mail-fetch-field "to"))
12195 (subject (mail-fetch-field "subject")))
12196 (org-store-link-props
12197 :type "rmail" :from from :to to
12198 :subject subject :message-id message-id)
12199 (setq message-id (org-remove-angle-brackets message-id))
12200 (setq cpltxt (org-email-link-description))
12201 (setq link (org-make-link "rmail:" folder "#" message-id)))
12202 (rmail-show-message rmail-current-message))))
12203
12204 ((eq major-mode 'gnus-group-mode)
12205 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12206 (gnus-group-group-name)) ; version
12207 ((fboundp 'gnus-group-name)
12208 (gnus-group-name))
12209 (t "???"))))
12210 (unless group (error "Not on a group"))
12211 (org-store-link-props :type "gnus" :group group)
12212 (setq cpltxt (concat
12213 (if (org-xor arg org-usenet-links-prefer-google)
12214 "http://groups.google.com/groups?group="
12215 "gnus:")
12216 group)
12217 link (org-make-link cpltxt))))
12218
12219 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12220 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12221 (let* ((group gnus-newsgroup-name)
12222 (article (gnus-summary-article-number))
12223 (header (gnus-summary-article-header article))
12224 (from (mail-header-from header))
12225 (message-id (mail-header-id header))
12226 (date (mail-header-date header))
12227 (subject (gnus-summary-subject-string)))
12228 (org-store-link-props :type "gnus" :from from :subject subject
12229 :message-id message-id :group group)
12230 (setq cpltxt (org-email-link-description))
12231 (if (org-xor arg org-usenet-links-prefer-google)
12232 (setq link
12233 (concat
12234 cpltxt "\n "
12235 (format "http://groups.google.com/groups?as_umsgid=%s"
12236 (org-fixup-message-id-for-http message-id))))
12237 (setq link (org-make-link "gnus:" group
12238 "#" (number-to-string article))))))
12239
12240 ((eq major-mode 'w3-mode)
12241 (setq cpltxt (url-view-url t)
12242 link (org-make-link cpltxt))
12243 (org-store-link-props :type "w3" :url (url-view-url t)))
12244
12245 ((eq major-mode 'w3m-mode)
12246 (setq cpltxt (or w3m-current-title w3m-current-url)
12247 link (org-make-link w3m-current-url))
12248 (org-store-link-props :type "w3m" :url (url-view-url t)))
12249
12250 ((setq search (run-hook-with-args-until-success
12251 'org-create-file-search-functions))
12252 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12253 "::" search))
12254 (setq cpltxt (or description link)))
12255
12256 ((eq major-mode 'image-mode)
12257 (setq cpltxt (concat "file:"
12258 (abbreviate-file-name buffer-file-name))
12259 link (org-make-link cpltxt))
12260 (org-store-link-props :type "image" :file buffer-file-name))
12261
12262 ((eq major-mode 'dired-mode)
12263 ;; link to the file in the current line
12264 (setq cpltxt (concat "file:"
12265 (abbreviate-file-name
12266 (expand-file-name
12267 (dired-get-filename nil t))))
12268 link (org-make-link cpltxt)))
12269
12270 ((and buffer-file-name (org-mode-p))
12271 ;; Just link to current headline
12272 (setq cpltxt (concat "file:"
12273 (abbreviate-file-name buffer-file-name)))
12274 ;; Add a context search string
12275 (when (org-xor org-context-in-file-links arg)
12276 ;; Check if we are on a target
12277 (if (org-in-regexp "<<\\(.*?\\)>>")
12278 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12279 (setq txt (cond
12280 ((org-on-heading-p) nil)
12281 ((org-region-active-p)
12282 (buffer-substring (region-beginning) (region-end)))
12283 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12284 (when (or (null txt) (string-match "\\S-" txt))
12285 (setq cpltxt
12286 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12287 desc "NONE"))))
12288 (if (string-match "::\\'" cpltxt)
12289 (setq cpltxt (substring cpltxt 0 -2)))
12290 (setq link (org-make-link cpltxt)))
12291
12292 ((buffer-file-name (buffer-base-buffer))
12293 ;; Just link to this file here.
12294 (setq cpltxt (concat "file:"
12295 (abbreviate-file-name
12296 (buffer-file-name (buffer-base-buffer)))))
12297 ;; Add a context string
12298 (when (org-xor org-context-in-file-links arg)
12299 (setq txt (if (org-region-active-p)
12300 (buffer-substring (region-beginning) (region-end))
12301 (buffer-substring (point-at-bol) (point-at-eol))))
12302 ;; Only use search option if there is some text.
12303 (when (string-match "\\S-" txt)
12304 (setq cpltxt
12305 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12306 desc "NONE")))
12307 (setq link (org-make-link cpltxt)))
12308
12309 ((interactive-p)
12310 (error "Cannot link to a buffer which is not visiting a file"))
12311
12312 (t (setq link nil)))
12313
12314 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12315 (setq link (or link cpltxt)
12316 desc (or desc cpltxt))
12317 (if (equal desc "NONE") (setq desc nil))
12318
12319 (if (and (interactive-p) link)
12320 (progn
12321 (setq org-stored-links
12322 (cons (list link desc) org-stored-links))
12323 (message "Stored: %s" (or desc link)))
12324 (and link (org-make-link-string link desc)))))
12325
12326 (defun org-store-link-props (&rest plist)
12327 "Store link properties, extract names and addresses."
12328 (let (x adr)
12329 (when (setq x (plist-get plist :from))
12330 (setq adr (mail-extract-address-components x))
12331 (plist-put plist :fromname (car adr))
12332 (plist-put plist :fromaddress (nth 1 adr)))
12333 (when (setq x (plist-get plist :to))
12334 (setq adr (mail-extract-address-components x))
12335 (plist-put plist :toname (car adr))
12336 (plist-put plist :toaddress (nth 1 adr))))
12337 (let ((from (plist-get plist :from))
12338 (to (plist-get plist :to)))
12339 (when (and from to org-from-is-user-regexp)
12340 (plist-put plist :fromto
12341 (if (string-match org-from-is-user-regexp from)
12342 (concat "to %t")
12343 (concat "from %f")))))
12344 (setq org-store-link-plist plist))
12345
12346 (defun org-email-link-description (&optional fmt)
12347 "Return the description part of an email link.
12348 This takes information from `org-store-link-plist' and formats it
12349 according to FMT (default from `org-email-link-description-format')."
12350 (setq fmt (or fmt org-email-link-description-format))
12351 (let* ((p org-store-link-plist)
12352 (to (plist-get p :toaddress))
12353 (from (plist-get p :fromaddress))
12354 (table
12355 (list
12356 (cons "%c" (plist-get p :fromto))
12357 (cons "%F" (plist-get p :from))
12358 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12359 (cons "%T" (plist-get p :to))
12360 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12361 (cons "%s" (plist-get p :subject))
12362 (cons "%m" (plist-get p :message-id)))))
12363 (when (string-match "%c" fmt)
12364 ;; Check if the user wrote this message
12365 (if (and org-from-is-user-regexp from to
12366 (save-match-data (string-match org-from-is-user-regexp from)))
12367 (setq fmt (replace-match "to %t" t t fmt))
12368 (setq fmt (replace-match "from %f" t t fmt))))
12369 (org-replace-escapes fmt table)))
12370
12371 (defun org-make-org-heading-search-string (&optional string heading)
12372 "Make search string for STRING or current headline."
12373 (interactive)
12374 (let ((s (or string (org-get-heading))))
12375 (unless (and string (not heading))
12376 ;; We are using a headline, clean up garbage in there.
12377 (if (string-match org-todo-regexp s)
12378 (setq s (replace-match "" t t s)))
12379 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12380 (setq s (replace-match "" t t s)))
12381 (setq s (org-trim s))
12382 (if (string-match (concat "^\\(" org-quote-string "\\|"
12383 org-comment-string "\\)") s)
12384 (setq s (replace-match "" t t s)))
12385 (while (string-match org-ts-regexp s)
12386 (setq s (replace-match "" t t s))))
12387 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12388 (setq s (replace-match " " t t s)))
12389 (or string (setq s (concat "*" s))) ; Add * for headlines
12390 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12391
12392 (defun org-make-link (&rest strings)
12393 "Concatenate STRINGS."
12394 (apply 'concat strings))
12395
12396 (defun org-make-link-string (link &optional description)
12397 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12398 (unless (string-match "\\S-" link)
12399 (error "Empty link"))
12400 (when (stringp description)
12401 ;; Remove brackets from the description, they are fatal.
12402 (while (string-match "\\[" description)
12403 (setq description (replace-match "{" t t description)))
12404 (while (string-match "\\]" description)
12405 (setq description (replace-match "}" t t description))))
12406 (when (equal (org-link-escape link) description)
12407 ;; No description needed, it is identical
12408 (setq description nil))
12409 (when (and (not description)
12410 (not (equal link (org-link-escape link))))
12411 (setq description link))
12412 (concat "[[" (org-link-escape link) "]"
12413 (if description (concat "[" description "]") "")
12414 "]"))
12415
12416 (defconst org-link-escape-chars
12417 '((?\ . "%20")
12418 (?\[ . "%5B")
12419 (?\] . "%5D")
12420 (?\340 . "%E0") ; `a
12421 (?\342 . "%E2") ; ^a
12422 (?\347 . "%E7") ; ,c
12423 (?\350 . "%E8") ; `e
12424 (?\351 . "%E9") ; 'e
12425 (?\352 . "%EA") ; ^e
12426 (?\356 . "%EE") ; ^i
12427 (?\364 . "%F4") ; ^o
12428 (?\371 . "%F9") ; `u
12429 (?\373 . "%FB") ; ^u
12430 (?\; . "%3B")
12431 (?? . "%3F")
12432 (?= . "%3D")
12433 (?+ . "%2B")
12434 )
12435 "Association list of escapes for some characters problematic in links.
12436 This is the list that is used for internal purposes.")
12437
12438 (defconst org-link-escape-chars-browser
12439 '((?\ . "%20")) ; 32 for the SPC char
12440 "Association list of escapes for some characters problematic in links.
12441 This is the list that is used before handing over to the browser.")
12442
12443 (defun org-link-escape (text &optional table)
12444 "Escape charaters in TEXT that are problematic for links."
12445 (setq table (or table org-link-escape-chars))
12446 (when text
12447 (let ((re (mapconcat (lambda (x) (regexp-quote
12448 (char-to-string (car x))))
12449 table "\\|")))
12450 (while (string-match re text)
12451 (setq text
12452 (replace-match
12453 (cdr (assoc (string-to-char (match-string 0 text))
12454 table))
12455 t t text)))
12456 text)))
12457
12458 (defun org-link-unescape (text &optional table)
12459 "Reverse the action of `org-link-escape'."
12460 (setq table (or table org-link-escape-chars))
12461 (when text
12462 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12463 table "\\|")))
12464 (while (string-match re text)
12465 (setq text
12466 (replace-match
12467 (char-to-string (car (rassoc (match-string 0 text) table)))
12468 t t text)))
12469 text)))
12470
12471 (defun org-xor (a b)
12472 "Exclusive or."
12473 (if a (not b) b))
12474
12475 (defun org-get-header (header)
12476 "Find a header field in the current buffer."
12477 (save-excursion
12478 (goto-char (point-min))
12479 (let ((case-fold-search t) s)
12480 (cond
12481 ((eq header 'from)
12482 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12483 (setq s (match-string 1)))
12484 (while (string-match "\"" s)
12485 (setq s (replace-match "" t t s)))
12486 (if (string-match "[<(].*" s)
12487 (setq s (replace-match "" t t s))))
12488 ((eq header 'message-id)
12489 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12490 (setq s (match-string 1))))
12491 ((eq header 'subject)
12492 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12493 (setq s (match-string 1)))))
12494 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12495 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12496 s)))
12497
12498
12499 (defun org-fixup-message-id-for-http (s)
12500 "Replace special characters in a message id, so it can be used in an http query."
12501 (while (string-match "<" s)
12502 (setq s (replace-match "%3C" t t s)))
12503 (while (string-match ">" s)
12504 (setq s (replace-match "%3E" t t s)))
12505 (while (string-match "@" s)
12506 (setq s (replace-match "%40" t t s)))
12507 s)
12508
12509 ;;;###autoload
12510 (defun org-insert-link-global ()
12511 "Insert a link like Org-mode does.
12512 This command can be called in any mode to insert a link in Org-mode syntax."
12513 (interactive)
12514 (org-run-like-in-org-mode 'org-insert-link))
12515
12516 (defun org-insert-link (&optional complete-file)
12517 "Insert a link. At the prompt, enter the link.
12518
12519 Completion can be used to select a link previously stored with
12520 `org-store-link'. When the empty string is entered (i.e. if you just
12521 press RET at the prompt), the link defaults to the most recently
12522 stored link. As SPC triggers completion in the minibuffer, you need to
12523 use M-SPC or C-q SPC to force the insertion of a space character.
12524
12525 You will also be prompted for a description, and if one is given, it will
12526 be displayed in the buffer instead of the link.
12527
12528 If there is already a link at point, this command will allow you to edit link
12529 and description parts.
12530
12531 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12532 selected using completion. The path to the file will be relative to
12533 the current directory if the file is in the current directory or a
12534 subdirectory. Otherwise, the link will be the absolute path as
12535 completed in the minibuffer (i.e. normally ~/path/to/file).
12536
12537 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12538 is in the current directory or below.
12539 With three \\[universal-argument] prefixes, negate the meaning of
12540 `org-keep-stored-link-after-insertion'."
12541 (interactive "P")
12542 (let* ((wcf (current-window-configuration))
12543 (region (if (org-region-active-p)
12544 (buffer-substring (region-beginning) (region-end))))
12545 (remove (and region (list (region-beginning) (region-end))))
12546 (desc region)
12547 tmphist ; byte-compile incorrectly complains about this
12548 link entry file)
12549 (cond
12550 ((org-in-regexp org-bracket-link-regexp 1)
12551 ;; We do have a link at point, and we are going to edit it.
12552 (setq remove (list (match-beginning 0) (match-end 0)))
12553 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12554 (setq link (read-string "Link: "
12555 (org-link-unescape
12556 (org-match-string-no-properties 1)))))
12557 ((or (org-in-regexp org-angle-link-re)
12558 (org-in-regexp org-plain-link-re))
12559 ;; Convert to bracket link
12560 (setq remove (list (match-beginning 0) (match-end 0))
12561 link (read-string "Link: "
12562 (org-remove-angle-brackets (match-string 0)))))
12563 ((equal complete-file '(4))
12564 ;; Completing read for file names.
12565 (setq file (read-file-name "File: "))
12566 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12567 (pwd1 (file-name-as-directory (abbreviate-file-name
12568 (expand-file-name ".")))))
12569 (cond
12570 ((equal complete-file '(16))
12571 (setq link (org-make-link
12572 "file:"
12573 (abbreviate-file-name (expand-file-name file)))))
12574 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12575 (setq link (org-make-link "file:" (match-string 1 file))))
12576 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12577 (expand-file-name file))
12578 (setq link (org-make-link
12579 "file:" (match-string 1 (expand-file-name file)))))
12580 (t (setq link (org-make-link "file:" file))))))
12581 (t
12582 ;; Read link, with completion for stored links.
12583 (with-output-to-temp-buffer "*Org Links*"
12584 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12585 (when org-stored-links
12586 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12587 (princ (mapconcat
12588 (lambda (x)
12589 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12590 (reverse org-stored-links) "\n"))))
12591 (let ((cw (selected-window)))
12592 (select-window (get-buffer-window "*Org Links*"))
12593 (shrink-window-if-larger-than-buffer)
12594 (setq truncate-lines t)
12595 (select-window cw))
12596 ;; Fake a link history, containing the stored links.
12597 (setq tmphist (append (mapcar 'car org-stored-links)
12598 org-insert-link-history))
12599 (unwind-protect
12600 (setq link (org-completing-read
12601 "Link: "
12602 (append
12603 (mapcar (lambda (x) (list (concat (car x) ":")))
12604 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12605 (mapcar (lambda (x) (list (concat x ":")))
12606 org-link-types))
12607 nil nil nil
12608 'tmphist
12609 (or (car (car org-stored-links)))))
12610 (set-window-configuration wcf)
12611 (kill-buffer "*Org Links*"))
12612 (setq entry (assoc link org-stored-links))
12613 (or entry (push link org-insert-link-history))
12614 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12615 (not org-keep-stored-link-after-insertion))
12616 (setq org-stored-links (delq (assoc link org-stored-links)
12617 org-stored-links)))
12618 (setq desc (or desc (nth 1 entry)))))
12619
12620 (if (string-match org-plain-link-re link)
12621 ;; URL-like link, normalize the use of angular brackets.
12622 (setq link (org-make-link (org-remove-angle-brackets link))))
12623
12624 ;; Check if we are linking to the current file with a search option
12625 ;; If yes, simplify the link by using only the search option.
12626 (when (and buffer-file-name
12627 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12628 (let* ((path (match-string 1 link))
12629 (case-fold-search nil)
12630 (search (match-string 2 link)))
12631 (save-match-data
12632 (if (equal (file-truename buffer-file-name) (file-truename path))
12633 ;; We are linking to this same file, with a search option
12634 (setq link search)))))
12635
12636 ;; Check if we can/should use a relative path. If yes, simplify the link
12637 (when (string-match "\\<file:\\(.*\\)" link)
12638 (let* ((path (match-string 1 link))
12639 (origpath path)
12640 (case-fold-search nil))
12641 (cond
12642 ((eq org-link-file-path-type 'absolute)
12643 (setq path (abbreviate-file-name (expand-file-name path))))
12644 ((eq org-link-file-path-type 'noabbrev)
12645 (setq path (expand-file-name path)))
12646 ((eq org-link-file-path-type 'relative)
12647 (setq path (file-relative-name path)))
12648 (t
12649 (save-match-data
12650 (if (string-match (concat "^" (regexp-quote
12651 (file-name-as-directory
12652 (expand-file-name "."))))
12653 (expand-file-name path))
12654 ;; We are linking a file with relative path name.
12655 (setq path (substring (expand-file-name path)
12656 (match-end 0)))))))
12657 (setq link (concat "file:" path))
12658 (if (equal desc origpath)
12659 (setq desc path))))
12660
12661 (setq desc (read-string "Description: " desc))
12662 (unless (string-match "\\S-" desc) (setq desc nil))
12663 (if remove (apply 'delete-region remove))
12664 (insert (org-make-link-string link desc))))
12665
12666 (defun org-completing-read (&rest args)
12667 (let ((minibuffer-local-completion-map
12668 (copy-keymap minibuffer-local-completion-map)))
12669 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12670 (apply 'completing-read args)))
12671
12672 ;;; Opening/following a link
12673 (defvar org-link-search-failed nil)
12674
12675 (defun org-next-link ()
12676 "Move forward to the next link.
12677 If the link is in hidden text, expose it."
12678 (interactive)
12679 (when (and org-link-search-failed (eq this-command last-command))
12680 (goto-char (point-min))
12681 (message "Link search wrapped back to beginning of buffer"))
12682 (setq org-link-search-failed nil)
12683 (let* ((pos (point))
12684 (ct (org-context))
12685 (a (assoc :link ct)))
12686 (if a (goto-char (nth 2 a)))
12687 (if (re-search-forward org-any-link-re nil t)
12688 (progn
12689 (goto-char (match-beginning 0))
12690 (if (org-invisible-p) (org-show-context)))
12691 (goto-char pos)
12692 (setq org-link-search-failed t)
12693 (error "No further link found"))))
12694
12695 (defun org-previous-link ()
12696 "Move backward to the previous link.
12697 If the link is in hidden text, expose it."
12698 (interactive)
12699 (when (and org-link-search-failed (eq this-command last-command))
12700 (goto-char (point-max))
12701 (message "Link search wrapped back to end of buffer"))
12702 (setq org-link-search-failed nil)
12703 (let* ((pos (point))
12704 (ct (org-context))
12705 (a (assoc :link ct)))
12706 (if a (goto-char (nth 1 a)))
12707 (if (re-search-backward org-any-link-re nil t)
12708 (progn
12709 (goto-char (match-beginning 0))
12710 (if (org-invisible-p) (org-show-context)))
12711 (goto-char pos)
12712 (setq org-link-search-failed t)
12713 (error "No further link found"))))
12714
12715 (defun org-find-file-at-mouse (ev)
12716 "Open file link or URL at mouse."
12717 (interactive "e")
12718 (mouse-set-point ev)
12719 (org-open-at-point 'in-emacs))
12720
12721 (defun org-open-at-mouse (ev)
12722 "Open file link or URL at mouse."
12723 (interactive "e")
12724 (mouse-set-point ev)
12725 (org-open-at-point))
12726
12727 (defvar org-window-config-before-follow-link nil
12728 "The window configuration before following a link.
12729 This is saved in case the need arises to restore it.")
12730
12731 (defvar org-open-link-marker (make-marker)
12732 "Marker pointing to the location where `org-open-at-point; was called.")
12733
12734 ;;;###autoload
12735 (defun org-open-at-point-global ()
12736 "Follow a link like Org-mode does.
12737 This command can be called in any mode to follow a link that has
12738 Org-mode syntax."
12739 (interactive)
12740 (org-run-like-in-org-mode 'org-open-at-point))
12741
12742 (defun org-open-at-point (&optional in-emacs)
12743 "Open link at or after point.
12744 If there is no link at point, this function will search forward up to
12745 the end of the current subtree.
12746 Normally, files will be opened by an appropriate application. If the
12747 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12748 (interactive "P")
12749 (require 'org-irc)
12750 (move-marker org-open-link-marker (point))
12751 (setq org-window-config-before-follow-link (current-window-configuration))
12752 (org-remove-occur-highlights nil nil t)
12753 (if (org-at-timestamp-p t)
12754 (org-follow-timestamp-link)
12755 (let (type path link line search (pos (point)))
12756 (catch 'match
12757 (save-excursion
12758 (skip-chars-forward "^]\n\r")
12759 (when (org-in-regexp org-bracket-link-regexp)
12760 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12761 (while (string-match " *\n *" link)
12762 (setq link (replace-match " " t t link)))
12763 (setq link (org-link-expand-abbrev link))
12764 (if (string-match org-link-re-with-space2 link)
12765 (setq type (match-string 1 link) path (match-string 2 link))
12766 (setq type "thisfile" path link))
12767 (throw 'match t)))
12768
12769 (when (get-text-property (point) 'org-linked-text)
12770 (setq type "thisfile"
12771 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12772 (1+ (point)) (point))
12773 path (buffer-substring
12774 (previous-single-property-change pos 'org-linked-text)
12775 (next-single-property-change pos 'org-linked-text)))
12776 (throw 'match t))
12777
12778 (save-excursion
12779 (when (or (org-in-regexp org-angle-link-re)
12780 (org-in-regexp org-plain-link-re))
12781 (setq type (match-string 1) path (match-string 2))
12782 (throw 'match t)))
12783 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12784 (setq type "tree-match"
12785 path (match-string 1))
12786 (throw 'match t))
12787 (save-excursion
12788 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12789 (setq type "tags"
12790 path (match-string 1))
12791 (while (string-match ":" path)
12792 (setq path (replace-match "+" t t path)))
12793 (throw 'match t))))
12794 (unless path
12795 (error "No link found"))
12796 ;; Remove any trailing spaces in path
12797 (if (string-match " +\\'" path)
12798 (setq path (replace-match "" t t path)))
12799
12800 (cond
12801
12802 ((assoc type org-link-protocols)
12803 (funcall (nth 1 (assoc type org-link-protocols)) path))
12804
12805 ((equal type "mailto")
12806 (let ((cmd (car org-link-mailto-program))
12807 (args (cdr org-link-mailto-program)) args1
12808 (address path) (subject "") a)
12809 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12810 (setq address (match-string 1 path)
12811 subject (org-link-escape (match-string 2 path))))
12812 (while args
12813 (cond
12814 ((not (stringp (car args))) (push (pop args) args1))
12815 (t (setq a (pop args))
12816 (if (string-match "%a" a)
12817 (setq a (replace-match address t t a)))
12818 (if (string-match "%s" a)
12819 (setq a (replace-match subject t t a)))
12820 (push a args1))))
12821 (apply cmd (nreverse args1))))
12822
12823 ((member type '("http" "https" "ftp" "news"))
12824 (browse-url (concat type ":" (org-link-escape
12825 path org-link-escape-chars-browser))))
12826
12827 ((member type '("message"))
12828 (browse-url (concat type ":" path)))
12829
12830 ((string= type "tags")
12831 (org-tags-view in-emacs path))
12832 ((string= type "thisfile")
12833 (if in-emacs
12834 (switch-to-buffer-other-window
12835 (org-get-buffer-for-internal-link (current-buffer)))
12836 (org-mark-ring-push))
12837 (let ((cmd `(org-link-search
12838 ,path
12839 ,(cond ((equal in-emacs '(4)) 'occur)
12840 ((equal in-emacs '(16)) 'org-occur)
12841 (t nil))
12842 ,pos)))
12843 (condition-case nil (eval cmd)
12844 (error (progn (widen) (eval cmd))))))
12845
12846 ((string= type "tree-match")
12847 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12848
12849 ((string= type "file")
12850 (if (string-match "::\\([0-9]+\\)\\'" path)
12851 (setq line (string-to-number (match-string 1 path))
12852 path (substring path 0 (match-beginning 0)))
12853 (if (string-match "::\\(.+\\)\\'" path)
12854 (setq search (match-string 1 path)
12855 path (substring path 0 (match-beginning 0)))))
12856 (if (string-match "[*?{]" (file-name-nondirectory path))
12857 (dired path)
12858 (org-open-file path in-emacs line search)))
12859
12860 ((string= type "news")
12861 (org-follow-gnus-link path))
12862
12863 ((string= type "bbdb")
12864 (org-follow-bbdb-link path))
12865
12866 ((string= type "info")
12867 (org-follow-info-link path))
12868
12869 ((string= type "gnus")
12870 (let (group article)
12871 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12872 (error "Error in Gnus link"))
12873 (setq group (match-string 1 path)
12874 article (match-string 3 path))
12875 (org-follow-gnus-link group article)))
12876
12877 ((string= type "vm")
12878 (let (folder article)
12879 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12880 (error "Error in VM link"))
12881 (setq folder (match-string 1 path)
12882 article (match-string 3 path))
12883 ;; in-emacs is the prefix arg, will be interpreted as read-only
12884 (org-follow-vm-link folder article in-emacs)))
12885
12886 ((string= type "wl")
12887 (let (folder article)
12888 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12889 (error "Error in Wanderlust link"))
12890 (setq folder (match-string 1 path)
12891 article (match-string 3 path))
12892 (org-follow-wl-link folder article)))
12893
12894 ((string= type "mhe")
12895 (let (folder article)
12896 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12897 (error "Error in MHE link"))
12898 (setq folder (match-string 1 path)
12899 article (match-string 3 path))
12900 (org-follow-mhe-link folder article)))
12901
12902 ((string= type "rmail")
12903 (let (folder article)
12904 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12905 (error "Error in RMAIL link"))
12906 (setq folder (match-string 1 path)
12907 article (match-string 3 path))
12908 (org-follow-rmail-link folder article)))
12909
12910 ((string= type "shell")
12911 (let ((cmd path))
12912 (if (or (not org-confirm-shell-link-function)
12913 (funcall org-confirm-shell-link-function
12914 (format "Execute \"%s\" in shell? "
12915 (org-add-props cmd nil
12916 'face 'org-warning))))
12917 (progn
12918 (message "Executing %s" cmd)
12919 (shell-command cmd))
12920 (error "Abort"))))
12921
12922 ((string= type "elisp")
12923 (let ((cmd path))
12924 (if (or (not org-confirm-elisp-link-function)
12925 (funcall org-confirm-elisp-link-function
12926 (format "Execute \"%s\" as elisp? "
12927 (org-add-props cmd nil
12928 'face 'org-warning))))
12929 (message "%s => %s" cmd (eval (read cmd)))
12930 (error "Abort"))))
12931
12932 (t
12933 (browse-url-at-point)))))
12934 (move-marker org-open-link-marker nil)
12935 (run-hook-with-args 'org-follow-link-hook))
12936
12937 ;;; File search
12938
12939 (defvar org-create-file-search-functions nil
12940 "List of functions to construct the right search string for a file link.
12941 These functions are called in turn with point at the location to
12942 which the link should point.
12943
12944 A function in the hook should first test if it would like to
12945 handle this file type, for example by checking the major-mode or
12946 the file extension. If it decides not to handle this file, it
12947 should just return nil to give other functions a chance. If it
12948 does handle the file, it must return the search string to be used
12949 when following the link. The search string will be part of the
12950 file link, given after a double colon, and `org-open-at-point'
12951 will automatically search for it. If special measures must be
12952 taken to make the search successful, another function should be
12953 added to the companion hook `org-execute-file-search-functions',
12954 which see.
12955
12956 A function in this hook may also use `setq' to set the variable
12957 `description' to provide a suggestion for the descriptive text to
12958 be used for this link when it gets inserted into an Org-mode
12959 buffer with \\[org-insert-link].")
12960
12961 (defvar org-execute-file-search-functions nil
12962 "List of functions to execute a file search triggered by a link.
12963
12964 Functions added to this hook must accept a single argument, the
12965 search string that was part of the file link, the part after the
12966 double colon. The function must first check if it would like to
12967 handle this search, for example by checking the major-mode or the
12968 file extension. If it decides not to handle this search, it
12969 should just return nil to give other functions a chance. If it
12970 does handle the search, it must return a non-nil value to keep
12971 other functions from trying.
12972
12973 Each function can access the current prefix argument through the
12974 variable `current-prefix-argument'. Note that a single prefix is
12975 used to force opening a link in Emacs, so it may be good to only
12976 use a numeric or double prefix to guide the search function.
12977
12978 In case this is needed, a function in this hook can also restore
12979 the window configuration before `org-open-at-point' was called using:
12980
12981 (set-window-configuration org-window-config-before-follow-link)")
12982
12983 (defun org-link-search (s &optional type avoid-pos)
12984 "Search for a link search option.
12985 If S is surrounded by forward slashes, it is interpreted as a
12986 regular expression. In org-mode files, this will create an `org-occur'
12987 sparse tree. In ordinary files, `occur' will be used to list matches.
12988 If the current buffer is in `dired-mode', grep will be used to search
12989 in all files. If AVOID-POS is given, ignore matches near that position."
12990 (let ((case-fold-search t)
12991 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12992 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12993 (append '(("") (" ") ("\t") ("\n"))
12994 org-emphasis-alist)
12995 "\\|") "\\)"))
12996 (pos (point))
12997 (pre "") (post "")
12998 words re0 re1 re2 re3 re4 re5 re2a reall)
12999 (cond
13000 ;; First check if there are any special
13001 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
13002 ;; Now try the builtin stuff
13003 ((save-excursion
13004 (goto-char (point-min))
13005 (and
13006 (re-search-forward
13007 (concat "<<" (regexp-quote s0) ">>") nil t)
13008 (setq pos (match-beginning 0))))
13009 ;; There is an exact target for this
13010 (goto-char pos))
13011 ((string-match "^/\\(.*\\)/$" s)
13012 ;; A regular expression
13013 (cond
13014 ((org-mode-p)
13015 (org-occur (match-string 1 s)))
13016 ;;((eq major-mode 'dired-mode)
13017 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
13018 (t (org-do-occur (match-string 1 s)))))
13019 (t
13020 ;; A normal search strings
13021 (when (equal (string-to-char s) ?*)
13022 ;; Anchor on headlines, post may include tags.
13023 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
13024 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
13025 s (substring s 1)))
13026 (remove-text-properties
13027 0 (length s)
13028 '(face nil mouse-face nil keymap nil fontified nil) s)
13029 ;; Make a series of regular expressions to find a match
13030 (setq words (org-split-string s "[ \n\r\t]+")
13031 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
13032 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
13033 "\\)" markers)
13034 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
13035 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
13036 re1 (concat pre re2 post)
13037 re3 (concat pre re4 post)
13038 re5 (concat pre ".*" re4)
13039 re2 (concat pre re2)
13040 re2a (concat pre re2a)
13041 re4 (concat pre re4)
13042 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
13043 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
13044 re5 "\\)"
13045 ))
13046 (cond
13047 ((eq type 'org-occur) (org-occur reall))
13048 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
13049 (t (goto-char (point-min))
13050 (if (or (org-search-not-self 1 re0 nil t)
13051 (org-search-not-self 1 re1 nil t)
13052 (org-search-not-self 1 re2 nil t)
13053 (org-search-not-self 1 re2a nil t)
13054 (org-search-not-self 1 re3 nil t)
13055 (org-search-not-self 1 re4 nil t)
13056 (org-search-not-self 1 re5 nil t)
13057 )
13058 (goto-char (match-beginning 1))
13059 (goto-char pos)
13060 (error "No match")))))
13061 (t
13062 ;; Normal string-search
13063 (goto-char (point-min))
13064 (if (search-forward s nil t)
13065 (goto-char (match-beginning 0))
13066 (error "No match"))))
13067 (and (org-mode-p) (org-show-context 'link-search))))
13068
13069 (defun org-search-not-self (group &rest args)
13070 "Execute `re-search-forward', but only accept matches that do not
13071 enclose the position of `org-open-link-marker'."
13072 (let ((m org-open-link-marker))
13073 (catch 'exit
13074 (while (apply 're-search-forward args)
13075 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
13076 (goto-char (match-end group))
13077 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
13078 (> (match-beginning 0) (marker-position m))
13079 (< (match-end 0) (marker-position m)))
13080 (save-match-data
13081 (or (not (org-in-regexp
13082 org-bracket-link-analytic-regexp 1))
13083 (not (match-end 4)) ; no description
13084 (and (<= (match-beginning 4) (point))
13085 (>= (match-end 4) (point))))))
13086 (throw 'exit (point))))))))
13087
13088 (defun org-get-buffer-for-internal-link (buffer)
13089 "Return a buffer to be used for displaying the link target of internal links."
13090 (cond
13091 ((not org-display-internal-link-with-indirect-buffer)
13092 buffer)
13093 ((string-match "(Clone)$" (buffer-name buffer))
13094 (message "Buffer is already a clone, not making another one")
13095 ;; we also do not modify visibility in this case
13096 buffer)
13097 (t ; make a new indirect buffer for displaying the link
13098 (let* ((bn (buffer-name buffer))
13099 (ibn (concat bn "(Clone)"))
13100 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13101 (with-current-buffer ib (org-overview))
13102 ib))))
13103
13104 (defun org-do-occur (regexp &optional cleanup)
13105 "Call the Emacs command `occur'.
13106 If CLEANUP is non-nil, remove the printout of the regular expression
13107 in the *Occur* buffer. This is useful if the regex is long and not useful
13108 to read."
13109 (occur regexp)
13110 (when cleanup
13111 (let ((cwin (selected-window)) win beg end)
13112 (when (setq win (get-buffer-window "*Occur*"))
13113 (select-window win))
13114 (goto-char (point-min))
13115 (when (re-search-forward "match[a-z]+" nil t)
13116 (setq beg (match-end 0))
13117 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13118 (setq end (1- (match-beginning 0)))))
13119 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13120 (goto-char (point-min))
13121 (select-window cwin))))
13122
13123 ;;; The mark ring for links jumps
13124
13125 (defvar org-mark-ring nil
13126 "Mark ring for positions before jumps in Org-mode.")
13127 (defvar org-mark-ring-last-goto nil
13128 "Last position in the mark ring used to go back.")
13129 ;; Fill and close the ring
13130 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13131 (loop for i from 1 to org-mark-ring-length do
13132 (push (make-marker) org-mark-ring))
13133 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13134 org-mark-ring)
13135
13136 (defun org-mark-ring-push (&optional pos buffer)
13137 "Put the current position or POS into the mark ring and rotate it."
13138 (interactive)
13139 (setq pos (or pos (point)))
13140 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13141 (move-marker (car org-mark-ring)
13142 (or pos (point))
13143 (or buffer (current-buffer)))
13144 (message "%s"
13145 (substitute-command-keys
13146 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13147
13148 (defun org-mark-ring-goto (&optional n)
13149 "Jump to the previous position in the mark ring.
13150 With prefix arg N, jump back that many stored positions. When
13151 called several times in succession, walk through the entire ring.
13152 Org-mode commands jumping to a different position in the current file,
13153 or to another Org-mode file, automatically push the old position
13154 onto the ring."
13155 (interactive "p")
13156 (let (p m)
13157 (if (eq last-command this-command)
13158 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13159 (setq p org-mark-ring))
13160 (setq org-mark-ring-last-goto p)
13161 (setq m (car p))
13162 (switch-to-buffer (marker-buffer m))
13163 (goto-char m)
13164 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13165
13166 (defun org-remove-angle-brackets (s)
13167 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13168 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13169 s)
13170 (defun org-add-angle-brackets (s)
13171 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13172 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13173 s)
13174
13175 ;;; Following specific links
13176
13177 (defun org-follow-timestamp-link ()
13178 (cond
13179 ((org-at-date-range-p t)
13180 (let ((org-agenda-start-on-weekday)
13181 (t1 (match-string 1))
13182 (t2 (match-string 2)))
13183 (setq t1 (time-to-days (org-time-string-to-time t1))
13184 t2 (time-to-days (org-time-string-to-time t2)))
13185 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13186 ((org-at-timestamp-p t)
13187 (org-agenda-list nil (time-to-days (org-time-string-to-time
13188 (substring (match-string 1) 0 10)))
13189 1))
13190 (t (error "This should not happen"))))
13191
13192
13193 (defun org-follow-bbdb-link (name)
13194 "Follow a BBDB link to NAME."
13195 (require 'bbdb)
13196 (let ((inhibit-redisplay (not debug-on-error))
13197 (bbdb-electric-p nil))
13198 (catch 'exit
13199 ;; Exact match on name
13200 (bbdb-name (concat "\\`" name "\\'") nil)
13201 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13202 ;; Exact match on name
13203 (bbdb-company (concat "\\`" name "\\'") nil)
13204 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13205 ;; Partial match on name
13206 (bbdb-name name nil)
13207 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13208 ;; Partial match on company
13209 (bbdb-company name nil)
13210 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13211 ;; General match including network address and notes
13212 (bbdb name nil)
13213 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13214 (delete-window (get-buffer-window "*BBDB*"))
13215 (error "No matching BBDB record")))))
13216
13217 (defun org-follow-info-link (name)
13218 "Follow an info file & node link to NAME."
13219 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13220 (string-match "\\(.*\\)" name))
13221 (progn
13222 (require 'info)
13223 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13224 (Info-find-node (match-string 1 name) (match-string 2 name))
13225 (Info-find-node (match-string 1 name) "Top")))
13226 (message "Could not open: %s" name)))
13227
13228 (defun org-follow-gnus-link (&optional group article)
13229 "Follow a Gnus link to GROUP and ARTICLE."
13230 (require 'gnus)
13231 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13232 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13233 (cond ((and group article)
13234 (gnus-group-read-group 1 nil group)
13235 (gnus-summary-goto-article (string-to-number article) nil t))
13236 (group (gnus-group-jump-to-group group))))
13237
13238 (defun org-follow-vm-link (&optional folder article readonly)
13239 "Follow a VM link to FOLDER and ARTICLE."
13240 (require 'vm)
13241 (setq article (org-add-angle-brackets article))
13242 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13243 ;; ange-ftp or efs or tramp access
13244 (let ((user (or (match-string 1 folder) (user-login-name)))
13245 (host (match-string 2 folder))
13246 (file (match-string 3 folder)))
13247 (cond
13248 ((featurep 'tramp)
13249 ;; use tramp to access the file
13250 (if (featurep 'xemacs)
13251 (setq folder (format "[%s@%s]%s" user host file))
13252 (setq folder (format "/%s@%s:%s" user host file))))
13253 (t
13254 ;; use ange-ftp or efs
13255 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13256 (setq folder (format "/%s@%s:%s" user host file))))))
13257 (when folder
13258 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13259 (sit-for 0.1)
13260 (when article
13261 (vm-select-folder-buffer)
13262 (widen)
13263 (let ((case-fold-search t))
13264 (goto-char (point-min))
13265 (if (not (re-search-forward
13266 (concat "^" "message-id: *" (regexp-quote article))))
13267 (error "Could not find the specified message in this folder"))
13268 (vm-isearch-update)
13269 (vm-isearch-narrow)
13270 (vm-beginning-of-message)
13271 (vm-summarize)))))
13272
13273 (defun org-follow-wl-link (folder article)
13274 "Follow a Wanderlust link to FOLDER and ARTICLE."
13275 (if (and (string= folder "%")
13276 article
13277 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13278 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13279 ;; Thus, we recompose folder and article ids.
13280 (setq folder (format "%s#%s" folder (match-string 1 article))
13281 article (match-string 3 article)))
13282 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13283 (error "No such folder: %s" folder))
13284 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13285 (and article
13286 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13287 (wl-summary-redisplay)))
13288
13289 (defun org-follow-rmail-link (folder article)
13290 "Follow an RMAIL link to FOLDER and ARTICLE."
13291 (setq article (org-add-angle-brackets article))
13292 (let (message-number)
13293 (save-excursion
13294 (save-window-excursion
13295 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13296 (setq message-number
13297 (save-restriction
13298 (widen)
13299 (goto-char (point-max))
13300 (if (re-search-backward
13301 (concat "^Message-ID:\\s-+" (regexp-quote
13302 (or article "")))
13303 nil t)
13304 (rmail-what-message))))))
13305 (if message-number
13306 (progn
13307 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13308 (rmail-show-message message-number)
13309 message-number)
13310 (error "Message not found"))))
13311
13312 ;;; mh-e integration based on planner-mode
13313 (defun org-mhe-get-message-real-folder ()
13314 "Return the name of the current message real folder, so if you use
13315 sequences, it will now work."
13316 (save-excursion
13317 (let* ((folder
13318 (if (equal major-mode 'mh-folder-mode)
13319 mh-current-folder
13320 ;; Refer to the show buffer
13321 mh-show-folder-buffer))
13322 (end-index
13323 (if (boundp 'mh-index-folder)
13324 (min (length mh-index-folder) (length folder))))
13325 )
13326 ;; a simple test on mh-index-data does not work, because
13327 ;; mh-index-data is always nil in a show buffer.
13328 (if (and (boundp 'mh-index-folder)
13329 (string= mh-index-folder (substring folder 0 end-index)))
13330 (if (equal major-mode 'mh-show-mode)
13331 (save-window-excursion
13332 (let (pop-up-frames)
13333 (when (buffer-live-p (get-buffer folder))
13334 (progn
13335 (pop-to-buffer folder)
13336 (org-mhe-get-message-folder-from-index)
13337 )
13338 )))
13339 (org-mhe-get-message-folder-from-index)
13340 )
13341 folder
13342 )
13343 )))
13344
13345 (defun org-mhe-get-message-folder-from-index ()
13346 "Returns the name of the message folder in a index folder buffer."
13347 (save-excursion
13348 (mh-index-previous-folder)
13349 (re-search-forward "^\\(+.*\\)$" nil t)
13350 (message "%s" (match-string 1))))
13351
13352 (defun org-mhe-get-message-folder ()
13353 "Return the name of the current message folder. Be careful if you
13354 use sequences."
13355 (save-excursion
13356 (if (equal major-mode 'mh-folder-mode)
13357 mh-current-folder
13358 ;; Refer to the show buffer
13359 mh-show-folder-buffer)))
13360
13361 (defun org-mhe-get-message-num ()
13362 "Return the number of the current message. Be careful if you
13363 use sequences."
13364 (save-excursion
13365 (if (equal major-mode 'mh-folder-mode)
13366 (mh-get-msg-num nil)
13367 ;; Refer to the show buffer
13368 (mh-show-buffer-message-number))))
13369
13370 (defun org-mhe-get-header (header)
13371 "Return a header of the message in folder mode. This will create a
13372 show buffer for the corresponding message. If you have a more clever
13373 idea..."
13374 (let* ((folder (org-mhe-get-message-folder))
13375 (num (org-mhe-get-message-num))
13376 (buffer (get-buffer-create (concat "show-" folder)))
13377 (header-field))
13378 (with-current-buffer buffer
13379 (mh-display-msg num folder)
13380 (if (equal major-mode 'mh-folder-mode)
13381 (mh-header-display)
13382 (mh-show-header-display))
13383 (set-buffer buffer)
13384 (setq header-field (mh-get-header-field header))
13385 (if (equal major-mode 'mh-folder-mode)
13386 (mh-show)
13387 (mh-show-show))
13388 header-field)))
13389
13390 (defun org-follow-mhe-link (folder article)
13391 "Follow an MHE link to FOLDER and ARTICLE.
13392 If ARTICLE is nil FOLDER is shown. If the configuration variable
13393 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13394 ARTICLE is searched in all folders. Indexed searches (swish++,
13395 namazu, and others supported by MH-E) will always search in all
13396 folders."
13397 (require 'mh-e)
13398 (require 'mh-search)
13399 (require 'mh-utils)
13400 (mh-find-path)
13401 (if (not article)
13402 (mh-visit-folder (mh-normalize-folder-name folder))
13403 (setq article (org-add-angle-brackets article))
13404 (mh-search-choose)
13405 (if (equal mh-searcher 'pick)
13406 (progn
13407 (mh-search folder (list "--message-id" article))
13408 (when (and org-mhe-search-all-folders
13409 (not (org-mhe-get-message-real-folder)))
13410 (kill-this-buffer)
13411 (mh-search "+" (list "--message-id" article))))
13412 (mh-search "+" article))
13413 (if (org-mhe-get-message-real-folder)
13414 (mh-show-msg 1)
13415 (kill-this-buffer)
13416 (error "Message not found"))))
13417
13418 ;;; BibTeX links
13419
13420 ;; Use the custom search meachnism to construct and use search strings for
13421 ;; file links to BibTeX database entries.
13422
13423 (defun org-create-file-search-in-bibtex ()
13424 "Create the search string and description for a BibTeX database entry."
13425 (when (eq major-mode 'bibtex-mode)
13426 ;; yes, we want to construct this search string.
13427 ;; Make a good description for this entry, using names, year and the title
13428 ;; Put it into the `description' variable which is dynamically scoped.
13429 (let ((bibtex-autokey-names 1)
13430 (bibtex-autokey-names-stretch 1)
13431 (bibtex-autokey-name-case-convert-function 'identity)
13432 (bibtex-autokey-name-separator " & ")
13433 (bibtex-autokey-additional-names " et al.")
13434 (bibtex-autokey-year-length 4)
13435 (bibtex-autokey-name-year-separator " ")
13436 (bibtex-autokey-titlewords 3)
13437 (bibtex-autokey-titleword-separator " ")
13438 (bibtex-autokey-titleword-case-convert-function 'identity)
13439 (bibtex-autokey-titleword-length 'infty)
13440 (bibtex-autokey-year-title-separator ": "))
13441 (setq description (bibtex-generate-autokey)))
13442 ;; Now parse the entry, get the key and return it.
13443 (save-excursion
13444 (bibtex-beginning-of-entry)
13445 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13446
13447 (defun org-execute-file-search-in-bibtex (s)
13448 "Find the link search string S as a key for a database entry."
13449 (when (eq major-mode 'bibtex-mode)
13450 ;; Yes, we want to do the search in this file.
13451 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13452 (goto-char (point-min))
13453 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13454 (regexp-quote s) "[ \t\n]*,") nil t)
13455 (goto-char (match-beginning 0)))
13456 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13457 ;; Use double prefix to indicate that any web link should be browsed
13458 (let ((b (current-buffer)) (p (point)))
13459 ;; Restore the window configuration because we just use the web link
13460 (set-window-configuration org-window-config-before-follow-link)
13461 (save-excursion (set-buffer b) (goto-char p)
13462 (bibtex-url)))
13463 (recenter 0)) ; Move entry start to beginning of window
13464 ;; return t to indicate that the search is done.
13465 t))
13466
13467 ;; Finally add the functions to the right hooks.
13468 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13469 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13470
13471 ;; end of Bibtex link setup
13472
13473 ;;; Following file links
13474
13475 (defun org-open-file (path &optional in-emacs line search)
13476 "Open the file at PATH.
13477 First, this expands any special file name abbreviations. Then the
13478 configuration variable `org-file-apps' is checked if it contains an
13479 entry for this file type, and if yes, the corresponding command is launched.
13480 If no application is found, Emacs simply visits the file.
13481 With optional argument IN-EMACS, Emacs will visit the file.
13482 Optional LINE specifies a line to go to, optional SEARCH a string to
13483 search for. If LINE or SEARCH is given, the file will always be
13484 opened in Emacs.
13485 If the file does not exist, an error is thrown."
13486 (setq in-emacs (or in-emacs line search))
13487 (let* ((file (if (equal path "")
13488 buffer-file-name
13489 (substitute-in-file-name (expand-file-name path))))
13490 (apps (append org-file-apps (org-default-apps)))
13491 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13492 (dirp (if remp nil (file-directory-p file)))
13493 (dfile (downcase file))
13494 (old-buffer (current-buffer))
13495 (old-pos (point))
13496 (old-mode major-mode)
13497 ext cmd)
13498 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13499 (setq ext (match-string 1 dfile))
13500 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13501 (setq ext (match-string 1 dfile))))
13502 (if in-emacs
13503 (setq cmd 'emacs)
13504 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13505 (and dirp (cdr (assoc 'directory apps)))
13506 (cdr (assoc ext apps))
13507 (cdr (assoc t apps)))))
13508 (when (eq cmd 'mailcap)
13509 (require 'mailcap)
13510 (mailcap-parse-mailcaps)
13511 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13512 (command (mailcap-mime-info mime-type)))
13513 (if (stringp command)
13514 (setq cmd command)
13515 (setq cmd 'emacs))))
13516 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13517 (not (file-exists-p file))
13518 (not org-open-non-existing-files))
13519 (error "No such file: %s" file))
13520 (cond
13521 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13522 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13523 (while (string-match "['\"]%s['\"]" cmd)
13524 (setq cmd (replace-match "%s" t t cmd)))
13525 (while (string-match "%s" cmd)
13526 (setq cmd (replace-match
13527 (save-match-data (shell-quote-argument file))
13528 t t cmd)))
13529 (save-window-excursion
13530 (start-process-shell-command cmd nil cmd)))
13531 ((or (stringp cmd)
13532 (eq cmd 'emacs))
13533 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13534 (widen)
13535 (if line (goto-line line)
13536 (if search (org-link-search search))))
13537 ((consp cmd)
13538 (eval cmd))
13539 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13540 (and (org-mode-p) (eq old-mode 'org-mode)
13541 (or (not (equal old-buffer (current-buffer)))
13542 (not (equal old-pos (point))))
13543 (org-mark-ring-push old-pos old-buffer))))
13544
13545 (defun org-default-apps ()
13546 "Return the default applications for this operating system."
13547 (cond
13548 ((eq system-type 'darwin)
13549 org-file-apps-defaults-macosx)
13550 ((eq system-type 'windows-nt)
13551 org-file-apps-defaults-windowsnt)
13552 (t org-file-apps-defaults-gnu)))
13553
13554 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13555 (defun org-file-remote-p (file)
13556 "Test whether FILE specifies a location on a remote system.
13557 Return non-nil if the location is indeed remote.
13558
13559 For example, the filename \"/user@host:/foo\" specifies a location
13560 on the system \"/user@host:\"."
13561 (cond ((fboundp 'file-remote-p)
13562 (file-remote-p file))
13563 ((fboundp 'tramp-handle-file-remote-p)
13564 (tramp-handle-file-remote-p file))
13565 ((and (boundp 'ange-ftp-name-format)
13566 (string-match (car ange-ftp-name-format) file))
13567 t)
13568 (t nil)))
13569
13570
13571 ;;;; Hooks for remember.el, and refiling
13572
13573 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13574 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13575
13576 ;;;###autoload
13577 (defun org-remember-insinuate ()
13578 "Setup remember.el for use wiht Org-mode."
13579 (require 'remember)
13580 (setq remember-annotation-functions '(org-remember-annotation))
13581 (setq remember-handler-functions '(org-remember-handler))
13582 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13583
13584 ;;;###autoload
13585 (defun org-remember-annotation ()
13586 "Return a link to the current location as an annotation for remember.el.
13587 If you are using Org-mode files as target for data storage with
13588 remember.el, then the annotations should include a link compatible with the
13589 conventions in Org-mode. This function returns such a link."
13590 (org-store-link nil))
13591
13592 (defconst org-remember-help
13593 "Select a destination location for the note.
13594 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13595 RET on headline -> Store as sublevel entry to current headline
13596 RET at beg-of-buf -> Append to file as level 2 headline
13597 <left>/<right> -> before/after current headline, same headings level")
13598
13599 (defvar org-remember-previous-location nil)
13600 (defvar org-force-remember-template-char) ;; dynamically scoped
13601
13602 ;; Save the major mode of the buffer we called remember from
13603 (defvar org-select-template-temp-major-mode nil)
13604
13605 ;; Temporary store the buffer where remember was called from
13606 (defvar org-select-template-original-buffer nil)
13607
13608 (defun org-select-remember-template (&optional use-char)
13609 (when org-remember-templates
13610 (let* ((pre-selected-templates
13611 (mapcar
13612 (lambda (tpl)
13613 (let ((ctxt (nth 5 tpl))
13614 (mode org-select-template-temp-major-mode)
13615 (buf org-select-template-original-buffer))
13616 (and (or (not ctxt) (eq ctxt t)
13617 (and (listp ctxt) (memq mode ctxt))
13618 (and (functionp ctxt)
13619 (with-current-buffer buf
13620 ;; Protect the user-defined function from error
13621 (condition-case nil (funcall ctxt) (error nil)))))
13622 tpl)))
13623 org-remember-templates))
13624 ;; If no template at this point, add the default templates:
13625 (pre-selected-templates1
13626 (if (not (delq nil pre-selected-templates))
13627 (mapcar (lambda(x) (if (not (nth 5 x)) x))
13628 org-remember-templates)
13629 pre-selected-templates))
13630 ;; Then unconditionnally add template for any contexts
13631 (pre-selected-templates2
13632 (append (mapcar (lambda(x) (if (eq (nth 5 x) t) x))
13633 org-remember-templates)
13634 (delq nil pre-selected-templates1)))
13635 (templates (mapcar (lambda (x)
13636 (if (stringp (car x))
13637 (append (list (nth 1 x) (car x)) (cddr x))
13638 (append (list (car x) "") (cdr x))))
13639 (delq nil pre-selected-templates2)))
13640 (char (or use-char
13641 (cond
13642 ((= (length templates) 1)
13643 (caar templates))
13644 ((and (boundp 'org-force-remember-template-char)
13645 org-force-remember-template-char)
13646 (if (stringp org-force-remember-template-char)
13647 (string-to-char org-force-remember-template-char)
13648 org-force-remember-template-char))
13649 (t
13650 (message "Select template: %s"
13651 (mapconcat
13652 (lambda (x)
13653 (cond
13654 ((not (string-match "\\S-" (nth 1 x)))
13655 (format "[%c]" (car x)))
13656 ((equal (downcase (car x))
13657 (downcase (aref (nth 1 x) 0)))
13658 (format "[%c]%s" (car x)
13659 (substring (nth 1 x) 1)))
13660 (t (format "[%c]%s" (car x) (nth 1 x)))))
13661 templates " "))
13662 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13663 (when (equal char0 ?\C-g)
13664 (jump-to-register remember-register)
13665 (kill-buffer remember-buffer))
13666 char0))))))
13667 (cddr (assoc char templates)))))
13668
13669 (defvar x-last-selected-text)
13670 (defvar x-last-selected-text-primary)
13671
13672 ;;;###autoload
13673 (defun org-remember-apply-template (&optional use-char skip-interactive)
13674 "Initialize *remember* buffer with template, invoke `org-mode'.
13675 This function should be placed into `remember-mode-hook' and in fact requires
13676 to be run from that hook to function properly."
13677 (if org-remember-templates
13678 (let* ((entry (org-select-remember-template use-char))
13679 (tpl (car entry))
13680 (plist-p (if org-store-link-plist t nil))
13681 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13682 (string-match "\\S-" (nth 1 entry)))
13683 (nth 1 entry)
13684 org-default-notes-file))
13685 (headline (nth 2 entry))
13686 (v-c (or (and (eq window-system 'x)
13687 (fboundp 'x-cut-buffer-or-selection-value)
13688 (x-cut-buffer-or-selection-value))
13689 (org-bound-and-true-p x-last-selected-text)
13690 (org-bound-and-true-p x-last-selected-text-primary)
13691 (and (> (length kill-ring) 0) (current-kill 0))))
13692 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13693 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13694 (v-u (concat "[" (substring v-t 1 -1) "]"))
13695 (v-U (concat "[" (substring v-T 1 -1) "]"))
13696 ;; `initial' and `annotation' are bound in `remember'
13697 (v-i (if (boundp 'initial) initial))
13698 (v-a (if (and (boundp 'annotation) annotation)
13699 (if (equal annotation "[[]]") "" annotation)
13700 ""))
13701 (v-A (if (and v-a
13702 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13703 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13704 v-a))
13705 (v-n user-full-name)
13706 (org-startup-folded nil)
13707 org-time-was-given org-end-time-was-given x
13708 prompt completions char time pos default histvar)
13709 (setq org-store-link-plist
13710 (append (list :annotation v-a :initial v-i)
13711 org-store-link-plist))
13712 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13713 (erase-buffer)
13714 (insert (substitute-command-keys
13715 (format
13716 "## Filing location: Select interactively, default, or last used:
13717 ## %s to select file and header location interactively.
13718 ## %s \"%s\" -> \"* %s\"
13719 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13720 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13721 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13722 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13723 (abbreviate-file-name (or file org-default-notes-file))
13724 (or headline "")
13725 (or (car org-remember-previous-location) "???")
13726 (or (cdr org-remember-previous-location) "???"))))
13727 (insert tpl) (goto-char (point-min))
13728 ;; Simple %-escapes
13729 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13730 (when (and initial (equal (match-string 0) "%i"))
13731 (save-match-data
13732 (let* ((lead (buffer-substring
13733 (point-at-bol) (match-beginning 0))))
13734 (setq v-i (mapconcat 'identity
13735 (org-split-string initial "\n")
13736 (concat "\n" lead))))))
13737 (replace-match
13738 (or (eval (intern (concat "v-" (match-string 1)))) "")
13739 t t))
13740
13741 ;; %[] Insert contents of a file.
13742 (goto-char (point-min))
13743 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13744 (let ((start (match-beginning 0))
13745 (end (match-end 0))
13746 (filename (expand-file-name (match-string 1))))
13747 (goto-char start)
13748 (delete-region start end)
13749 (condition-case error
13750 (insert-file-contents filename)
13751 (error (insert (format "%%![Couldn't insert %s: %s]"
13752 filename error))))))
13753 ;; %() embedded elisp
13754 (goto-char (point-min))
13755 (while (re-search-forward "%\\((.+)\\)" nil t)
13756 (goto-char (match-beginning 0))
13757 (let ((template-start (point)))
13758 (forward-char 1)
13759 (let ((result
13760 (condition-case error
13761 (eval (read (current-buffer)))
13762 (error (format "%%![Error: %s]" error)))))
13763 (delete-region template-start (point))
13764 (insert result))))
13765
13766 ;; From the property list
13767 (when plist-p
13768 (goto-char (point-min))
13769 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13770 (and (setq x (or (plist-get org-store-link-plist
13771 (intern (match-string 1))) ""))
13772 (replace-match x t t))))
13773
13774 ;; Turn on org-mode in the remember buffer, set local variables
13775 (org-mode)
13776 (org-set-local 'org-finish-function 'org-remember-finalize)
13777 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13778 (org-set-local 'org-default-notes-file file))
13779 (if (and headline (stringp headline) (string-match "\\S-" headline))
13780 (org-set-local 'org-remember-default-headline headline))
13781 ;; Interactive template entries
13782 (goto-char (point-min))
13783 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13784 (setq char (if (match-end 3) (match-string 3))
13785 prompt (if (match-end 2) (match-string 2)))
13786 (goto-char (match-beginning 0))
13787 (replace-match "")
13788 (setq completions nil default nil)
13789 (when prompt
13790 (setq completions (org-split-string prompt "|")
13791 prompt (pop completions)
13792 default (car completions)
13793 histvar (intern (concat
13794 "org-remember-template-prompt-history::"
13795 (or prompt "")))
13796 completions (mapcar 'list completions)))
13797 (cond
13798 ((member char '("G" "g"))
13799 (let* ((org-last-tags-completion-table
13800 (org-global-tags-completion-table
13801 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13802 (org-add-colon-after-tag-completion t)
13803 (ins (completing-read
13804 (if prompt (concat prompt ": ") "Tags: ")
13805 'org-tags-completion-function nil nil nil
13806 'org-tags-history)))
13807 (setq ins (mapconcat 'identity
13808 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13809 ":"))
13810 (when (string-match "\\S-" ins)
13811 (or (equal (char-before) ?:) (insert ":"))
13812 (insert ins)
13813 (or (equal (char-after) ?:) (insert ":")))))
13814 (char
13815 (setq org-time-was-given (equal (upcase char) char))
13816 (setq time (org-read-date (equal (upcase char) "U") t nil
13817 prompt))
13818 (org-insert-time-stamp time org-time-was-given
13819 (member char '("u" "U"))
13820 nil nil (list org-end-time-was-given)))
13821 (t
13822 (insert (org-completing-read
13823 (concat (if prompt prompt "Enter string")
13824 (if default (concat " [" default "]"))
13825 ": ")
13826 completions nil nil nil histvar default)))))
13827 (goto-char (point-min))
13828 (if (re-search-forward "%\\?" nil t)
13829 (replace-match "")
13830 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13831 (org-mode)
13832 (org-set-local 'org-finish-function 'org-remember-finalize))
13833 (when (save-excursion
13834 (goto-char (point-min))
13835 (re-search-forward "%!" nil t))
13836 (replace-match "")
13837 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13838
13839 (defun org-remember-finish-immediately ()
13840 "File remember note immediately.
13841 This should be run in `post-command-hook' and will remove itself
13842 from that hook."
13843 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13844 (when org-finish-function
13845 (funcall org-finish-function)))
13846
13847 (defvar org-clock-marker) ; Defined below
13848 (defun org-remember-finalize ()
13849 "Finalize the remember process."
13850 (unless (fboundp 'remember-finalize)
13851 (defalias 'remember-finalize 'remember-buffer))
13852 (when (and org-clock-marker
13853 (equal (marker-buffer org-clock-marker) (current-buffer)))
13854 ;; FIXME: test this, this is w/o notetaking!
13855 (let (org-log-note-clock-out) (org-clock-out)))
13856 (when buffer-file-name
13857 (save-buffer)
13858 (setq buffer-file-name nil))
13859 (remember-finalize))
13860
13861 ;;;###autoload
13862 (defun org-remember (&optional goto org-force-remember-template-char)
13863 "Call `remember'. If this is already a remember buffer, re-apply template.
13864 If there is an active region, make sure remember uses it as initial content
13865 of the remember buffer.
13866
13867 When called interactively with a `C-u' prefix argument GOTO, don't remember
13868 anything, just go to the file/headline where the selected template usually
13869 stores its notes. With a double prefix arg `C-u C-u', go to the last
13870 note stored by remember.
13871
13872 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13873 associated with a template in `org-remember-templates'."
13874 (interactive "P")
13875 (cond
13876 ((equal goto '(4)) (org-go-to-remember-target))
13877 ((equal goto '(16)) (org-remember-goto-last-stored))
13878 (t
13879 ;; set temporary variables that will be needed in
13880 ;; `org-select-remember-template'
13881 (setq org-select-template-temp-major-mode major-mode)
13882 (setq org-select-template-original-buffer (current-buffer))
13883 (if (memq org-finish-function '(remember-buffer remember-finalize))
13884 (progn
13885 (when (< (length org-remember-templates) 2)
13886 (error "No other template available"))
13887 (erase-buffer)
13888 (let ((annotation (plist-get org-store-link-plist :annotation))
13889 (initial (plist-get org-store-link-plist :initial)))
13890 (org-remember-apply-template))
13891 (message "Press C-c C-c to remember data"))
13892 (if (org-region-active-p)
13893 (remember (buffer-substring (point) (mark)))
13894 (call-interactively 'remember))))))
13895
13896 (defun org-remember-goto-last-stored ()
13897 "Go to the location where the last remember note was stored."
13898 (interactive)
13899 (bookmark-jump "org-remember-last-stored")
13900 (message "This is the last note stored by remember"))
13901
13902 (defun org-go-to-remember-target (&optional template-key)
13903 "Go to the target location of a remember template.
13904 The user is queried for the template."
13905 (interactive)
13906 (let* (org-select-template-temp-major-mode
13907 (entry (org-select-remember-template template-key))
13908 (file (nth 1 entry))
13909 (heading (nth 2 entry))
13910 visiting)
13911 (unless (and file (stringp file) (string-match "\\S-" file))
13912 (setq file org-default-notes-file))
13913 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13914 (setq heading org-remember-default-headline))
13915 (setq visiting (org-find-base-buffer-visiting file))
13916 (if (not visiting) (find-file-noselect file))
13917 (switch-to-buffer (or visiting (get-file-buffer file)))
13918 (widen)
13919 (goto-char (point-min))
13920 (if (re-search-forward
13921 (concat "^\\*+[ \t]+" (regexp-quote heading)
13922 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13923 nil t)
13924 (goto-char (match-beginning 0))
13925 (error "Target headline not found: %s" heading))))
13926
13927 (defvar org-note-abort nil) ; dynamically scoped
13928
13929 ;;;###autoload
13930 (defun org-remember-handler ()
13931 "Store stuff from remember.el into an org file.
13932 First prompts for an org file. If the user just presses return, the value
13933 of `org-default-notes-file' is used.
13934 Then the command offers the headings tree of the selected file in order to
13935 file the text at a specific location.
13936 You can either immediately press RET to get the note appended to the
13937 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13938 find a better place. Then press RET or <left> or <right> in insert the note.
13939
13940 Key Cursor position Note gets inserted
13941 -----------------------------------------------------------------------------
13942 RET buffer-start as level 1 heading at end of file
13943 RET on headline as sublevel of the heading at cursor
13944 RET no heading at cursor position, level taken from context.
13945 Or use prefix arg to specify level manually.
13946 <left> on headline as same level, before current heading
13947 <right> on headline as same level, after current heading
13948
13949 So the fastest way to store the note is to press RET RET to append it to
13950 the default file. This way your current train of thought is not
13951 interrupted, in accordance with the principles of remember.el.
13952 You can also get the fast execution without prompting by using
13953 C-u C-c C-c to exit the remember buffer. See also the variable
13954 `org-remember-store-without-prompt'.
13955
13956 Before being stored away, the function ensures that the text has a
13957 headline, i.e. a first line that starts with a \"*\". If not, a headline
13958 is constructed from the current date and some additional data.
13959
13960 If the variable `org-adapt-indentation' is non-nil, the entire text is
13961 also indented so that it starts in the same column as the headline
13962 \(i.e. after the stars).
13963
13964 See also the variable `org-reverse-note-order'."
13965 (goto-char (point-min))
13966 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13967 (replace-match ""))
13968 (goto-char (point-max))
13969 (beginning-of-line 1)
13970 (while (looking-at "[ \t]*$\\|##.*")
13971 (delete-region (1- (point)) (point-max))
13972 (beginning-of-line 1))
13973 (catch 'quit
13974 (if org-note-abort (throw 'quit nil))
13975 (let* ((txt (buffer-substring (point-min) (point-max)))
13976 (fastp (org-xor (equal current-prefix-arg '(4))
13977 org-remember-store-without-prompt))
13978 (file (cond
13979 (fastp org-default-notes-file)
13980 ((and (eq org-remember-interactive-interface 'refile)
13981 org-refile-targets)
13982 org-default-notes-file)
13983 ((not (and (equal current-prefix-arg '(16))
13984 org-remember-previous-location))
13985 (org-get-org-file))))
13986 (heading org-remember-default-headline)
13987 (visiting (and file (org-find-base-buffer-visiting file)))
13988 (org-startup-folded nil)
13989 (org-startup-align-all-tables nil)
13990 (org-goto-start-pos 1)
13991 spos exitcmd level indent reversed)
13992 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13993 (setq file (car org-remember-previous-location)
13994 heading (cdr org-remember-previous-location)
13995 fastp t))
13996 (setq current-prefix-arg nil)
13997 (if (string-match "[ \t\n]+\\'" txt)
13998 (setq txt (replace-match "" t t txt)))
13999 ;; Modify text so that it becomes a nice subtree which can be inserted
14000 ;; into an org tree.
14001 (let* ((lines (split-string txt "\n"))
14002 first)
14003 (setq first (car lines) lines (cdr lines))
14004 (if (string-match "^\\*+ " first)
14005 ;; Is already a headline
14006 (setq indent nil)
14007 ;; We need to add a headline: Use time and first buffer line
14008 (setq lines (cons first lines)
14009 first (concat "* " (current-time-string)
14010 " (" (remember-buffer-desc) ")")
14011 indent " "))
14012 (if (and org-adapt-indentation indent)
14013 (setq lines (mapcar
14014 (lambda (x)
14015 (if (string-match "\\S-" x)
14016 (concat indent x) x))
14017 lines)))
14018 (setq txt (concat first "\n"
14019 (mapconcat 'identity lines "\n"))))
14020 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
14021 (setq txt (replace-match "\n\n" t t txt))
14022 (if (string-match "[ \t\n]*\\'" txt)
14023 (setq txt (replace-match "\n" t t txt))))
14024 ;; Put the modified text back into the remember buffer, for refile.
14025 (erase-buffer)
14026 (insert txt)
14027 (goto-char (point-min))
14028 (when (and (eq org-remember-interactive-interface 'refile)
14029 (not fastp))
14030 (org-refile nil (or visiting (find-file-noselect file)))
14031 (throw 'quit t))
14032 ;; Find the file
14033 (if (not visiting) (find-file-noselect file))
14034 (with-current-buffer (or visiting (get-file-buffer file))
14035 (unless (org-mode-p)
14036 (error "Target files for remember notes must be in Org-mode"))
14037 (save-excursion
14038 (save-restriction
14039 (widen)
14040 (and (goto-char (point-min))
14041 (not (re-search-forward "^\\* " nil t))
14042 (insert "\n* " (or heading "Notes") "\n"))
14043 (setq reversed (org-notes-order-reversed-p))
14044
14045 ;; Find the default location
14046 (when (and heading (stringp heading) (string-match "\\S-" heading))
14047 (goto-char (point-min))
14048 (if (re-search-forward
14049 (concat "^\\*+[ \t]+" (regexp-quote heading)
14050 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
14051 nil t)
14052 (setq org-goto-start-pos (match-beginning 0))
14053 (when fastp
14054 (goto-char (point-max))
14055 (unless (bolp) (newline))
14056 (insert "* " heading "\n")
14057 (setq org-goto-start-pos (point-at-bol 0)))))
14058
14059 ;; Ask the User for a location, using the appropriate interface
14060 (cond
14061 (fastp (setq spos org-goto-start-pos
14062 exitcmd 'return))
14063 ((eq org-remember-interactive-interface 'outline)
14064 (setq spos (org-get-location (current-buffer)
14065 org-remember-help)
14066 exitcmd (cdr spos)
14067 spos (car spos)))
14068 ((eq org-remember-interactive-interface 'outline-path-completion)
14069 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
14070 (org-refile-use-outline-path t))
14071 (setq spos (org-refile-get-location "Heading: ")
14072 exitcmd 'return
14073 spos (nth 3 spos))))
14074 (t (error "this should not hapen")))
14075 (if (not spos) (throw 'quit nil)) ; return nil to show we did
14076 ; not handle this note
14077 (goto-char spos)
14078 (cond ((org-on-heading-p t)
14079 (org-back-to-heading t)
14080 (setq level (funcall outline-level))
14081 (cond
14082 ((eq exitcmd 'return)
14083 ;; sublevel of current
14084 (setq org-remember-previous-location
14085 (cons (abbreviate-file-name file)
14086 (org-get-heading 'notags)))
14087 (if reversed
14088 (outline-next-heading)
14089 (org-end-of-subtree t)
14090 (if (not (bolp))
14091 (if (looking-at "[ \t]*\n")
14092 (beginning-of-line 2)
14093 (end-of-line 1)
14094 (insert "\n"))))
14095 (bookmark-set "org-remember-last-stored")
14096 (org-paste-subtree (org-get-valid-level level 1) txt))
14097 ((eq exitcmd 'left)
14098 ;; before current
14099 (bookmark-set "org-remember-last-stored")
14100 (org-paste-subtree level txt))
14101 ((eq exitcmd 'right)
14102 ;; after current
14103 (org-end-of-subtree t)
14104 (bookmark-set "org-remember-last-stored")
14105 (org-paste-subtree level txt))
14106 (t (error "This should not happen"))))
14107
14108 ((and (bobp) (not reversed))
14109 ;; Put it at the end, one level below level 1
14110 (save-restriction
14111 (widen)
14112 (goto-char (point-max))
14113 (if (not (bolp)) (newline))
14114 (bookmark-set "org-remember-last-stored")
14115 (org-paste-subtree (org-get-valid-level 1 1) txt)))
14116
14117 ((and (bobp) reversed)
14118 ;; Put it at the start, as level 1
14119 (save-restriction
14120 (widen)
14121 (goto-char (point-min))
14122 (re-search-forward "^\\*+ " nil t)
14123 (beginning-of-line 1)
14124 (bookmark-set "org-remember-last-stored")
14125 (org-paste-subtree 1 txt)))
14126 (t
14127 ;; Put it right there, with automatic level determined by
14128 ;; org-paste-subtree or from prefix arg
14129 (bookmark-set "org-remember-last-stored")
14130 (org-paste-subtree
14131 (if (numberp current-prefix-arg) current-prefix-arg)
14132 txt)))
14133 (when remember-save-after-remembering
14134 (save-buffer)
14135 (if (not visiting) (kill-buffer (current-buffer)))))))))
14136
14137 t) ;; return t to indicate that we took care of this note.
14138
14139 (defun org-get-org-file ()
14140 "Read a filename, with default directory `org-directory'."
14141 (let ((default (or org-default-notes-file remember-data-file)))
14142 (read-file-name (format "File name [%s]: " default)
14143 (file-name-as-directory org-directory)
14144 default)))
14145
14146 (defun org-notes-order-reversed-p ()
14147 "Check if the current file should receive notes in reversed order."
14148 (cond
14149 ((not org-reverse-note-order) nil)
14150 ((eq t org-reverse-note-order) t)
14151 ((not (listp org-reverse-note-order)) nil)
14152 (t (catch 'exit
14153 (let ((all org-reverse-note-order)
14154 entry)
14155 (while (setq entry (pop all))
14156 (if (string-match (car entry) buffer-file-name)
14157 (throw 'exit (cdr entry))))
14158 nil)))))
14159
14160 ;;; Refiling
14161
14162 (defvar org-refile-target-table nil
14163 "The list of refile targets, created by `org-refile'.")
14164
14165 (defvar org-agenda-new-buffers nil
14166 "Buffers created to visit agenda files.")
14167
14168 (defun org-get-refile-targets (&optional default-buffer)
14169 "Produce a table with refile targets."
14170 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
14171 targets txt re files f desc descre)
14172 (with-current-buffer (or default-buffer (current-buffer))
14173 (while (setq entry (pop entries))
14174 (setq files (car entry) desc (cdr entry))
14175 (cond
14176 ((null files) (setq files (list (current-buffer))))
14177 ((eq files 'org-agenda-files)
14178 (setq files (org-agenda-files 'unrestricted)))
14179 ((and (symbolp files) (fboundp files))
14180 (setq files (funcall files)))
14181 ((and (symbolp files) (boundp files))
14182 (setq files (symbol-value files))))
14183 (if (stringp files) (setq files (list files)))
14184 (cond
14185 ((eq (car desc) :tag)
14186 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
14187 ((eq (car desc) :todo)
14188 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
14189 ((eq (car desc) :regexp)
14190 (setq descre (cdr desc)))
14191 ((eq (car desc) :level)
14192 (setq descre (concat "^\\*\\{" (number-to-string
14193 (if org-odd-levels-only
14194 (1- (* 2 (cdr desc)))
14195 (cdr desc)))
14196 "\\}[ \t]")))
14197 ((eq (car desc) :maxlevel)
14198 (setq descre (concat "^\\*\\{1," (number-to-string
14199 (if org-odd-levels-only
14200 (1- (* 2 (cdr desc)))
14201 (cdr desc)))
14202 "\\}[ \t]")))
14203 (t (error "Bad refiling target description %s" desc)))
14204 (while (setq f (pop files))
14205 (save-excursion
14206 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
14207 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
14208 (save-excursion
14209 (save-restriction
14210 (widen)
14211 (goto-char (point-min))
14212 (while (re-search-forward descre nil t)
14213 (goto-char (point-at-bol))
14214 (when (looking-at org-complex-heading-regexp)
14215 (setq txt (match-string 4)
14216 re (concat "^" (regexp-quote
14217 (buffer-substring (match-beginning 1)
14218 (match-end 4)))))
14219 (if (match-end 5) (setq re (concat re "[ \t]+"
14220 (regexp-quote
14221 (match-string 5)))))
14222 (setq re (concat re "[ \t]*$"))
14223 (when org-refile-use-outline-path
14224 (setq txt (mapconcat 'identity
14225 (append
14226 (if (eq org-refile-use-outline-path 'file)
14227 (list (file-name-nondirectory
14228 (buffer-file-name (buffer-base-buffer))))
14229 (if (eq org-refile-use-outline-path 'full-file-path)
14230 (list (buffer-file-name (buffer-base-buffer)))))
14231 (org-get-outline-path)
14232 (list txt))
14233 "/")))
14234 (push (list txt f re (point)) targets))
14235 (goto-char (point-at-eol))))))))
14236 (nreverse targets))))
14237
14238 (defun org-get-outline-path ()
14239 "Return the outline path to the current entry, as a list."
14240 (let (rtn)
14241 (save-excursion
14242 (while (org-up-heading-safe)
14243 (when (looking-at org-complex-heading-regexp)
14244 (push (org-match-string-no-properties 4) rtn)))
14245 rtn)))
14246
14247 (defvar org-refile-history nil
14248 "History for refiling operations.")
14249
14250 (defun org-refile (&optional goto default-buffer)
14251 "Move the entry at point to another heading.
14252 The list of target headings is compiled using the information in
14253 `org-refile-targets', which see. This list is created upon first use, and
14254 you can update it by calling this command with a double prefix (`C-u C-u').
14255 FIXME: Can we find a better way of updating?
14256
14257 At the target location, the entry is filed as a subitem of the target heading.
14258 Depending on `org-reverse-note-order', the new subitem will either be the
14259 first of the last subitem.
14260
14261 With prefix arg GOTO, the command will only visit the target location,
14262 not actually move anything.
14263 With a double prefix `C-c C-c', go to the location where the last refiling
14264 operation has put the subtree.
14265
14266 With a double prefix argument, the command can be used to jump to any
14267 heading in the current buffer."
14268 (interactive "P")
14269 (let* ((cbuf (current-buffer))
14270 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14271 pos it nbuf file re level reversed)
14272 (if (equal goto '(16))
14273 (org-refile-goto-last-stored)
14274 (when (setq it (org-refile-get-location
14275 (if goto "Goto: " "Refile to: ") default-buffer))
14276 (setq file (nth 1 it)
14277 re (nth 2 it)
14278 pos (nth 3 it))
14279 (setq nbuf (or (find-buffer-visiting file)
14280 (find-file-noselect file)))
14281 (if goto
14282 (progn
14283 (switch-to-buffer nbuf)
14284 (goto-char pos)
14285 (org-show-context 'org-goto))
14286 (org-copy-special)
14287 (save-excursion
14288 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14289 (find-file-noselect file))))
14290 (setq reversed (org-notes-order-reversed-p))
14291 (save-excursion
14292 (save-restriction
14293 (widen)
14294 (goto-char pos)
14295 (looking-at outline-regexp)
14296 (setq level (org-get-valid-level (funcall outline-level) 1))
14297 (goto-char
14298 (if reversed
14299 (outline-next-heading)
14300 (or (save-excursion (outline-get-next-sibling))
14301 (org-end-of-subtree t t)
14302 (point-max))))
14303 (bookmark-set "org-refile-last-stored")
14304 (org-paste-subtree level))))
14305 (org-cut-special)
14306 (message "Entry refiled to \"%s\"" (car it)))))))
14307
14308 (defun org-refile-goto-last-stored ()
14309 "Go to the location where the last refile was stored."
14310 (interactive)
14311 (bookmark-jump "org-refile-last-stored")
14312 (message "This is the location of the last refile"))
14313
14314 (defun org-refile-get-location (&optional prompt default-buffer)
14315 "Prompt the user for a refile location, using PROMPT."
14316 (let ((org-refile-targets org-refile-targets)
14317 (org-refile-use-outline-path org-refile-use-outline-path))
14318 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14319 (unless org-refile-target-table
14320 (error "No refile targets"))
14321 (let* ((cbuf (current-buffer))
14322 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14323 (fname (and filename (file-truename filename)))
14324 (tbl (mapcar
14325 (lambda (x)
14326 (if (not (equal fname (file-truename (nth 1 x))))
14327 (cons (concat (car x) " (" (file-name-nondirectory
14328 (nth 1 x)) ")")
14329 (cdr x))
14330 x))
14331 org-refile-target-table))
14332 (completion-ignore-case t))
14333 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14334 tbl)))
14335
14336 ;;;; Dynamic blocks
14337
14338 (defun org-find-dblock (name)
14339 "Find the first dynamic block with name NAME in the buffer.
14340 If not found, stay at current position and return nil."
14341 (let (pos)
14342 (save-excursion
14343 (goto-char (point-min))
14344 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14345 nil t)
14346 (match-beginning 0))))
14347 (if pos (goto-char pos))
14348 pos))
14349
14350 (defconst org-dblock-start-re
14351 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14352 "Matches the startline of a dynamic block, with parameters.")
14353
14354 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14355 "Matches the end of a dyhamic block.")
14356
14357 (defun org-create-dblock (plist)
14358 "Create a dynamic block section, with parameters taken from PLIST.
14359 PLIST must containe a :name entry which is used as name of the block."
14360 (unless (bolp) (newline))
14361 (let ((name (plist-get plist :name)))
14362 (insert "#+BEGIN: " name)
14363 (while plist
14364 (if (eq (car plist) :name)
14365 (setq plist (cddr plist))
14366 (insert " " (prin1-to-string (pop plist)))))
14367 (insert "\n\n#+END:\n")
14368 (beginning-of-line -2)))
14369
14370 (defun org-prepare-dblock ()
14371 "Prepare dynamic block for refresh.
14372 This empties the block, puts the cursor at the insert position and returns
14373 the property list including an extra property :name with the block name."
14374 (unless (looking-at org-dblock-start-re)
14375 (error "Not at a dynamic block"))
14376 (let* ((begdel (1+ (match-end 0)))
14377 (name (org-no-properties (match-string 1)))
14378 (params (append (list :name name)
14379 (read (concat "(" (match-string 3) ")")))))
14380 (unless (re-search-forward org-dblock-end-re nil t)
14381 (error "Dynamic block not terminated"))
14382 (setq params
14383 (append params
14384 (list :content (buffer-substring
14385 begdel (match-beginning 0)))))
14386 (delete-region begdel (match-beginning 0))
14387 (goto-char begdel)
14388 (open-line 1)
14389 params))
14390
14391 (defun org-map-dblocks (&optional command)
14392 "Apply COMMAND to all dynamic blocks in the current buffer.
14393 If COMMAND is not given, use `org-update-dblock'."
14394 (let ((cmd (or command 'org-update-dblock))
14395 pos)
14396 (save-excursion
14397 (goto-char (point-min))
14398 (while (re-search-forward org-dblock-start-re nil t)
14399 (goto-char (setq pos (match-beginning 0)))
14400 (condition-case nil
14401 (funcall cmd)
14402 (error (message "Error during update of dynamic block")))
14403 (goto-char pos)
14404 (unless (re-search-forward org-dblock-end-re nil t)
14405 (error "Dynamic block not terminated"))))))
14406
14407 (defun org-dblock-update (&optional arg)
14408 "User command for updating dynamic blocks.
14409 Update the dynamic block at point. With prefix ARG, update all dynamic
14410 blocks in the buffer."
14411 (interactive "P")
14412 (if arg
14413 (org-update-all-dblocks)
14414 (or (looking-at org-dblock-start-re)
14415 (org-beginning-of-dblock))
14416 (org-update-dblock)))
14417
14418 (defun org-update-dblock ()
14419 "Update the dynamic block at point
14420 This means to empty the block, parse for parameters and then call
14421 the correct writing function."
14422 (save-window-excursion
14423 (let* ((pos (point))
14424 (line (org-current-line))
14425 (params (org-prepare-dblock))
14426 (name (plist-get params :name))
14427 (cmd (intern (concat "org-dblock-write:" name))))
14428 (message "Updating dynamic block `%s' at line %d..." name line)
14429 (funcall cmd params)
14430 (message "Updating dynamic block `%s' at line %d...done" name line)
14431 (goto-char pos))))
14432
14433 (defun org-beginning-of-dblock ()
14434 "Find the beginning of the dynamic block at point.
14435 Error if there is no scuh block at point."
14436 (let ((pos (point))
14437 beg)
14438 (end-of-line 1)
14439 (if (and (re-search-backward org-dblock-start-re nil t)
14440 (setq beg (match-beginning 0))
14441 (re-search-forward org-dblock-end-re nil t)
14442 (> (match-end 0) pos))
14443 (goto-char beg)
14444 (goto-char pos)
14445 (error "Not in a dynamic block"))))
14446
14447 (defun org-update-all-dblocks ()
14448 "Update all dynamic blocks in the buffer.
14449 This function can be used in a hook."
14450 (when (org-mode-p)
14451 (org-map-dblocks 'org-update-dblock)))
14452
14453
14454 ;;;; Completion
14455
14456 (defconst org-additional-option-like-keywords
14457 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14458 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14459 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14460
14461 (defun org-complete (&optional arg)
14462 "Perform completion on word at point.
14463 At the beginning of a headline, this completes TODO keywords as given in
14464 `org-todo-keywords'.
14465 If the current word is preceded by a backslash, completes the TeX symbols
14466 that are supported for HTML support.
14467 If the current word is preceded by \"#+\", completes special words for
14468 setting file options.
14469 In the line after \"#+STARTUP:, complete valid keywords.\"
14470 At all other locations, this simply calls the value of
14471 `org-completion-fallback-command'."
14472 (interactive "P")
14473 (org-without-partial-completion
14474 (catch 'exit
14475 (let* ((end (point))
14476 (beg1 (save-excursion
14477 (skip-chars-backward (org-re "[:alnum:]_@"))
14478 (point)))
14479 (beg (save-excursion
14480 (skip-chars-backward "a-zA-Z0-9_:$")
14481 (point)))
14482 (confirm (lambda (x) (stringp (car x))))
14483 (searchhead (equal (char-before beg) ?*))
14484 (tag (and (equal (char-before beg1) ?:)
14485 (equal (char-after (point-at-bol)) ?*)))
14486 (prop (and (equal (char-before beg1) ?:)
14487 (not (equal (char-after (point-at-bol)) ?*))))
14488 (texp (equal (char-before beg) ?\\))
14489 (link (equal (char-before beg) ?\[))
14490 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14491 beg)
14492 "#+"))
14493 (startup (string-match "^#\\+STARTUP:.*"
14494 (buffer-substring (point-at-bol) (point))))
14495 (completion-ignore-case opt)
14496 (type nil)
14497 (tbl nil)
14498 (table (cond
14499 (opt
14500 (setq type :opt)
14501 (append
14502 (mapcar
14503 (lambda (x)
14504 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14505 (cons (match-string 2 x) (match-string 1 x)))
14506 (org-split-string (org-get-current-options) "\n"))
14507 (mapcar 'list org-additional-option-like-keywords)))
14508 (startup
14509 (setq type :startup)
14510 org-startup-options)
14511 (link (append org-link-abbrev-alist-local
14512 org-link-abbrev-alist))
14513 (texp
14514 (setq type :tex)
14515 org-html-entities)
14516 ((string-match "\\`\\*+[ \t]+\\'"
14517 (buffer-substring (point-at-bol) beg))
14518 (setq type :todo)
14519 (mapcar 'list org-todo-keywords-1))
14520 (searchhead
14521 (setq type :searchhead)
14522 (save-excursion
14523 (goto-char (point-min))
14524 (while (re-search-forward org-todo-line-regexp nil t)
14525 (push (list
14526 (org-make-org-heading-search-string
14527 (match-string 3) t))
14528 tbl)))
14529 tbl)
14530 (tag (setq type :tag beg beg1)
14531 (or org-tag-alist (org-get-buffer-tags)))
14532 (prop (setq type :prop beg beg1)
14533 (mapcar 'list (org-buffer-property-keys nil t t)))
14534 (t (progn
14535 (call-interactively org-completion-fallback-command)
14536 (throw 'exit nil)))))
14537 (pattern (buffer-substring-no-properties beg end))
14538 (completion (try-completion pattern table confirm)))
14539 (cond ((eq completion t)
14540 (if (not (assoc (upcase pattern) table))
14541 (message "Already complete")
14542 (if (equal type :opt)
14543 (insert (substring (cdr (assoc (upcase pattern) table))
14544 (length pattern)))
14545 (if (memq type '(:tag :prop)) (insert ":")))))
14546 ((null completion)
14547 (message "Can't find completion for \"%s\"" pattern)
14548 (ding))
14549 ((not (string= pattern completion))
14550 (delete-region beg end)
14551 (if (string-match " +$" completion)
14552 (setq completion (replace-match "" t t completion)))
14553 (insert completion)
14554 (if (get-buffer-window "*Completions*")
14555 (delete-window (get-buffer-window "*Completions*")))
14556 (if (assoc completion table)
14557 (if (eq type :todo) (insert " ")
14558 (if (memq type '(:tag :prop)) (insert ":"))))
14559 (if (and (equal type :opt) (assoc completion table))
14560 (message "%s" (substitute-command-keys
14561 "Press \\[org-complete] again to insert example settings"))))
14562 (t
14563 (message "Making completion list...")
14564 (let ((list (sort (all-completions pattern table confirm)
14565 'string<)))
14566 (with-output-to-temp-buffer "*Completions*"
14567 (condition-case nil
14568 ;; Protection needed for XEmacs and emacs 21
14569 (display-completion-list list pattern)
14570 (error (display-completion-list list)))))
14571 (message "Making completion list...%s" "done")))))))
14572
14573 ;;;; TODO, DEADLINE, Comments
14574
14575 (defun org-toggle-comment ()
14576 "Change the COMMENT state of an entry."
14577 (interactive)
14578 (save-excursion
14579 (org-back-to-heading)
14580 (let (case-fold-search)
14581 (if (looking-at (concat outline-regexp
14582 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14583 (replace-match "" t t nil 1)
14584 (if (looking-at outline-regexp)
14585 (progn
14586 (goto-char (match-end 0))
14587 (insert org-comment-string " ")))))))
14588
14589 (defvar org-last-todo-state-is-todo nil
14590 "This is non-nil when the last TODO state change led to a TODO state.
14591 If the last change removed the TODO tag or switched to DONE, then
14592 this is nil.")
14593
14594 (defvar org-setting-tags nil) ; dynamically skiped
14595
14596 ;; FIXME: better place
14597 (defun org-property-or-variable-value (var &optional inherit)
14598 "Check if there is a property fixing the value of VAR.
14599 If yes, return this value. If not, return the current value of the variable."
14600 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14601 (if (and prop (stringp prop) (string-match "\\S-" prop))
14602 (read prop)
14603 (symbol-value var))))
14604
14605 (defun org-parse-local-options (string var)
14606 "Parse STRING for startup setting relevant for variable VAR."
14607 (let ((rtn (symbol-value var))
14608 e opts)
14609 (save-match-data
14610 (if (or (not string) (not (string-match "\\S-" string)))
14611 rtn
14612 (setq opts (delq nil (mapcar (lambda (x)
14613 (setq e (assoc x org-startup-options))
14614 (if (eq (nth 1 e) var) e nil))
14615 (org-split-string string "[ \t]+"))))
14616 (if (not opts)
14617 rtn
14618 (setq rtn nil)
14619 (while (setq e (pop opts))
14620 (if (not (nth 3 e))
14621 (setq rtn (nth 2 e))
14622 (if (not (listp rtn)) (setq rtn nil))
14623 (push (nth 2 e) rtn)))
14624 rtn)))))
14625
14626 (defvar org-blocker-hook nil
14627 "Hook for functions that are allowed to block a state change.
14628
14629 Each function gets as its single argument a property list, see
14630 `org-trigger-hook' for more information about this list.
14631
14632 If any of the functions in this hook returns nil, the state change
14633 is blocked.")
14634
14635 (defvar org-trigger-hook nil
14636 "Hook for functions that are triggered by a state change.
14637
14638 Each function gets as its single argument a property list with at least
14639 the following elements:
14640
14641 (:type type-of-change :position pos-at-entry-start
14642 :from old-state :to new-state)
14643
14644 Depending on the type, more properties may be present.
14645
14646 This mechanism is currently implemented for:
14647
14648 TODO state changes
14649 ------------------
14650 :type todo-state-change
14651 :from previous state (keyword as a string), or nil
14652 :to new state (keyword as a string), or nil")
14653
14654
14655 (defun org-todo (&optional arg)
14656 "Change the TODO state of an item.
14657 The state of an item is given by a keyword at the start of the heading,
14658 like
14659 *** TODO Write paper
14660 *** DONE Call mom
14661
14662 The different keywords are specified in the variable `org-todo-keywords'.
14663 By default the available states are \"TODO\" and \"DONE\".
14664 So for this example: when the item starts with TODO, it is changed to DONE.
14665 When it starts with DONE, the DONE is removed. And when neither TODO nor
14666 DONE are present, add TODO at the beginning of the heading.
14667
14668 With C-u prefix arg, use completion to determine the new state.
14669 With numeric prefix arg, switch to that state.
14670
14671 For calling through lisp, arg is also interpreted in the following way:
14672 'none -> empty state
14673 \"\"(empty string) -> switch to empty state
14674 'done -> switch to DONE
14675 'nextset -> switch to the next set of keywords
14676 'previousset -> switch to the previous set of keywords
14677 \"WAITING\" -> switch to the specified keyword, but only if it
14678 really is a member of `org-todo-keywords'."
14679 (interactive "P")
14680 (save-excursion
14681 (catch 'exit
14682 (org-back-to-heading)
14683 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14684 (or (looking-at (concat " +" org-todo-regexp " *"))
14685 (looking-at " *"))
14686 (let* ((match-data (match-data))
14687 (startpos (point-at-bol))
14688 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14689 (org-log-done org-log-done)
14690 (org-log-repeat org-log-repeat)
14691 (org-todo-log-states org-todo-log-states)
14692 (this (match-string 1))
14693 (hl-pos (match-beginning 0))
14694 (head (org-get-todo-sequence-head this))
14695 (ass (assoc head org-todo-kwd-alist))
14696 (interpret (nth 1 ass))
14697 (done-word (nth 3 ass))
14698 (final-done-word (nth 4 ass))
14699 (last-state (or this ""))
14700 (completion-ignore-case t)
14701 (member (member this org-todo-keywords-1))
14702 (tail (cdr member))
14703 (state (cond
14704 ((and org-todo-key-trigger
14705 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14706 (and (not arg) org-use-fast-todo-selection
14707 (not (eq org-use-fast-todo-selection 'prefix)))))
14708 ;; Use fast selection
14709 (org-fast-todo-selection))
14710 ((and (equal arg '(4))
14711 (or (not org-use-fast-todo-selection)
14712 (not org-todo-key-trigger)))
14713 ;; Read a state with completion
14714 (completing-read "State: " (mapcar (lambda(x) (list x))
14715 org-todo-keywords-1)
14716 nil t))
14717 ((eq arg 'right)
14718 (if this
14719 (if tail (car tail) nil)
14720 (car org-todo-keywords-1)))
14721 ((eq arg 'left)
14722 (if (equal member org-todo-keywords-1)
14723 nil
14724 (if this
14725 (nth (- (length org-todo-keywords-1) (length tail) 2)
14726 org-todo-keywords-1)
14727 (org-last org-todo-keywords-1))))
14728 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14729 (setq arg nil))) ; hack to fall back to cycling
14730 (arg
14731 ;; user or caller requests a specific state
14732 (cond
14733 ((equal arg "") nil)
14734 ((eq arg 'none) nil)
14735 ((eq arg 'done) (or done-word (car org-done-keywords)))
14736 ((eq arg 'nextset)
14737 (or (car (cdr (member head org-todo-heads)))
14738 (car org-todo-heads)))
14739 ((eq arg 'previousset)
14740 (let ((org-todo-heads (reverse org-todo-heads)))
14741 (or (car (cdr (member head org-todo-heads)))
14742 (car org-todo-heads))))
14743 ((car (member arg org-todo-keywords-1)))
14744 ((nth (1- (prefix-numeric-value arg))
14745 org-todo-keywords-1))))
14746 ((null member) (or head (car org-todo-keywords-1)))
14747 ((equal this final-done-word) nil) ;; -> make empty
14748 ((null tail) nil) ;; -> first entry
14749 ((eq interpret 'sequence)
14750 (car tail))
14751 ((memq interpret '(type priority))
14752 (if (eq this-command last-command)
14753 (car tail)
14754 (if (> (length tail) 0)
14755 (or done-word (car org-done-keywords))
14756 nil)))
14757 (t nil)))
14758 (next (if state (concat " " state " ") " "))
14759 (change-plist (list :type 'todo-state-change :from this :to state
14760 :position startpos))
14761 dolog now-done-p)
14762 (when org-blocker-hook
14763 (unless (save-excursion
14764 (save-match-data
14765 (run-hook-with-args-until-failure
14766 'org-blocker-hook change-plist)))
14767 (if (interactive-p)
14768 (error "TODO state change from %s to %s blocked" this state)
14769 ;; fail silently
14770 (message "TODO state change from %s to %s blocked" this state)
14771 (throw 'exit nil))))
14772 (store-match-data match-data)
14773 (replace-match next t t)
14774 (unless (pos-visible-in-window-p hl-pos)
14775 (message "TODO state changed to %s" (org-trim next)))
14776 (unless head
14777 (setq head (org-get-todo-sequence-head state)
14778 ass (assoc head org-todo-kwd-alist)
14779 interpret (nth 1 ass)
14780 done-word (nth 3 ass)
14781 final-done-word (nth 4 ass)))
14782 (when (memq arg '(nextset previousset))
14783 (message "Keyword-Set %d/%d: %s"
14784 (- (length org-todo-sets) -1
14785 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14786 (length org-todo-sets)
14787 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14788 (setq org-last-todo-state-is-todo
14789 (not (member state org-done-keywords)))
14790 (setq now-done-p (and (member state org-done-keywords)
14791 (not (member this org-done-keywords))))
14792 (and logging (org-local-logging logging))
14793 (when (and (or org-todo-log-states org-log-done)
14794 (not (memq arg '(nextset previousset))))
14795 ;; we need to look at recording a time and note
14796 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14797 (nth 2 (assoc this org-todo-log-states))))
14798 (when (and state
14799 (member state org-not-done-keywords)
14800 (not (member this org-not-done-keywords)))
14801 ;; This is now a todo state and was not one before
14802 ;; If there was a CLOSED time stamp, get rid of it.
14803 (org-add-planning-info nil nil 'closed))
14804 (when (and now-done-p org-log-done)
14805 ;; It is now done, and it was not done before
14806 (org-add-planning-info 'closed (org-current-time))
14807 (if (and (not dolog) (eq 'note org-log-done))
14808 (org-add-log-maybe 'done state 'findpos 'note)))
14809 (when (and state dolog)
14810 ;; This is a non-nil state, and we need to log it
14811 (org-add-log-maybe 'state state 'findpos dolog)))
14812 ;; Fixup tag positioning
14813 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14814 (run-hooks 'org-after-todo-state-change-hook)
14815 (if (and arg (not (member state org-done-keywords)))
14816 (setq head (org-get-todo-sequence-head state)))
14817 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14818 ;; Do we need to trigger a repeat?
14819 (when now-done-p (org-auto-repeat-maybe state))
14820 ;; Fixup cursor location if close to the keyword
14821 (if (and (outline-on-heading-p)
14822 (not (bolp))
14823 (save-excursion (beginning-of-line 1)
14824 (looking-at org-todo-line-regexp))
14825 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14826 (progn
14827 (goto-char (or (match-end 2) (match-end 1)))
14828 (just-one-space)))
14829 (when org-trigger-hook
14830 (save-excursion
14831 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14832
14833 (defun org-local-logging (value)
14834 "Get logging settings from a property VALUE."
14835 (let* (words w a)
14836 ;; directly set the variables, they are already local.
14837 (setq org-log-done nil
14838 org-log-repeat nil
14839 org-todo-log-states nil)
14840 (setq words (org-split-string value))
14841 (while (setq w (pop words))
14842 (cond
14843 ((setq a (assoc w org-startup-options))
14844 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14845 (set (nth 1 a) (nth 2 a))))
14846 ((setq a (org-extract-log-state-settings w))
14847 (and (member (car a) org-todo-keywords-1)
14848 (push a org-todo-log-states)))))))
14849
14850 (defun org-get-todo-sequence-head (kwd)
14851 "Return the head of the TODO sequence to which KWD belongs.
14852 If KWD is not set, check if there is a text property remembering the
14853 right sequence."
14854 (let (p)
14855 (cond
14856 ((not kwd)
14857 (or (get-text-property (point-at-bol) 'org-todo-head)
14858 (progn
14859 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14860 nil (point-at-eol)))
14861 (get-text-property p 'org-todo-head))))
14862 ((not (member kwd org-todo-keywords-1))
14863 (car org-todo-keywords-1))
14864 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14865
14866 (defun org-fast-todo-selection ()
14867 "Fast TODO keyword selection with single keys.
14868 Returns the new TODO keyword, or nil if no state change should occur."
14869 (let* ((fulltable org-todo-key-alist)
14870 (done-keywords org-done-keywords) ;; needed for the faces.
14871 (maxlen (apply 'max (mapcar
14872 (lambda (x)
14873 (if (stringp (car x)) (string-width (car x)) 0))
14874 fulltable)))
14875 (expert nil)
14876 (fwidth (+ maxlen 3 1 3))
14877 (ncol (/ (- (window-width) 4) fwidth))
14878 tg cnt e c tbl
14879 groups ingroup)
14880 (save-window-excursion
14881 (if expert
14882 (set-buffer (get-buffer-create " *Org todo*"))
14883 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14884 (erase-buffer)
14885 (org-set-local 'org-done-keywords done-keywords)
14886 (setq tbl fulltable cnt 0)
14887 (while (setq e (pop tbl))
14888 (cond
14889 ((equal e '(:startgroup))
14890 (push '() groups) (setq ingroup t)
14891 (when (not (= cnt 0))
14892 (setq cnt 0)
14893 (insert "\n"))
14894 (insert "{ "))
14895 ((equal e '(:endgroup))
14896 (setq ingroup nil cnt 0)
14897 (insert "}\n"))
14898 (t
14899 (setq tg (car e) c (cdr e))
14900 (if ingroup (push tg (car groups)))
14901 (setq tg (org-add-props tg nil 'face
14902 (org-get-todo-face tg)))
14903 (if (and (= cnt 0) (not ingroup)) (insert " "))
14904 (insert "[" c "] " tg (make-string
14905 (- fwidth 4 (length tg)) ?\ ))
14906 (when (= (setq cnt (1+ cnt)) ncol)
14907 (insert "\n")
14908 (if ingroup (insert " "))
14909 (setq cnt 0)))))
14910 (insert "\n")
14911 (goto-char (point-min))
14912 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14913 (fit-window-to-buffer))
14914 (message "[a-z..]:Set [SPC]:clear")
14915 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14916 (cond
14917 ((or (= c ?\C-g)
14918 (and (= c ?q) (not (rassoc c fulltable))))
14919 (setq quit-flag t))
14920 ((= c ?\ ) nil)
14921 ((setq e (rassoc c fulltable) tg (car e))
14922 tg)
14923 (t (setq quit-flag t))))))
14924
14925 (defun org-get-repeat ()
14926 "Check if tere is a deadline/schedule with repeater in this entry."
14927 (save-match-data
14928 (save-excursion
14929 (org-back-to-heading t)
14930 (if (re-search-forward
14931 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14932 (match-string 1)))))
14933
14934 (defvar org-last-changed-timestamp)
14935 (defvar org-log-post-message)
14936 (defvar org-log-note-purpose)
14937 (defun org-auto-repeat-maybe (done-word)
14938 "Check if the current headline contains a repeated deadline/schedule.
14939 If yes, set TODO state back to what it was and change the base date
14940 of repeating deadline/scheduled time stamps to new date.
14941 This function is run automatically after each state change to a DONE state."
14942 ;; last-state is dynamically scoped into this function
14943 (let* ((repeat (org-get-repeat))
14944 (aa (assoc last-state org-todo-kwd-alist))
14945 (interpret (nth 1 aa))
14946 (head (nth 2 aa))
14947 (whata '(("d" . day) ("m" . month) ("y" . year)))
14948 (msg "Entry repeats: ")
14949 (org-log-done nil)
14950 (org-todo-log-states nil)
14951 (nshiftmax 10) (nshift 0)
14952 re type n what ts mb0 time)
14953 (when repeat
14954 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
14955 (org-todo (if (eq interpret 'type) last-state head))
14956 (when (and org-log-repeat
14957 (or (not (memq 'org-add-log-note
14958 (default-value 'post-command-hook)))
14959 (eq org-log-note-purpose 'done)))
14960 ;; Make sure a note is taken;
14961 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
14962 'findpos org-log-repeat))
14963 (org-back-to-heading t)
14964 (org-add-planning-info nil nil 'closed)
14965 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14966 org-deadline-time-regexp "\\)\\|\\("
14967 org-ts-regexp "\\)"))
14968 (while (re-search-forward
14969 re (save-excursion (outline-next-heading) (point)) t)
14970 (setq type (if (match-end 1) org-scheduled-string
14971 (if (match-end 3) org-deadline-string "Plain:"))
14972 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
14973 mb0 (match-beginning 0))
14974 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
14975 (setq n (string-to-number (match-string 2 ts))
14976 what (match-string 3 ts))
14977 (if (equal what "w") (setq n (* n 7) what "d"))
14978 ;; Preparation, see if we need to modify the start date for the change
14979 (when (match-end 1)
14980 (setq time (save-match-data (org-time-string-to-time ts)))
14981 (cond
14982 ((equal (match-string 1 ts) ".")
14983 ;; Shift starting date to today
14984 (org-timestamp-change
14985 (- (time-to-days (current-time)) (time-to-days time))
14986 'day))
14987 ((equal (match-string 1 ts) "+")
14988 (while (< (time-to-days time) (time-to-days (current-time)))
14989 (when (= (incf nshift) nshiftmax)
14990 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
14991 (error "Abort")))
14992 (org-timestamp-change n (cdr (assoc what whata)))
14993 (sit-for .0001) ;; so we can watch the date shifting
14994 (org-at-timestamp-p t)
14995 (setq ts (match-string 1))
14996 (setq time (save-match-data (org-time-string-to-time ts))))
14997 (org-timestamp-change (- n) (cdr (assoc what whata)))
14998 ;; rematch, so that we have everything in place for the real shift
14999 (org-at-timestamp-p t)
15000 (setq ts (match-string 1))
15001 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
15002 (org-timestamp-change n (cdr (assoc what whata)))
15003 (setq msg (concat msg type org-last-changed-timestamp " "))))
15004 (setq org-log-post-message msg)
15005 (message "%s" msg))))
15006
15007 (defun org-show-todo-tree (arg)
15008 "Make a compact tree which shows all headlines marked with TODO.
15009 The tree will show the lines where the regexp matches, and all higher
15010 headlines above the match.
15011 With a \\[universal-argument] prefix, also show the DONE entries.
15012 With a numeric prefix N, construct a sparse tree for the Nth element
15013 of `org-todo-keywords-1'."
15014 (interactive "P")
15015 (let ((case-fold-search nil)
15016 (kwd-re
15017 (cond ((null arg) org-not-done-regexp)
15018 ((equal arg '(4))
15019 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
15020 (mapcar 'list org-todo-keywords-1))))
15021 (concat "\\("
15022 (mapconcat 'identity (org-split-string kwd "|") "\\|")
15023 "\\)\\>")))
15024 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
15025 (regexp-quote (nth (1- (prefix-numeric-value arg))
15026 org-todo-keywords-1)))
15027 (t (error "Invalid prefix argument: %s" arg)))))
15028 (message "%d TODO entries found"
15029 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
15030
15031 (defun org-deadline (&optional remove)
15032 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
15033 With argument REMOVE, remove any deadline from the item."
15034 (interactive "P")
15035 (if remove
15036 (progn
15037 (org-remove-timestamp-with-keyword org-deadline-string)
15038 (message "Item no longer has a deadline."))
15039 (org-add-planning-info 'deadline nil 'closed)))
15040
15041 (defun org-schedule (&optional remove)
15042 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
15043 With argument REMOVE, remove any scheduling date from the item."
15044 (interactive "P")
15045 (if remove
15046 (progn
15047 (org-remove-timestamp-with-keyword org-scheduled-string)
15048 (message "Item is no longer scheduled."))
15049 (org-add-planning-info 'scheduled nil 'closed)))
15050
15051 (defun org-remove-timestamp-with-keyword (keyword)
15052 "Remove all time stamps with KEYWORD in the current entry."
15053 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
15054 beg)
15055 (save-excursion
15056 (org-back-to-heading t)
15057 (setq beg (point))
15058 (org-end-of-subtree t t)
15059 (while (re-search-backward re beg t)
15060 (replace-match "")
15061 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
15062 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
15063
15064 (defun org-add-planning-info (what &optional time &rest remove)
15065 "Insert new timestamp with keyword in the line directly after the headline.
15066 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
15067 If non is given, the user is prompted for a date.
15068 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
15069 be removed."
15070 (interactive)
15071 (let (org-time-was-given org-end-time-was-given)
15072 (when what (setq time (or time (org-read-date nil 'to-time))))
15073 (when (and org-insert-labeled-timestamps-at-point
15074 (member what '(scheduled deadline)))
15075 (insert
15076 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
15077 (org-insert-time-stamp time org-time-was-given
15078 nil nil nil (list org-end-time-was-given))
15079 (setq what nil))
15080 (save-excursion
15081 (save-restriction
15082 (let (col list elt ts buffer-invisibility-spec)
15083 (org-back-to-heading t)
15084 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
15085 (goto-char (match-end 1))
15086 (setq col (current-column))
15087 (goto-char (match-end 0))
15088 (if (eobp) (insert "\n") (forward-char 1))
15089 (if (and (not (looking-at outline-regexp))
15090 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
15091 "[^\r\n]*"))
15092 (not (equal (match-string 1) org-clock-string)))
15093 (narrow-to-region (match-beginning 0) (match-end 0))
15094 (insert-before-markers "\n")
15095 (backward-char 1)
15096 (narrow-to-region (point) (point))
15097 (indent-to-column col))
15098 ;; Check if we have to remove something.
15099 (setq list (cons what remove))
15100 (while list
15101 (setq elt (pop list))
15102 (goto-char (point-min))
15103 (when (or (and (eq elt 'scheduled)
15104 (re-search-forward org-scheduled-time-regexp nil t))
15105 (and (eq elt 'deadline)
15106 (re-search-forward org-deadline-time-regexp nil t))
15107 (and (eq elt 'closed)
15108 (re-search-forward org-closed-time-regexp nil t)))
15109 (replace-match "")
15110 (if (looking-at "--+<[^>]+>") (replace-match ""))
15111 (if (looking-at " +") (replace-match ""))))
15112 (goto-char (point-max))
15113 (when what
15114 (insert
15115 (if (not (equal (char-before) ?\ )) " " "")
15116 (cond ((eq what 'scheduled) org-scheduled-string)
15117 ((eq what 'deadline) org-deadline-string)
15118 ((eq what 'closed) org-closed-string))
15119 " ")
15120 (setq ts (org-insert-time-stamp
15121 time
15122 (or org-time-was-given
15123 (and (eq what 'closed) org-log-done-with-time))
15124 (eq what 'closed)
15125 nil nil (list org-end-time-was-given)))
15126 (end-of-line 1))
15127 (goto-char (point-min))
15128 (widen)
15129 (if (looking-at "[ \t]+\r?\n")
15130 (replace-match ""))
15131 ts)))))
15132
15133 (defvar org-log-note-marker (make-marker))
15134 (defvar org-log-note-purpose nil)
15135 (defvar org-log-note-state nil)
15136 (defvar org-log-note-how nil)
15137 (defvar org-log-note-window-configuration nil)
15138 (defvar org-log-note-return-to (make-marker))
15139 (defvar org-log-post-message nil
15140 "Message to be displayed after a log note has been stored.
15141 The auto-repeater uses this.")
15142
15143 (defun org-add-log-maybe (&optional purpose state findpos how)
15144 "Set up the post command hook to take a note.
15145 If this is about to TODO state change, the new state is expected in STATE.
15146 When FINDPOS is non-nil, find the correct position for the note in
15147 the current entry. If not, assume that it can be inserted at point."
15148 (save-excursion
15149 (when findpos
15150 (org-back-to-heading t)
15151 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
15152 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
15153 "[^\r\n]*\\)?"))
15154 (goto-char (match-end 0))
15155 (unless org-log-states-order-reversed
15156 (and (= (char-after) ?\n) (forward-char 1))
15157 (org-skip-over-state-notes)
15158 (skip-chars-backward " \t\n\r")))
15159 (move-marker org-log-note-marker (point))
15160 (setq org-log-note-purpose purpose
15161 org-log-note-state state
15162 org-log-note-how how)
15163 (add-hook 'post-command-hook 'org-add-log-note 'append)))
15164
15165 (defun org-skip-over-state-notes ()
15166 "Skip past the list of State notes in an entry."
15167 (if (looking-at "\n[ \t]*- State") (forward-char 1))
15168 (while (looking-at "[ \t]*- State")
15169 (condition-case nil
15170 (org-next-item)
15171 (error (org-end-of-item)))))
15172
15173 (defun org-add-log-note (&optional purpose)
15174 "Pop up a window for taking a note, and add this note later at point."
15175 (remove-hook 'post-command-hook 'org-add-log-note)
15176 (setq org-log-note-window-configuration (current-window-configuration))
15177 (delete-other-windows)
15178 (move-marker org-log-note-return-to (point))
15179 (switch-to-buffer (marker-buffer org-log-note-marker))
15180 (goto-char org-log-note-marker)
15181 (org-switch-to-buffer-other-window "*Org Note*")
15182 (erase-buffer)
15183 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
15184 (org-store-log-note)
15185 (let ((org-inhibit-startup t)) (org-mode))
15186 (insert (format "# Insert note for %s.
15187 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
15188 (cond
15189 ((eq org-log-note-purpose 'clock-out) "stopped clock")
15190 ((eq org-log-note-purpose 'done) "closed todo item")
15191 ((eq org-log-note-purpose 'state)
15192 (format "state change to \"%s\"" org-log-note-state))
15193 (t (error "This should not happen")))))
15194 (org-set-local 'org-finish-function 'org-store-log-note)))
15195
15196 (defun org-store-log-note ()
15197 "Finish taking a log note, and insert it to where it belongs."
15198 (let ((txt (buffer-string))
15199 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
15200 lines ind)
15201 (kill-buffer (current-buffer))
15202 (while (string-match "\\`#.*\n[ \t\n]*" txt)
15203 (setq txt (replace-match "" t t txt)))
15204 (if (string-match "\\s-+\\'" txt)
15205 (setq txt (replace-match "" t t txt)))
15206 (setq lines (org-split-string txt "\n"))
15207 (when (and note (string-match "\\S-" note))
15208 (setq note
15209 (org-replace-escapes
15210 note
15211 (list (cons "%u" (user-login-name))
15212 (cons "%U" user-full-name)
15213 (cons "%t" (format-time-string
15214 (org-time-stamp-format 'long 'inactive)
15215 (current-time)))
15216 (cons "%s" (if org-log-note-state
15217 (concat "\"" org-log-note-state "\"")
15218 "")))))
15219 (if lines (setq note (concat note " \\\\")))
15220 (push note lines))
15221 (when (or current-prefix-arg org-note-abort) (setq lines nil))
15222 (when lines
15223 (save-excursion
15224 (set-buffer (marker-buffer org-log-note-marker))
15225 (save-excursion
15226 (goto-char org-log-note-marker)
15227 (move-marker org-log-note-marker nil)
15228 (end-of-line 1)
15229 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
15230 (indent-relative nil)
15231 (insert "- " (pop lines))
15232 (org-indent-line-function)
15233 (beginning-of-line 1)
15234 (looking-at "[ \t]*")
15235 (setq ind (concat (match-string 0) " "))
15236 (end-of-line 1)
15237 (while lines (insert "\n" ind (pop lines)))))))
15238 (set-window-configuration org-log-note-window-configuration)
15239 (with-current-buffer (marker-buffer org-log-note-return-to)
15240 (goto-char org-log-note-return-to))
15241 (move-marker org-log-note-return-to nil)
15242 (and org-log-post-message (message "%s" org-log-post-message)))
15243
15244 ;; FIXME: what else would be useful?
15245 ;; - priority
15246 ;; - date
15247
15248 (defun org-sparse-tree (&optional arg)
15249 "Create a sparse tree, prompt for the details.
15250 This command can create sparse trees. You first need to select the type
15251 of match used to create the tree:
15252
15253 t Show entries with a specific TODO keyword.
15254 T Show entries selected by a tags match.
15255 p Enter a property name and its value (both with completion on existing
15256 names/values) and show entries with that property.
15257 r Show entries matching a regular expression
15258 d Show deadlines due within `org-deadline-warning-days'."
15259 (interactive "P")
15260 (let (ans kwd value)
15261 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15262 (setq ans (read-char-exclusive))
15263 (cond
15264 ((equal ans ?d)
15265 (call-interactively 'org-check-deadlines))
15266 ((equal ans ?b)
15267 (call-interactively 'org-check-before-date))
15268 ((equal ans ?t)
15269 (org-show-todo-tree '(4)))
15270 ((equal ans ?T)
15271 (call-interactively 'org-tags-sparse-tree))
15272 ((member ans '(?p ?P))
15273 (setq kwd (completing-read "Property: "
15274 (mapcar 'list (org-buffer-property-keys))))
15275 (setq value (completing-read "Value: "
15276 (mapcar 'list (org-property-values kwd))))
15277 (unless (string-match "\\`{.*}\\'" value)
15278 (setq value (concat "\"" value "\"")))
15279 (org-tags-sparse-tree arg (concat kwd "=" value)))
15280 ((member ans '(?r ?R ?/))
15281 (call-interactively 'org-occur))
15282 (t (error "No such sparse tree command \"%c\"" ans)))))
15283
15284 (defvar org-occur-highlights nil
15285 "List of overlays used for occur matches.")
15286 (make-variable-buffer-local 'org-occur-highlights)
15287 (defvar org-occur-parameters nil
15288 "Parameters of the active org-occur calls.
15289 This is a list, each call to org-occur pushes as cons cell,
15290 containing the regular expression and the callback, onto the list.
15291 The list can contain several entries if `org-occur' has been called
15292 several time with the KEEP-PREVIOUS argument. Otherwise, this list
15293 will only contain one set of parameters. When the highlights are
15294 removed (for example with `C-c C-c', or with the next edit (depending
15295 on `org-remove-highlights-with-change'), this variable is emptied
15296 as well.")
15297 (make-variable-buffer-local 'org-occur-parameters)
15298
15299 (defun org-occur (regexp &optional keep-previous callback)
15300 "Make a compact tree which shows all matches of REGEXP.
15301 The tree will show the lines where the regexp matches, and all higher
15302 headlines above the match. It will also show the heading after the match,
15303 to make sure editing the matching entry is easy.
15304 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15305 call to `org-occur' will be kept, to allow stacking of calls to this
15306 command.
15307 If CALLBACK is non-nil, it is a function which is called to confirm
15308 that the match should indeed be shown."
15309 (interactive "sRegexp: \nP")
15310 (unless keep-previous
15311 (org-remove-occur-highlights nil nil t))
15312 (push (cons regexp callback) org-occur-parameters)
15313 (let ((cnt 0))
15314 (save-excursion
15315 (goto-char (point-min))
15316 (if (or (not keep-previous) ; do not want to keep
15317 (not org-occur-highlights)) ; no previous matches
15318 ;; hide everything
15319 (org-overview))
15320 (while (re-search-forward regexp nil t)
15321 (when (or (not callback)
15322 (save-match-data (funcall callback)))
15323 (setq cnt (1+ cnt))
15324 (when org-highlight-sparse-tree-matches
15325 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15326 (org-show-context 'occur-tree))))
15327 (when org-remove-highlights-with-change
15328 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15329 nil 'local))
15330 (unless org-sparse-tree-open-archived-trees
15331 (org-hide-archived-subtrees (point-min) (point-max)))
15332 (run-hooks 'org-occur-hook)
15333 (if (interactive-p)
15334 (message "%d match(es) for regexp %s" cnt regexp))
15335 cnt))
15336
15337 (defun org-show-context (&optional key)
15338 "Make sure point and context and visible.
15339 How much context is shown depends upon the variables
15340 `org-show-hierarchy-above', `org-show-following-heading'. and
15341 `org-show-siblings'."
15342 (let ((heading-p (org-on-heading-p t))
15343 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15344 (following-p (org-get-alist-option org-show-following-heading key))
15345 (entry-p (org-get-alist-option org-show-entry-below key))
15346 (siblings-p (org-get-alist-option org-show-siblings key)))
15347 (catch 'exit
15348 ;; Show heading or entry text
15349 (if (and heading-p (not entry-p))
15350 (org-flag-heading nil) ; only show the heading
15351 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15352 (org-show-hidden-entry))) ; show entire entry
15353 (when following-p
15354 ;; Show next sibling, or heading below text
15355 (save-excursion
15356 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15357 (org-flag-heading nil))))
15358 (when siblings-p (org-show-siblings))
15359 (when hierarchy-p
15360 ;; show all higher headings, possibly with siblings
15361 (save-excursion
15362 (while (and (condition-case nil
15363 (progn (org-up-heading-all 1) t)
15364 (error nil))
15365 (not (bobp)))
15366 (org-flag-heading nil)
15367 (when siblings-p (org-show-siblings))))))))
15368
15369 (defun org-reveal (&optional siblings)
15370 "Show current entry, hierarchy above it, and the following headline.
15371 This can be used to show a consistent set of context around locations
15372 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15373 not t for the search context.
15374
15375 With optional argument SIBLINGS, on each level of the hierarchy all
15376 siblings are shown. This repairs the tree structure to what it would
15377 look like when opened with hierarchical calls to `org-cycle'."
15378 (interactive "P")
15379 (let ((org-show-hierarchy-above t)
15380 (org-show-following-heading t)
15381 (org-show-siblings (if siblings t org-show-siblings)))
15382 (org-show-context nil)))
15383
15384 (defun org-highlight-new-match (beg end)
15385 "Highlight from BEG to END and mark the highlight is an occur headline."
15386 (let ((ov (org-make-overlay beg end)))
15387 (org-overlay-put ov 'face 'secondary-selection)
15388 (push ov org-occur-highlights)))
15389
15390 (defun org-remove-occur-highlights (&optional beg end noremove)
15391 "Remove the occur highlights from the buffer.
15392 BEG and END are ignored. If NOREMOVE is nil, remove this function
15393 from the `before-change-functions' in the current buffer."
15394 (interactive)
15395 (unless org-inhibit-highlight-removal
15396 (mapc 'org-delete-overlay org-occur-highlights)
15397 (setq org-occur-highlights nil)
15398 (setq org-occur-parameters nil)
15399 (unless noremove
15400 (remove-hook 'before-change-functions
15401 'org-remove-occur-highlights 'local))))
15402
15403 ;;;; Priorities
15404
15405 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15406 "Regular expression matching the priority indicator.")
15407
15408 (defvar org-remove-priority-next-time nil)
15409
15410 (defun org-priority-up ()
15411 "Increase the priority of the current item."
15412 (interactive)
15413 (org-priority 'up))
15414
15415 (defun org-priority-down ()
15416 "Decrease the priority of the current item."
15417 (interactive)
15418 (org-priority 'down))
15419
15420 (defun org-priority (&optional action)
15421 "Change the priority of an item by ARG.
15422 ACTION can be `set', `up', `down', or a character."
15423 (interactive)
15424 (setq action (or action 'set))
15425 (let (current new news have remove)
15426 (save-excursion
15427 (org-back-to-heading)
15428 (if (looking-at org-priority-regexp)
15429 (setq current (string-to-char (match-string 2))
15430 have t)
15431 (setq current org-default-priority))
15432 (cond
15433 ((or (eq action 'set) (integerp action))
15434 (if (integerp action)
15435 (setq new action)
15436 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15437 (setq new (read-char-exclusive)))
15438 (if (and (= (upcase org-highest-priority) org-highest-priority)
15439 (= (upcase org-lowest-priority) org-lowest-priority))
15440 (setq new (upcase new)))
15441 (cond ((equal new ?\ ) (setq remove t))
15442 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15443 (error "Priority must be between `%c' and `%c'"
15444 org-highest-priority org-lowest-priority))))
15445 ((eq action 'up)
15446 (if (and (not have) (eq last-command this-command))
15447 (setq new org-lowest-priority)
15448 (setq new (if (and org-priority-start-cycle-with-default (not have))
15449 org-default-priority (1- current)))))
15450 ((eq action 'down)
15451 (if (and (not have) (eq last-command this-command))
15452 (setq new org-highest-priority)
15453 (setq new (if (and org-priority-start-cycle-with-default (not have))
15454 org-default-priority (1+ current)))))
15455 (t (error "Invalid action")))
15456 (if (or (< (upcase new) org-highest-priority)
15457 (> (upcase new) org-lowest-priority))
15458 (setq remove t))
15459 (setq news (format "%c" new))
15460 (if have
15461 (if remove
15462 (replace-match "" t t nil 1)
15463 (replace-match news t t nil 2))
15464 (if remove
15465 (error "No priority cookie found in line")
15466 (looking-at org-todo-line-regexp)
15467 (if (match-end 2)
15468 (progn
15469 (goto-char (match-end 2))
15470 (insert " [#" news "]"))
15471 (goto-char (match-beginning 3))
15472 (insert "[#" news "] ")))))
15473 (org-preserve-lc (org-set-tags nil 'align))
15474 (if remove
15475 (message "Priority removed")
15476 (message "Priority of current item set to %s" news))))
15477
15478
15479 (defun org-get-priority (s)
15480 "Find priority cookie and return priority."
15481 (save-match-data
15482 (if (not (string-match org-priority-regexp s))
15483 (* 1000 (- org-lowest-priority org-default-priority))
15484 (* 1000 (- org-lowest-priority
15485 (string-to-char (match-string 2 s)))))))
15486
15487 ;;;; Tags
15488
15489 (defun org-scan-tags (action matcher &optional todo-only)
15490 "Scan headline tags with inheritance and produce output ACTION.
15491 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15492 evaluated, testing if a given set of tags qualifies a headline for
15493 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15494 are included in the output."
15495 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15496 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15497 (org-re
15498 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15499 (props (list 'face nil
15500 'done-face 'org-done
15501 'undone-face nil
15502 'mouse-face 'highlight
15503 'org-not-done-regexp org-not-done-regexp
15504 'org-todo-regexp org-todo-regexp
15505 'keymap org-agenda-keymap
15506 'help-echo
15507 (format "mouse-2 or RET jump to org file %s"
15508 (abbreviate-file-name
15509 (or (buffer-file-name (buffer-base-buffer))
15510 (buffer-name (buffer-base-buffer)))))))
15511 (case-fold-search nil)
15512 lspos
15513 tags tags-list tags-alist (llast 0) rtn level category i txt
15514 todo marker entry priority)
15515 (save-excursion
15516 (goto-char (point-min))
15517 (when (eq action 'sparse-tree)
15518 (org-overview)
15519 (org-remove-occur-highlights))
15520 (while (re-search-forward re nil t)
15521 (catch :skip
15522 (setq todo (if (match-end 1) (match-string 2))
15523 tags (if (match-end 4) (match-string 4)))
15524 (goto-char (setq lspos (1+ (match-beginning 0))))
15525 (setq level (org-reduced-level (funcall outline-level))
15526 category (org-get-category))
15527 (setq i llast llast level)
15528 ;; remove tag lists from same and sublevels
15529 (while (>= i level)
15530 (when (setq entry (assoc i tags-alist))
15531 (setq tags-alist (delete entry tags-alist)))
15532 (setq i (1- i)))
15533 ;; add the nex tags
15534 (when tags
15535 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15536 tags-alist
15537 (cons (cons level tags) tags-alist)))
15538 ;; compile tags for current headline
15539 (setq tags-list
15540 (if org-use-tag-inheritance
15541 (apply 'append (mapcar 'cdr tags-alist))
15542 tags))
15543 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15544 (eval matcher)
15545 (or (not org-agenda-skip-archived-trees)
15546 (not (member org-archive-tag tags-list))))
15547 (and (eq action 'agenda) (org-agenda-skip))
15548 ;; list this headline
15549
15550 (if (eq action 'sparse-tree)
15551 (progn
15552 (and org-highlight-sparse-tree-matches
15553 (org-get-heading) (match-end 0)
15554 (org-highlight-new-match
15555 (match-beginning 0) (match-beginning 1)))
15556 (org-show-context 'tags-tree))
15557 (setq txt (org-format-agenda-item
15558 ""
15559 (concat
15560 (if org-tags-match-list-sublevels
15561 (make-string (1- level) ?.) "")
15562 (org-get-heading))
15563 category tags-list)
15564 priority (org-get-priority txt))
15565 (goto-char lspos)
15566 (setq marker (org-agenda-new-marker))
15567 (org-add-props txt props
15568 'org-marker marker 'org-hd-marker marker 'org-category category
15569 'priority priority 'type "tagsmatch")
15570 (push txt rtn))
15571 ;; if we are to skip sublevels, jump to end of subtree
15572 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15573 (when (and (eq action 'sparse-tree)
15574 (not org-sparse-tree-open-archived-trees))
15575 (org-hide-archived-subtrees (point-min) (point-max)))
15576 (nreverse rtn)))
15577
15578 (defvar todo-only) ;; dynamically scoped
15579
15580 (defun org-tags-sparse-tree (&optional todo-only match)
15581 "Create a sparse tree according to tags string MATCH.
15582 MATCH can contain positive and negative selection of tags, like
15583 \"+WORK+URGENT-WITHBOSS\".
15584 If optional argument TODO_ONLY is non-nil, only select lines that are
15585 also TODO lines."
15586 (interactive "P")
15587 (org-prepare-agenda-buffers (list (current-buffer)))
15588 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15589
15590 (defvar org-cached-props nil)
15591 (defun org-cached-entry-get (pom property)
15592 (if (or (eq t org-use-property-inheritance)
15593 (member property org-use-property-inheritance))
15594 ;; Caching is not possible, check it directly
15595 (org-entry-get pom property 'inherit)
15596 ;; Get all properties, so that we can do complicated checks easily
15597 (cdr (assoc property (or org-cached-props
15598 (setq org-cached-props
15599 (org-entry-properties pom)))))))
15600
15601 (defun org-global-tags-completion-table (&optional files)
15602 "Return the list of all tags in all agenda buffer/files."
15603 (save-excursion
15604 (org-uniquify
15605 (delq nil
15606 (apply 'append
15607 (mapcar
15608 (lambda (file)
15609 (set-buffer (find-file-noselect file))
15610 (append (org-get-buffer-tags)
15611 (mapcar (lambda (x) (if (stringp (car-safe x))
15612 (list (car-safe x)) nil))
15613 org-tag-alist)))
15614 (if (and files (car files))
15615 files
15616 (org-agenda-files))))))))
15617
15618 (defun org-make-tags-matcher (match)
15619 "Create the TAGS//TODO matcher form for the selection string MATCH."
15620 ;; todo-only is scoped dynamically into this function, and the function
15621 ;; may change it it the matcher asksk for it.
15622 (unless match
15623 ;; Get a new match request, with completion
15624 (let ((org-last-tags-completion-table
15625 (org-global-tags-completion-table)))
15626 (setq match (completing-read
15627 "Match: " 'org-tags-completion-function nil nil nil
15628 'org-tags-history))))
15629
15630 ;; Parse the string and create a lisp form
15631 (let ((match0 match)
15632 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15633 minus tag mm
15634 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15635 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15636 (if (string-match "/+" match)
15637 ;; match contains also a todo-matching request
15638 (progn
15639 (setq tagsmatch (substring match 0 (match-beginning 0))
15640 todomatch (substring match (match-end 0)))
15641 (if (string-match "^!" todomatch)
15642 (setq todo-only t todomatch (substring todomatch 1)))
15643 (if (string-match "^\\s-*$" todomatch)
15644 (setq todomatch nil)))
15645 ;; only matching tags
15646 (setq tagsmatch match todomatch nil))
15647
15648 ;; Make the tags matcher
15649 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15650 (setq tagsmatcher t)
15651 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15652 (while (setq term (pop orterms))
15653 (while (and (equal (substring term -1) "\\") orterms)
15654 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15655 (while (string-match re term)
15656 (setq minus (and (match-end 1)
15657 (equal (match-string 1 term) "-"))
15658 tag (match-string 2 term)
15659 re-p (equal (string-to-char tag) ?{)
15660 level-p (match-end 3)
15661 prop-p (match-end 4)
15662 mm (cond
15663 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15664 (level-p `(= level ,(string-to-number
15665 (match-string 3 term))))
15666 (prop-p
15667 (setq pn (match-string 4 term)
15668 pv (match-string 5 term)
15669 cat-p (equal pn "CATEGORY")
15670 re-p (equal (string-to-char pv) ?{)
15671 pv (substring pv 1 -1))
15672 (if (equal pn "CATEGORY")
15673 (setq gv '(get-text-property (point) 'org-category))
15674 (setq gv `(org-cached-entry-get nil ,pn)))
15675 (if re-p
15676 `(string-match ,pv (or ,gv ""))
15677 `(equal ,pv (or ,gv ""))))
15678 (t `(member ,(downcase tag) tags-list)))
15679 mm (if minus (list 'not mm) mm)
15680 term (substring term (match-end 0)))
15681 (push mm tagsmatcher))
15682 (push (if (> (length tagsmatcher) 1)
15683 (cons 'and tagsmatcher)
15684 (car tagsmatcher))
15685 orlist)
15686 (setq tagsmatcher nil))
15687 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15688 (setq tagsmatcher
15689 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15690
15691 ;; Make the todo matcher
15692 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15693 (setq todomatcher t)
15694 (setq orterms (org-split-string todomatch "|") orlist nil)
15695 (while (setq term (pop orterms))
15696 (while (string-match re term)
15697 (setq minus (and (match-end 1)
15698 (equal (match-string 1 term) "-"))
15699 kwd (match-string 2 term)
15700 re-p (equal (string-to-char kwd) ?{)
15701 term (substring term (match-end 0))
15702 mm (if re-p
15703 `(string-match ,(substring kwd 1 -1) todo)
15704 (list 'equal 'todo kwd))
15705 mm (if minus (list 'not mm) mm))
15706 (push mm todomatcher))
15707 (push (if (> (length todomatcher) 1)
15708 (cons 'and todomatcher)
15709 (car todomatcher))
15710 orlist)
15711 (setq todomatcher nil))
15712 (setq todomatcher (if (> (length orlist) 1)
15713 (cons 'or orlist) (car orlist))))
15714
15715 ;; Return the string and lisp forms of the matcher
15716 (setq matcher (if todomatcher
15717 (list 'and tagsmatcher todomatcher)
15718 tagsmatcher))
15719 (cons match0 matcher)))
15720
15721 (defun org-match-any-p (re list)
15722 "Does re match any element of list?"
15723 (setq list (mapcar (lambda (x) (string-match re x)) list))
15724 (delq nil list))
15725
15726 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15727 (defvar org-tags-overlay (org-make-overlay 1 1))
15728 (org-detach-overlay org-tags-overlay)
15729
15730 (defun org-align-tags-here (to-col)
15731 ;; Assumes that this is a headline
15732 (let ((pos (point)) (col (current-column)) tags)
15733 (beginning-of-line 1)
15734 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15735 (< pos (match-beginning 2)))
15736 (progn
15737 (setq tags (match-string 2))
15738 (goto-char (match-beginning 1))
15739 (insert " ")
15740 (delete-region (point) (1+ (match-end 0)))
15741 (backward-char 1)
15742 (move-to-column
15743 (max (1+ (current-column))
15744 (1+ col)
15745 (if (> to-col 0)
15746 to-col
15747 (- (abs to-col) (length tags))))
15748 t)
15749 (insert tags)
15750 (move-to-column (min (current-column) col) t))
15751 (goto-char pos))))
15752
15753 (defun org-set-tags (&optional arg just-align)
15754 "Set the tags for the current headline.
15755 With prefix ARG, realign all tags in headings in the current buffer."
15756 (interactive "P")
15757 (let* ((re (concat "^" outline-regexp))
15758 (current (org-get-tags-string))
15759 (col (current-column))
15760 (org-setting-tags t)
15761 table current-tags inherited-tags ; computed below when needed
15762 tags p0 c0 c1 rpl)
15763 (if arg
15764 (save-excursion
15765 (goto-char (point-min))
15766 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15767 (while (re-search-forward re nil t)
15768 (org-set-tags nil t)
15769 (end-of-line 1)))
15770 (message "All tags realigned to column %d" org-tags-column))
15771 (if just-align
15772 (setq tags current)
15773 ;; Get a new set of tags from the user
15774 (save-excursion
15775 (setq table (or org-tag-alist (org-get-buffer-tags))
15776 org-last-tags-completion-table table
15777 current-tags (org-split-string current ":")
15778 inherited-tags (nreverse
15779 (nthcdr (length current-tags)
15780 (nreverse (org-get-tags-at))))
15781 tags
15782 (if (or (eq t org-use-fast-tag-selection)
15783 (and org-use-fast-tag-selection
15784 (delq nil (mapcar 'cdr table))))
15785 (org-fast-tag-selection
15786 current-tags inherited-tags table
15787 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15788 (let ((org-add-colon-after-tag-completion t))
15789 (org-trim
15790 (org-without-partial-completion
15791 (completing-read "Tags: " 'org-tags-completion-function
15792 nil nil current 'org-tags-history)))))))
15793 (while (string-match "[-+&]+" tags)
15794 ;; No boolean logic, just a list
15795 (setq tags (replace-match ":" t t tags))))
15796
15797 (if (string-match "\\`[\t ]*\\'" tags)
15798 (setq tags "")
15799 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15800 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15801
15802 ;; Insert new tags at the correct column
15803 (beginning-of-line 1)
15804 (cond
15805 ((and (equal current "") (equal tags "")))
15806 ((re-search-forward
15807 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15808 (point-at-eol) t)
15809 (if (equal tags "")
15810 (setq rpl "")
15811 (goto-char (match-beginning 0))
15812 (setq c0 (current-column) p0 (point)
15813 c1 (max (1+ c0) (if (> org-tags-column 0)
15814 org-tags-column
15815 (- (- org-tags-column) (length tags))))
15816 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15817 (replace-match rpl t t)
15818 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15819 tags)
15820 (t (error "Tags alignment failed")))
15821 (move-to-column col)
15822 (unless just-align
15823 (run-hooks 'org-after-tags-change-hook)))))
15824
15825 (defun org-change-tag-in-region (beg end tag off)
15826 "Add or remove TAG for each entry in the region.
15827 This works in the agenda, and also in an org-mode buffer."
15828 (interactive
15829 (list (region-beginning) (region-end)
15830 (let ((org-last-tags-completion-table
15831 (if (org-mode-p)
15832 (org-get-buffer-tags)
15833 (org-global-tags-completion-table))))
15834 (completing-read
15835 "Tag: " 'org-tags-completion-function nil nil nil
15836 'org-tags-history))
15837 (progn
15838 (message "[s]et or [r]emove? ")
15839 (equal (read-char-exclusive) ?r))))
15840 (if (fboundp 'deactivate-mark) (deactivate-mark))
15841 (let ((agendap (equal major-mode 'org-agenda-mode))
15842 l1 l2 m buf pos newhead (cnt 0))
15843 (goto-char end)
15844 (setq l2 (1- (org-current-line)))
15845 (goto-char beg)
15846 (setq l1 (org-current-line))
15847 (loop for l from l1 to l2 do
15848 (goto-line l)
15849 (setq m (get-text-property (point) 'org-hd-marker))
15850 (when (or (and (org-mode-p) (org-on-heading-p))
15851 (and agendap m))
15852 (setq buf (if agendap (marker-buffer m) (current-buffer))
15853 pos (if agendap m (point)))
15854 (with-current-buffer buf
15855 (save-excursion
15856 (save-restriction
15857 (goto-char pos)
15858 (setq cnt (1+ cnt))
15859 (org-toggle-tag tag (if off 'off 'on))
15860 (setq newhead (org-get-heading)))))
15861 (and agendap (org-agenda-change-all-lines newhead m))))
15862 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15863
15864 (defun org-tags-completion-function (string predicate &optional flag)
15865 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15866 (confirm (lambda (x) (stringp (car x)))))
15867 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15868 (setq s1 (match-string 1 string)
15869 s2 (match-string 2 string))
15870 (setq s1 "" s2 string))
15871 (cond
15872 ((eq flag nil)
15873 ;; try completion
15874 (setq rtn (try-completion s2 ctable confirm))
15875 (if (stringp rtn)
15876 (setq rtn
15877 (concat s1 s2 (substring rtn (length s2))
15878 (if (and org-add-colon-after-tag-completion
15879 (assoc rtn ctable))
15880 ":" ""))))
15881 rtn)
15882 ((eq flag t)
15883 ;; all-completions
15884 (all-completions s2 ctable confirm)
15885 )
15886 ((eq flag 'lambda)
15887 ;; exact match?
15888 (assoc s2 ctable)))
15889 ))
15890
15891 (defun org-fast-tag-insert (kwd tags face &optional end)
15892 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15893 (insert (format "%-12s" (concat kwd ":"))
15894 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15895 (or end "")))
15896
15897 (defun org-fast-tag-show-exit (flag)
15898 (save-excursion
15899 (goto-line 3)
15900 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15901 (replace-match ""))
15902 (when flag
15903 (end-of-line 1)
15904 (move-to-column (- (window-width) 19) t)
15905 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15906
15907 (defun org-set-current-tags-overlay (current prefix)
15908 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15909 (if (featurep 'xemacs)
15910 (org-overlay-display org-tags-overlay (concat prefix s)
15911 'secondary-selection)
15912 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15913 (org-overlay-display org-tags-overlay (concat prefix s)))))
15914
15915 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15916 "Fast tag selection with single keys.
15917 CURRENT is the current list of tags in the headline, INHERITED is the
15918 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15919 possibly with grouping information. TODO-TABLE is a similar table with
15920 TODO keywords, should these have keys assigned to them.
15921 If the keys are nil, a-z are automatically assigned.
15922 Returns the new tags string, or nil to not change the current settings."
15923 (let* ((fulltable (append table todo-table))
15924 (maxlen (apply 'max (mapcar
15925 (lambda (x)
15926 (if (stringp (car x)) (string-width (car x)) 0))
15927 fulltable)))
15928 (buf (current-buffer))
15929 (expert (eq org-fast-tag-selection-single-key 'expert))
15930 (buffer-tags nil)
15931 (fwidth (+ maxlen 3 1 3))
15932 (ncol (/ (- (window-width) 4) fwidth))
15933 (i-face 'org-done)
15934 (c-face 'org-todo)
15935 tg cnt e c char c1 c2 ntable tbl rtn
15936 ov-start ov-end ov-prefix
15937 (exit-after-next org-fast-tag-selection-single-key)
15938 (done-keywords org-done-keywords)
15939 groups ingroup)
15940 (save-excursion
15941 (beginning-of-line 1)
15942 (if (looking-at
15943 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15944 (setq ov-start (match-beginning 1)
15945 ov-end (match-end 1)
15946 ov-prefix "")
15947 (setq ov-start (1- (point-at-eol))
15948 ov-end (1+ ov-start))
15949 (skip-chars-forward "^\n\r")
15950 (setq ov-prefix
15951 (concat
15952 (buffer-substring (1- (point)) (point))
15953 (if (> (current-column) org-tags-column)
15954 " "
15955 (make-string (- org-tags-column (current-column)) ?\ ))))))
15956 (org-move-overlay org-tags-overlay ov-start ov-end)
15957 (save-window-excursion
15958 (if expert
15959 (set-buffer (get-buffer-create " *Org tags*"))
15960 (delete-other-windows)
15961 (split-window-vertically)
15962 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15963 (erase-buffer)
15964 (org-set-local 'org-done-keywords done-keywords)
15965 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15966 (org-fast-tag-insert "Current" current c-face "\n\n")
15967 (org-fast-tag-show-exit exit-after-next)
15968 (org-set-current-tags-overlay current ov-prefix)
15969 (setq tbl fulltable char ?a cnt 0)
15970 (while (setq e (pop tbl))
15971 (cond
15972 ((equal e '(:startgroup))
15973 (push '() groups) (setq ingroup t)
15974 (when (not (= cnt 0))
15975 (setq cnt 0)
15976 (insert "\n"))
15977 (insert "{ "))
15978 ((equal e '(:endgroup))
15979 (setq ingroup nil cnt 0)
15980 (insert "}\n"))
15981 (t
15982 (setq tg (car e) c2 nil)
15983 (if (cdr e)
15984 (setq c (cdr e))
15985 ;; automatically assign a character.
15986 (setq c1 (string-to-char
15987 (downcase (substring
15988 tg (if (= (string-to-char tg) ?@) 1 0)))))
15989 (if (or (rassoc c1 ntable) (rassoc c1 table))
15990 (while (or (rassoc char ntable) (rassoc char table))
15991 (setq char (1+ char)))
15992 (setq c2 c1))
15993 (setq c (or c2 char)))
15994 (if ingroup (push tg (car groups)))
15995 (setq tg (org-add-props tg nil 'face
15996 (cond
15997 ((not (assoc tg table))
15998 (org-get-todo-face tg))
15999 ((member tg current) c-face)
16000 ((member tg inherited) i-face)
16001 (t nil))))
16002 (if (and (= cnt 0) (not ingroup)) (insert " "))
16003 (insert "[" c "] " tg (make-string
16004 (- fwidth 4 (length tg)) ?\ ))
16005 (push (cons tg c) ntable)
16006 (when (= (setq cnt (1+ cnt)) ncol)
16007 (insert "\n")
16008 (if ingroup (insert " "))
16009 (setq cnt 0)))))
16010 (setq ntable (nreverse ntable))
16011 (insert "\n")
16012 (goto-char (point-min))
16013 (if (and (not expert) (fboundp 'fit-window-to-buffer))
16014 (fit-window-to-buffer))
16015 (setq rtn
16016 (catch 'exit
16017 (while t
16018 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
16019 (if groups " [!] no groups" " [!]groups")
16020 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
16021 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
16022 (cond
16023 ((= c ?\r) (throw 'exit t))
16024 ((= c ?!)
16025 (setq groups (not groups))
16026 (goto-char (point-min))
16027 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
16028 ((= c ?\C-c)
16029 (if (not expert)
16030 (org-fast-tag-show-exit
16031 (setq exit-after-next (not exit-after-next)))
16032 (setq expert nil)
16033 (delete-other-windows)
16034 (split-window-vertically)
16035 (org-switch-to-buffer-other-window " *Org tags*")
16036 (and (fboundp 'fit-window-to-buffer)
16037 (fit-window-to-buffer))))
16038 ((or (= c ?\C-g)
16039 (and (= c ?q) (not (rassoc c ntable))))
16040 (org-detach-overlay org-tags-overlay)
16041 (setq quit-flag t))
16042 ((= c ?\ )
16043 (setq current nil)
16044 (if exit-after-next (setq exit-after-next 'now)))
16045 ((= c ?\t)
16046 (condition-case nil
16047 (setq tg (completing-read
16048 "Tag: "
16049 (or buffer-tags
16050 (with-current-buffer buf
16051 (org-get-buffer-tags)))))
16052 (quit (setq tg "")))
16053 (when (string-match "\\S-" tg)
16054 (add-to-list 'buffer-tags (list tg))
16055 (if (member tg current)
16056 (setq current (delete tg current))
16057 (push tg current)))
16058 (if exit-after-next (setq exit-after-next 'now)))
16059 ((setq e (rassoc c todo-table) tg (car e))
16060 (with-current-buffer buf
16061 (save-excursion (org-todo tg)))
16062 (if exit-after-next (setq exit-after-next 'now)))
16063 ((setq e (rassoc c ntable) tg (car e))
16064 (if (member tg current)
16065 (setq current (delete tg current))
16066 (loop for g in groups do
16067 (if (member tg g)
16068 (mapc (lambda (x)
16069 (setq current (delete x current)))
16070 g)))
16071 (push tg current))
16072 (if exit-after-next (setq exit-after-next 'now))))
16073
16074 ;; Create a sorted list
16075 (setq current
16076 (sort current
16077 (lambda (a b)
16078 (assoc b (cdr (memq (assoc a ntable) ntable))))))
16079 (if (eq exit-after-next 'now) (throw 'exit t))
16080 (goto-char (point-min))
16081 (beginning-of-line 2)
16082 (delete-region (point) (point-at-eol))
16083 (org-fast-tag-insert "Current" current c-face)
16084 (org-set-current-tags-overlay current ov-prefix)
16085 (while (re-search-forward
16086 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
16087 (setq tg (match-string 1))
16088 (add-text-properties
16089 (match-beginning 1) (match-end 1)
16090 (list 'face
16091 (cond
16092 ((member tg current) c-face)
16093 ((member tg inherited) i-face)
16094 (t (get-text-property (match-beginning 1) 'face))))))
16095 (goto-char (point-min)))))
16096 (org-detach-overlay org-tags-overlay)
16097 (if rtn
16098 (mapconcat 'identity current ":")
16099 nil))))
16100
16101 (defun org-get-tags-string ()
16102 "Get the TAGS string in the current headline."
16103 (unless (org-on-heading-p t)
16104 (error "Not on a heading"))
16105 (save-excursion
16106 (beginning-of-line 1)
16107 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16108 (org-match-string-no-properties 1)
16109 "")))
16110
16111 (defun org-get-tags ()
16112 "Get the list of tags specified in the current headline."
16113 (org-split-string (org-get-tags-string) ":"))
16114
16115 (defun org-get-buffer-tags ()
16116 "Get a table of all tags used in the buffer, for completion."
16117 (let (tags)
16118 (save-excursion
16119 (goto-char (point-min))
16120 (while (re-search-forward
16121 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
16122 (when (equal (char-after (point-at-bol 0)) ?*)
16123 (mapc (lambda (x) (add-to-list 'tags x))
16124 (org-split-string (org-match-string-no-properties 1) ":")))))
16125 (mapcar 'list tags)))
16126
16127
16128 ;;;; Properties
16129
16130 ;;; Setting and retrieving properties
16131
16132 (defconst org-special-properties
16133 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
16134 "TIMESTAMP" "TIMESTAMP_IA")
16135 "The special properties valid in Org-mode.
16136
16137 These are properties that are not defined in the property drawer,
16138 but in some other way.")
16139
16140 (defconst org-default-properties
16141 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
16142 "LOCATION" "LOGGING" "COLUMNS")
16143 "Some properties that are used by Org-mode for various purposes.
16144 Being in this list makes sure that they are offered for completion.")
16145
16146 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
16147 "Regular expression matching the first line of a property drawer.")
16148
16149 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
16150 "Regular expression matching the first line of a property drawer.")
16151
16152 (defun org-property-action ()
16153 "Do an action on properties."
16154 (interactive)
16155 (let (c)
16156 (org-at-property-p)
16157 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
16158 (setq c (read-char-exclusive))
16159 (cond
16160 ((equal c ?s)
16161 (call-interactively 'org-set-property))
16162 ((equal c ?d)
16163 (call-interactively 'org-delete-property))
16164 ((equal c ?D)
16165 (call-interactively 'org-delete-property-globally))
16166 ((equal c ?c)
16167 (call-interactively 'org-compute-property-at-point))
16168 (t (error "No such property action %c" c)))))
16169
16170 (defun org-at-property-p ()
16171 "Is the cursor in a property line?"
16172 ;; FIXME: Does not check if we are actually in the drawer.
16173 ;; FIXME: also returns true on any drawers.....
16174 ;; This is used by C-c C-c for property action.
16175 (save-excursion
16176 (beginning-of-line 1)
16177 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
16178
16179 (defmacro org-with-point-at (pom &rest body)
16180 "Move to buffer and point of point-or-marker POM for the duration of BODY."
16181 (declare (indent 1) (debug t))
16182 `(save-excursion
16183 (if (markerp pom) (set-buffer (marker-buffer pom)))
16184 (save-excursion
16185 (goto-char (or pom (point)))
16186 ,@body)))
16187
16188 (defun org-get-property-block (&optional beg end force)
16189 "Return the (beg . end) range of the body of the property drawer.
16190 BEG and END can be beginning and end of subtree, if not given
16191 they will be found.
16192 If the drawer does not exist and FORCE is non-nil, create the drawer."
16193 (catch 'exit
16194 (save-excursion
16195 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
16196 (end (or end (progn (outline-next-heading) (point)))))
16197 (goto-char beg)
16198 (if (re-search-forward org-property-start-re end t)
16199 (setq beg (1+ (match-end 0)))
16200 (if force
16201 (save-excursion
16202 (org-insert-property-drawer)
16203 (setq end (progn (outline-next-heading) (point))))
16204 (throw 'exit nil))
16205 (goto-char beg)
16206 (if (re-search-forward org-property-start-re end t)
16207 (setq beg (1+ (match-end 0)))))
16208 (if (re-search-forward org-property-end-re end t)
16209 (setq end (match-beginning 0))
16210 (or force (throw 'exit nil))
16211 (goto-char beg)
16212 (setq end beg)
16213 (org-indent-line-function)
16214 (insert ":END:\n"))
16215 (cons beg end)))))
16216
16217 (defun org-entry-properties (&optional pom which)
16218 "Get all properties of the entry at point-or-marker POM.
16219 This includes the TODO keyword, the tags, time strings for deadline,
16220 scheduled, and clocking, and any additional properties defined in the
16221 entry. The return value is an alist, keys may occur multiple times
16222 if the property key was used several times.
16223 POM may also be nil, in which case the current entry is used.
16224 If WHICH is nil or `all', get all properties. If WHICH is
16225 `special' or `standard', only get that subclass."
16226 (setq which (or which 'all))
16227 (org-with-point-at pom
16228 (let ((clockstr (substring org-clock-string 0 -1))
16229 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
16230 beg end range props sum-props key value string clocksum)
16231 (save-excursion
16232 (when (condition-case nil (org-back-to-heading t) (error nil))
16233 (setq beg (point))
16234 (setq sum-props (get-text-property (point) 'org-summaries))
16235 (setq clocksum (get-text-property (point) :org-clock-minutes))
16236 (outline-next-heading)
16237 (setq end (point))
16238 (when (memq which '(all special))
16239 ;; Get the special properties, like TODO and tags
16240 (goto-char beg)
16241 (when (and (looking-at org-todo-line-regexp) (match-end 2))
16242 (push (cons "TODO" (org-match-string-no-properties 2)) props))
16243 (when (looking-at org-priority-regexp)
16244 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16245 (when (and (setq value (org-get-tags-string))
16246 (string-match "\\S-" value))
16247 (push (cons "TAGS" value) props))
16248 (when (setq value (org-get-tags-at))
16249 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16250 props))
16251 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16252 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16253 string (if (equal key clockstr)
16254 (org-no-properties
16255 (org-trim
16256 (buffer-substring
16257 (match-beginning 3) (goto-char (point-at-eol)))))
16258 (substring (org-match-string-no-properties 3) 1 -1)))
16259 (unless key
16260 (if (= (char-after (match-beginning 3)) ?\[)
16261 (setq key "TIMESTAMP_IA")
16262 (setq key "TIMESTAMP")))
16263 (when (or (equal key clockstr) (not (assoc key props)))
16264 (push (cons key string) props)))
16265
16266 )
16267
16268 (when (memq which '(all standard))
16269 ;; Get the standard properties, like :PORP: ...
16270 (setq range (org-get-property-block beg end))
16271 (when range
16272 (goto-char (car range))
16273 (while (re-search-forward
16274 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16275 (cdr range) t)
16276 (setq key (org-match-string-no-properties 1)
16277 value (org-trim (or (org-match-string-no-properties 2) "")))
16278 (unless (member key excluded)
16279 (push (cons key (or value "")) props)))))
16280 (if clocksum
16281 (push (cons "CLOCKSUM"
16282 (org-column-number-to-string (/ (float clocksum) 60.)
16283 'add_times))
16284 props))
16285 (append sum-props (nreverse props)))))))
16286
16287 (defun org-entry-get (pom property &optional inherit)
16288 "Get value of PROPERTY for entry at point-or-marker POM.
16289 If INHERIT is non-nil and the entry does not have the property,
16290 then also check higher levels of the hierarchy.
16291 If the property is present but empty, the return value is the empty string.
16292 If the property is not present at all, nil is returned."
16293 (org-with-point-at pom
16294 (if inherit
16295 (org-entry-get-with-inheritance property)
16296 (if (member property org-special-properties)
16297 ;; We need a special property. Use brute force, get all properties.
16298 (cdr (assoc property (org-entry-properties nil 'special)))
16299 (let ((range (org-get-property-block)))
16300 (if (and range
16301 (goto-char (car range))
16302 (re-search-forward
16303 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16304 (cdr range) t))
16305 ;; Found the property, return it.
16306 (if (match-end 1)
16307 (org-match-string-no-properties 1)
16308 "")))))))
16309
16310 (defun org-entry-delete (pom property)
16311 "Delete the property PROPERTY from entry at point-or-marker POM."
16312 (org-with-point-at pom
16313 (if (member property org-special-properties)
16314 nil ; cannot delete these properties.
16315 (let ((range (org-get-property-block)))
16316 (if (and range
16317 (goto-char (car range))
16318 (re-search-forward
16319 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16320 (cdr range) t))
16321 (progn
16322 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16323 t)
16324 nil)))))
16325
16326 ;; Multi-values properties are properties that contain multiple values
16327 ;; These values are assumed to be single words, separated by whitespace.
16328 (defun org-entry-add-to-multivalued-property (pom property value)
16329 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16330 (let* ((old (org-entry-get pom property))
16331 (values (and old (org-split-string old "[ \t]"))))
16332 (unless (member value values)
16333 (setq values (cons value values))
16334 (org-entry-put pom property
16335 (mapconcat 'identity values " ")))))
16336
16337 (defun org-entry-remove-from-multivalued-property (pom property value)
16338 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16339 (let* ((old (org-entry-get pom property))
16340 (values (and old (org-split-string old "[ \t]"))))
16341 (when (member value values)
16342 (setq values (delete value values))
16343 (org-entry-put pom property
16344 (mapconcat 'identity values " ")))))
16345
16346 (defun org-entry-member-in-multivalued-property (pom property value)
16347 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16348 (let* ((old (org-entry-get pom property))
16349 (values (and old (org-split-string old "[ \t]"))))
16350 (member value values)))
16351
16352 (defvar org-entry-property-inherited-from (make-marker))
16353
16354 (defun org-entry-get-with-inheritance (property)
16355 "Get entry property, and search higher levels if not present."
16356 (let (tmp)
16357 (save-excursion
16358 (save-restriction
16359 (widen)
16360 (catch 'ex
16361 (while t
16362 (when (setq tmp (org-entry-get nil property))
16363 (org-back-to-heading t)
16364 (move-marker org-entry-property-inherited-from (point))
16365 (throw 'ex tmp))
16366 (or (org-up-heading-safe) (throw 'ex nil)))))
16367 (or tmp (cdr (assoc property org-local-properties))
16368 (cdr (assoc property org-global-properties))))))
16369
16370 (defun org-entry-put (pom property value)
16371 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16372 (org-with-point-at pom
16373 (org-back-to-heading t)
16374 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16375 range)
16376 (cond
16377 ((equal property "TODO")
16378 (when (and (stringp value) (string-match "\\S-" value)
16379 (not (member value org-todo-keywords-1)))
16380 (error "\"%s\" is not a valid TODO state" value))
16381 (if (or (not value)
16382 (not (string-match "\\S-" value)))
16383 (setq value 'none))
16384 (org-todo value)
16385 (org-set-tags nil 'align))
16386 ((equal property "PRIORITY")
16387 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16388 (string-to-char value) ?\ ))
16389 (org-set-tags nil 'align))
16390 ((equal property "SCHEDULED")
16391 (if (re-search-forward org-scheduled-time-regexp end t)
16392 (cond
16393 ((eq value 'earlier) (org-timestamp-change -1 'day))
16394 ((eq value 'later) (org-timestamp-change 1 'day))
16395 (t (call-interactively 'org-schedule)))
16396 (call-interactively 'org-schedule)))
16397 ((equal property "DEADLINE")
16398 (if (re-search-forward org-deadline-time-regexp end t)
16399 (cond
16400 ((eq value 'earlier) (org-timestamp-change -1 'day))
16401 ((eq value 'later) (org-timestamp-change 1 'day))
16402 (t (call-interactively 'org-deadline)))
16403 (call-interactively 'org-deadline)))
16404 ((member property org-special-properties)
16405 (error "The %s property can not yet be set with `org-entry-put'"
16406 property))
16407 (t ; a non-special property
16408 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16409 (setq range (org-get-property-block beg end 'force))
16410 (goto-char (car range))
16411 (if (re-search-forward
16412 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16413 (progn
16414 (delete-region (match-beginning 1) (match-end 1))
16415 (goto-char (match-beginning 1)))
16416 (goto-char (cdr range))
16417 (insert "\n")
16418 (backward-char 1)
16419 (org-indent-line-function)
16420 (insert ":" property ":"))
16421 (and value (insert " " value))
16422 (org-indent-line-function)))))))
16423
16424 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16425 "Get all property keys in the current buffer.
16426 With INCLUDE-SPECIALS, also list the special properties that relect things
16427 like tags and TODO state.
16428 With INCLUDE-DEFAULTS, also include properties that has special meaning
16429 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16430 With INCLUDE-COLUMNS, also include property names given in COLUMN
16431 formats in the current buffer."
16432 (let (rtn range cfmt cols s p)
16433 (save-excursion
16434 (save-restriction
16435 (widen)
16436 (goto-char (point-min))
16437 (while (re-search-forward org-property-start-re nil t)
16438 (setq range (org-get-property-block))
16439 (goto-char (car range))
16440 (while (re-search-forward
16441 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16442 (cdr range) t)
16443 (add-to-list 'rtn (org-match-string-no-properties 1)))
16444 (outline-next-heading))))
16445
16446 (when include-specials
16447 (setq rtn (append org-special-properties rtn)))
16448
16449 (when include-defaults
16450 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16451
16452 (when include-columns
16453 (save-excursion
16454 (save-restriction
16455 (widen)
16456 (goto-char (point-min))
16457 (while (re-search-forward
16458 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16459 nil t)
16460 (setq cfmt (match-string 2) s 0)
16461 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16462 cfmt s)
16463 (setq s (match-end 0)
16464 p (match-string 1 cfmt))
16465 (unless (or (equal p "ITEM")
16466 (member p org-special-properties))
16467 (add-to-list 'rtn (match-string 1 cfmt))))))))
16468
16469 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16470
16471 (defun org-property-values (key)
16472 "Return a list of all values of property KEY."
16473 (save-excursion
16474 (save-restriction
16475 (widen)
16476 (goto-char (point-min))
16477 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16478 values)
16479 (while (re-search-forward re nil t)
16480 (add-to-list 'values (org-trim (match-string 1))))
16481 (delete "" values)))))
16482
16483 (defun org-insert-property-drawer ()
16484 "Insert a property drawer into the current entry."
16485 (interactive)
16486 (org-back-to-heading t)
16487 (looking-at outline-regexp)
16488 (let ((indent (- (match-end 0)(match-beginning 0)))
16489 (beg (point))
16490 (re (concat "^[ \t]*" org-keyword-time-regexp))
16491 end hiddenp)
16492 (outline-next-heading)
16493 (setq end (point))
16494 (goto-char beg)
16495 (while (re-search-forward re end t))
16496 (setq hiddenp (org-invisible-p))
16497 (end-of-line 1)
16498 (and (equal (char-after) ?\n) (forward-char 1))
16499 (org-skip-over-state-notes)
16500 (skip-chars-backward " \t\n\r")
16501 (if (eq (char-before) ?*) (forward-char 1))
16502 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16503 (beginning-of-line 0)
16504 (indent-to-column indent)
16505 (beginning-of-line 2)
16506 (indent-to-column indent)
16507 (beginning-of-line 0)
16508 (if hiddenp
16509 (save-excursion
16510 (org-back-to-heading t)
16511 (hide-entry))
16512 (org-flag-drawer t))))
16513
16514 (defun org-set-property (property value)
16515 "In the current entry, set PROPERTY to VALUE.
16516 When called interactively, this will prompt for a property name, offering
16517 completion on existing and default properties. And then it will prompt
16518 for a value, offering competion either on allowed values (via an inherited
16519 xxx_ALL property) or on existing values in other instances of this property
16520 in the current file."
16521 (interactive
16522 (let* ((prop (completing-read
16523 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16524 (cur (org-entry-get nil prop))
16525 (allowed (org-property-get-allowed-values nil prop 'table))
16526 (existing (mapcar 'list (org-property-values prop)))
16527 (val (if allowed
16528 (completing-read "Value: " allowed nil 'req-match)
16529 (completing-read
16530 (concat "Value" (if (and cur (string-match "\\S-" cur))
16531 (concat "[" cur "]") "")
16532 ": ")
16533 existing nil nil "" nil cur))))
16534 (list prop (if (equal val "") cur val))))
16535 (unless (equal (org-entry-get nil property) value)
16536 (org-entry-put nil property value)))
16537
16538 (defun org-delete-property (property)
16539 "In the current entry, delete PROPERTY."
16540 (interactive
16541 (let* ((prop (completing-read
16542 "Property: " (org-entry-properties nil 'standard))))
16543 (list prop)))
16544 (message "Property %s %s" property
16545 (if (org-entry-delete nil property)
16546 "deleted"
16547 "was not present in the entry")))
16548
16549 (defun org-delete-property-globally (property)
16550 "Remove PROPERTY globally, from all entries."
16551 (interactive
16552 (let* ((prop (completing-read
16553 "Globally remove property: "
16554 (mapcar 'list (org-buffer-property-keys)))))
16555 (list prop)))
16556 (save-excursion
16557 (save-restriction
16558 (widen)
16559 (goto-char (point-min))
16560 (let ((cnt 0))
16561 (while (re-search-forward
16562 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16563 nil t)
16564 (setq cnt (1+ cnt))
16565 (replace-match ""))
16566 (message "Property \"%s\" removed from %d entries" property cnt)))))
16567
16568 (defvar org-columns-current-fmt-compiled) ; defined below
16569
16570 (defun org-compute-property-at-point ()
16571 "Compute the property at point.
16572 This looks for an enclosing column format, extracts the operator and
16573 then applies it to the proerty in the column format's scope."
16574 (interactive)
16575 (unless (org-at-property-p)
16576 (error "Not at a property"))
16577 (let ((prop (org-match-string-no-properties 2)))
16578 (org-columns-get-format-and-top-level)
16579 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16580 (error "No operator defined for property %s" prop))
16581 (org-columns-compute prop)))
16582
16583 (defun org-property-get-allowed-values (pom property &optional table)
16584 "Get allowed values for the property PROPERTY.
16585 When TABLE is non-nil, return an alist that can directly be used for
16586 completion."
16587 (let (vals)
16588 (cond
16589 ((equal property "TODO")
16590 (setq vals (org-with-point-at pom
16591 (append org-todo-keywords-1 '("")))))
16592 ((equal property "PRIORITY")
16593 (let ((n org-lowest-priority))
16594 (while (>= n org-highest-priority)
16595 (push (char-to-string n) vals)
16596 (setq n (1- n)))))
16597 ((member property org-special-properties))
16598 (t
16599 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16600
16601 (when (and vals (string-match "\\S-" vals))
16602 (setq vals (car (read-from-string (concat "(" vals ")"))))
16603 (setq vals (mapcar (lambda (x)
16604 (cond ((stringp x) x)
16605 ((numberp x) (number-to-string x))
16606 ((symbolp x) (symbol-name x))
16607 (t "???")))
16608 vals)))))
16609 (if table (mapcar 'list vals) vals)))
16610
16611 (defun org-property-previous-allowed-value (&optional previous)
16612 "Switch to the next allowed value for this property."
16613 (interactive)
16614 (org-property-next-allowed-value t))
16615
16616 (defun org-property-next-allowed-value (&optional previous)
16617 "Switch to the next allowed value for this property."
16618 (interactive)
16619 (unless (org-at-property-p)
16620 (error "Not at a property"))
16621 (let* ((key (match-string 2))
16622 (value (match-string 3))
16623 (allowed (or (org-property-get-allowed-values (point) key)
16624 (and (member value '("[ ]" "[-]" "[X]"))
16625 '("[ ]" "[X]"))))
16626 nval)
16627 (unless allowed
16628 (error "Allowed values for this property have not been defined"))
16629 (if previous (setq allowed (reverse allowed)))
16630 (if (member value allowed)
16631 (setq nval (car (cdr (member value allowed)))))
16632 (setq nval (or nval (car allowed)))
16633 (if (equal nval value)
16634 (error "Only one allowed value for this property"))
16635 (org-at-property-p)
16636 (replace-match (concat " :" key ": " nval) t t)
16637 (org-indent-line-function)
16638 (beginning-of-line 1)
16639 (skip-chars-forward " \t")))
16640
16641 (defun org-find-entry-with-id (ident)
16642 "Locate the entry that contains the ID property with exact value IDENT.
16643 IDENT can be a string, a symbol or a number, this function will search for
16644 the string representation of it.
16645 Return the position where this entry starts, or nil if there is no such entry."
16646 (let ((id (cond
16647 ((stringp ident) ident)
16648 ((symbol-name ident) (symbol-name ident))
16649 ((numberp ident) (number-to-string ident))
16650 (t (error "IDENT %s must be a string, symbol or number" ident))))
16651 (case-fold-search nil))
16652 (save-excursion
16653 (save-restriction
16654 (widen)
16655 (goto-char (point-min))
16656 (when (re-search-forward
16657 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16658 nil t)
16659 (org-back-to-heading)
16660 (point))))))
16661
16662 ;;; Column View
16663
16664 (defvar org-columns-overlays nil
16665 "Holds the list of current column overlays.")
16666
16667 (defvar org-columns-current-fmt nil
16668 "Local variable, holds the currently active column format.")
16669 (defvar org-columns-current-fmt-compiled nil
16670 "Local variable, holds the currently active column format.
16671 This is the compiled version of the format.")
16672 (defvar org-columns-current-widths nil
16673 "Loval variable, holds the currently widths of fields.")
16674 (defvar org-columns-current-maxwidths nil
16675 "Loval variable, holds the currently active maximum column widths.")
16676 (defvar org-columns-begin-marker (make-marker)
16677 "Points to the position where last a column creation command was called.")
16678 (defvar org-columns-top-level-marker (make-marker)
16679 "Points to the position where current columns region starts.")
16680
16681 (defvar org-columns-map (make-sparse-keymap)
16682 "The keymap valid in column display.")
16683
16684 (defun org-columns-content ()
16685 "Switch to contents view while in columns view."
16686 (interactive)
16687 (org-overview)
16688 (org-content))
16689
16690 (org-defkey org-columns-map "c" 'org-columns-content)
16691 (org-defkey org-columns-map "o" 'org-overview)
16692 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16693 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16694 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16695 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16696 (org-defkey org-columns-map "v" 'org-columns-show-value)
16697 (org-defkey org-columns-map "q" 'org-columns-quit)
16698 (org-defkey org-columns-map "r" 'org-columns-redo)
16699 (org-defkey org-columns-map "g" 'org-columns-redo)
16700 (org-defkey org-columns-map [left] 'backward-char)
16701 (org-defkey org-columns-map "\M-b" 'backward-char)
16702 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16703 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16704 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16705 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16706 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16707 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16708 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16709 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16710 (org-defkey org-columns-map "<" 'org-columns-narrow)
16711 (org-defkey org-columns-map ">" 'org-columns-widen)
16712 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16713 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16714 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16715 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16716
16717 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16718 '("Column"
16719 ["Edit property" org-columns-edit-value t]
16720 ["Next allowed value" org-columns-next-allowed-value t]
16721 ["Previous allowed value" org-columns-previous-allowed-value t]
16722 ["Show full value" org-columns-show-value t]
16723 ["Edit allowed values" org-columns-edit-allowed t]
16724 "--"
16725 ["Edit column attributes" org-columns-edit-attributes t]
16726 ["Increase column width" org-columns-widen t]
16727 ["Decrease column width" org-columns-narrow t]
16728 "--"
16729 ["Move column right" org-columns-move-right t]
16730 ["Move column left" org-columns-move-left t]
16731 ["Add column" org-columns-new t]
16732 ["Delete column" org-columns-delete t]
16733 "--"
16734 ["CONTENTS" org-columns-content t]
16735 ["OVERVIEW" org-overview t]
16736 ["Refresh columns display" org-columns-redo t]
16737 "--"
16738 ["Open link" org-columns-open-link t]
16739 "--"
16740 ["Quit" org-columns-quit t]))
16741
16742 (defun org-columns-new-overlay (beg end &optional string face)
16743 "Create a new column overlay and add it to the list."
16744 (let ((ov (org-make-overlay beg end)))
16745 (org-overlay-put ov 'face (or face 'secondary-selection))
16746 (org-overlay-display ov string face)
16747 (push ov org-columns-overlays)
16748 ov))
16749
16750 (defun org-columns-display-here (&optional props)
16751 "Overlay the current line with column display."
16752 (interactive)
16753 (let* ((fmt org-columns-current-fmt-compiled)
16754 (beg (point-at-bol))
16755 (level-face (save-excursion
16756 (beginning-of-line 1)
16757 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16758 (org-get-level-face 2))))
16759 (color (list :foreground
16760 (face-attribute (or level-face 'default) :foreground)))
16761 props pom property ass width f string ov column val modval)
16762 ;; Check if the entry is in another buffer.
16763 (unless props
16764 (if (eq major-mode 'org-agenda-mode)
16765 (setq pom (or (get-text-property (point) 'org-hd-marker)
16766 (get-text-property (point) 'org-marker))
16767 props (if pom (org-entry-properties pom) nil))
16768 (setq props (org-entry-properties nil))))
16769 ;; Walk the format
16770 (while (setq column (pop fmt))
16771 (setq property (car column)
16772 ass (if (equal property "ITEM")
16773 (cons "ITEM"
16774 (save-match-data
16775 (org-no-properties
16776 (org-remove-tabs
16777 (buffer-substring-no-properties
16778 (point-at-bol) (point-at-eol))))))
16779 (assoc property props))
16780 width (or (cdr (assoc property org-columns-current-maxwidths))
16781 (nth 2 column)
16782 (length property))
16783 f (format "%%-%d.%ds | " width width)
16784 val (or (cdr ass) "")
16785 modval (if (equal property "ITEM")
16786 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16787 string (format f (or modval val)))
16788 ;; Create the overlay
16789 (org-unmodified
16790 (setq ov (org-columns-new-overlay
16791 beg (setq beg (1+ beg)) string
16792 (list color 'org-column)))
16793 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16794 (org-overlay-put ov 'keymap org-columns-map)
16795 (org-overlay-put ov 'org-columns-key property)
16796 (org-overlay-put ov 'org-columns-value (cdr ass))
16797 (org-overlay-put ov 'org-columns-value-modified modval)
16798 (org-overlay-put ov 'org-columns-pom pom)
16799 (org-overlay-put ov 'org-columns-format f))
16800 (if (or (not (char-after beg))
16801 (equal (char-after beg) ?\n))
16802 (let ((inhibit-read-only t))
16803 (save-excursion
16804 (goto-char beg)
16805 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16806 ;; Make the rest of the line disappear.
16807 (org-unmodified
16808 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16809 (org-overlay-put ov 'invisible t)
16810 (org-overlay-put ov 'keymap org-columns-map)
16811 (org-overlay-put ov 'intangible t)
16812 (push ov org-columns-overlays)
16813 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16814 (org-overlay-put ov 'keymap org-columns-map)
16815 (push ov org-columns-overlays)
16816 (let ((inhibit-read-only t))
16817 (put-text-property (max (point-min) (1- (point-at-bol)))
16818 (min (point-max) (1+ (point-at-eol)))
16819 'read-only "Type `e' to edit property")))))
16820
16821 (defvar org-previous-header-line-format nil
16822 "The header line format before column view was turned on.")
16823 (defvar org-columns-inhibit-recalculation nil
16824 "Inhibit recomputing of columns on column view startup.")
16825
16826
16827 (defvar header-line-format)
16828 (defun org-columns-display-here-title ()
16829 "Overlay the newline before the current line with the table title."
16830 (interactive)
16831 (let ((fmt org-columns-current-fmt-compiled)
16832 string (title "")
16833 property width f column str widths)
16834 (while (setq column (pop fmt))
16835 (setq property (car column)
16836 str (or (nth 1 column) property)
16837 width (or (cdr (assoc property org-columns-current-maxwidths))
16838 (nth 2 column)
16839 (length str))
16840 widths (push width widths)
16841 f (format "%%-%d.%ds | " width width)
16842 string (format f str)
16843 title (concat title string)))
16844 (setq title (concat
16845 (org-add-props " " nil 'display '(space :align-to 0))
16846 (org-add-props title nil 'face '(:weight bold :underline t))))
16847 (org-set-local 'org-previous-header-line-format header-line-format)
16848 (org-set-local 'org-columns-current-widths (nreverse widths))
16849 (setq header-line-format title)))
16850
16851 (defun org-columns-remove-overlays ()
16852 "Remove all currently active column overlays."
16853 (interactive)
16854 (when (marker-buffer org-columns-begin-marker)
16855 (with-current-buffer (marker-buffer org-columns-begin-marker)
16856 (when (local-variable-p 'org-previous-header-line-format)
16857 (setq header-line-format org-previous-header-line-format)
16858 (kill-local-variable 'org-previous-header-line-format))
16859 (move-marker org-columns-begin-marker nil)
16860 (move-marker org-columns-top-level-marker nil)
16861 (org-unmodified
16862 (mapc 'org-delete-overlay org-columns-overlays)
16863 (setq org-columns-overlays nil)
16864 (let ((inhibit-read-only t))
16865 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16866
16867 (defun org-columns-cleanup-item (item fmt)
16868 "Remove from ITEM what is a column in the format FMT."
16869 (if (not org-complex-heading-regexp)
16870 item
16871 (when (string-match org-complex-heading-regexp item)
16872 (concat
16873 (org-add-props (concat (match-string 1 item) " ") nil
16874 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16875 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16876 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16877 " " (match-string 4 item)
16878 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16879
16880 (defun org-columns-show-value ()
16881 "Show the full value of the property."
16882 (interactive)
16883 (let ((value (get-char-property (point) 'org-columns-value)))
16884 (message "Value is: %s" (or value ""))))
16885
16886 (defun org-columns-quit ()
16887 "Remove the column overlays and in this way exit column editing."
16888 (interactive)
16889 (org-unmodified
16890 (org-columns-remove-overlays)
16891 (let ((inhibit-read-only t))
16892 (remove-text-properties (point-min) (point-max) '(read-only t))))
16893 (when (eq major-mode 'org-agenda-mode)
16894 (message
16895 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16896
16897 (defun org-columns-check-computed ()
16898 "Check if this column value is computed.
16899 If yes, throw an error indicating that changing it does not make sense."
16900 (let ((val (get-char-property (point) 'org-columns-value)))
16901 (when (and (stringp val)
16902 (get-char-property 0 'org-computed val))
16903 (error "This value is computed from the entry's children"))))
16904
16905 (defun org-columns-todo (&optional arg)
16906 "Change the TODO state during column view."
16907 (interactive "P")
16908 (org-columns-edit-value "TODO"))
16909
16910 (defun org-columns-set-tags-or-toggle (&optional arg)
16911 "Toggle checkbox at point, or set tags for current headline."
16912 (interactive "P")
16913 (if (string-match "\\`\\[[ xX-]\\]\\'"
16914 (get-char-property (point) 'org-columns-value))
16915 (org-columns-next-allowed-value)
16916 (org-columns-edit-value "TAGS")))
16917
16918 (defun org-columns-edit-value (&optional key)
16919 "Edit the value of the property at point in column view.
16920 Where possible, use the standard interface for changing this line."
16921 (interactive)
16922 (org-columns-check-computed)
16923 (let* ((external-key key)
16924 (col (current-column))
16925 (key (or key (get-char-property (point) 'org-columns-key)))
16926 (value (get-char-property (point) 'org-columns-value))
16927 (bol (point-at-bol)) (eol (point-at-eol))
16928 (pom (or (get-text-property bol 'org-hd-marker)
16929 (point))) ; keep despite of compiler waring
16930 (line-overlays
16931 (delq nil (mapcar (lambda (x)
16932 (and (eq (overlay-buffer x) (current-buffer))
16933 (>= (overlay-start x) bol)
16934 (<= (overlay-start x) eol)
16935 x))
16936 org-columns-overlays)))
16937 nval eval allowed)
16938 (cond
16939 ((equal key "CLOCKSUM")
16940 (error "This special column cannot be edited"))
16941 ((equal key "ITEM")
16942 (setq eval '(org-with-point-at pom
16943 (org-edit-headline))))
16944 ((equal key "TODO")
16945 (setq eval '(org-with-point-at pom
16946 (let ((current-prefix-arg
16947 (if external-key current-prefix-arg '(4))))
16948 (call-interactively 'org-todo)))))
16949 ((equal key "PRIORITY")
16950 (setq eval '(org-with-point-at pom
16951 (call-interactively 'org-priority))))
16952 ((equal key "TAGS")
16953 (setq eval '(org-with-point-at pom
16954 (let ((org-fast-tag-selection-single-key
16955 (if (eq org-fast-tag-selection-single-key 'expert)
16956 t org-fast-tag-selection-single-key)))
16957 (call-interactively 'org-set-tags)))))
16958 ((equal key "DEADLINE")
16959 (setq eval '(org-with-point-at pom
16960 (call-interactively 'org-deadline))))
16961 ((equal key "SCHEDULED")
16962 (setq eval '(org-with-point-at pom
16963 (call-interactively 'org-schedule))))
16964 (t
16965 (setq allowed (org-property-get-allowed-values pom key 'table))
16966 (if allowed
16967 (setq nval (completing-read "Value: " allowed nil t))
16968 (setq nval (read-string "Edit: " value)))
16969 (setq nval (org-trim nval))
16970 (when (not (equal nval value))
16971 (setq eval '(org-entry-put pom key nval)))))
16972 (when eval
16973 (let ((inhibit-read-only t))
16974 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16975 (unwind-protect
16976 (progn
16977 (setq org-columns-overlays
16978 (org-delete-all line-overlays org-columns-overlays))
16979 (mapc 'org-delete-overlay line-overlays)
16980 (org-columns-eval eval))
16981 (org-columns-display-here))))
16982 (move-to-column col)
16983 (if (and (org-mode-p)
16984 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16985 (org-columns-update key))))
16986
16987 (defun org-edit-headline () ; FIXME: this is not columns specific
16988 "Edit the current headline, the part without TODO keyword, TAGS."
16989 (org-back-to-heading)
16990 (when (looking-at org-todo-line-regexp)
16991 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16992 (txt (match-string 3))
16993 (post "")
16994 txt2)
16995 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16996 (setq post (match-string 0 txt)
16997 txt (substring txt 0 (match-beginning 0))))
16998 (setq txt2 (read-string "Edit: " txt))
16999 (when (not (equal txt txt2))
17000 (beginning-of-line 1)
17001 (insert pre txt2 post)
17002 (delete-region (point) (point-at-eol))
17003 (org-set-tags nil t)))))
17004
17005 (defun org-columns-edit-allowed ()
17006 "Edit the list of allowed values for the current property."
17007 (interactive)
17008 (let* ((key (get-char-property (point) 'org-columns-key))
17009 (key1 (concat key "_ALL"))
17010 (allowed (org-entry-get (point) key1 t))
17011 nval)
17012 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
17013 (setq nval (read-string "Allowed: " allowed))
17014 (org-entry-put
17015 (cond ((marker-position org-entry-property-inherited-from)
17016 org-entry-property-inherited-from)
17017 ((marker-position org-columns-top-level-marker)
17018 org-columns-top-level-marker))
17019 key1 nval)))
17020
17021 (defmacro org-no-warnings (&rest body)
17022 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
17023
17024 (defun org-columns-eval (form)
17025 (let (hidep)
17026 (save-excursion
17027 (beginning-of-line 1)
17028 ;; `next-line' is needed here, because it skips invisible line.
17029 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
17030 (setq hidep (org-on-heading-p 1)))
17031 (eval form)
17032 (and hidep (hide-entry))))
17033
17034 (defun org-columns-previous-allowed-value ()
17035 "Switch to the previous allowed value for this column."
17036 (interactive)
17037 (org-columns-next-allowed-value t))
17038
17039 (defun org-columns-next-allowed-value (&optional previous)
17040 "Switch to the next allowed value for this column."
17041 (interactive)
17042 (org-columns-check-computed)
17043 (let* ((col (current-column))
17044 (key (get-char-property (point) 'org-columns-key))
17045 (value (get-char-property (point) 'org-columns-value))
17046 (bol (point-at-bol)) (eol (point-at-eol))
17047 (pom (or (get-text-property bol 'org-hd-marker)
17048 (point))) ; keep despite of compiler waring
17049 (line-overlays
17050 (delq nil (mapcar (lambda (x)
17051 (and (eq (overlay-buffer x) (current-buffer))
17052 (>= (overlay-start x) bol)
17053 (<= (overlay-start x) eol)
17054 x))
17055 org-columns-overlays)))
17056 (allowed (or (org-property-get-allowed-values pom key)
17057 (and (memq
17058 (nth 4 (assoc key org-columns-current-fmt-compiled))
17059 '(checkbox checkbox-n-of-m checkbox-percent))
17060 '("[ ]" "[X]"))))
17061 nval)
17062 (when (equal key "ITEM")
17063 (error "Cannot edit item headline from here"))
17064 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
17065 (error "Allowed values for this property have not been defined"))
17066 (if (member key '("SCHEDULED" "DEADLINE"))
17067 (setq nval (if previous 'earlier 'later))
17068 (if previous (setq allowed (reverse allowed)))
17069 (if (member value allowed)
17070 (setq nval (car (cdr (member value allowed)))))
17071 (setq nval (or nval (car allowed)))
17072 (if (equal nval value)
17073 (error "Only one allowed value for this property")))
17074 (let ((inhibit-read-only t))
17075 (remove-text-properties (1- bol) eol '(read-only t))
17076 (unwind-protect
17077 (progn
17078 (setq org-columns-overlays
17079 (org-delete-all line-overlays org-columns-overlays))
17080 (mapc 'org-delete-overlay line-overlays)
17081 (org-columns-eval '(org-entry-put pom key nval)))
17082 (org-columns-display-here)))
17083 (move-to-column col)
17084 (if (and (org-mode-p)
17085 (nth 3 (assoc key org-columns-current-fmt-compiled)))
17086 (org-columns-update key))))
17087
17088 (defun org-verify-version (task)
17089 (cond
17090 ((eq task 'columns)
17091 (if (or (featurep 'xemacs)
17092 (< emacs-major-version 22))
17093 (error "Emacs 22 is required for the columns feature")))))
17094
17095 (defun org-columns-open-link (&optional arg)
17096 (interactive "P")
17097 (let ((value (get-char-property (point) 'org-columns-value)))
17098 (org-open-link-from-string value arg)))
17099
17100 (defun org-open-link-from-string (s &optional arg)
17101 "Open a link in the string S, as if it was in Org-mode."
17102 (interactive)
17103 (with-temp-buffer
17104 (let ((org-inhibit-startup t))
17105 (org-mode)
17106 (insert s)
17107 (goto-char (point-min))
17108 (org-open-at-point arg))))
17109
17110 (defun org-columns-get-format-and-top-level ()
17111 (let (fmt)
17112 (when (condition-case nil (org-back-to-heading) (error nil))
17113 (move-marker org-entry-property-inherited-from nil)
17114 (setq fmt (org-entry-get nil "COLUMNS" t)))
17115 (setq fmt (or fmt org-columns-default-format))
17116 (org-set-local 'org-columns-current-fmt fmt)
17117 (org-columns-compile-format fmt)
17118 (if (marker-position org-entry-property-inherited-from)
17119 (move-marker org-columns-top-level-marker
17120 org-entry-property-inherited-from)
17121 (move-marker org-columns-top-level-marker (point)))
17122 fmt))
17123
17124 (defun org-columns ()
17125 "Turn on column view on an org-mode file."
17126 (interactive)
17127 (org-verify-version 'columns)
17128 (org-columns-remove-overlays)
17129 (move-marker org-columns-begin-marker (point))
17130 (let (beg end fmt cache maxwidths)
17131 (setq fmt (org-columns-get-format-and-top-level))
17132 (save-excursion
17133 (goto-char org-columns-top-level-marker)
17134 (setq beg (point))
17135 (unless org-columns-inhibit-recalculation
17136 (org-columns-compute-all))
17137 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
17138 (point-max)))
17139 ;; Get and cache the properties
17140 (goto-char beg)
17141 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
17142 (save-excursion
17143 (save-restriction
17144 (narrow-to-region beg end)
17145 (org-clock-sum))))
17146 (while (re-search-forward (concat "^" outline-regexp) end t)
17147 (push (cons (org-current-line) (org-entry-properties)) cache))
17148 (when cache
17149 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17150 (org-set-local 'org-columns-current-maxwidths maxwidths)
17151 (org-columns-display-here-title)
17152 (mapc (lambda (x)
17153 (goto-line (car x))
17154 (org-columns-display-here (cdr x)))
17155 cache)))))
17156
17157 (defun org-columns-new (&optional prop title width op fmt &rest rest)
17158 "Insert a new column, to the left of the current column."
17159 (interactive)
17160 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
17161 cell)
17162 (setq prop (completing-read
17163 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
17164 nil nil prop))
17165 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
17166 (setq width (read-string "Column width: " (if width (number-to-string width))))
17167 (if (string-match "\\S-" width)
17168 (setq width (string-to-number width))
17169 (setq width nil))
17170 (setq fmt (completing-read "Summary [none]: "
17171 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
17172 nil t))
17173 (if (string-match "\\S-" fmt)
17174 (setq fmt (intern fmt))
17175 (setq fmt nil))
17176 (if (eq fmt 'none) (setq fmt nil))
17177 (if editp
17178 (progn
17179 (setcar editp prop)
17180 (setcdr editp (list title width nil fmt)))
17181 (setq cell (nthcdr (1- (current-column))
17182 org-columns-current-fmt-compiled))
17183 (setcdr cell (cons (list prop title width nil fmt)
17184 (cdr cell))))
17185 (org-columns-store-format)
17186 (org-columns-redo)))
17187
17188 (defun org-columns-delete ()
17189 "Delete the column at point from columns view."
17190 (interactive)
17191 (let* ((n (current-column))
17192 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
17193 (when (y-or-n-p
17194 (format "Are you sure you want to remove column \"%s\"? " title))
17195 (setq org-columns-current-fmt-compiled
17196 (delq (nth n org-columns-current-fmt-compiled)
17197 org-columns-current-fmt-compiled))
17198 (org-columns-store-format)
17199 (org-columns-redo)
17200 (if (>= (current-column) (length org-columns-current-fmt-compiled))
17201 (backward-char 1)))))
17202
17203 (defun org-columns-edit-attributes ()
17204 "Edit the attributes of the current column."
17205 (interactive)
17206 (let* ((n (current-column))
17207 (info (nth n org-columns-current-fmt-compiled)))
17208 (apply 'org-columns-new info)))
17209
17210 (defun org-columns-widen (arg)
17211 "Make the column wider by ARG characters."
17212 (interactive "p")
17213 (let* ((n (current-column))
17214 (entry (nth n org-columns-current-fmt-compiled))
17215 (width (or (nth 2 entry)
17216 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
17217 (setq width (max 1 (+ width arg)))
17218 (setcar (nthcdr 2 entry) width)
17219 (org-columns-store-format)
17220 (org-columns-redo)))
17221
17222 (defun org-columns-narrow (arg)
17223 "Make the column nrrower by ARG characters."
17224 (interactive "p")
17225 (org-columns-widen (- arg)))
17226
17227 (defun org-columns-move-right ()
17228 "Swap this column with the one to the right."
17229 (interactive)
17230 (let* ((n (current-column))
17231 (cell (nthcdr n org-columns-current-fmt-compiled))
17232 e)
17233 (when (>= n (1- (length org-columns-current-fmt-compiled)))
17234 (error "Cannot shift this column further to the right"))
17235 (setq e (car cell))
17236 (setcar cell (car (cdr cell)))
17237 (setcdr cell (cons e (cdr (cdr cell))))
17238 (org-columns-store-format)
17239 (org-columns-redo)
17240 (forward-char 1)))
17241
17242 (defun org-columns-move-left ()
17243 "Swap this column with the one to the left."
17244 (interactive)
17245 (let* ((n (current-column)))
17246 (when (= n 0)
17247 (error "Cannot shift this column further to the left"))
17248 (backward-char 1)
17249 (org-columns-move-right)
17250 (backward-char 1)))
17251
17252 (defun org-columns-store-format ()
17253 "Store the text version of the current columns format in appropriate place.
17254 This is either in the COLUMNS property of the node starting the current column
17255 display, or in the #+COLUMNS line of the current buffer."
17256 (let (fmt (cnt 0))
17257 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17258 (org-set-local 'org-columns-current-fmt fmt)
17259 (if (marker-position org-columns-top-level-marker)
17260 (save-excursion
17261 (goto-char org-columns-top-level-marker)
17262 (if (and (org-at-heading-p)
17263 (org-entry-get nil "COLUMNS"))
17264 (org-entry-put nil "COLUMNS" fmt)
17265 (goto-char (point-min))
17266 ;; Overwrite all #+COLUMNS lines....
17267 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17268 (setq cnt (1+ cnt))
17269 (replace-match (concat "#+COLUMNS: " fmt) t t))
17270 (unless (> cnt 0)
17271 (goto-char (point-min))
17272 (or (org-on-heading-p t) (outline-next-heading))
17273 (let ((inhibit-read-only t))
17274 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17275 (org-set-local 'org-columns-default-format fmt))))))
17276
17277 (defvar org-overriding-columns-format nil
17278 "When set, overrides any other definition.")
17279 (defvar org-agenda-view-columns-initially nil
17280 "When set, switch to columns view immediately after creating the agenda.")
17281
17282 (defun org-agenda-columns ()
17283 "Turn on column view in the agenda."
17284 (interactive)
17285 (org-verify-version 'columns)
17286 (org-columns-remove-overlays)
17287 (move-marker org-columns-begin-marker (point))
17288 (let (fmt cache maxwidths m)
17289 (cond
17290 ((and (local-variable-p 'org-overriding-columns-format)
17291 org-overriding-columns-format)
17292 (setq fmt org-overriding-columns-format))
17293 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17294 (setq fmt (org-entry-get m "COLUMNS" t)))
17295 ((and (boundp 'org-columns-current-fmt)
17296 (local-variable-p 'org-columns-current-fmt)
17297 org-columns-current-fmt)
17298 (setq fmt org-columns-current-fmt))
17299 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17300 (setq m (get-text-property m 'org-hd-marker))
17301 (setq fmt (org-entry-get m "COLUMNS" t))))
17302 (setq fmt (or fmt org-columns-default-format))
17303 (org-set-local 'org-columns-current-fmt fmt)
17304 (org-columns-compile-format fmt)
17305 (save-excursion
17306 ;; Get and cache the properties
17307 (goto-char (point-min))
17308 (while (not (eobp))
17309 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17310 (get-text-property (point) 'org-marker)))
17311 (push (cons (org-current-line) (org-entry-properties m)) cache))
17312 (beginning-of-line 2))
17313 (when cache
17314 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17315 (org-set-local 'org-columns-current-maxwidths maxwidths)
17316 (org-columns-display-here-title)
17317 (mapc (lambda (x)
17318 (goto-line (car x))
17319 (org-columns-display-here (cdr x)))
17320 cache)))))
17321
17322 (defun org-columns-get-autowidth-alist (s cache)
17323 "Derive the maximum column widths from the format and the cache."
17324 (let ((start 0) rtn)
17325 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17326 (push (cons (match-string 1 s) 1) rtn)
17327 (setq start (match-end 0)))
17328 (mapc (lambda (x)
17329 (setcdr x (apply 'max
17330 (mapcar
17331 (lambda (y)
17332 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17333 cache))))
17334 rtn)
17335 rtn))
17336
17337 (defun org-columns-compute-all ()
17338 "Compute all columns that have operators defined."
17339 (org-unmodified
17340 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17341 (let ((columns org-columns-current-fmt-compiled) col)
17342 (while (setq col (pop columns))
17343 (when (nth 3 col)
17344 (save-excursion
17345 (org-columns-compute (car col)))))))
17346
17347 (defun org-columns-update (property)
17348 "Recompute PROPERTY, and update the columns display for it."
17349 (org-columns-compute property)
17350 (let (fmt val pos)
17351 (save-excursion
17352 (mapc (lambda (ov)
17353 (when (equal (org-overlay-get ov 'org-columns-key) property)
17354 (setq pos (org-overlay-start ov))
17355 (goto-char pos)
17356 (when (setq val (cdr (assoc property
17357 (get-text-property
17358 (point-at-bol) 'org-summaries))))
17359 (setq fmt (org-overlay-get ov 'org-columns-format))
17360 (org-overlay-put ov 'org-columns-value val)
17361 (org-overlay-put ov 'display (format fmt val)))))
17362 org-columns-overlays))))
17363
17364 (defun org-columns-compute (property)
17365 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17366 (interactive)
17367 (let* ((re (concat "^" outline-regexp))
17368 (lmax 30) ; Does anyone use deeper levels???
17369 (lsum (make-vector lmax 0))
17370 (lflag (make-vector lmax nil))
17371 (level 0)
17372 (ass (assoc property org-columns-current-fmt-compiled))
17373 (format (nth 4 ass))
17374 (printf (nth 5 ass))
17375 (beg org-columns-top-level-marker)
17376 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17377 (save-excursion
17378 ;; Find the region to compute
17379 (goto-char beg)
17380 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17381 (goto-char end)
17382 ;; Walk the tree from the back and do the computations
17383 (while (re-search-backward re beg t)
17384 (setq sumpos (match-beginning 0)
17385 last-level level
17386 level (org-outline-level)
17387 val (org-entry-get nil property)
17388 valflag (and val (string-match "\\S-" val)))
17389 (cond
17390 ((< level last-level)
17391 ;; put the sum of lower levels here as a property
17392 (setq sum (aref lsum last-level) ; current sum
17393 flag (aref lflag last-level) ; any valid entries from children?
17394 str (org-column-number-to-string sum format printf)
17395 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17396 useval (if flag str1 (if valflag val ""))
17397 sum-alist (get-text-property sumpos 'org-summaries))
17398 (if (assoc property sum-alist)
17399 (setcdr (assoc property sum-alist) useval)
17400 (push (cons property useval) sum-alist)
17401 (org-unmodified
17402 (add-text-properties sumpos (1+ sumpos)
17403 (list 'org-summaries sum-alist))))
17404 (when val
17405 (org-entry-put nil property (if flag str val)))
17406 ;; add current to current level accumulator
17407 (when (or flag valflag)
17408 (aset lsum level (+ (aref lsum level)
17409 (if flag sum (org-column-string-to-number
17410 (if flag str val) format))))
17411 (aset lflag level t))
17412 ;; clear accumulators for deeper levels
17413 (loop for l from (1+ level) to (1- lmax) do
17414 (aset lsum l 0)
17415 (aset lflag l nil)))
17416 ((>= level last-level)
17417 ;; add what we have here to the accumulator for this level
17418 (aset lsum level (+ (aref lsum level)
17419 (org-column-string-to-number (or val "0") format)))
17420 (and valflag (aset lflag level t)))
17421 (t (error "This should not happen")))))))
17422
17423 (defun org-columns-redo ()
17424 "Construct the column display again."
17425 (interactive)
17426 (message "Recomputing columns...")
17427 (save-excursion
17428 (if (marker-position org-columns-begin-marker)
17429 (goto-char org-columns-begin-marker))
17430 (org-columns-remove-overlays)
17431 (if (org-mode-p)
17432 (call-interactively 'org-columns)
17433 (call-interactively 'org-agenda-columns)))
17434 (message "Recomputing columns...done"))
17435
17436 (defun org-columns-not-in-agenda ()
17437 (if (eq major-mode 'org-agenda-mode)
17438 (error "This command is only allowed in Org-mode buffers")))
17439
17440
17441 (defun org-string-to-number (s)
17442 "Convert string to number, and interpret hh:mm:ss."
17443 (if (not (string-match ":" s))
17444 (string-to-number s)
17445 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17446 (while l
17447 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17448 sum)))
17449
17450 (defun org-column-number-to-string (n fmt &optional printf)
17451 "Convert a computed column number to a string value, according to FMT."
17452 (cond
17453 ((eq fmt 'add_times)
17454 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17455 (format "%d:%02d" h m)))
17456 ((eq fmt 'checkbox)
17457 (cond ((= n (floor n)) "[X]")
17458 ((> n 1.) "[-]")
17459 (t "[ ]")))
17460 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17461 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17462 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17463 (printf (format printf n))
17464 ((eq fmt 'currency)
17465 (format "%.2f" n))
17466 (t (number-to-string n))))
17467
17468 (defun org-nofm-to-completion (n m &optional percent)
17469 (if (not percent)
17470 (format "[%d/%d]" n m)
17471 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17472
17473 (defun org-column-string-to-number (s fmt)
17474 "Convert a column value to a number that can be used for column computing."
17475 (cond
17476 ((string-match ":" s)
17477 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17478 (while l
17479 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17480 sum))
17481 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17482 (if (equal s "[X]") 1. 0.000001))
17483 (t (string-to-number s))))
17484
17485 (defun org-columns-uncompile-format (cfmt)
17486 "Turn the compiled columns format back into a string representation."
17487 (let ((rtn "") e s prop title op width fmt printf)
17488 (while (setq e (pop cfmt))
17489 (setq prop (car e)
17490 title (nth 1 e)
17491 width (nth 2 e)
17492 op (nth 3 e)
17493 fmt (nth 4 e)
17494 printf (nth 5 e))
17495 (cond
17496 ((eq fmt 'add_times) (setq op ":"))
17497 ((eq fmt 'checkbox) (setq op "X"))
17498 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17499 ((eq fmt 'checkbox-percent) (setq op "X%"))
17500 ((eq fmt 'add_numbers) (setq op "+"))
17501 ((eq fmt 'currency) (setq op "$")))
17502 (if (and op printf) (setq op (concat op ";" printf)))
17503 (if (equal title prop) (setq title nil))
17504 (setq s (concat "%" (if width (number-to-string width))
17505 prop
17506 (if title (concat "(" title ")"))
17507 (if op (concat "{" op "}"))))
17508 (setq rtn (concat rtn " " s)))
17509 (org-trim rtn)))
17510
17511 (defun org-columns-compile-format (fmt)
17512 "Turn a column format string into an alist of specifications.
17513 The alist has one entry for each column in the format. The elements of
17514 that list are:
17515 property the property
17516 title the title field for the columns
17517 width the column width in characters, can be nil for automatic
17518 operator the operator if any
17519 format the output format for computed results, derived from operator
17520 printf a printf format for computed values"
17521 (let ((start 0) width prop title op f printf)
17522 (setq org-columns-current-fmt-compiled nil)
17523 (while (string-match
17524 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17525 fmt start)
17526 (setq start (match-end 0)
17527 width (match-string 1 fmt)
17528 prop (match-string 2 fmt)
17529 title (or (match-string 3 fmt) prop)
17530 op (match-string 4 fmt)
17531 f nil
17532 printf nil)
17533 (if width (setq width (string-to-number width)))
17534 (when (and op (string-match ";" op))
17535 (setq printf (substring op (match-end 0))
17536 op (substring op 0 (match-beginning 0))))
17537 (cond
17538 ((equal op "+") (setq f 'add_numbers))
17539 ((equal op "$") (setq f 'currency))
17540 ((equal op ":") (setq f 'add_times))
17541 ((equal op "X") (setq f 'checkbox))
17542 ((equal op "X/") (setq f 'checkbox-n-of-m))
17543 ((equal op "X%") (setq f 'checkbox-percent))
17544 )
17545 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17546 (setq org-columns-current-fmt-compiled
17547 (nreverse org-columns-current-fmt-compiled))))
17548
17549
17550 ;;; Dynamic block for Column view
17551
17552 (defun org-columns-capture-view (&optional maxlevel skip-empty-rows)
17553 "Get the column view of the current buffer or subtree.
17554 The first optional argument MAXLEVEL sets the level limit. A
17555 second optional argument SKIP-EMPTY-ROWS tells whether to skip
17556 empty rows, an empty row being one where all the column view
17557 specifiers except ITEM are empty. This function returns a list
17558 containing the title row and all other rows. Each row is a list
17559 of fields."
17560 (save-excursion
17561 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17562 (n (length title)) row tbl)
17563 (goto-char (point-min))
17564 (while (and (re-search-forward "^\\(\\*+\\) " nil t)
17565 (or (null maxlevel)
17566 (>= maxlevel
17567 (if org-odd-levels-only
17568 (/ (1+ (length (match-string 1))) 2)
17569 (length (match-string 1))))))
17570 (when (get-char-property (match-beginning 0) 'org-columns-key)
17571 (setq row nil)
17572 (loop for i from 0 to (1- n) do
17573 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17574 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17575 "")
17576 row))
17577 (setq row (nreverse row))
17578 (unless (and skip-empty-rows
17579 (eq 1 (length (delete "" (delete-dups row)))))
17580 (push row tbl))))
17581 (append (list title 'hline) (nreverse tbl)))))
17582
17583 (defun org-dblock-write:columnview (params)
17584 "Write the column view table.
17585 PARAMS is a property list of parameters:
17586
17587 :width enforce same column widths with <N> specifiers.
17588 :id the :ID: property of the entry where the columns view
17589 should be built, as a string. When `local', call locally.
17590 When `global' call column view with the cursor at the beginning
17591 of the buffer (usually this means that the whole buffer switches
17592 to column view).
17593 :hlines When t, insert a hline before each item. When a number, insert
17594 a hline before each level <= that number.
17595 :vlines When t, make each column a colgroup to enforce vertical lines.
17596 :maxlevel When set to a number, don't capture headlines below this level.
17597 :skip-empty-rows
17598 When t, skip rows where all specifiers other than ITEM are empty."
17599 (let ((pos (move-marker (make-marker) (point)))
17600 (hlines (plist-get params :hlines))
17601 (vlines (plist-get params :vlines))
17602 (maxlevel (plist-get params :maxlevel))
17603 (skip-empty-rows (plist-get params :skip-empty-rows))
17604 tbl id idpos nfields tmp)
17605 (save-excursion
17606 (save-restriction
17607 (when (setq id (plist-get params :id))
17608 (cond ((not id) nil)
17609 ((eq id 'global) (goto-char (point-min)))
17610 ((eq id 'local) nil)
17611 ((setq idpos (org-find-entry-with-id id))
17612 (goto-char idpos))
17613 (t (error "Cannot find entry with :ID: %s" id))))
17614 (org-columns)
17615 (setq tbl (org-columns-capture-view maxlevel skip-empty-rows))
17616 (setq nfields (length (car tbl)))
17617 (org-columns-quit)))
17618 (goto-char pos)
17619 (move-marker pos nil)
17620 (when tbl
17621 (when (plist-get params :hlines)
17622 (setq tmp nil)
17623 (while tbl
17624 (if (eq (car tbl) 'hline)
17625 (push (pop tbl) tmp)
17626 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17627 (if (and (not (eq (car tmp) 'hline))
17628 (or (eq hlines t)
17629 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17630 (push 'hline tmp)))
17631 (push (pop tbl) tmp)))
17632 (setq tbl (nreverse tmp)))
17633 (when vlines
17634 (setq tbl (mapcar (lambda (x)
17635 (if (eq 'hline x) x (cons "" x)))
17636 tbl))
17637 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17638 (setq pos (point))
17639 (insert (org-listtable-to-string tbl))
17640 (when (plist-get params :width)
17641 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17642 org-columns-current-widths "|")))
17643 (goto-char pos)
17644 (org-table-align))))
17645
17646 (defun org-listtable-to-string (tbl)
17647 "Convert a listtable TBL to a string that contains the Org-mode table.
17648 The table still need to be alligned. The resulting string has no leading
17649 and tailing newline characters."
17650 (mapconcat
17651 (lambda (x)
17652 (cond
17653 ((listp x)
17654 (concat "|" (mapconcat 'identity x "|") "|"))
17655 ((eq x 'hline) "|-|")
17656 (t (error "Garbage in listtable: %s" x))))
17657 tbl "\n"))
17658
17659 (defun org-insert-columns-dblock ()
17660 "Create a dynamic block capturing a column view table."
17661 (interactive)
17662 (let ((defaults '(:name "columnview" :hlines 1))
17663 (id (completing-read
17664 "Capture columns (local, global, entry with :ID: property) [local]: "
17665 (append '(("global") ("local"))
17666 (mapcar 'list (org-property-values "ID"))))))
17667 (if (equal id "") (setq id 'local))
17668 (if (equal id "global") (setq id 'global))
17669 (setq defaults (append defaults (list :id id)))
17670 (org-create-dblock defaults)
17671 (org-update-dblock)))
17672
17673 ;;;; Timestamps
17674
17675 (defvar org-last-changed-timestamp nil)
17676 (defvar org-time-was-given) ; dynamically scoped parameter
17677 (defvar org-end-time-was-given) ; dynamically scoped parameter
17678 (defvar org-ts-what) ; dynamically scoped parameter
17679
17680 (defun org-time-stamp (arg)
17681 "Prompt for a date/time and insert a time stamp.
17682 If the user specifies a time like HH:MM, or if this command is called
17683 with a prefix argument, the time stamp will contain date and time.
17684 Otherwise, only the date will be included. All parts of a date not
17685 specified by the user will be filled in from the current date/time.
17686 So if you press just return without typing anything, the time stamp
17687 will represent the current date/time. If there is already a timestamp
17688 at the cursor, it will be modified."
17689 (interactive "P")
17690 (let* ((ts nil)
17691 (default-time
17692 ;; Default time is either today, or, when entering a range,
17693 ;; the range start.
17694 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17695 (save-excursion
17696 (re-search-backward
17697 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17698 (- (point) 20) t)))
17699 (apply 'encode-time (org-parse-time-string (match-string 1)))
17700 (current-time)))
17701 (default-input (and ts (org-get-compact-tod ts)))
17702 org-time-was-given org-end-time-was-given time)
17703 (cond
17704 ((and (org-at-timestamp-p)
17705 (eq last-command 'org-time-stamp)
17706 (eq this-command 'org-time-stamp))
17707 (insert "--")
17708 (setq time (let ((this-command this-command))
17709 (org-read-date arg 'totime nil nil default-time default-input)))
17710 (org-insert-time-stamp time (or org-time-was-given arg)))
17711 ((org-at-timestamp-p)
17712 (setq time (let ((this-command this-command))
17713 (org-read-date arg 'totime nil nil default-time default-input)))
17714 (when (org-at-timestamp-p) ; just to get the match data
17715 (replace-match "")
17716 (setq org-last-changed-timestamp
17717 (org-insert-time-stamp
17718 time (or org-time-was-given arg)
17719 nil nil nil (list org-end-time-was-given))))
17720 (message "Timestamp updated"))
17721 (t
17722 (setq time (let ((this-command this-command))
17723 (org-read-date arg 'totime nil nil default-time default-input)))
17724 (org-insert-time-stamp time (or org-time-was-given arg)
17725 nil nil nil (list org-end-time-was-given))))))
17726
17727 ;; FIXME: can we use this for something else????
17728 ;; like computing time differences?????
17729 (defun org-get-compact-tod (s)
17730 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17731 (let* ((t1 (match-string 1 s))
17732 (h1 (string-to-number (match-string 2 s)))
17733 (m1 (string-to-number (match-string 3 s)))
17734 (t2 (and (match-end 4) (match-string 5 s)))
17735 (h2 (and t2 (string-to-number (match-string 6 s))))
17736 (m2 (and t2 (string-to-number (match-string 7 s))))
17737 dh dm)
17738 (if (not t2)
17739 t1
17740 (setq dh (- h2 h1) dm (- m2 m1))
17741 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17742 (concat t1 "+" (number-to-string dh)
17743 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17744
17745 (defun org-time-stamp-inactive (&optional arg)
17746 "Insert an inactive time stamp.
17747 An inactive time stamp is enclosed in square brackets instead of angle
17748 brackets. It is inactive in the sense that it does not trigger agenda entries,
17749 does not link to the calendar and cannot be changed with the S-cursor keys.
17750 So these are more for recording a certain time/date."
17751 (interactive "P")
17752 (let (org-time-was-given org-end-time-was-given time)
17753 (setq time (org-read-date arg 'totime))
17754 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17755 nil nil (list org-end-time-was-given))))
17756
17757 (defvar org-date-ovl (org-make-overlay 1 1))
17758 (org-overlay-put org-date-ovl 'face 'org-warning)
17759 (org-detach-overlay org-date-ovl)
17760
17761 (defvar org-ans1) ; dynamically scoped parameter
17762 (defvar org-ans2) ; dynamically scoped parameter
17763
17764 (defvar org-plain-time-of-day-regexp) ; defined below
17765
17766 (defvar org-read-date-overlay nil)
17767 (defvar org-dcst nil) ; dynamically scoped
17768
17769 (defun org-read-date (&optional with-time to-time from-string prompt
17770 default-time default-input)
17771 "Read a date, possibly a time, and make things smooth for the user.
17772 The prompt will suggest to enter an ISO date, but you can also enter anything
17773 which will at least partially be understood by `parse-time-string'.
17774 Unrecognized parts of the date will default to the current day, month, year,
17775 hour and minute. If this command is called to replace a timestamp at point,
17776 of to enter the second timestamp of a range, the default time is taken from the
17777 existing stamp. For example,
17778 3-2-5 --> 2003-02-05
17779 feb 15 --> currentyear-02-15
17780 sep 12 9 --> 2009-09-12
17781 12:45 --> today 12:45
17782 22 sept 0:34 --> currentyear-09-22 0:34
17783 12 --> currentyear-currentmonth-12
17784 Fri --> nearest Friday (today or later)
17785 etc.
17786
17787 Furthermore you can specify a relative date by giving, as the *first* thing
17788 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17789 change in days weeks, months, years.
17790 With a single plus or minus, the date is relative to today. With a double
17791 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17792 +4d --> four days from today
17793 +4 --> same as above
17794 +2w --> two weeks from today
17795 ++5 --> five days from default date
17796
17797 The function understands only English month and weekday abbreviations,
17798 but this can be configured with the variables `parse-time-months' and
17799 `parse-time-weekdays'.
17800
17801 While prompting, a calendar is popped up - you can also select the
17802 date with the mouse (button 1). The calendar shows a period of three
17803 months. To scroll it to other months, use the keys `>' and `<'.
17804 If you don't like the calendar, turn it off with
17805 \(setq org-read-date-popup-calendar nil)
17806
17807 With optional argument TO-TIME, the date will immediately be converted
17808 to an internal time.
17809 With an optional argument WITH-TIME, the prompt will suggest to also
17810 insert a time. Note that when WITH-TIME is not set, you can still
17811 enter a time, and this function will inform the calling routine about
17812 this change. The calling routine may then choose to change the format
17813 used to insert the time stamp into the buffer to include the time.
17814 With optional argument FROM-STRING, read from this string instead from
17815 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17816 the time/date that is used for everything that is not specified by the
17817 user."
17818 (require 'parse-time)
17819 (let* ((org-time-stamp-rounding-minutes
17820 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
17821 (org-dcst org-display-custom-times)
17822 (ct (org-current-time))
17823 (def (or default-time ct))
17824 (defdecode (decode-time def))
17825 (dummy (progn
17826 (when (< (nth 2 defdecode) org-extend-today-until)
17827 (setcar (nthcdr 2 defdecode) -1)
17828 (setcar (nthcdr 1 defdecode) 59)
17829 (setq def (apply 'encode-time defdecode)
17830 defdecode (decode-time def)))))
17831 (calendar-move-hook nil)
17832 (calendar-view-diary-initially-flag nil)
17833 (view-diary-entries-initially nil)
17834 (calendar-view-holidays-initially-flag nil)
17835 (view-calendar-holidays-initially nil)
17836 (timestr (format-time-string
17837 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17838 (prompt (concat (if prompt (concat prompt " ") "")
17839 (format "Date+time [%s]: " timestr)))
17840 ans (org-ans0 "") org-ans1 org-ans2 final)
17841
17842 (cond
17843 (from-string (setq ans from-string))
17844 (org-read-date-popup-calendar
17845 (save-excursion
17846 (save-window-excursion
17847 (calendar)
17848 (calendar-forward-day (- (time-to-days def)
17849 (calendar-absolute-from-gregorian
17850 (calendar-current-date))))
17851 (org-eval-in-calendar nil t)
17852 (let* ((old-map (current-local-map))
17853 (map (copy-keymap calendar-mode-map))
17854 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17855 (org-defkey map (kbd "RET") 'org-calendar-select)
17856 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17857 'org-calendar-select-mouse)
17858 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17859 'org-calendar-select-mouse)
17860 (org-defkey minibuffer-local-map [(meta shift left)]
17861 (lambda () (interactive)
17862 (org-eval-in-calendar '(calendar-backward-month 1))))
17863 (org-defkey minibuffer-local-map [(meta shift right)]
17864 (lambda () (interactive)
17865 (org-eval-in-calendar '(calendar-forward-month 1))))
17866 (org-defkey minibuffer-local-map [(meta shift up)]
17867 (lambda () (interactive)
17868 (org-eval-in-calendar '(calendar-backward-year 1))))
17869 (org-defkey minibuffer-local-map [(meta shift down)]
17870 (lambda () (interactive)
17871 (org-eval-in-calendar '(calendar-forward-year 1))))
17872 (org-defkey minibuffer-local-map [(shift up)]
17873 (lambda () (interactive)
17874 (org-eval-in-calendar '(calendar-backward-week 1))))
17875 (org-defkey minibuffer-local-map [(shift down)]
17876 (lambda () (interactive)
17877 (org-eval-in-calendar '(calendar-forward-week 1))))
17878 (org-defkey minibuffer-local-map [(shift left)]
17879 (lambda () (interactive)
17880 (org-eval-in-calendar '(calendar-backward-day 1))))
17881 (org-defkey minibuffer-local-map [(shift right)]
17882 (lambda () (interactive)
17883 (org-eval-in-calendar '(calendar-forward-day 1))))
17884 (org-defkey minibuffer-local-map ">"
17885 (lambda () (interactive)
17886 (org-eval-in-calendar '(scroll-calendar-left 1))))
17887 (org-defkey minibuffer-local-map "<"
17888 (lambda () (interactive)
17889 (org-eval-in-calendar '(scroll-calendar-right 1))))
17890 (unwind-protect
17891 (progn
17892 (use-local-map map)
17893 (add-hook 'post-command-hook 'org-read-date-display)
17894 (setq org-ans0 (read-string prompt default-input nil nil))
17895 ;; org-ans0: from prompt
17896 ;; org-ans1: from mouse click
17897 ;; org-ans2: from calendar motion
17898 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17899 (remove-hook 'post-command-hook 'org-read-date-display)
17900 (use-local-map old-map)
17901 (when org-read-date-overlay
17902 (org-delete-overlay org-read-date-overlay)
17903 (setq org-read-date-overlay nil)))))))
17904
17905 (t ; Naked prompt only
17906 (unwind-protect
17907 (setq ans (read-string prompt default-input nil timestr))
17908 (when org-read-date-overlay
17909 (org-delete-overlay org-read-date-overlay)
17910 (setq org-read-date-overlay nil)))))
17911
17912 (setq final (org-read-date-analyze ans def defdecode))
17913
17914 (if to-time
17915 (apply 'encode-time final)
17916 (if (and (boundp 'org-time-was-given) org-time-was-given)
17917 (format "%04d-%02d-%02d %02d:%02d"
17918 (nth 5 final) (nth 4 final) (nth 3 final)
17919 (nth 2 final) (nth 1 final))
17920 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17921 (defvar def)
17922 (defvar defdecode)
17923 (defvar with-time)
17924 (defun org-read-date-display ()
17925 "Display the currrent date prompt interpretation in the minibuffer."
17926 (when org-read-date-display-live
17927 (when org-read-date-overlay
17928 (org-delete-overlay org-read-date-overlay))
17929 (let ((p (point)))
17930 (end-of-line 1)
17931 (while (not (equal (buffer-substring
17932 (max (point-min) (- (point) 4)) (point))
17933 " "))
17934 (insert " "))
17935 (goto-char p))
17936 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17937 " " (or org-ans1 org-ans2)))
17938 (org-end-time-was-given nil)
17939 (f (org-read-date-analyze ans def defdecode))
17940 (fmts (if org-dcst
17941 org-time-stamp-custom-formats
17942 org-time-stamp-formats))
17943 (fmt (if (or with-time
17944 (and (boundp 'org-time-was-given) org-time-was-given))
17945 (cdr fmts)
17946 (car fmts)))
17947 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17948 (when (and org-end-time-was-given
17949 (string-match org-plain-time-of-day-regexp txt))
17950 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17951 org-end-time-was-given
17952 (substring txt (match-end 0)))))
17953 (setq org-read-date-overlay
17954 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17955 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17956
17957 (defun org-read-date-analyze (ans def defdecode)
17958 "Analyze the combined answer of the date prompt."
17959 ;; FIXME: cleanup and comment
17960 (let (delta deltan deltaw deltadef year month day
17961 hour minute second wday pm h2 m2 tl wday1)
17962
17963 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17964 (setq ans (replace-match "" t t ans)
17965 deltan (car delta)
17966 deltaw (nth 1 delta)
17967 deltadef (nth 2 delta)))
17968
17969 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17970 (when (string-match
17971 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17972 (setq year (if (match-end 2)
17973 (string-to-number (match-string 2 ans))
17974 (string-to-number (format-time-string "%Y")))
17975 month (string-to-number (match-string 3 ans))
17976 day (string-to-number (match-string 4 ans)))
17977 (if (< year 100) (setq year (+ 2000 year)))
17978 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17979 t nil ans)))
17980 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17981 ;; If there is a time with am/pm, and *no* time without it, we convert
17982 ;; so that matching will be successful.
17983 (loop for i from 1 to 2 do ; twice, for end time as well
17984 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17985 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17986 (setq hour (string-to-number (match-string 1 ans))
17987 minute (if (match-end 3)
17988 (string-to-number (match-string 3 ans))
17989 0)
17990 pm (equal ?p
17991 (string-to-char (downcase (match-string 4 ans)))))
17992 (if (and (= hour 12) (not pm))
17993 (setq hour 0)
17994 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17995 (setq ans (replace-match (format "%02d:%02d" hour minute)
17996 t t ans))))
17997
17998 ;; Check if a time range is given as a duration
17999 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
18000 (setq hour (string-to-number (match-string 1 ans))
18001 h2 (+ hour (string-to-number (match-string 3 ans)))
18002 minute (string-to-number (match-string 2 ans))
18003 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
18004 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
18005 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
18006
18007 ;; Check if there is a time range
18008 (when (boundp 'org-end-time-was-given)
18009 (setq org-time-was-given nil)
18010 (when (and (string-match org-plain-time-of-day-regexp ans)
18011 (match-end 8))
18012 (setq org-end-time-was-given (match-string 8 ans))
18013 (setq ans (concat (substring ans 0 (match-beginning 7))
18014 (substring ans (match-end 7))))))
18015
18016 (setq tl (parse-time-string ans)
18017 day (or (nth 3 tl) (nth 3 defdecode))
18018 month (or (nth 4 tl)
18019 (if (and org-read-date-prefer-future
18020 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
18021 (1+ (nth 4 defdecode))
18022 (nth 4 defdecode)))
18023 year (or (nth 5 tl)
18024 (if (and org-read-date-prefer-future
18025 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
18026 (1+ (nth 5 defdecode))
18027 (nth 5 defdecode)))
18028 hour (or (nth 2 tl) (nth 2 defdecode))
18029 minute (or (nth 1 tl) (nth 1 defdecode))
18030 second (or (nth 0 tl) 0)
18031 wday (nth 6 tl))
18032 (when deltan
18033 (unless deltadef
18034 (let ((now (decode-time (current-time))))
18035 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
18036 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
18037 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
18038 ((equal deltaw "m") (setq month (+ month deltan)))
18039 ((equal deltaw "y") (setq year (+ year deltan)))))
18040 (when (and wday (not (nth 3 tl)))
18041 ;; Weekday was given, but no day, so pick that day in the week
18042 ;; on or after the derived date.
18043 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
18044 (unless (equal wday wday1)
18045 (setq day (+ day (% (- wday wday1 -7) 7)))))
18046 (if (and (boundp 'org-time-was-given)
18047 (nth 2 tl))
18048 (setq org-time-was-given t))
18049 (if (< year 100) (setq year (+ 2000 year)))
18050 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
18051 (list second minute hour day month year)))
18052
18053 (defvar parse-time-weekdays)
18054
18055 (defun org-read-date-get-relative (s today default)
18056 "Check string S for special relative date string.
18057 TODAY and DEFAULT are internal times, for today and for a default.
18058 Return shift list (N what def-flag)
18059 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
18060 N is the number of WHATs to shift.
18061 DEF-FLAG is t when a double ++ or -- indicates shift relative to
18062 the DEFAULT date rather than TODAY."
18063 (when (string-match
18064 (concat
18065 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
18066 "\\([0-9]+\\)?"
18067 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
18068 "\\([ \t]\\|$\\)") s)
18069 (let* ((dir (if (match-end 1)
18070 (string-to-char (substring (match-string 1 s) -1))
18071 ?+))
18072 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
18073 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
18074 (what (if (match-end 3) (match-string 3 s) "d"))
18075 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
18076 (date (if rel default today))
18077 (wday (nth 6 (decode-time date)))
18078 delta)
18079 (if wday1
18080 (progn
18081 (setq delta (mod (+ 7 (- wday1 wday)) 7))
18082 (if (= dir ?-) (setq delta (- delta 7)))
18083 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
18084 (list delta "d" rel))
18085 (list (* n (if (= dir ?-) -1 1)) what rel)))))
18086
18087 (defun org-eval-in-calendar (form &optional keepdate)
18088 "Eval FORM in the calendar window and return to current window.
18089 Also, store the cursor date in variable org-ans2."
18090 (let ((sw (selected-window)))
18091 (select-window (get-buffer-window "*Calendar*"))
18092 (eval form)
18093 (when (and (not keepdate) (calendar-cursor-to-date))
18094 (let* ((date (calendar-cursor-to-date))
18095 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18096 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
18097 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
18098 (select-window sw)))
18099
18100 ; ;; Update the prompt to show new default date
18101 ; (save-excursion
18102 ; (goto-char (point-min))
18103 ; (when (and org-ans2
18104 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
18105 ; (get-text-property (match-end 0) 'field))
18106 ; (let ((inhibit-read-only t))
18107 ; (replace-match (concat "[" org-ans2 "]") t t)
18108 ; (add-text-properties (point-min) (1+ (match-end 0))
18109 ; (text-properties-at (1+ (point-min)))))))))
18110
18111 (defun org-calendar-select ()
18112 "Return to `org-read-date' with the date currently selected.
18113 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18114 (interactive)
18115 (when (calendar-cursor-to-date)
18116 (let* ((date (calendar-cursor-to-date))
18117 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18118 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18119 (if (active-minibuffer-window) (exit-minibuffer))))
18120
18121 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
18122 "Insert a date stamp for the date given by the internal TIME.
18123 WITH-HM means, use the stamp format that includes the time of the day.
18124 INACTIVE means use square brackets instead of angular ones, so that the
18125 stamp will not contribute to the agenda.
18126 PRE and POST are optional strings to be inserted before and after the
18127 stamp.
18128 The command returns the inserted time stamp."
18129 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
18130 stamp)
18131 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
18132 (insert-before-markers (or pre ""))
18133 (insert-before-markers (setq stamp (format-time-string fmt time)))
18134 (when (listp extra)
18135 (setq extra (car extra))
18136 (if (and (stringp extra)
18137 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
18138 (setq extra (format "-%02d:%02d"
18139 (string-to-number (match-string 1 extra))
18140 (string-to-number (match-string 2 extra))))
18141 (setq extra nil)))
18142 (when extra
18143 (backward-char 1)
18144 (insert-before-markers extra)
18145 (forward-char 1))
18146 (insert-before-markers (or post ""))
18147 stamp))
18148
18149 (defun org-toggle-time-stamp-overlays ()
18150 "Toggle the use of custom time stamp formats."
18151 (interactive)
18152 (setq org-display-custom-times (not org-display-custom-times))
18153 (unless org-display-custom-times
18154 (let ((p (point-min)) (bmp (buffer-modified-p)))
18155 (while (setq p (next-single-property-change p 'display))
18156 (if (and (get-text-property p 'display)
18157 (eq (get-text-property p 'face) 'org-date))
18158 (remove-text-properties
18159 p (setq p (next-single-property-change p 'display))
18160 '(display t))))
18161 (set-buffer-modified-p bmp)))
18162 (if (featurep 'xemacs)
18163 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
18164 (org-restart-font-lock)
18165 (setq org-table-may-need-update t)
18166 (if org-display-custom-times
18167 (message "Time stamps are overlayed with custom format")
18168 (message "Time stamp overlays removed")))
18169
18170 (defun org-display-custom-time (beg end)
18171 "Overlay modified time stamp format over timestamp between BED and END."
18172 (let* ((ts (buffer-substring beg end))
18173 t1 w1 with-hm tf time str w2 (off 0))
18174 (save-match-data
18175 (setq t1 (org-parse-time-string ts t))
18176 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
18177 (setq off (- (match-end 0) (match-beginning 0)))))
18178 (setq end (- end off))
18179 (setq w1 (- end beg)
18180 with-hm (and (nth 1 t1) (nth 2 t1))
18181 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
18182 time (org-fix-decoded-time t1)
18183 str (org-add-props
18184 (format-time-string
18185 (substring tf 1 -1) (apply 'encode-time time))
18186 nil 'mouse-face 'highlight)
18187 w2 (length str))
18188 (if (not (= w2 w1))
18189 (add-text-properties (1+ beg) (+ 2 beg)
18190 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
18191 (if (featurep 'xemacs)
18192 (progn
18193 (put-text-property beg end 'invisible t)
18194 (put-text-property beg end 'end-glyph (make-glyph str)))
18195 (put-text-property beg end 'display str))))
18196
18197 (defun org-translate-time (string)
18198 "Translate all timestamps in STRING to custom format.
18199 But do this only if the variable `org-display-custom-times' is set."
18200 (when org-display-custom-times
18201 (save-match-data
18202 (let* ((start 0)
18203 (re org-ts-regexp-both)
18204 t1 with-hm inactive tf time str beg end)
18205 (while (setq start (string-match re string start))
18206 (setq beg (match-beginning 0)
18207 end (match-end 0)
18208 t1 (save-match-data
18209 (org-parse-time-string (substring string beg end) t))
18210 with-hm (and (nth 1 t1) (nth 2 t1))
18211 inactive (equal (substring string beg (1+ beg)) "[")
18212 tf (funcall (if with-hm 'cdr 'car)
18213 org-time-stamp-custom-formats)
18214 time (org-fix-decoded-time t1)
18215 str (format-time-string
18216 (concat
18217 (if inactive "[" "<") (substring tf 1 -1)
18218 (if inactive "]" ">"))
18219 (apply 'encode-time time))
18220 string (replace-match str t t string)
18221 start (+ start (length str)))))))
18222 string)
18223
18224 (defun org-fix-decoded-time (time)
18225 "Set 0 instead of nil for the first 6 elements of time.
18226 Don't touch the rest."
18227 (let ((n 0))
18228 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
18229
18230 (defun org-days-to-time (timestamp-string)
18231 "Difference between TIMESTAMP-STRING and now in days."
18232 (- (time-to-days (org-time-string-to-time timestamp-string))
18233 (time-to-days (current-time))))
18234
18235 (defun org-deadline-close (timestamp-string &optional ndays)
18236 "Is the time in TIMESTAMP-STRING close to the current date?"
18237 (setq ndays (or ndays (org-get-wdays timestamp-string)))
18238 (and (< (org-days-to-time timestamp-string) ndays)
18239 (not (org-entry-is-done-p))))
18240
18241 (defun org-get-wdays (ts)
18242 "Get the deadline lead time appropriate for timestring TS."
18243 (cond
18244 ((<= org-deadline-warning-days 0)
18245 ;; 0 or negative, enforce this value no matter what
18246 (- org-deadline-warning-days))
18247 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
18248 ;; lead time is specified.
18249 (floor (* (string-to-number (match-string 1 ts))
18250 (cdr (assoc (match-string 2 ts)
18251 '(("d" . 1) ("w" . 7)
18252 ("m" . 30.4) ("y" . 365.25)))))))
18253 ;; go for the default.
18254 (t org-deadline-warning-days)))
18255
18256 (defun org-calendar-select-mouse (ev)
18257 "Return to `org-read-date' with the date currently selected.
18258 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18259 (interactive "e")
18260 (mouse-set-point ev)
18261 (when (calendar-cursor-to-date)
18262 (let* ((date (calendar-cursor-to-date))
18263 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18264 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18265 (if (active-minibuffer-window) (exit-minibuffer))))
18266
18267 (defun org-check-deadlines (ndays)
18268 "Check if there are any deadlines due or past due.
18269 A deadline is considered due if it happens within `org-deadline-warning-days'
18270 days from today's date. If the deadline appears in an entry marked DONE,
18271 it is not shown. The prefix arg NDAYS can be used to test that many
18272 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18273 (interactive "P")
18274 (let* ((org-warn-days
18275 (cond
18276 ((equal ndays '(4)) 100000)
18277 (ndays (prefix-numeric-value ndays))
18278 (t (abs org-deadline-warning-days))))
18279 (case-fold-search nil)
18280 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18281 (callback
18282 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18283
18284 (message "%d deadlines past-due or due within %d days"
18285 (org-occur regexp nil callback)
18286 org-warn-days)))
18287
18288 (defun org-check-before-date (date)
18289 "Check if there are deadlines or scheduled entries before DATE."
18290 (interactive (list (org-read-date)))
18291 (let ((case-fold-search nil)
18292 (regexp (concat "\\<\\(" org-deadline-string
18293 "\\|" org-scheduled-string
18294 "\\) *<\\([^>]+\\)>"))
18295 (callback
18296 (lambda () (time-less-p
18297 (org-time-string-to-time (match-string 2))
18298 (org-time-string-to-time date)))))
18299 (message "%d entries before %s"
18300 (org-occur regexp nil callback) date)))
18301
18302 (defun org-evaluate-time-range (&optional to-buffer)
18303 "Evaluate a time range by computing the difference between start and end.
18304 Normally the result is just printed in the echo area, but with prefix arg
18305 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18306 If the time range is actually in a table, the result is inserted into the
18307 next column.
18308 For time difference computation, a year is assumed to be exactly 365
18309 days in order to avoid rounding problems."
18310 (interactive "P")
18311 (or
18312 (org-clock-update-time-maybe)
18313 (save-excursion
18314 (unless (org-at-date-range-p t)
18315 (goto-char (point-at-bol))
18316 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18317 (if (not (org-at-date-range-p t))
18318 (error "Not at a time-stamp range, and none found in current line")))
18319 (let* ((ts1 (match-string 1))
18320 (ts2 (match-string 2))
18321 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18322 (match-end (match-end 0))
18323 (time1 (org-time-string-to-time ts1))
18324 (time2 (org-time-string-to-time ts2))
18325 (t1 (time-to-seconds time1))
18326 (t2 (time-to-seconds time2))
18327 (diff (abs (- t2 t1)))
18328 (negative (< (- t2 t1) 0))
18329 ;; (ys (floor (* 365 24 60 60)))
18330 (ds (* 24 60 60))
18331 (hs (* 60 60))
18332 (fy "%dy %dd %02d:%02d")
18333 (fy1 "%dy %dd")
18334 (fd "%dd %02d:%02d")
18335 (fd1 "%dd")
18336 (fh "%02d:%02d")
18337 y d h m align)
18338 (if havetime
18339 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18340 y 0
18341 d (floor (/ diff ds)) diff (mod diff ds)
18342 h (floor (/ diff hs)) diff (mod diff hs)
18343 m (floor (/ diff 60)))
18344 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18345 y 0
18346 d (floor (+ (/ diff ds) 0.5))
18347 h 0 m 0))
18348 (if (not to-buffer)
18349 (message "%s" (org-make-tdiff-string y d h m))
18350 (if (org-at-table-p)
18351 (progn
18352 (goto-char match-end)
18353 (setq align t)
18354 (and (looking-at " *|") (goto-char (match-end 0))))
18355 (goto-char match-end))
18356 (if (looking-at
18357 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18358 (replace-match ""))
18359 (if negative (insert " -"))
18360 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18361 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18362 (insert " " (format fh h m))))
18363 (if align (org-table-align))
18364 (message "Time difference inserted")))))
18365
18366 (defun org-make-tdiff-string (y d h m)
18367 (let ((fmt "")
18368 (l nil))
18369 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18370 l (push y l)))
18371 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18372 l (push d l)))
18373 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18374 l (push h l)))
18375 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18376 l (push m l)))
18377 (apply 'format fmt (nreverse l))))
18378
18379 (defun org-time-string-to-time (s)
18380 (apply 'encode-time (org-parse-time-string s)))
18381
18382 (defun org-time-string-to-absolute (s &optional daynr prefer)
18383 "Convert a time stamp to an absolute day number.
18384 If there is a specifyer for a cyclic time stamp, get the closest date to
18385 DAYNR."
18386 (cond
18387 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18388 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18389 daynr
18390 (+ daynr 1000)))
18391 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18392 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18393 (time-to-days (current-time))) (match-string 0 s)
18394 prefer))
18395 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18396
18397 (defun org-time-from-absolute (d)
18398 "Return the time corresponding to date D.
18399 D may be an absolute day number, or a calendar-type list (month day year)."
18400 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18401 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18402
18403 (defun org-calendar-holiday ()
18404 "List of holidays, for Diary display in Org-mode."
18405 (require 'holidays)
18406 (let ((hl (funcall
18407 (if (fboundp 'calendar-check-holidays)
18408 'calendar-check-holidays 'check-calendar-holidays) date)))
18409 (if hl (mapconcat 'identity hl "; "))))
18410
18411 (defun org-diary-sexp-entry (sexp entry date)
18412 "Process a SEXP diary ENTRY for DATE."
18413 (require 'diary-lib)
18414 (let ((result (if calendar-debug-sexp
18415 (let ((stack-trace-on-error t))
18416 (eval (car (read-from-string sexp))))
18417 (condition-case nil
18418 (eval (car (read-from-string sexp)))
18419 (error
18420 (beep)
18421 (message "Bad sexp at line %d in %s: %s"
18422 (org-current-line)
18423 (buffer-file-name) sexp)
18424 (sleep-for 2))))))
18425 (cond ((stringp result) result)
18426 ((and (consp result)
18427 (stringp (cdr result))) (cdr result))
18428 (result entry)
18429 (t nil))))
18430
18431 (defun org-diary-to-ical-string (frombuf)
18432 "Get iCalendar entries from diary entries in buffer FROMBUF.
18433 This uses the icalendar.el library."
18434 (let* ((tmpdir (if (featurep 'xemacs)
18435 (temp-directory)
18436 temporary-file-directory))
18437 (tmpfile (make-temp-name
18438 (expand-file-name "orgics" tmpdir)))
18439 buf rtn b e)
18440 (save-excursion
18441 (set-buffer frombuf)
18442 (icalendar-export-region (point-min) (point-max) tmpfile)
18443 (setq buf (find-buffer-visiting tmpfile))
18444 (set-buffer buf)
18445 (goto-char (point-min))
18446 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18447 (setq b (match-beginning 0)))
18448 (goto-char (point-max))
18449 (if (re-search-backward "^END:VEVENT" nil t)
18450 (setq e (match-end 0)))
18451 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18452 (kill-buffer buf)
18453 (kill-buffer frombuf)
18454 (delete-file tmpfile)
18455 rtn))
18456
18457 (defun org-closest-date (start current change prefer)
18458 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18459 When PREFER is `past' return a date that is either CURRENT or past.
18460 When PREFER is `future', return a date that is either CURRENT or future."
18461 ;; Make the proper lists from the dates
18462 (catch 'exit
18463 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18464 dn dw sday cday n1 n2
18465 d m y y1 y2 date1 date2 nmonths nm ny m2)
18466
18467 (setq start (org-date-to-gregorian start)
18468 current (org-date-to-gregorian
18469 (if org-agenda-repeating-timestamp-show-all
18470 current
18471 (time-to-days (current-time))))
18472 sday (calendar-absolute-from-gregorian start)
18473 cday (calendar-absolute-from-gregorian current))
18474
18475 (if (<= cday sday) (throw 'exit sday))
18476
18477 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18478 (setq dn (string-to-number (match-string 1 change))
18479 dw (cdr (assoc (match-string 2 change) a1)))
18480 (error "Invalid change specifyer: %s" change))
18481 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18482 (cond
18483 ((eq dw 'day)
18484 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18485 n2 (+ n1 dn)))
18486 ((eq dw 'year)
18487 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18488 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18489 (setq date1 (list m d y1)
18490 n1 (calendar-absolute-from-gregorian date1)
18491 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18492 n2 (calendar-absolute-from-gregorian date2)))
18493 ((eq dw 'month)
18494 ;; approx number of month between the tow dates
18495 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18496 ;; How often does dn fit in there?
18497 (setq d (nth 1 start) m (car start) y (nth 2 start)
18498 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18499 m (+ m nm)
18500 ny (floor (/ m 12))
18501 y (+ y ny)
18502 m (- m (* ny 12)))
18503 (while (> m 12) (setq m (- m 12) y (1+ y)))
18504 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18505 (setq m2 (+ m dn) y2 y)
18506 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18507 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18508 (while (< n2 cday)
18509 (setq n1 n2 m m2 y y2)
18510 (setq m2 (+ m dn) y2 y)
18511 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18512 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18513
18514 (if org-agenda-repeating-timestamp-show-all
18515 (cond
18516 ((eq prefer 'past) n1)
18517 ((eq prefer 'future) (if (= cday n1) n1 n2))
18518 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18519 (cond
18520 ((eq prefer 'past) n1)
18521 ((eq prefer 'future) (if (= cday n1) n1 n2))
18522 (t (if (= cday n1) n1 n2)))))))
18523
18524 (defun org-date-to-gregorian (date)
18525 "Turn any specification of DATE into a gregorian date for the calendar."
18526 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18527 ((and (listp date) (= (length date) 3)) date)
18528 ((stringp date)
18529 (setq date (org-parse-time-string date))
18530 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18531 ((listp date)
18532 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18533
18534 (defun org-parse-time-string (s &optional nodefault)
18535 "Parse the standard Org-mode time string.
18536 This should be a lot faster than the normal `parse-time-string'.
18537 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18538 hour and minute fields will be nil if not given."
18539 (if (string-match org-ts-regexp0 s)
18540 (list 0
18541 (if (or (match-beginning 8) (not nodefault))
18542 (string-to-number (or (match-string 8 s) "0")))
18543 (if (or (match-beginning 7) (not nodefault))
18544 (string-to-number (or (match-string 7 s) "0")))
18545 (string-to-number (match-string 4 s))
18546 (string-to-number (match-string 3 s))
18547 (string-to-number (match-string 2 s))
18548 nil nil nil)
18549 (make-list 9 0)))
18550
18551 (defun org-timestamp-up (&optional arg)
18552 "Increase the date item at the cursor by one.
18553 If the cursor is on the year, change the year. If it is on the month or
18554 the day, change that.
18555 With prefix ARG, change by that many units."
18556 (interactive "p")
18557 (org-timestamp-change (prefix-numeric-value arg)))
18558
18559 (defun org-timestamp-down (&optional arg)
18560 "Decrease the date item at the cursor by one.
18561 If the cursor is on the year, change the year. If it is on the month or
18562 the day, change that.
18563 With prefix ARG, change by that many units."
18564 (interactive "p")
18565 (org-timestamp-change (- (prefix-numeric-value arg))))
18566
18567 (defun org-timestamp-up-day (&optional arg)
18568 "Increase the date in the time stamp by one day.
18569 With prefix ARG, change that many days."
18570 (interactive "p")
18571 (if (and (not (org-at-timestamp-p t))
18572 (org-on-heading-p))
18573 (org-todo 'up)
18574 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18575
18576 (defun org-timestamp-down-day (&optional arg)
18577 "Decrease the date in the time stamp by one day.
18578 With prefix ARG, change that many days."
18579 (interactive "p")
18580 (if (and (not (org-at-timestamp-p t))
18581 (org-on-heading-p))
18582 (org-todo 'down)
18583 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18584
18585 (defsubst org-pos-in-match-range (pos n)
18586 (and (match-beginning n)
18587 (<= (match-beginning n) pos)
18588 (>= (match-end n) pos)))
18589
18590 (defun org-at-timestamp-p (&optional inactive-ok)
18591 "Determine if the cursor is in or at a timestamp."
18592 (interactive)
18593 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18594 (pos (point))
18595 (ans (or (looking-at tsr)
18596 (save-excursion
18597 (skip-chars-backward "^[<\n\r\t")
18598 (if (> (point) (point-min)) (backward-char 1))
18599 (and (looking-at tsr)
18600 (> (- (match-end 0) pos) -1))))))
18601 (and ans
18602 (boundp 'org-ts-what)
18603 (setq org-ts-what
18604 (cond
18605 ((= pos (match-beginning 0)) 'bracket)
18606 ((= pos (1- (match-end 0))) 'bracket)
18607 ((org-pos-in-match-range pos 2) 'year)
18608 ((org-pos-in-match-range pos 3) 'month)
18609 ((org-pos-in-match-range pos 7) 'hour)
18610 ((org-pos-in-match-range pos 8) 'minute)
18611 ((or (org-pos-in-match-range pos 4)
18612 (org-pos-in-match-range pos 5)) 'day)
18613 ((and (> pos (or (match-end 8) (match-end 5)))
18614 (< pos (match-end 0)))
18615 (- pos (or (match-end 8) (match-end 5))))
18616 (t 'day))))
18617 ans))
18618
18619 (defun org-toggle-timestamp-type ()
18620 "Toggle the type (<active> or [inactive]) of a time stamp."
18621 (interactive)
18622 (when (org-at-timestamp-p t)
18623 (save-excursion
18624 (goto-char (match-beginning 0))
18625 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18626 (goto-char (1- (match-end 0)))
18627 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18628 (message "Timestamp is now %sactive"
18629 (if (equal (char-before) ?>) "in" ""))))
18630
18631 (defun org-timestamp-change (n &optional what)
18632 "Change the date in the time stamp at point.
18633 The date will be changed by N times WHAT. WHAT can be `day', `month',
18634 `year', `minute', `second'. If WHAT is not given, the cursor position
18635 in the timestamp determines what will be changed."
18636 (let ((pos (point))
18637 with-hm inactive
18638 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18639 org-ts-what
18640 extra rem
18641 ts time time0)
18642 (if (not (org-at-timestamp-p t))
18643 (error "Not at a timestamp"))
18644 (if (and (not what) (eq org-ts-what 'bracket))
18645 (org-toggle-timestamp-type)
18646 (if (and (not what) (not (eq org-ts-what 'day))
18647 org-display-custom-times
18648 (get-text-property (point) 'display)
18649 (not (get-text-property (1- (point)) 'display)))
18650 (setq org-ts-what 'day))
18651 (setq org-ts-what (or what org-ts-what)
18652 inactive (= (char-after (match-beginning 0)) ?\[)
18653 ts (match-string 0))
18654 (replace-match "")
18655 (if (string-match
18656 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
18657 ts)
18658 (setq extra (match-string 1 ts)))
18659 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18660 (setq with-hm t))
18661 (setq time0 (org-parse-time-string ts))
18662 (when (and (eq org-ts-what 'minute)
18663 (eq current-prefix-arg nil))
18664 (setq n (* dm (org-no-warnings (signum n))))
18665 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
18666 (setcar (cdr time0) (+ (nth 1 time0)
18667 (if (> n 0) (- rem) (- dm rem))))))
18668 (setq time
18669 (encode-time (or (car time0) 0)
18670 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18671 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18672 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18673 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18674 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18675 (nthcdr 6 time0)))
18676 (when (integerp org-ts-what)
18677 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18678 (if (eq what 'calendar)
18679 (let ((cal-date (org-get-date-from-calendar)))
18680 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18681 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18682 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18683 (setcar time0 (or (car time0) 0))
18684 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18685 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18686 (setq time (apply 'encode-time time0))))
18687 (setq org-last-changed-timestamp
18688 (org-insert-time-stamp time with-hm inactive nil nil extra))
18689 (org-clock-update-time-maybe)
18690 (goto-char pos)
18691 ;; Try to recenter the calendar window, if any
18692 (if (and org-calendar-follow-timestamp-change
18693 (get-buffer-window "*Calendar*" t)
18694 (memq org-ts-what '(day month year)))
18695 (org-recenter-calendar (time-to-days time))))))
18696
18697 ;; FIXME: does not yet work for lead times
18698 (defun org-modify-ts-extra (s pos n dm)
18699 "Change the different parts of the lead-time and repeat fields in timestamp."
18700 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18701 ng h m new rem)
18702 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18703 (cond
18704 ((or (org-pos-in-match-range pos 2)
18705 (org-pos-in-match-range pos 3))
18706 (setq m (string-to-number (match-string 3 s))
18707 h (string-to-number (match-string 2 s)))
18708 (if (org-pos-in-match-range pos 2)
18709 (setq h (+ h n))
18710 (setq n (* dm (org-no-warnings (signum n))))
18711 (when (not (= 0 (setq rem (% m dm))))
18712 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18713 (setq m (+ m n)))
18714 (if (< m 0) (setq m (+ m 60) h (1- h)))
18715 (if (> m 59) (setq m (- m 60) h (1+ h)))
18716 (setq h (min 24 (max 0 h)))
18717 (setq ng 1 new (format "-%02d:%02d" h m)))
18718 ((org-pos-in-match-range pos 6)
18719 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18720 ((org-pos-in-match-range pos 5)
18721 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18722
18723 ((org-pos-in-match-range pos 9)
18724 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18725 ((org-pos-in-match-range pos 8)
18726 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18727
18728 (when ng
18729 (setq s (concat
18730 (substring s 0 (match-beginning ng))
18731 new
18732 (substring s (match-end ng))))))
18733 s))
18734
18735 (defun org-recenter-calendar (date)
18736 "If the calendar is visible, recenter it to DATE."
18737 (let* ((win (selected-window))
18738 (cwin (get-buffer-window "*Calendar*" t))
18739 (calendar-move-hook nil))
18740 (when cwin
18741 (select-window cwin)
18742 (calendar-goto-date (if (listp date) date
18743 (calendar-gregorian-from-absolute date)))
18744 (select-window win))))
18745
18746 (defun org-goto-calendar (&optional arg)
18747 "Go to the Emacs calendar at the current date.
18748 If there is a time stamp in the current line, go to that date.
18749 A prefix ARG can be used to force the current date."
18750 (interactive "P")
18751 (let ((tsr org-ts-regexp) diff
18752 (calendar-move-hook nil)
18753 (calendar-view-holidays-initially-flag nil)
18754 (view-calendar-holidays-initially nil)
18755 (calendar-view-diary-initially-flag nil)
18756 (view-diary-entries-initially nil))
18757 (if (or (org-at-timestamp-p)
18758 (save-excursion
18759 (beginning-of-line 1)
18760 (looking-at (concat ".*" tsr))))
18761 (let ((d1 (time-to-days (current-time)))
18762 (d2 (time-to-days
18763 (org-time-string-to-time (match-string 1)))))
18764 (setq diff (- d2 d1))))
18765 (calendar)
18766 (calendar-goto-today)
18767 (if (and diff (not arg)) (calendar-forward-day diff))))
18768
18769 (defun org-get-date-from-calendar ()
18770 "Return a list (month day year) of date at point in calendar."
18771 (with-current-buffer "*Calendar*"
18772 (save-match-data
18773 (calendar-cursor-to-date))))
18774
18775 (defun org-date-from-calendar ()
18776 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18777 If there is already a time stamp at the cursor position, update it."
18778 (interactive)
18779 (if (org-at-timestamp-p t)
18780 (org-timestamp-change 0 'calendar)
18781 (let ((cal-date (org-get-date-from-calendar)))
18782 (org-insert-time-stamp
18783 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18784
18785 (defvar appt-time-msg-list)
18786
18787 ;;;###autoload
18788 (defun org-agenda-to-appt (&optional refresh filter)
18789 "Activate appointments found in `org-agenda-files'.
18790 With a \\[universal-argument] prefix, refresh the list of
18791 appointements.
18792
18793 If FILTER is t, interactively prompt the user for a regular
18794 expression, and filter out entries that don't match it.
18795
18796 If FILTER is a string, use this string as a regular expression
18797 for filtering entries out.
18798
18799 FILTER can also be an alist with the car of each cell being
18800 either 'headline or 'category. For example:
18801
18802 '((headline \"IMPORTANT\")
18803 (category \"Work\"))
18804
18805 will only add headlines containing IMPORTANT or headlines
18806 belonging to the \"Work\" category."
18807 (interactive "P")
18808 (require 'calendar)
18809 (if refresh (setq appt-time-msg-list nil))
18810 (if (eq filter t)
18811 (setq filter (read-from-minibuffer "Regexp filter: ")))
18812 (let* ((cnt 0) ; count added events
18813 (org-agenda-new-buffers nil)
18814 (org-deadline-warning-days 0)
18815 (today (org-date-to-gregorian
18816 (time-to-days (current-time))))
18817 (files (org-agenda-files)) entries file)
18818 ;; Get all entries which may contain an appt
18819 (while (setq file (pop files))
18820 (setq entries
18821 (append entries
18822 (org-agenda-get-day-entries
18823 file today :timestamp :scheduled :deadline))))
18824 (setq entries (delq nil entries))
18825 ;; Map thru entries and find if we should filter them out
18826 (mapc
18827 (lambda(x)
18828 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18829 (cat (get-text-property 1 'org-category x))
18830 (tod (get-text-property 1 'time-of-day x))
18831 (ok (or (null filter)
18832 (and (stringp filter) (string-match filter evt))
18833 (and (listp filter)
18834 (or (string-match
18835 (cadr (assoc 'category filter)) cat)
18836 (string-match
18837 (cadr (assoc 'headline filter)) evt))))))
18838 ;; FIXME: Shall we remove text-properties for the appt text?
18839 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18840 (when (and ok tod)
18841 (setq tod (number-to-string tod)
18842 tod (when (string-match
18843 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18844 (concat (match-string 1 tod) ":"
18845 (match-string 2 tod))))
18846 (appt-add tod evt)
18847 (setq cnt (1+ cnt))))) entries)
18848 (org-release-buffers org-agenda-new-buffers)
18849 (if (eq cnt 0)
18850 (message "No event to add")
18851 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18852
18853 ;;; The clock for measuring work time.
18854
18855 (defvar org-mode-line-string "")
18856 (put 'org-mode-line-string 'risky-local-variable t)
18857
18858 (defvar org-mode-line-timer nil)
18859 (defvar org-clock-heading "")
18860 (defvar org-clock-start-time "")
18861
18862 (defun org-update-mode-line ()
18863 (let* ((delta (- (time-to-seconds (current-time))
18864 (time-to-seconds org-clock-start-time)))
18865 (h (floor delta 3600))
18866 (m (floor (- delta (* 3600 h)) 60)))
18867 (setq org-mode-line-string
18868 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18869 'help-echo "Org-mode clock is running"))
18870 (force-mode-line-update)))
18871
18872 (defvar org-clock-marker (make-marker)
18873 "Marker recording the last clock-in.")
18874 (defvar org-clock-mode-line-entry nil
18875 "Information for the modeline about the running clock.")
18876
18877 (defun org-clock-in ()
18878 "Start the clock on the current item.
18879 If necessary, clock-out of the currently active clock."
18880 (interactive)
18881 (org-clock-out t)
18882 (let (ts)
18883 (save-excursion
18884 (org-back-to-heading t)
18885 (when (and org-clock-in-switch-to-state
18886 (not (looking-at (concat outline-regexp "[ \t]*"
18887 org-clock-in-switch-to-state
18888 "\\>"))))
18889 (org-todo org-clock-in-switch-to-state))
18890 (if (and org-clock-heading-function
18891 (functionp org-clock-heading-function))
18892 (setq org-clock-heading (funcall org-clock-heading-function))
18893 (if (looking-at org-complex-heading-regexp)
18894 (setq org-clock-heading (match-string 4))
18895 (setq org-clock-heading "???")))
18896 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18897 (org-clock-find-position)
18898
18899 (insert "\n") (backward-char 1)
18900 (indent-relative)
18901 (insert org-clock-string " ")
18902 (setq org-clock-start-time (current-time))
18903 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18904 (move-marker org-clock-marker (point) (buffer-base-buffer))
18905 (or global-mode-string (setq global-mode-string '("")))
18906 (or (memq 'org-mode-line-string global-mode-string)
18907 (setq global-mode-string
18908 (append global-mode-string '(org-mode-line-string))))
18909 (org-update-mode-line)
18910 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18911 (message "Clock started at %s" ts))))
18912
18913 (defun org-clock-find-position ()
18914 "Find the location where the next clock line should be inserted."
18915 (org-back-to-heading t)
18916 (catch 'exit
18917 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18918 (re (concat "^[ \t]*" org-clock-string))
18919 (cnt 0)
18920 first last)
18921 (goto-char beg)
18922 (when (eobp) (newline) (setq end (max (point) end)))
18923 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18924 ;; we seem to have a CLOCK drawer, so go there.
18925 (beginning-of-line 2)
18926 (throw 'exit t))
18927 ;; Lets count the CLOCK lines
18928 (goto-char beg)
18929 (while (re-search-forward re end t)
18930 (setq first (or first (match-beginning 0))
18931 last (match-beginning 0)
18932 cnt (1+ cnt)))
18933 (when (and (integerp org-clock-into-drawer)
18934 (>= (1+ cnt) org-clock-into-drawer))
18935 ;; Wrap current entries into a new drawer
18936 (goto-char last)
18937 (beginning-of-line 2)
18938 (if (org-at-item-p) (org-end-of-item))
18939 (insert ":END:\n")
18940 (beginning-of-line 0)
18941 (org-indent-line-function)
18942 (goto-char first)
18943 (insert ":CLOCK:\n")
18944 (beginning-of-line 0)
18945 (org-indent-line-function)
18946 (org-flag-drawer t)
18947 (beginning-of-line 2)
18948 (throw 'exit nil))
18949
18950 (goto-char beg)
18951 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18952 (not (equal (match-string 1) org-clock-string)))
18953 ;; Planning info, skip to after it
18954 (beginning-of-line 2)
18955 (or (bolp) (newline)))
18956 (when (eq t org-clock-into-drawer)
18957 (insert ":CLOCK:\n:END:\n")
18958 (beginning-of-line -1)
18959 (org-indent-line-function)
18960 (org-flag-drawer t)
18961 (beginning-of-line 2)
18962 (org-indent-line-function)))))
18963
18964 (defun org-clock-out (&optional fail-quietly)
18965 "Stop the currently running clock.
18966 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18967 (interactive)
18968 (catch 'exit
18969 (if (not (marker-buffer org-clock-marker))
18970 (if fail-quietly (throw 'exit t) (error "No active clock")))
18971 (let (ts te s h m)
18972 (save-excursion
18973 (set-buffer (marker-buffer org-clock-marker))
18974 (goto-char org-clock-marker)
18975 (beginning-of-line 1)
18976 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18977 (equal (match-string 1) org-clock-string))
18978 (setq ts (match-string 2))
18979 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18980 (goto-char (match-end 0))
18981 (delete-region (point) (point-at-eol))
18982 (insert "--")
18983 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18984 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18985 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18986 h (floor (/ s 3600))
18987 s (- s (* 3600 h))
18988 m (floor (/ s 60))
18989 s (- s (* 60 s)))
18990 (insert " => " (format "%2d:%02d" h m))
18991 (move-marker org-clock-marker nil)
18992 (when org-log-note-clock-out
18993 (org-add-log-maybe 'clock-out))
18994 (when org-mode-line-timer
18995 (cancel-timer org-mode-line-timer)
18996 (setq org-mode-line-timer nil))
18997 (setq global-mode-string
18998 (delq 'org-mode-line-string global-mode-string))
18999 (force-mode-line-update)
19000 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
19001
19002 (defun org-clock-cancel ()
19003 "Cancel the running clock be removing the start timestamp."
19004 (interactive)
19005 (if (not (marker-buffer org-clock-marker))
19006 (error "No active clock"))
19007 (save-excursion
19008 (set-buffer (marker-buffer org-clock-marker))
19009 (goto-char org-clock-marker)
19010 (delete-region (1- (point-at-bol)) (point-at-eol)))
19011 (setq global-mode-string
19012 (delq 'org-mode-line-string global-mode-string))
19013 (force-mode-line-update)
19014 (message "Clock canceled"))
19015
19016 (defun org-clock-goto (&optional delete-windows)
19017 "Go to the currently clocked-in entry."
19018 (interactive "P")
19019 (if (not (marker-buffer org-clock-marker))
19020 (error "No active clock"))
19021 (switch-to-buffer-other-window
19022 (marker-buffer org-clock-marker))
19023 (if delete-windows (delete-other-windows))
19024 (goto-char org-clock-marker)
19025 (org-show-entry)
19026 (org-back-to-heading)
19027 (recenter))
19028
19029 (defvar org-clock-file-total-minutes nil
19030 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
19031 (make-variable-buffer-local 'org-clock-file-total-minutes)
19032
19033 (defun org-clock-sum (&optional tstart tend)
19034 "Sum the times for each subtree.
19035 Puts the resulting times in minutes as a text property on each headline."
19036 (interactive)
19037 (let* ((bmp (buffer-modified-p))
19038 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
19039 org-clock-string
19040 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
19041 (lmax 30)
19042 (ltimes (make-vector lmax 0))
19043 (t1 0)
19044 (level 0)
19045 ts te dt
19046 time)
19047 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
19048 (save-excursion
19049 (goto-char (point-max))
19050 (while (re-search-backward re nil t)
19051 (cond
19052 ((match-end 2)
19053 ;; Two time stamps
19054 (setq ts (match-string 2)
19055 te (match-string 3)
19056 ts (time-to-seconds
19057 (apply 'encode-time (org-parse-time-string ts)))
19058 te (time-to-seconds
19059 (apply 'encode-time (org-parse-time-string te)))
19060 ts (if tstart (max ts tstart) ts)
19061 te (if tend (min te tend) te)
19062 dt (- te ts)
19063 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
19064 ((match-end 4)
19065 ;; A naket time
19066 (setq t1 (+ t1 (string-to-number (match-string 5))
19067 (* 60 (string-to-number (match-string 4))))))
19068 (t ;; A headline
19069 (setq level (- (match-end 1) (match-beginning 1)))
19070 (when (or (> t1 0) (> (aref ltimes level) 0))
19071 (loop for l from 0 to level do
19072 (aset ltimes l (+ (aref ltimes l) t1)))
19073 (setq t1 0 time (aref ltimes level))
19074 (loop for l from level to (1- lmax) do
19075 (aset ltimes l 0))
19076 (goto-char (match-beginning 0))
19077 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
19078 (setq org-clock-file-total-minutes (aref ltimes 0)))
19079 (set-buffer-modified-p bmp)))
19080
19081 (defun org-clock-display (&optional total-only)
19082 "Show subtree times in the entire buffer.
19083 If TOTAL-ONLY is non-nil, only show the total time for the entire file
19084 in the echo area."
19085 (interactive)
19086 (org-remove-clock-overlays)
19087 (let (time h m p)
19088 (org-clock-sum)
19089 (unless total-only
19090 (save-excursion
19091 (goto-char (point-min))
19092 (while (or (and (equal (setq p (point)) (point-min))
19093 (get-text-property p :org-clock-minutes))
19094 (setq p (next-single-property-change
19095 (point) :org-clock-minutes)))
19096 (goto-char p)
19097 (when (setq time (get-text-property p :org-clock-minutes))
19098 (org-put-clock-overlay time (funcall outline-level))))
19099 (setq h (/ org-clock-file-total-minutes 60)
19100 m (- org-clock-file-total-minutes (* 60 h)))
19101 ;; Arrange to remove the overlays upon next change.
19102 (when org-remove-highlights-with-change
19103 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
19104 nil 'local))))
19105 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
19106
19107 (defvar org-clock-overlays nil)
19108 (make-variable-buffer-local 'org-clock-overlays)
19109
19110 (defun org-put-clock-overlay (time &optional level)
19111 "Put an overlays on the current line, displaying TIME.
19112 If LEVEL is given, prefix time with a corresponding number of stars.
19113 This creates a new overlay and stores it in `org-clock-overlays', so that it
19114 will be easy to remove."
19115 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
19116 (l (if level (org-get-valid-level level 0) 0))
19117 (off 0)
19118 ov tx)
19119 (move-to-column c)
19120 (unless (eolp) (skip-chars-backward "^ \t"))
19121 (skip-chars-backward " \t")
19122 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
19123 tx (concat (buffer-substring (1- (point)) (point))
19124 (make-string (+ off (max 0 (- c (current-column)))) ?.)
19125 (org-add-props (format "%s %2d:%02d%s"
19126 (make-string l ?*) h m
19127 (make-string (- 16 l) ?\ ))
19128 '(face secondary-selection))
19129 ""))
19130 (if (not (featurep 'xemacs))
19131 (org-overlay-put ov 'display tx)
19132 (org-overlay-put ov 'invisible t)
19133 (org-overlay-put ov 'end-glyph (make-glyph tx)))
19134 (push ov org-clock-overlays)))
19135
19136 (defun org-remove-clock-overlays (&optional beg end noremove)
19137 "Remove the occur highlights from the buffer.
19138 BEG and END are ignored. If NOREMOVE is nil, remove this function
19139 from the `before-change-functions' in the current buffer."
19140 (interactive)
19141 (unless org-inhibit-highlight-removal
19142 (mapc 'org-delete-overlay org-clock-overlays)
19143 (setq org-clock-overlays nil)
19144 (unless noremove
19145 (remove-hook 'before-change-functions
19146 'org-remove-clock-overlays 'local))))
19147
19148 (defun org-clock-out-if-current ()
19149 "Clock out if the current entry contains the running clock.
19150 This is used to stop the clock after a TODO entry is marked DONE,
19151 and is only done if the variable `org-clock-out-when-done' is not nil."
19152 (when (and org-clock-out-when-done
19153 (member state org-done-keywords)
19154 (equal (marker-buffer org-clock-marker) (current-buffer))
19155 (< (point) org-clock-marker)
19156 (> (save-excursion (outline-next-heading) (point))
19157 org-clock-marker))
19158 ;; Clock out, but don't accept a logging message for this.
19159 (let ((org-log-note-clock-out nil))
19160 (org-clock-out))))
19161
19162 (add-hook 'org-after-todo-state-change-hook
19163 'org-clock-out-if-current)
19164
19165 (defun org-check-running-clock ()
19166 "Check if the current buffer contains the running clock.
19167 If yes, offer to stop it and to save the buffer with the changes."
19168 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
19169 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
19170 (buffer-name))))
19171 (org-clock-out)
19172 (when (y-or-n-p "Save changed buffer?")
19173 (save-buffer))))
19174
19175 (defun org-clock-report (&optional arg)
19176 "Create a table containing a report about clocked time.
19177 If the cursor is inside an existing clocktable block, then the table
19178 will be updated. If not, a new clocktable will be inserted.
19179 When called with a prefix argument, move to the first clock table in the
19180 buffer and update it."
19181 (interactive "P")
19182 (org-remove-clock-overlays)
19183 (when arg
19184 (org-find-dblock "clocktable")
19185 (org-show-entry))
19186 (if (org-in-clocktable-p)
19187 (goto-char (org-in-clocktable-p))
19188 (org-create-dblock (list :name "clocktable"
19189 :maxlevel 2 :scope 'file)))
19190 (org-update-dblock))
19191
19192 (defun org-in-clocktable-p ()
19193 "Check if the cursor is in a clocktable."
19194 (let ((pos (point)) start)
19195 (save-excursion
19196 (end-of-line 1)
19197 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
19198 (setq start (match-beginning 0))
19199 (re-search-forward "^#\\+END:.*" nil t)
19200 (>= (match-end 0) pos)
19201 start))))
19202
19203 (defun org-clock-update-time-maybe ()
19204 "If this is a CLOCK line, update it and return t.
19205 Otherwise, return nil."
19206 (interactive)
19207 (save-excursion
19208 (beginning-of-line 1)
19209 (skip-chars-forward " \t")
19210 (when (looking-at org-clock-string)
19211 (let ((re (concat "[ \t]*" org-clock-string
19212 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
19213 "\\([ \t]*=>.*\\)?"))
19214 ts te h m s)
19215 (if (not (looking-at re))
19216 nil
19217 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
19218 (end-of-line 1)
19219 (setq ts (match-string 1)
19220 te (match-string 2))
19221 (setq s (- (time-to-seconds
19222 (apply 'encode-time (org-parse-time-string te)))
19223 (time-to-seconds
19224 (apply 'encode-time (org-parse-time-string ts))))
19225 h (floor (/ s 3600))
19226 s (- s (* 3600 h))
19227 m (floor (/ s 60))
19228 s (- s (* 60 s)))
19229 (insert " => " (format "%2d:%02d" h m))
19230 t)))))
19231
19232 (defun org-clock-special-range (key &optional time as-strings)
19233 "Return two times bordering a special time range.
19234 Key is a symbol specifying the range and can be one of `today', `yesterday',
19235 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
19236 A week starts Monday 0:00 and ends Sunday 24:00.
19237 The range is determined relative to TIME. TIME defaults to the current time.
19238 The return value is a cons cell with two internal times like the ones
19239 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
19240 the returned times will be formatted strings."
19241 (let* ((tm (decode-time (or time (current-time))))
19242 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
19243 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
19244 (dow (nth 6 tm))
19245 s1 m1 h1 d1 month1 y1 diff ts te fm)
19246 (cond
19247 ((eq key 'today)
19248 (setq h 0 m 0 h1 24 m1 0))
19249 ((eq key 'yesterday)
19250 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19251 ((eq key 'thisweek)
19252 (setq diff (if (= dow 0) 6 (1- dow))
19253 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19254 ((eq key 'lastweek)
19255 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19256 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19257 ((eq key 'thismonth)
19258 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19259 ((eq key 'lastmonth)
19260 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19261 ((eq key 'thisyear)
19262 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19263 ((eq key 'lastyear)
19264 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19265 (t (error "No such time block %s" key)))
19266 (setq ts (encode-time s m h d month y)
19267 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19268 (or d1 d) (or month1 month) (or y1 y)))
19269 (setq fm (cdr org-time-stamp-formats))
19270 (if as-strings
19271 (cons (format-time-string fm ts) (format-time-string fm te))
19272 (cons ts te))))
19273
19274 (defun org-dblock-write:clocktable (params)
19275 "Write the standard clocktable."
19276 (catch 'exit
19277 (let* ((hlchars '((1 . "*") (2 . "/")))
19278 (ins (make-marker))
19279 (total-time nil)
19280 (scope (plist-get params :scope))
19281 (tostring (plist-get params :tostring))
19282 (multifile (plist-get params :multifile))
19283 (header (plist-get params :header))
19284 (maxlevel (or (plist-get params :maxlevel) 3))
19285 (step (plist-get params :step))
19286 (emph (plist-get params :emphasize))
19287 (ts (plist-get params :tstart))
19288 (te (plist-get params :tend))
19289 (block (plist-get params :block))
19290 (link (plist-get params :link))
19291 ipos time h m p level hlc hdl
19292 cc beg end pos tbl)
19293 (when step
19294 (org-clocktable-steps params)
19295 (throw 'exit nil))
19296 (when block
19297 (setq cc (org-clock-special-range block nil t)
19298 ts (car cc) te (cdr cc)))
19299 (if ts (setq ts (time-to-seconds
19300 (apply 'encode-time (org-parse-time-string ts)))))
19301 (if te (setq te (time-to-seconds
19302 (apply 'encode-time (org-parse-time-string te)))))
19303 (move-marker ins (point))
19304 (setq ipos (point))
19305
19306 ;; Get the right scope
19307 (setq pos (point))
19308 (save-restriction
19309 (cond
19310 ((not scope))
19311 ((eq scope 'file) (widen))
19312 ((eq scope 'subtree) (org-narrow-to-subtree))
19313 ((eq scope 'tree)
19314 (while (org-up-heading-safe))
19315 (org-narrow-to-subtree))
19316 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19317 (symbol-name scope)))
19318 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19319 (catch 'exit
19320 (while (org-up-heading-safe)
19321 (looking-at outline-regexp)
19322 (if (<= (org-reduced-level (funcall outline-level)) level)
19323 (throw 'exit nil))))
19324 (org-narrow-to-subtree))
19325 ((or (listp scope) (eq scope 'agenda))
19326 (let* ((files (if (listp scope) scope (org-agenda-files)))
19327 (scope 'agenda)
19328 (p1 (copy-sequence params))
19329 file)
19330 (plist-put p1 :tostring t)
19331 (plist-put p1 :multifile t)
19332 (plist-put p1 :scope 'file)
19333 (org-prepare-agenda-buffers files)
19334 (while (setq file (pop files))
19335 (with-current-buffer (find-buffer-visiting file)
19336 (push (org-clocktable-add-file
19337 file (org-dblock-write:clocktable p1)) tbl)
19338 (setq total-time (+ (or total-time 0)
19339 org-clock-file-total-minutes)))))))
19340 (goto-char pos)
19341
19342 (unless (eq scope 'agenda)
19343 (org-clock-sum ts te)
19344 (goto-char (point-min))
19345 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19346 (goto-char p)
19347 (when (setq time (get-text-property p :org-clock-minutes))
19348 (save-excursion
19349 (beginning-of-line 1)
19350 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19351 (setq level (org-reduced-level
19352 (- (match-end 1) (match-beginning 1))))
19353 (<= level maxlevel))
19354 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19355 hdl (if (not link)
19356 (match-string 2)
19357 (org-make-link-string
19358 (format "file:%s::%s"
19359 (buffer-file-name)
19360 (save-match-data
19361 (org-make-org-heading-search-string
19362 (match-string 2))))
19363 (match-string 2)))
19364 h (/ time 60)
19365 m (- time (* 60 h)))
19366 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19367 (push (concat
19368 "| " (int-to-string level) "|" hlc hdl hlc " |"
19369 (make-string (1- level) ?|)
19370 hlc (format "%d:%02d" h m) hlc
19371 " |") tbl))))))
19372 (setq tbl (nreverse tbl))
19373 (if tostring
19374 (if tbl (mapconcat 'identity tbl "\n") nil)
19375 (goto-char ins)
19376 (insert-before-markers
19377 (or header
19378 (concat
19379 "Clock summary at ["
19380 (substring
19381 (format-time-string (cdr org-time-stamp-formats))
19382 1 -1)
19383 "]."
19384 (if block
19385 (format " Considered range is /%s/." block)
19386 "")
19387 "\n\n"))
19388 (if (eq scope 'agenda) "|File" "")
19389 "|L|Headline|Time|\n")
19390 (setq total-time (or total-time org-clock-file-total-minutes)
19391 h (/ total-time 60)
19392 m (- total-time (* 60 h)))
19393 (insert-before-markers
19394 "|-\n|"
19395 (if (eq scope 'agenda) "|" "")
19396 "|"
19397 "*Total time*| "
19398 (format "*%d:%02d*" h m)
19399 "|\n|-\n")
19400 (setq tbl (delq nil tbl))
19401 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19402 (equal (substring (car tbl) 0 2) "|-"))
19403 (pop tbl))
19404 (insert-before-markers (mapconcat
19405 'identity (delq nil tbl)
19406 (if (eq scope 'agenda) "\n|-\n" "\n")))
19407 (backward-delete-char 1)
19408 (goto-char ipos)
19409 (skip-chars-forward "^|")
19410 (org-table-align))))))
19411
19412 (defun org-clocktable-steps (params)
19413 (let* ((p1 (copy-sequence params))
19414 (ts (plist-get p1 :tstart))
19415 (te (plist-get p1 :tend))
19416 (step0 (plist-get p1 :step))
19417 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19418 (block (plist-get p1 :block))
19419 cc)
19420 (when block
19421 (setq cc (org-clock-special-range block nil t)
19422 ts (car cc) te (cdr cc)))
19423 (if ts (setq ts (time-to-seconds
19424 (apply 'encode-time (org-parse-time-string ts)))))
19425 (if te (setq te (time-to-seconds
19426 (apply 'encode-time (org-parse-time-string te)))))
19427 (plist-put p1 :header "")
19428 (plist-put p1 :step nil)
19429 (plist-put p1 :block nil)
19430 (while (< ts te)
19431 (or (bolp) (insert "\n"))
19432 (plist-put p1 :tstart (format-time-string
19433 (car org-time-stamp-formats)
19434 (seconds-to-time ts)))
19435 (plist-put p1 :tend (format-time-string
19436 (car org-time-stamp-formats)
19437 (seconds-to-time (setq ts (+ ts step)))))
19438 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19439 (plist-get p1 :tstart) "\n")
19440 (org-dblock-write:clocktable p1)
19441 (re-search-forward "#\\+END:")
19442 (end-of-line 0))))
19443
19444
19445 (defun org-clocktable-add-file (file table)
19446 (if table
19447 (let ((lines (org-split-string table "\n"))
19448 (ff (file-name-nondirectory file)))
19449 (mapconcat 'identity
19450 (mapcar (lambda (x)
19451 (if (string-match org-table-dataline-regexp x)
19452 (concat "|" ff x)
19453 x))
19454 lines)
19455 "\n"))))
19456
19457 ;; FIXME: I don't think anybody uses this, ask David
19458 (defun org-collect-clock-time-entries ()
19459 "Return an internal list with clocking information.
19460 This list has one entry for each CLOCK interval.
19461 FIXME: describe the elements."
19462 (interactive)
19463 (let ((re (concat "^[ \t]*" org-clock-string
19464 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19465 rtn beg end next cont level title total closedp leafp
19466 clockpos titlepos h m donep)
19467 (save-excursion
19468 (org-clock-sum)
19469 (goto-char (point-min))
19470 (while (re-search-forward re nil t)
19471 (setq clockpos (match-beginning 0)
19472 beg (match-string 1) end (match-string 2)
19473 cont (match-end 0))
19474 (setq beg (apply 'encode-time (org-parse-time-string beg))
19475 end (apply 'encode-time (org-parse-time-string end)))
19476 (org-back-to-heading t)
19477 (setq donep (org-entry-is-done-p))
19478 (setq titlepos (point)
19479 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19480 h (/ total 60) m (- total (* 60 h))
19481 total (cons h m))
19482 (looking-at "\\(\\*+\\) +\\(.*\\)")
19483 (setq level (- (match-end 1) (match-beginning 1))
19484 title (org-match-string-no-properties 2))
19485 (save-excursion (outline-next-heading) (setq next (point)))
19486 (setq closedp (re-search-forward org-closed-time-regexp next t))
19487 (goto-char next)
19488 (setq leafp (and (looking-at "^\\*+ ")
19489 (<= (- (match-end 0) (point)) level)))
19490 (push (list beg end clockpos closedp donep
19491 total title titlepos level leafp)
19492 rtn)
19493 (goto-char cont)))
19494 (nreverse rtn)))
19495
19496 ;;;; Agenda, and Diary Integration
19497
19498 ;;; Define the Org-agenda-mode
19499
19500 (defvar org-agenda-mode-map (make-sparse-keymap)
19501 "Keymap for `org-agenda-mode'.")
19502
19503 (defvar org-agenda-menu) ; defined later in this file.
19504 (defvar org-agenda-follow-mode nil)
19505 (defvar org-agenda-show-log nil)
19506 (defvar org-agenda-redo-command nil)
19507 (defvar org-agenda-query-string nil)
19508 (defvar org-agenda-mode-hook nil)
19509 (defvar org-agenda-type nil)
19510 (defvar org-agenda-force-single-file nil)
19511
19512 (defun org-agenda-mode ()
19513 "Mode for time-sorted view on action items in Org-mode files.
19514
19515 The following commands are available:
19516
19517 \\{org-agenda-mode-map}"
19518 (interactive)
19519 (kill-all-local-variables)
19520 (setq org-agenda-undo-list nil
19521 org-agenda-pending-undo-list nil)
19522 (setq major-mode 'org-agenda-mode)
19523 ;; Keep global-font-lock-mode from turning on font-lock-mode
19524 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19525 (setq mode-name "Org-Agenda")
19526 (use-local-map org-agenda-mode-map)
19527 (easy-menu-add org-agenda-menu)
19528 (if org-startup-truncated (setq truncate-lines t))
19529 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19530 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19531 ;; Make sure properties are removed when copying text
19532 (when (boundp 'buffer-substring-filters)
19533 (org-set-local 'buffer-substring-filters
19534 (cons (lambda (x)
19535 (set-text-properties 0 (length x) nil x) x)
19536 buffer-substring-filters)))
19537 (unless org-agenda-keep-modes
19538 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19539 org-agenda-show-log nil))
19540 (easy-menu-change
19541 '("Agenda") "Agenda Files"
19542 (append
19543 (list
19544 (vector
19545 (if (get 'org-agenda-files 'org-restrict)
19546 "Restricted to single file"
19547 "Edit File List")
19548 '(org-edit-agenda-file-list)
19549 (not (get 'org-agenda-files 'org-restrict)))
19550 "--")
19551 (mapcar 'org-file-menu-entry (org-agenda-files))))
19552 (org-agenda-set-mode-name)
19553 (apply
19554 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19555 (list 'org-agenda-mode-hook)))
19556
19557 (substitute-key-definition 'undo 'org-agenda-undo
19558 org-agenda-mode-map global-map)
19559 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19560 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19561 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19562 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19563 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19564 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19565 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19566 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19567 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19568 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19569 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19570 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19571 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19572 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19573 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19574 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19575 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19576 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19577 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19578 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19579 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19580 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19581 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19582 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19583 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19584 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19585 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19586 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19587 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19588
19589 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19590 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19591 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19592 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19593 (while l (org-defkey org-agenda-mode-map
19594 (int-to-string (pop l)) 'digit-argument)))
19595
19596 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19597 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19598 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19599 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19600 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19601 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19602 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19603 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19604 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19605 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19606 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19607 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19608 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19609 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19610 (org-defkey org-agenda-mode-map "n" 'next-line)
19611 (org-defkey org-agenda-mode-map "p" 'previous-line)
19612 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19613 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19614 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19615 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19616 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19617 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19618 (eval-after-load "calendar"
19619 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19620 'org-calendar-goto-agenda))
19621 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19622 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19623 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19624 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19625 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19626 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19627 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19628 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19629 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19630 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19631 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19632 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19633 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19634 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19635 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19636 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19637 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19638 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19639 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19640 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19641 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19642 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19643
19644 (org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add)
19645 (org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract)
19646 (org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re)
19647 (org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re)
19648
19649 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19650 "Local keymap for agenda entries from Org-mode.")
19651
19652 (org-defkey org-agenda-keymap
19653 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19654 (org-defkey org-agenda-keymap
19655 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19656 (when org-agenda-mouse-1-follows-link
19657 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19658 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19659 '("Agenda"
19660 ("Agenda Files")
19661 "--"
19662 ["Show" org-agenda-show t]
19663 ["Go To (other window)" org-agenda-goto t]
19664 ["Go To (this window)" org-agenda-switch-to t]
19665 ["Follow Mode" org-agenda-follow-mode
19666 :style toggle :selected org-agenda-follow-mode :active t]
19667 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19668 "--"
19669 ["Cycle TODO" org-agenda-todo t]
19670 ["Archive subtree" org-agenda-archive t]
19671 ["Delete subtree" org-agenda-kill t]
19672 "--"
19673 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19674 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19675 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19676 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19677 "--"
19678 ("Tags and Properties"
19679 ["Show all Tags" org-agenda-show-tags t]
19680 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19681 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19682 "--"
19683 ["Column View" org-columns t])
19684 ("Date/Schedule"
19685 ["Schedule" org-agenda-schedule t]
19686 ["Set Deadline" org-agenda-deadline t]
19687 "--"
19688 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19689 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19690 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19691 ("Clock"
19692 ["Clock in" org-agenda-clock-in t]
19693 ["Clock out" org-agenda-clock-out t]
19694 ["Clock cancel" org-agenda-clock-cancel t]
19695 ["Goto running clock" org-clock-goto t])
19696 ("Priority"
19697 ["Set Priority" org-agenda-priority t]
19698 ["Increase Priority" org-agenda-priority-up t]
19699 ["Decrease Priority" org-agenda-priority-down t]
19700 ["Show Priority" org-agenda-show-priority t])
19701 ("Calendar/Diary"
19702 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19703 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19704 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19705 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19706 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19707 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19708 "--"
19709 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19710 "--"
19711 ("View"
19712 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19713 :style radio :selected (equal org-agenda-ndays 1)]
19714 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19715 :style radio :selected (equal org-agenda-ndays 7)]
19716 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19717 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19718 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19719 :style radio :selected (member org-agenda-ndays '(365 366))]
19720 "--"
19721 ["Show Logbook entries" org-agenda-log-mode
19722 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19723 ["Include Diary" org-agenda-toggle-diary
19724 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19725 ["Use Time Grid" org-agenda-toggle-time-grid
19726 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19727 ["Write view to file" org-write-agenda t]
19728 ["Rebuild buffer" org-agenda-redo t]
19729 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19730 "--"
19731 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19732 "--"
19733 ["Quit" org-agenda-quit t]
19734 ["Exit and Release Buffers" org-agenda-exit t]
19735 ))
19736
19737 ;;; Agenda undo
19738
19739 (defvar org-agenda-allow-remote-undo t
19740 "Non-nil means, allow remote undo from the agenda buffer.")
19741 (defvar org-agenda-undo-list nil
19742 "List of undoable operations in the agenda since last refresh.")
19743 (defvar org-agenda-undo-has-started-in nil
19744 "Buffers that have already seen `undo-start' in the current undo sequence.")
19745 (defvar org-agenda-pending-undo-list nil
19746 "In a series of undo commands, this is the list of remaning undo items.")
19747
19748 (defmacro org-if-unprotected (&rest body)
19749 "Execute BODY if there is no `org-protected' text property at point."
19750 (declare (debug t))
19751 `(unless (get-text-property (point) 'org-protected)
19752 ,@body))
19753
19754 (defmacro org-with-remote-undo (_buffer &rest _body)
19755 "Execute BODY while recording undo information in two buffers."
19756 (declare (indent 1) (debug t))
19757 `(let ((_cline (org-current-line))
19758 (_cmd this-command)
19759 (_buf1 (current-buffer))
19760 (_buf2 ,_buffer)
19761 (_undo1 buffer-undo-list)
19762 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19763 _c1 _c2)
19764 ,@_body
19765 (when org-agenda-allow-remote-undo
19766 (setq _c1 (org-verify-change-for-undo
19767 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19768 _c2 (org-verify-change-for-undo
19769 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19770 (when (or _c1 _c2)
19771 ;; make sure there are undo boundaries
19772 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19773 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19774 ;; remember which buffer to undo
19775 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19776 org-agenda-undo-list)))))
19777
19778 (defun org-agenda-undo ()
19779 "Undo a remote editing step in the agenda.
19780 This undoes changes both in the agenda buffer and in the remote buffer
19781 that have been changed along."
19782 (interactive)
19783 (or org-agenda-allow-remote-undo
19784 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19785 (if (not (eq this-command last-command))
19786 (setq org-agenda-undo-has-started-in nil
19787 org-agenda-pending-undo-list org-agenda-undo-list))
19788 (if (not org-agenda-pending-undo-list)
19789 (error "No further undo information"))
19790 (let* ((entry (pop org-agenda-pending-undo-list))
19791 buf line cmd rembuf)
19792 (setq cmd (pop entry) line (pop entry))
19793 (setq rembuf (nth 2 entry))
19794 (org-with-remote-undo rembuf
19795 (while (bufferp (setq buf (pop entry)))
19796 (if (pop entry)
19797 (with-current-buffer buf
19798 (let ((last-undo-buffer buf)
19799 (inhibit-read-only t))
19800 (unless (memq buf org-agenda-undo-has-started-in)
19801 (push buf org-agenda-undo-has-started-in)
19802 (make-local-variable 'pending-undo-list)
19803 (undo-start))
19804 (while (and pending-undo-list
19805 (listp pending-undo-list)
19806 (not (car pending-undo-list)))
19807 (pop pending-undo-list))
19808 (undo-more 1))))))
19809 (goto-line line)
19810 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19811
19812 (defun org-verify-change-for-undo (l1 l2)
19813 "Verify that a real change occurred between the undo lists L1 and L2."
19814 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19815 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19816 (not (eq l1 l2)))
19817
19818 ;;; Agenda dispatch
19819
19820 (defvar org-agenda-restrict nil)
19821 (defvar org-agenda-restrict-begin (make-marker))
19822 (defvar org-agenda-restrict-end (make-marker))
19823 (defvar org-agenda-last-dispatch-buffer nil)
19824 (defvar org-agenda-overriding-restriction nil)
19825
19826 ;;;###autoload
19827 (defun org-agenda (arg &optional keys restriction)
19828 "Dispatch agenda commands to collect entries to the agenda buffer.
19829 Prompts for a command to execute. Any prefix arg will be passed
19830 on to the selected command. The default selections are:
19831
19832 a Call `org-agenda-list' to display the agenda for current day or week.
19833 t Call `org-todo-list' to display the global todo list.
19834 T Call `org-todo-list' to display the global todo list, select only
19835 entries with a specific TODO keyword (the user gets a prompt).
19836 m Call `org-tags-view' to display headlines with tags matching
19837 a condition (the user is prompted for the condition).
19838 M Like `m', but select only TODO entries, no ordinary headlines.
19839 L Create a timeline for the current buffer.
19840 e Export views to associated files.
19841
19842 More commands can be added by configuring the variable
19843 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19844 searches can be pre-defined in this way.
19845
19846 If the current buffer is in Org-mode and visiting a file, you can also
19847 first press `<' once to indicate that the agenda should be temporarily
19848 \(until the next use of \\[org-agenda]) restricted to the current file.
19849 Pressing `<' twice means to restrict to the current subtree or region
19850 \(if active)."
19851 (interactive "P")
19852 (catch 'exit
19853 (let* ((prefix-descriptions nil)
19854 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19855 (org-agenda-custom-commands
19856 ;; normalize different versions
19857 (delq nil
19858 (mapcar
19859 (lambda (x)
19860 (cond ((stringp (cdr x))
19861 (push x prefix-descriptions)
19862 nil)
19863 ((stringp (nth 1 x)) x)
19864 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19865 (t (cons (car x) (cons "" (cdr x))))))
19866 org-agenda-custom-commands)))
19867 (buf (current-buffer))
19868 (bfn (buffer-file-name (buffer-base-buffer)))
19869 entry key type match lprops ans)
19870 ;; Turn off restriction unless there is an overriding one
19871 (unless org-agenda-overriding-restriction
19872 (put 'org-agenda-files 'org-restrict nil)
19873 (setq org-agenda-restrict nil)
19874 (move-marker org-agenda-restrict-begin nil)
19875 (move-marker org-agenda-restrict-end nil))
19876 ;; Delete old local properties
19877 (put 'org-agenda-redo-command 'org-lprops nil)
19878 ;; Remember where this call originated
19879 (setq org-agenda-last-dispatch-buffer (current-buffer))
19880 (unless keys
19881 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19882 keys (car ans)
19883 restriction (cdr ans)))
19884 ;; Estabish the restriction, if any
19885 (when (and (not org-agenda-overriding-restriction) restriction)
19886 (put 'org-agenda-files 'org-restrict (list bfn))
19887 (cond
19888 ((eq restriction 'region)
19889 (setq org-agenda-restrict t)
19890 (move-marker org-agenda-restrict-begin (region-beginning))
19891 (move-marker org-agenda-restrict-end (region-end)))
19892 ((eq restriction 'subtree)
19893 (save-excursion
19894 (setq org-agenda-restrict t)
19895 (org-back-to-heading t)
19896 (move-marker org-agenda-restrict-begin (point))
19897 (move-marker org-agenda-restrict-end
19898 (progn (org-end-of-subtree t)))))))
19899
19900 (require 'calendar) ; FIXME: can we avoid this for some commands?
19901 ;; For example the todo list should not need it (but does...)
19902 (cond
19903 ((setq entry (assoc keys org-agenda-custom-commands))
19904 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19905 (progn
19906 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19907 (put 'org-agenda-redo-command 'org-lprops lprops)
19908 (cond
19909 ((eq type 'agenda)
19910 (org-let lprops '(org-agenda-list current-prefix-arg)))
19911 ((eq type 'alltodo)
19912 (org-let lprops '(org-todo-list current-prefix-arg)))
19913 ((eq type 'search)
19914 (org-let lprops '(org-search-view current-prefix-arg match)))
19915 ((eq type 'stuck)
19916 (org-let lprops '(org-agenda-list-stuck-projects
19917 current-prefix-arg)))
19918 ((eq type 'tags)
19919 (org-let lprops '(org-tags-view current-prefix-arg match)))
19920 ((eq type 'tags-todo)
19921 (org-let lprops '(org-tags-view '(4) match)))
19922 ((eq type 'todo)
19923 (org-let lprops '(org-todo-list match)))
19924 ((eq type 'tags-tree)
19925 (org-check-for-org-mode)
19926 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19927 ((eq type 'todo-tree)
19928 (org-check-for-org-mode)
19929 (org-let lprops
19930 '(org-occur (concat "^" outline-regexp "[ \t]*"
19931 (regexp-quote match) "\\>"))))
19932 ((eq type 'occur-tree)
19933 (org-check-for-org-mode)
19934 (org-let lprops '(org-occur match)))
19935 ((functionp type)
19936 (org-let lprops '(funcall type match)))
19937 ((fboundp type)
19938 (org-let lprops '(funcall type match)))
19939 (t (error "Invalid custom agenda command type %s" type))))
19940 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19941 ((equal keys "C")
19942 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19943 (customize-variable 'org-agenda-custom-commands))
19944 ((equal keys "a") (call-interactively 'org-agenda-list))
19945 ((equal keys "s") (call-interactively 'org-search-view))
19946 ((equal keys "t") (call-interactively 'org-todo-list))
19947 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19948 ((equal keys "m") (call-interactively 'org-tags-view))
19949 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19950 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19951 ((equal keys "L")
19952 (unless (org-mode-p)
19953 (error "This is not an Org-mode file"))
19954 (unless restriction
19955 (put 'org-agenda-files 'org-restrict (list bfn))
19956 (org-call-with-arg 'org-timeline arg)))
19957 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19958 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19959 ((equal keys "!") (customize-variable 'org-stuck-projects))
19960 (t (error "Invalid agenda key"))))))
19961
19962 (defun org-agenda-normalize-custom-commands (cmds)
19963 (delq nil
19964 (mapcar
19965 (lambda (x)
19966 (cond ((stringp (cdr x)) nil)
19967 ((stringp (nth 1 x)) x)
19968 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19969 (t (cons (car x) (cons "" (cdr x))))))
19970 cmds)))
19971
19972 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19973 "The user interface for selecting an agenda command."
19974 (catch 'exit
19975 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19976 (restrict-ok (and bfn (org-mode-p)))
19977 (region-p (org-region-active-p))
19978 (custom org-agenda-custom-commands)
19979 (selstring "")
19980 restriction second-time
19981 c entry key type match prefixes rmheader header-end custom1 desc)
19982 (save-window-excursion
19983 (delete-other-windows)
19984 (org-switch-to-buffer-other-window " *Agenda Commands*")
19985 (erase-buffer)
19986 (insert (eval-when-compile
19987 (let ((header
19988 "
19989 Press key for an agenda command: < Buffer,subtree/region restriction
19990 -------------------------------- > Remove restriction
19991 a Agenda for current week or day e Export agenda views
19992 t List of all TODO entries T Entries with special TODO kwd
19993 m Match a TAGS query M Like m, but only TODO entries
19994 L Timeline for current buffer # List stuck projects (!=configure)
19995 s Search for keywords C Configure custom agenda commands
19996 / Multi-occur
19997 ")
19998 (start 0))
19999 (while (string-match
20000 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
20001 header start)
20002 (setq start (match-end 0))
20003 (add-text-properties (match-beginning 2) (match-end 2)
20004 '(face bold) header))
20005 header)))
20006 (setq header-end (move-marker (make-marker) (point)))
20007 (while t
20008 (setq custom1 custom)
20009 (when (eq rmheader t)
20010 (goto-line 1)
20011 (re-search-forward ":" nil t)
20012 (delete-region (match-end 0) (point-at-eol))
20013 (forward-char 1)
20014 (looking-at "-+")
20015 (delete-region (match-end 0) (point-at-eol))
20016 (move-marker header-end (match-end 0)))
20017 (goto-char header-end)
20018 (delete-region (point) (point-max))
20019 (while (setq entry (pop custom1))
20020 (setq key (car entry) desc (nth 1 entry)
20021 type (nth 2 entry) match (nth 3 entry))
20022 (if (> (length key) 1)
20023 (add-to-list 'prefixes (string-to-char key))
20024 (insert
20025 (format
20026 "\n%-4s%-14s: %s"
20027 (org-add-props (copy-sequence key)
20028 '(face bold))
20029 (cond
20030 ((string-match "\\S-" desc) desc)
20031 ((eq type 'agenda) "Agenda for current week or day")
20032 ((eq type 'alltodo) "List of all TODO entries")
20033 ((eq type 'search) "Word search")
20034 ((eq type 'stuck) "List of stuck projects")
20035 ((eq type 'todo) "TODO keyword")
20036 ((eq type 'tags) "Tags query")
20037 ((eq type 'tags-todo) "Tags (TODO)")
20038 ((eq type 'tags-tree) "Tags tree")
20039 ((eq type 'todo-tree) "TODO kwd tree")
20040 ((eq type 'occur-tree) "Occur tree")
20041 ((functionp type) (if (symbolp type)
20042 (symbol-name type)
20043 "Lambda expression"))
20044 (t "???"))
20045 (cond
20046 ((stringp match)
20047 (org-add-props match nil 'face 'org-warning))
20048 (match
20049 (format "set of %d commands" (length match)))
20050 (t ""))))))
20051 (when prefixes
20052 (mapc (lambda (x)
20053 (insert
20054 (format "\n%s %s"
20055 (org-add-props (char-to-string x)
20056 nil 'face 'bold)
20057 (or (cdr (assoc (concat selstring (char-to-string x))
20058 prefix-descriptions))
20059 "Prefix key"))))
20060 prefixes))
20061 (goto-char (point-min))
20062 (when (fboundp 'fit-window-to-buffer)
20063 (if second-time
20064 (if (not (pos-visible-in-window-p (point-max)))
20065 (fit-window-to-buffer))
20066 (setq second-time t)
20067 (fit-window-to-buffer)))
20068 (message "Press key for agenda command%s:"
20069 (if (or restrict-ok org-agenda-overriding-restriction)
20070 (if org-agenda-overriding-restriction
20071 " (restriction lock active)"
20072 (if restriction
20073 (format " (restricted to %s)" restriction)
20074 " (unrestricted)"))
20075 ""))
20076 (setq c (read-char-exclusive))
20077 (message "")
20078 (cond
20079 ((assoc (char-to-string c) custom)
20080 (setq selstring (concat selstring (char-to-string c)))
20081 (throw 'exit (cons selstring restriction)))
20082 ((memq c prefixes)
20083 (setq selstring (concat selstring (char-to-string c))
20084 prefixes nil
20085 rmheader (or rmheader t)
20086 custom (delq nil (mapcar
20087 (lambda (x)
20088 (if (or (= (length (car x)) 1)
20089 (/= (string-to-char (car x)) c))
20090 nil
20091 (cons (substring (car x) 1) (cdr x))))
20092 custom))))
20093 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
20094 (message "Restriction is only possible in Org-mode buffers")
20095 (ding) (sit-for 1))
20096 ((eq c ?1)
20097 (org-agenda-remove-restriction-lock 'noupdate)
20098 (setq restriction 'buffer))
20099 ((eq c ?0)
20100 (org-agenda-remove-restriction-lock 'noupdate)
20101 (setq restriction (if region-p 'region 'subtree)))
20102 ((eq c ?<)
20103 (org-agenda-remove-restriction-lock 'noupdate)
20104 (setq restriction
20105 (cond
20106 ((eq restriction 'buffer)
20107 (if region-p 'region 'subtree))
20108 ((memq restriction '(subtree region))
20109 nil)
20110 (t 'buffer))))
20111 ((eq c ?>)
20112 (org-agenda-remove-restriction-lock 'noupdate)
20113 (setq restriction nil))
20114 ((and (equal selstring "") (memq c '(?s ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
20115 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
20116 ((and (> (length selstring) 0) (eq c ?\d))
20117 (delete-window)
20118 (org-agenda-get-restriction-and-command prefix-descriptions))
20119
20120 ((equal c ?q) (error "Abort"))
20121 (t (error "Invalid key %c" c))))))))
20122
20123 (defun org-run-agenda-series (name series)
20124 (org-prepare-agenda name)
20125 (let* ((org-agenda-multi t)
20126 (redo (list 'org-run-agenda-series name (list 'quote series)))
20127 (cmds (car series))
20128 (gprops (nth 1 series))
20129 match ;; The byte compiler incorrectly complains about this. Keep it!
20130 cmd type lprops)
20131 (while (setq cmd (pop cmds))
20132 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
20133 (cond
20134 ((eq type 'agenda)
20135 (org-let2 gprops lprops
20136 '(call-interactively 'org-agenda-list)))
20137 ((eq type 'alltodo)
20138 (org-let2 gprops lprops
20139 '(call-interactively 'org-todo-list)))
20140 ((eq type 'search)
20141 (org-let2 gprops lprops
20142 '(org-search-view current-prefix-arg match)))
20143 ((eq type 'stuck)
20144 (org-let2 gprops lprops
20145 '(call-interactively 'org-agenda-list-stuck-projects)))
20146 ((eq type 'tags)
20147 (org-let2 gprops lprops
20148 '(org-tags-view current-prefix-arg match)))
20149 ((eq type 'tags-todo)
20150 (org-let2 gprops lprops
20151 '(org-tags-view '(4) match)))
20152 ((eq type 'todo)
20153 (org-let2 gprops lprops
20154 '(org-todo-list match)))
20155 ((fboundp type)
20156 (org-let2 gprops lprops
20157 '(funcall type match)))
20158 (t (error "Invalid type in command series"))))
20159 (widen)
20160 (setq org-agenda-redo-command redo)
20161 (goto-char (point-min)))
20162 (org-finalize-agenda))
20163
20164 ;;;###autoload
20165 (defmacro org-batch-agenda (cmd-key &rest parameters)
20166 "Run an agenda command in batch mode and send the result to STDOUT.
20167 If CMD-KEY is a string of length 1, it is used as a key in
20168 `org-agenda-custom-commands' and triggers this command. If it is a
20169 longer string it is used as a tags/todo match string.
20170 Paramters are alternating variable names and values that will be bound
20171 before running the agenda command."
20172 (let (pars)
20173 (while parameters
20174 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20175 (if (> (length cmd-key) 2)
20176 (eval (list 'let (nreverse pars)
20177 (list 'org-tags-view nil cmd-key)))
20178 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20179 (set-buffer org-agenda-buffer-name)
20180 (princ (org-encode-for-stdout (buffer-string)))))
20181
20182 (defun org-encode-for-stdout (string)
20183 (if (fboundp 'encode-coding-string)
20184 (encode-coding-string string buffer-file-coding-system)
20185 string))
20186
20187 (defvar org-agenda-info nil)
20188
20189 ;;;###autoload
20190 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
20191 "Run an agenda command in batch mode and send the result to STDOUT.
20192 If CMD-KEY is a string of length 1, it is used as a key in
20193 `org-agenda-custom-commands' and triggers this command. If it is a
20194 longer string it is used as a tags/todo match string.
20195 Paramters are alternating variable names and values that will be bound
20196 before running the agenda command.
20197
20198 The output gives a line for each selected agenda item. Each
20199 item is a list of comma-separated values, like this:
20200
20201 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
20202
20203 category The category of the item
20204 head The headline, without TODO kwd, TAGS and PRIORITY
20205 type The type of the agenda entry, can be
20206 todo selected in TODO match
20207 tagsmatch selected in tags match
20208 diary imported from diary
20209 deadline a deadline on given date
20210 scheduled scheduled on given date
20211 timestamp entry has timestamp on given date
20212 closed entry was closed on given date
20213 upcoming-deadline warning about deadline
20214 past-scheduled forwarded scheduled item
20215 block entry has date block including g. date
20216 todo The todo keyword, if any
20217 tags All tags including inherited ones, separated by colons
20218 date The relevant date, like 2007-2-14
20219 time The time, like 15:00-16:50
20220 extra Sting with extra planning info
20221 priority-l The priority letter if any was given
20222 priority-n The computed numerical priority
20223 agenda-day The day in the agenda where this is listed"
20224
20225 (let (pars)
20226 (while parameters
20227 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20228 (push (list 'org-agenda-remove-tags t) pars)
20229 (if (> (length cmd-key) 2)
20230 (eval (list 'let (nreverse pars)
20231 (list 'org-tags-view nil cmd-key)))
20232 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20233 (set-buffer org-agenda-buffer-name)
20234 (let* ((lines (org-split-string (buffer-string) "\n"))
20235 line)
20236 (while (setq line (pop lines))
20237 (catch 'next
20238 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
20239 (setq org-agenda-info
20240 (org-fix-agenda-info (text-properties-at 0 line)))
20241 (princ
20242 (org-encode-for-stdout
20243 (mapconcat 'org-agenda-export-csv-mapper
20244 '(org-category txt type todo tags date time-of-day extra
20245 priority-letter priority agenda-day)
20246 ",")))
20247 (princ "\n"))))))
20248
20249 (defun org-fix-agenda-info (props)
20250 "Make sure all properties on an agenda item have a canonical form,
20251 so the export commands can easily use it."
20252 (let (tmp re)
20253 (when (setq tmp (plist-get props 'tags))
20254 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20255 (when (setq tmp (plist-get props 'date))
20256 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20257 (let ((calendar-date-display-form '(year "-" month "-" day)))
20258 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20259
20260 (setq tmp (calendar-date-string tmp)))
20261 (setq props (plist-put props 'date tmp)))
20262 (when (setq tmp (plist-get props 'day))
20263 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20264 (let ((calendar-date-display-form '(year "-" month "-" day)))
20265 (setq tmp (calendar-date-string tmp)))
20266 (setq props (plist-put props 'day tmp))
20267 (setq props (plist-put props 'agenda-day tmp)))
20268 (when (setq tmp (plist-get props 'txt))
20269 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20270 (plist-put props 'priority-letter (match-string 1 tmp))
20271 (setq tmp (replace-match "" t t tmp)))
20272 (when (and (setq re (plist-get props 'org-todo-regexp))
20273 (setq re (concat "\\`\\.*" re " ?"))
20274 (string-match re tmp))
20275 (plist-put props 'todo (match-string 1 tmp))
20276 (setq tmp (replace-match "" t t tmp)))
20277 (plist-put props 'txt tmp)))
20278 props)
20279
20280 (defun org-agenda-export-csv-mapper (prop)
20281 (let ((res (plist-get org-agenda-info prop)))
20282 (setq res
20283 (cond
20284 ((not res) "")
20285 ((stringp res) res)
20286 (t (prin1-to-string res))))
20287 (while (string-match "," res)
20288 (setq res (replace-match ";" t t res)))
20289 (org-trim res)))
20290
20291
20292 ;;;###autoload
20293 (defun org-store-agenda-views (&rest parameters)
20294 (interactive)
20295 (eval (list 'org-batch-store-agenda-views)))
20296
20297 ;; FIXME, why is this a macro?????
20298 ;;;###autoload
20299 (defmacro org-batch-store-agenda-views (&rest parameters)
20300 "Run all custom agenda commands that have a file argument."
20301 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20302 (pop-up-frames nil)
20303 (dir default-directory)
20304 pars cmd thiscmdkey files opts)
20305 (while parameters
20306 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20307 (setq pars (reverse pars))
20308 (save-window-excursion
20309 (while cmds
20310 (setq cmd (pop cmds)
20311 thiscmdkey (car cmd)
20312 opts (nth 4 cmd)
20313 files (nth 5 cmd))
20314 (if (stringp files) (setq files (list files)))
20315 (when files
20316 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20317 (list 'org-agenda nil thiscmdkey)))
20318 (set-buffer org-agenda-buffer-name)
20319 (while files
20320 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20321 (list 'org-write-agenda
20322 (expand-file-name (pop files) dir) t))))
20323 (and (get-buffer org-agenda-buffer-name)
20324 (kill-buffer org-agenda-buffer-name)))))))
20325
20326 (defun org-write-agenda (file &optional nosettings)
20327 "Write the current buffer (an agenda view) as a file.
20328 Depending on the extension of the file name, plain text (.txt),
20329 HTML (.html or .htm) or Postscript (.ps) is produced.
20330 If the extension is .ics, run icalendar export over all files used
20331 to construct the agenda and limit the export to entries listed in the
20332 agenda now.
20333 If NOSETTINGS is given, do not scope the settings of
20334 `org-agenda-exporter-settings' into the export commands. This is used when
20335 the settings have already been scoped and we do not wish to overrule other,
20336 higher priority settings."
20337 (interactive "FWrite agenda to file: ")
20338 (if (not (file-writable-p file))
20339 (error "Cannot write agenda to file %s" file))
20340 (cond
20341 ((string-match "\\.html?\\'" file) (require 'htmlize))
20342 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20343 (org-let (if nosettings nil org-agenda-exporter-settings)
20344 '(save-excursion
20345 (save-window-excursion
20346 (cond
20347 ((string-match "\\.html?\\'" file)
20348 (set-buffer (htmlize-buffer (current-buffer)))
20349
20350 (when (and org-agenda-export-html-style
20351 (string-match "<style>" org-agenda-export-html-style))
20352 ;; replace <style> section with org-agenda-export-html-style
20353 (goto-char (point-min))
20354 (kill-region (- (search-forward "<style") 6)
20355 (search-forward "</style>"))
20356 (insert org-agenda-export-html-style))
20357 (write-file file)
20358 (kill-buffer (current-buffer))
20359 (message "HTML written to %s" file))
20360 ((string-match "\\.ps\\'" file)
20361 (ps-print-buffer-with-faces file)
20362 (message "Postscript written to %s" file))
20363 ((string-match "\\.ics\\'" file)
20364 (let ((org-agenda-marker-table
20365 (org-create-marker-find-array
20366 (org-agenda-collect-markers)))
20367 (org-icalendar-verify-function 'org-check-agenda-marker-table)
20368 (org-combined-agenda-icalendar-file file))
20369 (apply 'org-export-icalendar 'combine (org-agenda-files))))
20370 (t
20371 (let ((bs (buffer-string)))
20372 (find-file file)
20373 (insert bs)
20374 (save-buffer 0)
20375 (kill-buffer (current-buffer))
20376 (message "Plain text written to %s" file))))))
20377 (set-buffer org-agenda-buffer-name)))
20378
20379 (defun org-agenda-collect-markers ()
20380 "Collect the markers pointing to entries in the agenda buffer."
20381 (let (m markers)
20382 (save-excursion
20383 (goto-char (point-min))
20384 (while (not (eobp))
20385 (when (setq m (or (get-text-property (point) 'org-hd-marker)
20386 (get-text-property (point) 'org-marker)))
20387 (push m markers))
20388 (beginning-of-line 2)))
20389 (nreverse markers)))
20390
20391 (defun org-create-marker-find-array (marker-list)
20392 "Create a alist of files names with all marker positions in that file."
20393 (let (f tbl m a p)
20394 (while (setq m (pop marker-list))
20395 (setq p (marker-position m)
20396 f (buffer-file-name (or (buffer-base-buffer
20397 (marker-buffer m))
20398 (marker-buffer m))))
20399 (if (setq a (assoc f tbl))
20400 (push (marker-position m) (cdr a))
20401 (push (list f p) tbl)))
20402 (mapcar (lambda (x) (setcdr x (sort (copy-sequence (cdr x)) '<)) x)
20403 tbl)))
20404
20405 (defvar org-agenda-marker-table nil) ; dyamically scoped parameter
20406 (defun org-check-agenda-marker-table ()
20407 "Check of the current entry is on the marker list."
20408 (let ((file (buffer-file-name (or (buffer-base-buffer) (current-buffer))))
20409 a)
20410 (and (setq a (assoc file org-agenda-marker-table))
20411 (save-match-data
20412 (save-excursion
20413 (org-back-to-heading t)
20414 (member (point) (cdr a)))))))
20415
20416 (defmacro org-no-read-only (&rest body)
20417 "Inhibit read-only for BODY."
20418 `(let ((inhibit-read-only t)) ,@body))
20419
20420 (defun org-check-for-org-mode ()
20421 "Make sure current buffer is in org-mode. Error if not."
20422 (or (org-mode-p)
20423 (error "Cannot execute org-mode agenda command on buffer in %s."
20424 major-mode)))
20425
20426 (defun org-fit-agenda-window ()
20427 "Fit the window to the buffer size."
20428 (and (memq org-agenda-window-setup '(reorganize-frame))
20429 (fboundp 'fit-window-to-buffer)
20430 (fit-window-to-buffer
20431 nil
20432 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20433 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20434
20435 ;;; Agenda file list
20436
20437 (defun org-agenda-files (&optional unrestricted)
20438 "Get the list of agenda files.
20439 Optional UNRESTRICTED means return the full list even if a restriction
20440 is currently in place."
20441 (let ((files
20442 (cond
20443 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20444 ((stringp org-agenda-files) (org-read-agenda-file-list))
20445 ((listp org-agenda-files) org-agenda-files)
20446 (t (error "Invalid value of `org-agenda-files'")))))
20447 (setq files (apply 'append
20448 (mapcar (lambda (f)
20449 (if (file-directory-p f)
20450 (directory-files f t
20451 org-agenda-file-regexp)
20452 (list f)))
20453 files)))
20454 (if org-agenda-skip-unavailable-files
20455 (delq nil
20456 (mapcar (function
20457 (lambda (file)
20458 (and (file-readable-p file) file)))
20459 files))
20460 files))) ; `org-check-agenda-file' will remove them from the list
20461
20462 (defun org-edit-agenda-file-list ()
20463 "Edit the list of agenda files.
20464 Depending on setup, this either uses customize to edit the variable
20465 `org-agenda-files', or it visits the file that is holding the list. In the
20466 latter case, the buffer is set up in a way that saving it automatically kills
20467 the buffer and restores the previous window configuration."
20468 (interactive)
20469 (if (stringp org-agenda-files)
20470 (let ((cw (current-window-configuration)))
20471 (find-file org-agenda-files)
20472 (org-set-local 'org-window-configuration cw)
20473 (org-add-hook 'after-save-hook
20474 (lambda ()
20475 (set-window-configuration
20476 (prog1 org-window-configuration
20477 (kill-buffer (current-buffer))))
20478 (org-install-agenda-files-menu)
20479 (message "New agenda file list installed"))
20480 nil 'local)
20481 (message "%s" (substitute-command-keys
20482 "Edit list and finish with \\[save-buffer]")))
20483 (customize-variable 'org-agenda-files)))
20484
20485 (defun org-store-new-agenda-file-list (list)
20486 "Set new value for the agenda file list and save it correcly."
20487 (if (stringp org-agenda-files)
20488 (let ((f org-agenda-files) b)
20489 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20490 (with-temp-file f
20491 (insert (mapconcat 'identity list "\n") "\n")))
20492 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20493 (setq org-agenda-files list)
20494 (customize-save-variable 'org-agenda-files org-agenda-files))))
20495
20496 (defun org-read-agenda-file-list ()
20497 "Read the list of agenda files from a file."
20498 (when (stringp org-agenda-files)
20499 (with-temp-buffer
20500 (insert-file-contents org-agenda-files)
20501 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20502
20503
20504 ;;;###autoload
20505 (defun org-cycle-agenda-files ()
20506 "Cycle through the files in `org-agenda-files'.
20507 If the current buffer visits an agenda file, find the next one in the list.
20508 If the current buffer does not, find the first agenda file."
20509 (interactive)
20510 (let* ((fs (org-agenda-files t))
20511 (files (append fs (list (car fs))))
20512 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20513 file)
20514 (unless files (error "No agenda files"))
20515 (catch 'exit
20516 (while (setq file (pop files))
20517 (if (equal (file-truename file) tcf)
20518 (when (car files)
20519 (find-file (car files))
20520 (throw 'exit t))))
20521 (find-file (car fs)))
20522 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20523
20524 (defun org-agenda-file-to-front (&optional to-end)
20525 "Move/add the current file to the top of the agenda file list.
20526 If the file is not present in the list, it is added to the front. If it is
20527 present, it is moved there. With optional argument TO-END, add/move to the
20528 end of the list."
20529 (interactive "P")
20530 (let ((org-agenda-skip-unavailable-files nil)
20531 (file-alist (mapcar (lambda (x)
20532 (cons (file-truename x) x))
20533 (org-agenda-files t)))
20534 (ctf (file-truename buffer-file-name))
20535 x had)
20536 (setq x (assoc ctf file-alist) had x)
20537
20538 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20539 (if to-end
20540 (setq file-alist (append (delq x file-alist) (list x)))
20541 (setq file-alist (cons x (delq x file-alist))))
20542 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20543 (org-install-agenda-files-menu)
20544 (message "File %s to %s of agenda file list"
20545 (if had "moved" "added") (if to-end "end" "front"))))
20546
20547 (defun org-remove-file (&optional file)
20548 "Remove current file from the list of files in variable `org-agenda-files'.
20549 These are the files which are being checked for agenda entries.
20550 Optional argument FILE means, use this file instead of the current."
20551 (interactive)
20552 (let* ((org-agenda-skip-unavailable-files nil)
20553 (file (or file buffer-file-name))
20554 (true-file (file-truename file))
20555 (afile (abbreviate-file-name file))
20556 (files (delq nil (mapcar
20557 (lambda (x)
20558 (if (equal true-file
20559 (file-truename x))
20560 nil x))
20561 (org-agenda-files t)))))
20562 (if (not (= (length files) (length (org-agenda-files t))))
20563 (progn
20564 (org-store-new-agenda-file-list files)
20565 (org-install-agenda-files-menu)
20566 (message "Removed file: %s" afile))
20567 (message "File was not in list: %s (not removed)" afile))))
20568
20569 (defun org-file-menu-entry (file)
20570 (vector file (list 'find-file file) t))
20571
20572 (defun org-check-agenda-file (file)
20573 "Make sure FILE exists. If not, ask user what to do."
20574 (when (not (file-exists-p file))
20575 (message "non-existent file %s. [R]emove from list or [A]bort?"
20576 (abbreviate-file-name file))
20577 (let ((r (downcase (read-char-exclusive))))
20578 (cond
20579 ((equal r ?r)
20580 (org-remove-file file)
20581 (throw 'nextfile t))
20582 (t (error "Abort"))))))
20583
20584 ;;; Agenda prepare and finalize
20585
20586 (defvar org-agenda-multi nil) ; dynammically scoped
20587 (defvar org-agenda-buffer-name "*Org Agenda*")
20588 (defvar org-pre-agenda-window-conf nil)
20589 (defvar org-agenda-name nil)
20590 (defun org-prepare-agenda (&optional name)
20591 (setq org-todo-keywords-for-agenda nil)
20592 (setq org-done-keywords-for-agenda nil)
20593 (if org-agenda-multi
20594 (progn
20595 (setq buffer-read-only nil)
20596 (goto-char (point-max))
20597 (unless (or (bobp) org-agenda-compact-blocks)
20598 (insert "\n" (make-string (window-width) ?=) "\n"))
20599 (narrow-to-region (point) (point-max)))
20600 (org-agenda-reset-markers)
20601 (org-prepare-agenda-buffers (org-agenda-files))
20602 (setq org-todo-keywords-for-agenda
20603 (org-uniquify org-todo-keywords-for-agenda))
20604 (setq org-done-keywords-for-agenda
20605 (org-uniquify org-done-keywords-for-agenda))
20606 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20607 (awin (get-buffer-window abuf)))
20608 (cond
20609 ((equal (current-buffer) abuf) nil)
20610 (awin (select-window awin))
20611 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20612 ((equal org-agenda-window-setup 'current-window)
20613 (switch-to-buffer abuf))
20614 ((equal org-agenda-window-setup 'other-window)
20615 (org-switch-to-buffer-other-window abuf))
20616 ((equal org-agenda-window-setup 'other-frame)
20617 (switch-to-buffer-other-frame abuf))
20618 ((equal org-agenda-window-setup 'reorganize-frame)
20619 (delete-other-windows)
20620 (org-switch-to-buffer-other-window abuf))))
20621 (setq buffer-read-only nil)
20622 (erase-buffer)
20623 (org-agenda-mode)
20624 (and name (not org-agenda-name)
20625 (org-set-local 'org-agenda-name name)))
20626 (setq buffer-read-only nil))
20627
20628 (defun org-finalize-agenda ()
20629 "Finishing touch for the agenda buffer, called just before displaying it."
20630 (unless org-agenda-multi
20631 (save-excursion
20632 (let ((inhibit-read-only t))
20633 (goto-char (point-min))
20634 (while (org-activate-bracket-links (point-max))
20635 (add-text-properties (match-beginning 0) (match-end 0)
20636 '(face org-link)))
20637 (org-agenda-align-tags)
20638 (unless org-agenda-with-colors
20639 (remove-text-properties (point-min) (point-max) '(face nil))))
20640 (if (and (boundp 'org-overriding-columns-format)
20641 org-overriding-columns-format)
20642 (org-set-local 'org-overriding-columns-format
20643 org-overriding-columns-format))
20644 (if (and (boundp 'org-agenda-view-columns-initially)
20645 org-agenda-view-columns-initially)
20646 (org-agenda-columns))
20647 (when org-agenda-fontify-priorities
20648 (org-fontify-priorities))
20649 (run-hooks 'org-finalize-agenda-hook)
20650 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20651 )))
20652
20653 (defun org-fontify-priorities ()
20654 "Make highest priority lines bold, and lowest italic."
20655 (interactive)
20656 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20657 (org-delete-overlay o)))
20658 (org-overlays-in (point-min) (point-max)))
20659 (save-excursion
20660 (let ((inhibit-read-only t)
20661 b e p ov h l)
20662 (goto-char (point-min))
20663 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20664 (setq h (or (get-char-property (point) 'org-highest-priority)
20665 org-highest-priority)
20666 l (or (get-char-property (point) 'org-lowest-priority)
20667 org-lowest-priority)
20668 p (string-to-char (match-string 1))
20669 b (match-beginning 0) e (point-at-eol)
20670 ov (org-make-overlay b e))
20671 (org-overlay-put
20672 ov 'face
20673 (cond ((listp org-agenda-fontify-priorities)
20674 (cdr (assoc p org-agenda-fontify-priorities)))
20675 ((equal p l) 'italic)
20676 ((equal p h) 'bold)))
20677 (org-overlay-put ov 'org-type 'org-priority)))))
20678
20679 (defun org-prepare-agenda-buffers (files)
20680 "Create buffers for all agenda files, protect archived trees and comments."
20681 (interactive)
20682 (let ((pa '(:org-archived t))
20683 (pc '(:org-comment t))
20684 (pall '(:org-archived t :org-comment t))
20685 (inhibit-read-only t)
20686 (rea (concat ":" org-archive-tag ":"))
20687 bmp file re)
20688 (save-excursion
20689 (save-restriction
20690 (while (setq file (pop files))
20691 (if (bufferp file)
20692 (set-buffer file)
20693 (org-check-agenda-file file)
20694 (set-buffer (org-get-agenda-file-buffer file)))
20695 (widen)
20696 (setq bmp (buffer-modified-p))
20697 (org-refresh-category-properties)
20698 (setq org-todo-keywords-for-agenda
20699 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20700 (setq org-done-keywords-for-agenda
20701 (append org-done-keywords-for-agenda org-done-keywords))
20702 (save-excursion
20703 (remove-text-properties (point-min) (point-max) pall)
20704 (when org-agenda-skip-archived-trees
20705 (goto-char (point-min))
20706 (while (re-search-forward rea nil t)
20707 (if (org-on-heading-p t)
20708 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20709 (goto-char (point-min))
20710 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20711 (while (re-search-forward re nil t)
20712 (add-text-properties
20713 (match-beginning 0) (org-end-of-subtree t) pc)))
20714 (set-buffer-modified-p bmp))))))
20715
20716 (defvar org-agenda-skip-function nil
20717 "Function to be called at each match during agenda construction.
20718 If this function returns nil, the current match should not be skipped.
20719 Otherwise, the function must return a position from where the search
20720 should be continued.
20721 This may also be a Lisp form, it will be evaluated.
20722 Never set this variable using `setq' or so, because then it will apply
20723 to all future agenda commands. Instead, bind it with `let' to scope
20724 it dynamically into the agenda-constructing command. A good way to set
20725 it is through options in org-agenda-custom-commands.")
20726
20727 (defun org-agenda-skip ()
20728 "Throw to `:skip' in places that should be skipped.
20729 Also moves point to the end of the skipped region, so that search can
20730 continue from there."
20731 (let ((p (point-at-bol)) to fp)
20732 (and org-agenda-skip-archived-trees
20733 (get-text-property p :org-archived)
20734 (org-end-of-subtree t)
20735 (throw :skip t))
20736 (and (get-text-property p :org-comment)
20737 (org-end-of-subtree t)
20738 (throw :skip t))
20739 (if (equal (char-after p) ?#) (throw :skip t))
20740 (when (and (or (setq fp (functionp org-agenda-skip-function))
20741 (consp org-agenda-skip-function))
20742 (setq to (save-excursion
20743 (save-match-data
20744 (if fp
20745 (funcall org-agenda-skip-function)
20746 (eval org-agenda-skip-function))))))
20747 (goto-char to)
20748 (throw :skip t))))
20749
20750 (defvar org-agenda-markers nil
20751 "List of all currently active markers created by `org-agenda'.")
20752 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20753 "Creation time of the last agenda marker.")
20754
20755 (defun org-agenda-new-marker (&optional pos)
20756 "Return a new agenda marker.
20757 Org-mode keeps a list of these markers and resets them when they are
20758 no longer in use."
20759 (let ((m (copy-marker (or pos (point)))))
20760 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20761 (push m org-agenda-markers)
20762 m))
20763
20764 (defun org-agenda-reset-markers ()
20765 "Reset markers created by `org-agenda'."
20766 (while org-agenda-markers
20767 (move-marker (pop org-agenda-markers) nil)))
20768
20769 (defun org-get-agenda-file-buffer (file)
20770 "Get a buffer visiting FILE. If the buffer needs to be created, add
20771 it to the list of buffers which might be released later."
20772 (let ((buf (org-find-base-buffer-visiting file)))
20773 (if buf
20774 buf ; just return it
20775 ;; Make a new buffer and remember it
20776 (setq buf (find-file-noselect file))
20777 (if buf (push buf org-agenda-new-buffers))
20778 buf)))
20779
20780 (defun org-release-buffers (blist)
20781 "Release all buffers in list, asking the user for confirmation when needed.
20782 When a buffer is unmodified, it is just killed. When modified, it is saved
20783 \(if the user agrees) and then killed."
20784 (let (buf file)
20785 (while (setq buf (pop blist))
20786 (setq file (buffer-file-name buf))
20787 (when (and (buffer-modified-p buf)
20788 file
20789 (y-or-n-p (format "Save file %s? " file)))
20790 (with-current-buffer buf (save-buffer)))
20791 (kill-buffer buf))))
20792
20793 (defun org-get-category (&optional pos)
20794 "Get the category applying to position POS."
20795 (get-text-property (or pos (point)) 'org-category))
20796
20797 ;;; Agenda timeline
20798
20799 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20800
20801 (defun org-timeline (&optional include-all)
20802 "Show a time-sorted view of the entries in the current org file.
20803 Only entries with a time stamp of today or later will be listed. With
20804 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20805 under the current date.
20806 If the buffer contains an active region, only check the region for
20807 dates."
20808 (interactive "P")
20809 (require 'calendar)
20810 (org-compile-prefix-format 'timeline)
20811 (org-set-sorting-strategy 'timeline)
20812 (let* ((dopast t)
20813 (dotodo include-all)
20814 (doclosed org-agenda-show-log)
20815 (entry buffer-file-name)
20816 (date (calendar-current-date))
20817 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20818 (end (if (org-region-active-p) (region-end) (point-max)))
20819 (day-numbers (org-get-all-dates beg end 'no-ranges
20820 t doclosed ; always include today
20821 org-timeline-show-empty-dates))
20822 (org-deadline-warning-days 0)
20823 (org-agenda-only-exact-dates t)
20824 (today (time-to-days (current-time)))
20825 (past t)
20826 args
20827 s e rtn d emptyp)
20828 (setq org-agenda-redo-command
20829 (list 'progn
20830 (list 'org-switch-to-buffer-other-window (current-buffer))
20831 (list 'org-timeline (list 'quote include-all))))
20832 (if (not dopast)
20833 ;; Remove past dates from the list of dates.
20834 (setq day-numbers (delq nil (mapcar (lambda(x)
20835 (if (>= x today) x nil))
20836 day-numbers))))
20837 (org-prepare-agenda (concat "Timeline "
20838 (file-name-nondirectory buffer-file-name)))
20839 (if doclosed (push :closed args))
20840 (push :timestamp args)
20841 (push :deadline args)
20842 (push :scheduled args)
20843 (push :sexp args)
20844 (if dotodo (push :todo args))
20845 (while (setq d (pop day-numbers))
20846 (if (and (listp d) (eq (car d) :omitted))
20847 (progn
20848 (setq s (point))
20849 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20850 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20851 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20852 (if (and (>= d today)
20853 dopast
20854 past)
20855 (progn
20856 (setq past nil)
20857 (insert (make-string 79 ?-) "\n")))
20858 (setq date (calendar-gregorian-from-absolute d))
20859 (setq s (point))
20860 (setq rtn (and (not emptyp)
20861 (apply 'org-agenda-get-day-entries entry
20862 date args)))
20863 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20864 (progn
20865 (insert
20866 (if (stringp org-agenda-format-date)
20867 (format-time-string org-agenda-format-date
20868 (org-time-from-absolute date))
20869 (funcall org-agenda-format-date date))
20870 "\n")
20871 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20872 (put-text-property s (1- (point)) 'org-date-line t)
20873 (if (equal d today)
20874 (put-text-property s (1- (point)) 'org-today t))
20875 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20876 (put-text-property s (1- (point)) 'day d)))))
20877 (goto-char (point-min))
20878 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20879 (point-min)))
20880 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20881 (org-finalize-agenda)
20882 (setq buffer-read-only t)))
20883
20884 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20885 "Return a list of all relevant day numbers from BEG to END buffer positions.
20886 If NO-RANGES is non-nil, include only the start and end dates of a range,
20887 not every single day in the range. If FORCE-TODAY is non-nil, make
20888 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20889 inactive time stamps (those in square brackets) are included.
20890 When EMPTY is non-nil, also include days without any entries."
20891 (let ((re (concat
20892 (if pre-re pre-re "")
20893 (if inactive org-ts-regexp-both org-ts-regexp)))
20894 dates dates1 date day day1 day2 ts1 ts2)
20895 (if force-today
20896 (setq dates (list (time-to-days (current-time)))))
20897 (save-excursion
20898 (goto-char beg)
20899 (while (re-search-forward re end t)
20900 (setq day (time-to-days (org-time-string-to-time
20901 (substring (match-string 1) 0 10))))
20902 (or (memq day dates) (push day dates)))
20903 (unless no-ranges
20904 (goto-char beg)
20905 (while (re-search-forward org-tr-regexp end t)
20906 (setq ts1 (substring (match-string 1) 0 10)
20907 ts2 (substring (match-string 2) 0 10)
20908 day1 (time-to-days (org-time-string-to-time ts1))
20909 day2 (time-to-days (org-time-string-to-time ts2)))
20910 (while (< (setq day1 (1+ day1)) day2)
20911 (or (memq day1 dates) (push day1 dates)))))
20912 (setq dates (sort dates '<))
20913 (when empty
20914 (while (setq day (pop dates))
20915 (setq day2 (car dates))
20916 (push day dates1)
20917 (when (and day2 empty)
20918 (if (or (eq empty t)
20919 (and (numberp empty) (<= (- day2 day) empty)))
20920 (while (< (setq day (1+ day)) day2)
20921 (push (list day) dates1))
20922 (push (cons :omitted (- day2 day)) dates1))))
20923 (setq dates (nreverse dates1)))
20924 dates)))
20925
20926 ;;; Agenda Daily/Weekly
20927
20928 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20929 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20930 (defvar org-agenda-last-arguments nil
20931 "The arguments of the previous call to org-agenda")
20932 (defvar org-starting-day nil) ; local variable in the agenda buffer
20933 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20934 (defvar org-include-all-loc nil) ; local variable
20935 (defvar org-agenda-remove-date nil) ; dynamically scoped FIXME: not used???
20936
20937 ;;;###autoload
20938 (defun org-agenda-list (&optional include-all start-day ndays)
20939 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20940 The view will be for the current day or week, but from the overview buffer
20941 you will be able to go to other days/weeks.
20942
20943 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20944 all unfinished TODO items will also be shown, before the agenda.
20945 This feature is considered obsolete, please use the TODO list or a block
20946 agenda instead.
20947
20948 With a numeric prefix argument in an interactive call, the agenda will
20949 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20950 the number of days. NDAYS defaults to `org-agenda-ndays'.
20951
20952 START-DAY defaults to TODAY, or to the most recent match for the weekday
20953 given in `org-agenda-start-on-weekday'."
20954 (interactive "P")
20955 (if (and (integerp include-all) (> include-all 0))
20956 (setq ndays include-all include-all nil))
20957 (setq ndays (or ndays org-agenda-ndays)
20958 start-day (or start-day org-agenda-start-day))
20959 (if org-agenda-overriding-arguments
20960 (setq include-all (car org-agenda-overriding-arguments)
20961 start-day (nth 1 org-agenda-overriding-arguments)
20962 ndays (nth 2 org-agenda-overriding-arguments)))
20963 (if (stringp start-day)
20964 ;; Convert to an absolute day number
20965 (setq start-day (time-to-days (org-read-date nil t start-day))))
20966 (setq org-agenda-last-arguments (list include-all start-day ndays))
20967 (org-compile-prefix-format 'agenda)
20968 (org-set-sorting-strategy 'agenda)
20969 (require 'calendar)
20970 (let* ((org-agenda-start-on-weekday
20971 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20972 org-agenda-start-on-weekday nil))
20973 (thefiles (org-agenda-files))
20974 (files thefiles)
20975 (today (time-to-days
20976 (time-subtract (current-time)
20977 (list 0 (* 3600 org-extend-today-until) 0))))
20978 (sd (or start-day today))
20979 (start (if (or (null org-agenda-start-on-weekday)
20980 (< org-agenda-ndays 7))
20981 sd
20982 (let* ((nt (calendar-day-of-week
20983 (calendar-gregorian-from-absolute sd)))
20984 (n1 org-agenda-start-on-weekday)
20985 (d (- nt n1)))
20986 (- sd (+ (if (< d 0) 7 0) d)))))
20987 (day-numbers (list start))
20988 (day-cnt 0)
20989 (inhibit-redisplay (not debug-on-error))
20990 s e rtn rtnall file date d start-pos end-pos todayp nd)
20991 (setq org-agenda-redo-command
20992 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20993 ;; Make the list of days
20994 (setq ndays (or ndays org-agenda-ndays)
20995 nd ndays)
20996 (while (> ndays 1)
20997 (push (1+ (car day-numbers)) day-numbers)
20998 (setq ndays (1- ndays)))
20999 (setq day-numbers (nreverse day-numbers))
21000 (org-prepare-agenda "Day/Week")
21001 (org-set-local 'org-starting-day (car day-numbers))
21002 (org-set-local 'org-include-all-loc include-all)
21003 (org-set-local 'org-agenda-span
21004 (org-agenda-ndays-to-span nd))
21005 (when (and (or include-all org-agenda-include-all-todo)
21006 (member today day-numbers))
21007 (setq files thefiles
21008 rtnall nil)
21009 (while (setq file (pop files))
21010 (catch 'nextfile
21011 (org-check-agenda-file file)
21012 (setq date (calendar-gregorian-from-absolute today)
21013 rtn (org-agenda-get-day-entries
21014 file date :todo))
21015 (setq rtnall (append rtnall rtn))))
21016 (when rtnall
21017 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
21018 (add-text-properties (point-min) (1- (point))
21019 (list 'face 'org-agenda-structure))
21020 (insert (org-finalize-agenda-entries rtnall) "\n")))
21021 (unless org-agenda-compact-blocks
21022 (setq s (point))
21023 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
21024 "-agenda:\n")
21025 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
21026 'org-date-line t)))
21027 (while (setq d (pop day-numbers))
21028 (setq date (calendar-gregorian-from-absolute d)
21029 s (point))
21030 (if (or (setq todayp (= d today))
21031 (and (not start-pos) (= d sd)))
21032 (setq start-pos (point))
21033 (if (and start-pos (not end-pos))
21034 (setq end-pos (point))))
21035 (setq files thefiles
21036 rtnall nil)
21037 (while (setq file (pop files))
21038 (catch 'nextfile
21039 (org-check-agenda-file file)
21040 (if org-agenda-show-log
21041 (setq rtn (org-agenda-get-day-entries
21042 file date
21043 :deadline :scheduled :timestamp :sexp :closed))
21044 (setq rtn (org-agenda-get-day-entries
21045 file date
21046 :deadline :scheduled :sexp :timestamp)))
21047 (setq rtnall (append rtnall rtn))))
21048 (if org-agenda-include-diary
21049 (progn
21050 (require 'diary-lib)
21051 (setq rtn (org-get-entries-from-diary date))
21052 (setq rtnall (append rtnall rtn))))
21053 (if (or rtnall org-agenda-show-all-dates)
21054 (progn
21055 (setq day-cnt (1+ day-cnt))
21056 (insert
21057 (if (stringp org-agenda-format-date)
21058 (format-time-string org-agenda-format-date
21059 (org-time-from-absolute date))
21060 (funcall org-agenda-format-date date))
21061 "\n")
21062 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
21063 (put-text-property s (1- (point)) 'org-date-line t)
21064 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
21065 (if todayp (put-text-property s (1- (point)) 'org-today t))
21066 (if rtnall (insert
21067 (org-finalize-agenda-entries
21068 (org-agenda-add-time-grid-maybe
21069 rtnall nd todayp))
21070 "\n"))
21071 (put-text-property s (1- (point)) 'day d)
21072 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
21073 (goto-char (point-min))
21074 (org-fit-agenda-window)
21075 (unless (and (pos-visible-in-window-p (point-min))
21076 (pos-visible-in-window-p (point-max)))
21077 (goto-char (1- (point-max)))
21078 (recenter -1)
21079 (if (not (pos-visible-in-window-p (or start-pos 1)))
21080 (progn
21081 (goto-char (or start-pos 1))
21082 (recenter 1))))
21083 (goto-char (or start-pos 1))
21084 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
21085 (org-finalize-agenda)
21086 (setq buffer-read-only t)
21087 (message "")))
21088
21089 (defun org-agenda-ndays-to-span (n)
21090 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
21091
21092 ;;; Agenda word search
21093
21094 (defvar org-agenda-search-history nil)
21095
21096 ;;;###autoload
21097 (defun org-search-view (&optional arg string)
21098 "Show all entries that contain words or regular expressions.
21099 If the first character of the search string is an asterisks,
21100 search only the headlines.
21101
21102 The search string is broken into \"words\" by splitting at whitespace.
21103 The individual words are then interpreted as a boolean expression with
21104 logical AND. Words prefixed with a minus must not occur in the entry.
21105 Words without a prefix or prefixed with a plus must occur in the entry.
21106 Matching is case-insensitive and the words are enclosed by word delimiters.
21107
21108 Words enclosed by curly braces are interpreted as regular expressions
21109 that must or must not match in the entry.
21110
21111 This command searches the agenda files, and in addition the files listed
21112 in `org-agenda-text-search-extra-files'."
21113 (interactive "P")
21114 (org-compile-prefix-format 'search)
21115 (org-set-sorting-strategy 'search)
21116 (org-prepare-agenda "SEARCH")
21117 (let* ((props (list 'face nil
21118 'done-face 'org-done
21119 'org-not-done-regexp org-not-done-regexp
21120 'org-todo-regexp org-todo-regexp
21121 'mouse-face 'highlight
21122 'keymap org-agenda-keymap
21123 'help-echo (format "mouse-2 or RET jump to location")))
21124 regexp rtn rtnall files file pos
21125 marker priority category tags c neg re
21126 ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
21127 (unless (and (not arg)
21128 (stringp string)
21129 (string-match "\\S-" string))
21130 (setq string (read-string "[+-]Word/{Regexp} ...: "
21131 (cond
21132 ((integerp arg) (cons string arg))
21133 (arg string))
21134 'org-agenda-search-history)))
21135 (setq org-agenda-redo-command
21136 (list 'org-search-view 'current-prefix-arg string))
21137 (setq org-agenda-query-string string)
21138
21139 (if (equal (string-to-char string) ?*)
21140 (setq hdl-only t
21141 words (substring string 1))
21142 (setq words string))
21143 (setq words (org-split-string words))
21144 (mapc (lambda (w)
21145 (setq c (string-to-char w))
21146 (if (equal c ?-)
21147 (setq neg t w (substring w 1))
21148 (if (equal c ?+)
21149 (setq neg nil w (substring w 1))
21150 (setq neg nil)))
21151 (if (string-match "\\`{.*}\\'" w)
21152 (setq re (substring w 1 -1))
21153 (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>")))
21154 (if neg (push re regexps-) (push re regexps+)))
21155 words)
21156 (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b)))))
21157 (if (not regexps+)
21158 (setq regexp (concat "^" org-outline-regexp))
21159 (setq regexp (pop regexps+))
21160 (if hdl-only (setq regexp (concat "^" org-outline-regexp ".*?"
21161 regexp))))
21162 (setq files (append (org-agenda-files) org-agenda-text-search-extra-files)
21163 rtnall nil)
21164 (while (setq file (pop files))
21165 (setq ee nil)
21166 (catch 'nextfile
21167 (org-check-agenda-file file)
21168 (setq buffer (if (file-exists-p file)
21169 (org-get-agenda-file-buffer file)
21170 (error "No such file %s" file)))
21171 (if (not buffer)
21172 ;; If file does not exist, make sure an error message is sent
21173 (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s"
21174 file))))
21175 (with-current-buffer buffer
21176 (unless (org-mode-p)
21177 (error "Agenda file %s is not in `org-mode'" file))
21178 (let ((case-fold-search t))
21179 (save-excursion
21180 (save-restriction
21181 (if org-agenda-restrict
21182 (narrow-to-region org-agenda-restrict-begin
21183 org-agenda-restrict-end)
21184 (widen))
21185 (goto-char (point-min))
21186 (unless (or (org-on-heading-p)
21187 (outline-next-heading))
21188 (throw 'nextfile t))
21189 (goto-char (max (point-min) (1- (point))))
21190 (while (re-search-forward regexp nil t)
21191 (org-back-to-heading t)
21192 (skip-chars-forward "* ")
21193 (setq beg (point-at-bol)
21194 beg1 (point)
21195 end (progn (outline-next-heading) (point)))
21196 (catch :skip
21197 (goto-char beg)
21198 (org-agenda-skip)
21199 (setq str (buffer-substring-no-properties
21200 (point-at-bol)
21201 (if hdl-only (point-at-eol) end)))
21202 (mapc (lambda (wr) (when (string-match wr str)
21203 (goto-char (1- end))
21204 (throw :skip t)))
21205 regexps-)
21206 (mapc (lambda (wr) (unless (string-match wr str)
21207 (goto-char (1- end))
21208 (throw :skip t)))
21209 regexps+)
21210 (goto-char beg)
21211 (setq marker (org-agenda-new-marker (point))
21212 category (org-get-category)
21213 tags (org-get-tags-at (point))
21214 txt (org-format-agenda-item
21215 ""
21216 (buffer-substring-no-properties
21217 beg1 (point-at-eol))
21218 category tags))
21219 (org-add-props txt props
21220 'org-marker marker 'org-hd-marker marker
21221 'priority 1000 'org-category category
21222 'type "search")
21223 (push txt ee)
21224 (goto-char (1- end)))))))))
21225 (setq rtn (nreverse ee))
21226 (setq rtnall (append rtnall rtn)))
21227 (if org-agenda-overriding-header
21228 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21229 nil 'face 'org-agenda-structure) "\n")
21230 (insert "Search words: ")
21231 (add-text-properties (point-min) (1- (point))
21232 (list 'face 'org-agenda-structure))
21233 (setq pos (point))
21234 (insert string "\n")
21235 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21236 (setq pos (point))
21237 (unless org-agenda-multi
21238 (insert "Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit\n")
21239 (add-text-properties pos (1- (point))
21240 (list 'face 'org-agenda-structure))))
21241 (when rtnall
21242 (insert (org-finalize-agenda-entries rtnall) "\n"))
21243 (goto-char (point-min))
21244 (org-fit-agenda-window)
21245 (add-text-properties (point-min) (point-max) '(org-agenda-type search))
21246 (org-finalize-agenda)
21247 (setq buffer-read-only t)))
21248
21249 ;;; Agenda TODO list
21250
21251 (defvar org-select-this-todo-keyword nil)
21252 (defvar org-last-arg nil)
21253
21254 ;;;###autoload
21255 (defun org-todo-list (arg)
21256 "Show all TODO entries from all agenda file in a single list.
21257 The prefix arg can be used to select a specific TODO keyword and limit
21258 the list to these. When using \\[universal-argument], you will be prompted
21259 for a keyword. A numeric prefix directly selects the Nth keyword in
21260 `org-todo-keywords-1'."
21261 (interactive "P")
21262 (require 'calendar)
21263 (org-compile-prefix-format 'todo)
21264 (org-set-sorting-strategy 'todo)
21265 (org-prepare-agenda "TODO")
21266 (let* ((today (time-to-days (current-time)))
21267 (date (calendar-gregorian-from-absolute today))
21268 (kwds org-todo-keywords-for-agenda)
21269 (completion-ignore-case t)
21270 (org-select-this-todo-keyword
21271 (if (stringp arg) arg
21272 (and arg (integerp arg) (> arg 0)
21273 (nth (1- arg) kwds))))
21274 rtn rtnall files file pos)
21275 (when (equal arg '(4))
21276 (setq org-select-this-todo-keyword
21277 (completing-read "Keyword (or KWD1|K2D2|...): "
21278 (mapcar 'list kwds) nil nil)))
21279 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
21280 (org-set-local 'org-last-arg arg)
21281 (setq org-agenda-redo-command
21282 '(org-todo-list (or current-prefix-arg org-last-arg)))
21283 (setq files (org-agenda-files)
21284 rtnall nil)
21285 (while (setq file (pop files))
21286 (catch 'nextfile
21287 (org-check-agenda-file file)
21288 (setq rtn (org-agenda-get-day-entries file date :todo))
21289 (setq rtnall (append rtnall rtn))))
21290 (if org-agenda-overriding-header
21291 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21292 nil 'face 'org-agenda-structure) "\n")
21293 (insert "Global list of TODO items of type: ")
21294 (add-text-properties (point-min) (1- (point))
21295 (list 'face 'org-agenda-structure))
21296 (setq pos (point))
21297 (insert (or org-select-this-todo-keyword "ALL") "\n")
21298 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21299 (setq pos (point))
21300 (unless org-agenda-multi
21301 (insert "Available with `N r': (0)ALL")
21302 (let ((n 0) s)
21303 (mapc (lambda (x)
21304 (setq s (format "(%d)%s" (setq n (1+ n)) x))
21305 (if (> (+ (current-column) (string-width s) 1) (frame-width))
21306 (insert "\n "))
21307 (insert " " s))
21308 kwds))
21309 (insert "\n"))
21310 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21311 (when rtnall
21312 (insert (org-finalize-agenda-entries rtnall) "\n"))
21313 (goto-char (point-min))
21314 (org-fit-agenda-window)
21315 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
21316 (org-finalize-agenda)
21317 (setq buffer-read-only t)))
21318
21319 ;;; Agenda tags match
21320
21321 ;;;###autoload
21322 (defun org-tags-view (&optional todo-only match)
21323 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
21324 The prefix arg TODO-ONLY limits the search to TODO entries."
21325 (interactive "P")
21326 (org-compile-prefix-format 'tags)
21327 (org-set-sorting-strategy 'tags)
21328 (let* ((org-tags-match-list-sublevels
21329 (if todo-only t org-tags-match-list-sublevels))
21330 (completion-ignore-case t)
21331 rtn rtnall files file pos matcher
21332 buffer)
21333 (setq matcher (org-make-tags-matcher match)
21334 match (car matcher) matcher (cdr matcher))
21335 (org-prepare-agenda (concat "TAGS " match))
21336 (setq org-agenda-query-string match)
21337 (setq org-agenda-redo-command
21338 (list 'org-tags-view (list 'quote todo-only)
21339 (list 'if 'current-prefix-arg nil 'org-agenda-query-string)))
21340 (setq files (org-agenda-files)
21341 rtnall nil)
21342 (while (setq file (pop files))
21343 (catch 'nextfile
21344 (org-check-agenda-file file)
21345 (setq buffer (if (file-exists-p file)
21346 (org-get-agenda-file-buffer file)
21347 (error "No such file %s" file)))
21348 (if (not buffer)
21349 ;; If file does not exist, merror message to agenda
21350 (setq rtn (list
21351 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21352 rtnall (append rtnall rtn))
21353 (with-current-buffer buffer
21354 (unless (org-mode-p)
21355 (error "Agenda file %s is not in `org-mode'" file))
21356 (save-excursion
21357 (save-restriction
21358 (if org-agenda-restrict
21359 (narrow-to-region org-agenda-restrict-begin
21360 org-agenda-restrict-end)
21361 (widen))
21362 (setq rtn (org-scan-tags 'agenda matcher todo-only))
21363 (setq rtnall (append rtnall rtn))))))))
21364 (if org-agenda-overriding-header
21365 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21366 nil 'face 'org-agenda-structure) "\n")
21367 (insert "Headlines with TAGS match: ")
21368 (add-text-properties (point-min) (1- (point))
21369 (list 'face 'org-agenda-structure))
21370 (setq pos (point))
21371 (insert match "\n")
21372 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21373 (setq pos (point))
21374 (unless org-agenda-multi
21375 (insert "Press `C-u r' to search again with new search string\n"))
21376 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21377 (when rtnall
21378 (insert (org-finalize-agenda-entries rtnall) "\n"))
21379 (goto-char (point-min))
21380 (org-fit-agenda-window)
21381 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
21382 (org-finalize-agenda)
21383 (setq buffer-read-only t)))
21384
21385 ;;; Agenda Finding stuck projects
21386
21387 (defvar org-agenda-skip-regexp nil
21388 "Regular expression used in skipping subtrees for the agenda.
21389 This is basically a temporary global variable that can be set and then
21390 used by user-defined selections using `org-agenda-skip-function'.")
21391
21392 (defvar org-agenda-overriding-header nil
21393 "When this is set during todo and tags searches, will replace header.")
21394
21395 (defun org-agenda-skip-subtree-when-regexp-matches ()
21396 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
21397 If yes, it returns the end position of this tree, causing agenda commands
21398 to skip this subtree. This is a function that can be put into
21399 `org-agenda-skip-function' for the duration of a command."
21400 (let ((end (save-excursion (org-end-of-subtree t)))
21401 skip)
21402 (save-excursion
21403 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
21404 (and skip end)))
21405
21406 (defun org-agenda-skip-entry-if (&rest conditions)
21407 "Skip entry if any of CONDITIONS is true.
21408 See `org-agenda-skip-if' for details."
21409 (org-agenda-skip-if nil conditions))
21410
21411 (defun org-agenda-skip-subtree-if (&rest conditions)
21412 "Skip entry if any of CONDITIONS is true.
21413 See `org-agenda-skip-if' for details."
21414 (org-agenda-skip-if t conditions))
21415
21416 (defun org-agenda-skip-if (subtree conditions)
21417 "Checks current entity for CONDITIONS.
21418 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21419 the entry, i.e. the text before the next heading is checked.
21420
21421 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21422 from different tests. Valid conditions are:
21423
21424 scheduled Check if there is a scheduled cookie
21425 notscheduled Check if there is no scheduled cookie
21426 deadline Check if there is a deadline
21427 notdeadline Check if there is no deadline
21428 regexp Check if regexp matches
21429 notregexp Check if regexp does not match.
21430
21431 The regexp is taken from the conditions list, it must come right after
21432 the `regexp' or `notregexp' element.
21433
21434 If any of these conditions is met, this function returns the end point of
21435 the entity, causing the search to continue from there. This is a function
21436 that can be put into `org-agenda-skip-function' for the duration of a command."
21437 (let (beg end m)
21438 (org-back-to-heading t)
21439 (setq beg (point)
21440 end (if subtree
21441 (progn (org-end-of-subtree t) (point))
21442 (progn (outline-next-heading) (1- (point)))))
21443 (goto-char beg)
21444 (and
21445 (or
21446 (and (memq 'scheduled conditions)
21447 (re-search-forward org-scheduled-time-regexp end t))
21448 (and (memq 'notscheduled conditions)
21449 (not (re-search-forward org-scheduled-time-regexp end t)))
21450 (and (memq 'deadline conditions)
21451 (re-search-forward org-deadline-time-regexp end t))
21452 (and (memq 'notdeadline conditions)
21453 (not (re-search-forward org-deadline-time-regexp end t)))
21454 (and (setq m (memq 'regexp conditions))
21455 (stringp (nth 1 m))
21456 (re-search-forward (nth 1 m) end t))
21457 (and (setq m (memq 'notregexp conditions))
21458 (stringp (nth 1 m))
21459 (not (re-search-forward (nth 1 m) end t))))
21460 end)))
21461
21462 ;;;###autoload
21463 (defun org-agenda-list-stuck-projects (&rest ignore)
21464 "Create agenda view for projects that are stuck.
21465 Stuck projects are project that have no next actions. For the definitions
21466 of what a project is and how to check if it stuck, customize the variable
21467 `org-stuck-projects'.
21468 MATCH is being ignored."
21469 (interactive)
21470 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21471 ;; FIXME: we could have used org-agenda-skip-if here.
21472 (org-agenda-overriding-header "List of stuck projects: ")
21473 (matcher (nth 0 org-stuck-projects))
21474 (todo (nth 1 org-stuck-projects))
21475 (todo-wds (if (member "*" todo)
21476 (progn
21477 (org-prepare-agenda-buffers (org-agenda-files))
21478 (org-delete-all
21479 org-done-keywords-for-agenda
21480 (copy-sequence org-todo-keywords-for-agenda)))
21481 todo))
21482 (todo-re (concat "^\\*+[ \t]+\\("
21483 (mapconcat 'identity todo-wds "\\|")
21484 "\\)\\>"))
21485 (tags (nth 2 org-stuck-projects))
21486 (tags-re (if (member "*" tags)
21487 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21488 (concat "^\\*+ .*:\\("
21489 (mapconcat 'identity tags "\\|")
21490 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21491 (gen-re (nth 3 org-stuck-projects))
21492 (re-list
21493 (delq nil
21494 (list
21495 (if todo todo-re)
21496 (if tags tags-re)
21497 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21498 gen-re)))))
21499 (setq org-agenda-skip-regexp
21500 (if re-list
21501 (mapconcat 'identity re-list "\\|")
21502 (error "No information how to identify unstuck projects")))
21503 (org-tags-view nil matcher)
21504 (with-current-buffer org-agenda-buffer-name
21505 (setq org-agenda-redo-command
21506 '(org-agenda-list-stuck-projects
21507 (or current-prefix-arg org-last-arg))))))
21508
21509 ;;; Diary integration
21510
21511 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21512 (defvar list-diary-entries-hook)
21513
21514 (defun org-get-entries-from-diary (date)
21515 "Get the (Emacs Calendar) diary entries for DATE."
21516 (require 'diary-lib)
21517 (let* ((diary-fancy-buffer "*temporary-fancy-diary-buffer*")
21518 (fancy-diary-buffer diary-fancy-buffer)
21519 (diary-display-hook '(fancy-diary-display))
21520 (pop-up-frames nil)
21521 (list-diary-entries-hook
21522 (cons 'org-diary-default-entry list-diary-entries-hook))
21523 (diary-file-name-prefix-function nil) ; turn this feature off
21524 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21525 entries
21526 (org-disable-agenda-to-diary t))
21527 (save-excursion
21528 (save-window-excursion
21529 (funcall (if (fboundp 'diary-list-entries)
21530 'diary-list-entries 'list-diary-entries)
21531 date 1)))
21532 (if (not (get-buffer diary-fancy-buffer))
21533 (setq entries nil)
21534 (with-current-buffer diary-fancy-buffer
21535 (setq buffer-read-only nil)
21536 (if (zerop (buffer-size))
21537 ;; No entries
21538 (setq entries nil)
21539 ;; Omit the date and other unnecessary stuff
21540 (org-agenda-cleanup-fancy-diary)
21541 ;; Add prefix to each line and extend the text properties
21542 (if (zerop (buffer-size))
21543 (setq entries nil)
21544 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21545 (set-buffer-modified-p nil)
21546 (kill-buffer diary-fancy-buffer)))
21547 (when entries
21548 (setq entries (org-split-string entries "\n"))
21549 (setq entries
21550 (mapcar
21551 (lambda (x)
21552 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21553 ;; Extend the text properties to the beginning of the line
21554 (org-add-props x (text-properties-at (1- (length x)) x)
21555 'type "diary" 'date date))
21556 entries)))))
21557
21558 (defun org-agenda-cleanup-fancy-diary ()
21559 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21560 This gets rid of the date, the underline under the date, and
21561 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21562 date. It also removes lines that contain only whitespace."
21563 (goto-char (point-min))
21564 (if (looking-at ".*?:[ \t]*")
21565 (progn
21566 (replace-match "")
21567 (re-search-forward "\n=+$" nil t)
21568 (replace-match "")
21569 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21570 (re-search-forward "\n=+$" nil t)
21571 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21572 (goto-char (point-min))
21573 (while (re-search-forward "^ +\n" nil t)
21574 (replace-match ""))
21575 (goto-char (point-min))
21576 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21577 (replace-match "")))
21578
21579 ;; Make sure entries from the diary have the right text properties.
21580 (eval-after-load "diary-lib"
21581 '(if (boundp 'diary-modify-entry-list-string-function)
21582 ;; We can rely on the hook, nothing to do
21583 nil
21584 ;; Hook not avaiable, must use advice to make this work
21585 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21586 "Make the position visible."
21587 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21588 (stringp string)
21589 buffer-file-name)
21590 (setq string (org-modify-diary-entry-string string))))))
21591
21592 (defun org-modify-diary-entry-string (string)
21593 "Add text properties to string, allowing org-mode to act on it."
21594 (org-add-props string nil
21595 'mouse-face 'highlight
21596 'keymap org-agenda-keymap
21597 'help-echo (if buffer-file-name
21598 (format "mouse-2 or RET jump to diary file %s"
21599 (abbreviate-file-name buffer-file-name))
21600 "")
21601 'org-agenda-diary-link t
21602 'org-marker (org-agenda-new-marker (point-at-bol))))
21603
21604 (defun org-diary-default-entry ()
21605 "Add a dummy entry to the diary.
21606 Needed to avoid empty dates which mess up holiday display."
21607 ;; Catch the error if dealing with the new add-to-diary-alist
21608 (when org-disable-agenda-to-diary
21609 (condition-case nil
21610 (add-to-diary-list original-date "Org-mode dummy" "")
21611 (error
21612 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21613
21614 ;;;###autoload
21615 (defun org-diary (&rest args)
21616 "Return diary information from org-files.
21617 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21618 It accesses org files and extracts information from those files to be
21619 listed in the diary. The function accepts arguments specifying what
21620 items should be listed. The following arguments are allowed:
21621
21622 :timestamp List the headlines of items containing a date stamp or
21623 date range matching the selected date. Deadlines will
21624 also be listed, on the expiration day.
21625
21626 :sexp List entries resulting from diary-like sexps.
21627
21628 :deadline List any deadlines past due, or due within
21629 `org-deadline-warning-days'. The listing occurs only
21630 in the diary for *today*, not at any other date. If
21631 an entry is marked DONE, it is no longer listed.
21632
21633 :scheduled List all items which are scheduled for the given date.
21634 The diary for *today* also contains items which were
21635 scheduled earlier and are not yet marked DONE.
21636
21637 :todo List all TODO items from the org-file. This may be a
21638 long list - so this is not turned on by default.
21639 Like deadlines, these entries only show up in the
21640 diary for *today*, not at any other date.
21641
21642 The call in the diary file should look like this:
21643
21644 &%%(org-diary) ~/path/to/some/orgfile.org
21645
21646 Use a separate line for each org file to check. Or, if you omit the file name,
21647 all files listed in `org-agenda-files' will be checked automatically:
21648
21649 &%%(org-diary)
21650
21651 If you don't give any arguments (as in the example above), the default
21652 arguments (:deadline :scheduled :timestamp :sexp) are used.
21653 So the example above may also be written as
21654
21655 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21656
21657 The function expects the lisp variables `entry' and `date' to be provided
21658 by the caller, because this is how the calendar works. Don't use this
21659 function from a program - use `org-agenda-get-day-entries' instead."
21660 (when (> (- (time-to-seconds (current-time))
21661 org-agenda-last-marker-time)
21662 5)
21663 (org-agenda-reset-markers))
21664 (org-compile-prefix-format 'agenda)
21665 (org-set-sorting-strategy 'agenda)
21666 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21667 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21668 (list entry)
21669 (org-agenda-files t)))
21670 file rtn results)
21671 (org-prepare-agenda-buffers files)
21672 ;; If this is called during org-agenda, don't return any entries to
21673 ;; the calendar. Org Agenda will list these entries itself.
21674 (if org-disable-agenda-to-diary (setq files nil))
21675 (while (setq file (pop files))
21676 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21677 (setq results (append results rtn)))
21678 (if results
21679 (concat (org-finalize-agenda-entries results) "\n"))))
21680
21681 ;;; Agenda entry finders
21682
21683 (defun org-agenda-get-day-entries (file date &rest args)
21684 "Does the work for `org-diary' and `org-agenda'.
21685 FILE is the path to a file to be checked for entries. DATE is date like
21686 the one returned by `calendar-current-date'. ARGS are symbols indicating
21687 which kind of entries should be extracted. For details about these, see
21688 the documentation of `org-diary'."
21689 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21690 (let* ((org-startup-folded nil)
21691 (org-startup-align-all-tables nil)
21692 (buffer (if (file-exists-p file)
21693 (org-get-agenda-file-buffer file)
21694 (error "No such file %s" file)))
21695 arg results rtn)
21696 (if (not buffer)
21697 ;; If file does not exist, make sure an error message ends up in diary
21698 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21699 (with-current-buffer buffer
21700 (unless (org-mode-p)
21701 (error "Agenda file %s is not in `org-mode'" file))
21702 (let ((case-fold-search nil))
21703 (save-excursion
21704 (save-restriction
21705 (if org-agenda-restrict
21706 (narrow-to-region org-agenda-restrict-begin
21707 org-agenda-restrict-end)
21708 (widen))
21709 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21710 (while (setq arg (pop args))
21711 (cond
21712 ((and (eq arg :todo)
21713 (equal date (calendar-current-date)))
21714 (setq rtn (org-agenda-get-todos))
21715 (setq results (append results rtn)))
21716 ((eq arg :timestamp)
21717 (setq rtn (org-agenda-get-blocks))
21718 (setq results (append results rtn))
21719 (setq rtn (org-agenda-get-timestamps))
21720 (setq results (append results rtn)))
21721 ((eq arg :sexp)
21722 (setq rtn (org-agenda-get-sexps))
21723 (setq results (append results rtn)))
21724 ((eq arg :scheduled)
21725 (setq rtn (org-agenda-get-scheduled))
21726 (setq results (append results rtn)))
21727 ((eq arg :closed)
21728 (setq rtn (org-agenda-get-closed))
21729 (setq results (append results rtn)))
21730 ((eq arg :deadline)
21731 (setq rtn (org-agenda-get-deadlines))
21732 (setq results (append results rtn))))))))
21733 results))))
21734
21735 (defun org-entry-is-todo-p ()
21736 (member (org-get-todo-state) org-not-done-keywords))
21737
21738 (defun org-entry-is-done-p ()
21739 (member (org-get-todo-state) org-done-keywords))
21740
21741 (defun org-get-todo-state ()
21742 (save-excursion
21743 (org-back-to-heading t)
21744 (and (looking-at org-todo-line-regexp)
21745 (match-end 2)
21746 (match-string 2))))
21747
21748 (defun org-at-date-range-p (&optional inactive-ok)
21749 "Is the cursor inside a date range?"
21750 (interactive)
21751 (save-excursion
21752 (catch 'exit
21753 (let ((pos (point)))
21754 (skip-chars-backward "^[<\r\n")
21755 (skip-chars-backward "<[")
21756 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21757 (>= (match-end 0) pos)
21758 (throw 'exit t))
21759 (skip-chars-backward "^<[\r\n")
21760 (skip-chars-backward "<[")
21761 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21762 (>= (match-end 0) pos)
21763 (throw 'exit t)))
21764 nil)))
21765
21766 (defun org-agenda-get-todos ()
21767 "Return the TODO information for agenda display."
21768 (let* ((props (list 'face nil
21769 'done-face 'org-done
21770 'org-not-done-regexp org-not-done-regexp
21771 'org-todo-regexp org-todo-regexp
21772 'mouse-face 'highlight
21773 'keymap org-agenda-keymap
21774 'help-echo
21775 (format "mouse-2 or RET jump to org file %s"
21776 (abbreviate-file-name buffer-file-name))))
21777 ;; FIXME: get rid of the \n at some point but watch out
21778 (regexp (concat "^\\*+[ \t]+\\("
21779 (if org-select-this-todo-keyword
21780 (if (equal org-select-this-todo-keyword "*")
21781 org-todo-regexp
21782 (concat "\\<\\("
21783 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21784 "\\)\\>"))
21785 org-not-done-regexp)
21786 "[^\n\r]*\\)"))
21787 marker priority category tags
21788 ee txt beg end)
21789 (goto-char (point-min))
21790 (while (re-search-forward regexp nil t)
21791 (catch :skip
21792 (save-match-data
21793 (beginning-of-line)
21794 (setq beg (point) end (progn (outline-next-heading) (point)))
21795 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21796 (re-search-forward org-ts-regexp end t))
21797 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21798 (re-search-forward org-scheduled-time-regexp end t))
21799 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21800 (re-search-forward org-deadline-time-regexp end t)
21801 (org-deadline-close (match-string 1))))
21802 (goto-char (1+ beg))
21803 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21804 (throw :skip nil)))
21805 (goto-char beg)
21806 (org-agenda-skip)
21807 (goto-char (match-beginning 1))
21808 (setq marker (org-agenda-new-marker (match-beginning 0))
21809 category (org-get-category)
21810 tags (org-get-tags-at (point))
21811 txt (org-format-agenda-item "" (match-string 1) category tags)
21812 priority (1+ (org-get-priority txt)))
21813 (org-add-props txt props
21814 'org-marker marker 'org-hd-marker marker
21815 'priority priority 'org-category category
21816 'type "todo")
21817 (push txt ee)
21818 (if org-agenda-todo-list-sublevels
21819 (goto-char (match-end 1))
21820 (org-end-of-subtree 'invisible))))
21821 (nreverse ee)))
21822
21823 (defconst org-agenda-no-heading-message
21824 "No heading for this item in buffer or region.")
21825
21826 (defun org-agenda-get-timestamps ()
21827 "Return the date stamp information for agenda display."
21828 (let* ((props (list 'face nil
21829 'org-not-done-regexp org-not-done-regexp
21830 'org-todo-regexp org-todo-regexp
21831 'mouse-face 'highlight
21832 'keymap org-agenda-keymap
21833 'help-echo
21834 (format "mouse-2 or RET jump to org file %s"
21835 (abbreviate-file-name buffer-file-name))))
21836 (d1 (calendar-absolute-from-gregorian date))
21837 (remove-re
21838 (concat
21839 (regexp-quote
21840 (format-time-string
21841 "<%Y-%m-%d"
21842 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21843 ".*?>"))
21844 (regexp
21845 (concat
21846 (regexp-quote
21847 (substring
21848 (format-time-string
21849 (car org-time-stamp-formats)
21850 (apply 'encode-time ; DATE bound by calendar
21851 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21852 0 11))
21853 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21854 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21855 marker hdmarker deadlinep scheduledp donep tmp priority category
21856 ee txt timestr tags b0 b3 e3 head)
21857 (goto-char (point-min))
21858 (while (re-search-forward regexp nil t)
21859 (setq b0 (match-beginning 0)
21860 b3 (match-beginning 3) e3 (match-end 3))
21861 (catch :skip
21862 (and (org-at-date-range-p) (throw :skip nil))
21863 (org-agenda-skip)
21864 (if (and (match-end 1)
21865 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21866 (throw :skip nil))
21867 (if (and e3
21868 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21869 (throw :skip nil))
21870 (setq marker (org-agenda-new-marker b0)
21871 category (org-get-category b0)
21872 tmp (buffer-substring (max (point-min)
21873 (- b0 org-ds-keyword-length))
21874 b0)
21875 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21876 deadlinep (string-match org-deadline-regexp tmp)
21877 scheduledp (string-match org-scheduled-regexp tmp)
21878 donep (org-entry-is-done-p))
21879 (if (or scheduledp deadlinep) (throw :skip t))
21880 (if (string-match ">" timestr)
21881 ;; substring should only run to end of time stamp
21882 (setq timestr (substring timestr 0 (match-end 0))))
21883 (save-excursion
21884 (if (re-search-backward "^\\*+ " nil t)
21885 (progn
21886 (goto-char (match-beginning 0))
21887 (setq hdmarker (org-agenda-new-marker)
21888 tags (org-get-tags-at))
21889 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21890 (setq head (match-string 1))
21891 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21892 (setq txt (org-format-agenda-item
21893 nil head category tags timestr nil
21894 remove-re)))
21895 (setq txt org-agenda-no-heading-message))
21896 (setq priority (org-get-priority txt))
21897 (org-add-props txt props
21898 'org-marker marker 'org-hd-marker hdmarker)
21899 (org-add-props txt nil 'priority priority
21900 'org-category category 'date date
21901 'type "timestamp")
21902 (push txt ee))
21903 (outline-next-heading)))
21904 (nreverse ee)))
21905
21906 (defun org-agenda-get-sexps ()
21907 "Return the sexp information for agenda display."
21908 (require 'diary-lib)
21909 (let* ((props (list 'face nil
21910 'mouse-face 'highlight
21911 'keymap org-agenda-keymap
21912 'help-echo
21913 (format "mouse-2 or RET jump to org file %s"
21914 (abbreviate-file-name buffer-file-name))))
21915 (regexp "^&?%%(")
21916 marker category ee txt tags entry result beg b sexp sexp-entry)
21917 (goto-char (point-min))
21918 (while (re-search-forward regexp nil t)
21919 (catch :skip
21920 (org-agenda-skip)
21921 (setq beg (match-beginning 0))
21922 (goto-char (1- (match-end 0)))
21923 (setq b (point))
21924 (forward-sexp 1)
21925 (setq sexp (buffer-substring b (point)))
21926 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21927 (org-trim (match-string 1))
21928 ""))
21929 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21930 (when result
21931 (setq marker (org-agenda-new-marker beg)
21932 category (org-get-category beg))
21933
21934 (if (string-match "\\S-" result)
21935 (setq txt result)
21936 (setq txt "SEXP entry returned empty string"))
21937
21938 (setq txt (org-format-agenda-item
21939 "" txt category tags 'time))
21940 (org-add-props txt props 'org-marker marker)
21941 (org-add-props txt nil
21942 'org-category category 'date date
21943 'type "sexp")
21944 (push txt ee))))
21945 (nreverse ee)))
21946
21947 (defun org-agenda-get-closed ()
21948 "Return the logged TODO entries for agenda display."
21949 (let* ((props (list 'mouse-face 'highlight
21950 'org-not-done-regexp org-not-done-regexp
21951 'org-todo-regexp org-todo-regexp
21952 'keymap org-agenda-keymap
21953 'help-echo
21954 (format "mouse-2 or RET jump to org file %s"
21955 (abbreviate-file-name buffer-file-name))))
21956 (regexp (concat
21957 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21958 (regexp-quote
21959 (substring
21960 (format-time-string
21961 (car org-time-stamp-formats)
21962 (apply 'encode-time ; DATE bound by calendar
21963 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21964 1 11))))
21965 marker hdmarker priority category tags closedp
21966 ee txt timestr)
21967 (goto-char (point-min))
21968 (while (re-search-forward regexp nil t)
21969 (catch :skip
21970 (org-agenda-skip)
21971 (setq marker (org-agenda-new-marker (match-beginning 0))
21972 closedp (equal (match-string 1) org-closed-string)
21973 category (org-get-category (match-beginning 0))
21974 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21975 ;; donep (org-entry-is-done-p)
21976 )
21977 (if (string-match "\\]" timestr)
21978 ;; substring should only run to end of time stamp
21979 (setq timestr (substring timestr 0 (match-end 0))))
21980 (save-excursion
21981 (if (re-search-backward "^\\*+ " nil t)
21982 (progn
21983 (goto-char (match-beginning 0))
21984 (setq hdmarker (org-agenda-new-marker)
21985 tags (org-get-tags-at))
21986 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21987 (setq txt (org-format-agenda-item
21988 (if closedp "Closed: " "Clocked: ")
21989 (match-string 1) category tags timestr)))
21990 (setq txt org-agenda-no-heading-message))
21991 (setq priority 100000)
21992 (org-add-props txt props
21993 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21994 'priority priority 'org-category category
21995 'type "closed" 'date date
21996 'undone-face 'org-warning 'done-face 'org-done)
21997 (push txt ee))
21998 (goto-char (point-at-eol))))
21999 (nreverse ee)))
22000
22001 (defun org-agenda-get-deadlines ()
22002 "Return the deadline information for agenda display."
22003 (let* ((props (list 'mouse-face 'highlight
22004 'org-not-done-regexp org-not-done-regexp
22005 'org-todo-regexp org-todo-regexp
22006 'keymap org-agenda-keymap
22007 'help-echo
22008 (format "mouse-2 or RET jump to org file %s"
22009 (abbreviate-file-name buffer-file-name))))
22010 (regexp org-deadline-time-regexp)
22011 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
22012 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
22013 d2 diff dfrac wdays pos pos1 category tags
22014 ee txt head face s upcomingp donep timestr)
22015 (goto-char (point-min))
22016 (while (re-search-forward regexp nil t)
22017 (catch :skip
22018 (org-agenda-skip)
22019 (setq s (match-string 1)
22020 pos (1- (match-beginning 1))
22021 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
22022 diff (- d2 d1)
22023 wdays (org-get-wdays s)
22024 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
22025 upcomingp (and todayp (> diff 0)))
22026 ;; When to show a deadline in the calendar:
22027 ;; If the expiration is within wdays warning time.
22028 ;; Past-due deadlines are only shown on the current date
22029 (if (or (and (<= diff wdays)
22030 (and todayp (not org-agenda-only-exact-dates)))
22031 (= diff 0))
22032 (save-excursion
22033 (setq category (org-get-category))
22034 (if (re-search-backward "^\\*+[ \t]+" nil t)
22035 (progn
22036 (goto-char (match-end 0))
22037 (setq pos1 (match-beginning 0))
22038 (setq tags (org-get-tags-at pos1))
22039 (setq head (buffer-substring-no-properties
22040 (point)
22041 (progn (skip-chars-forward "^\r\n")
22042 (point))))
22043 (setq donep (string-match org-looking-at-done-regexp head))
22044 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
22045 (setq timestr
22046 (concat (substring s (match-beginning 1)) " "))
22047 (setq timestr 'time))
22048 (if (and donep
22049 (or org-agenda-skip-deadline-if-done
22050 (not (= diff 0))))
22051 (setq txt nil)
22052 (setq txt (org-format-agenda-item
22053 (if (= diff 0)
22054 (car org-agenda-deadline-leaders)
22055 (format (nth 1 org-agenda-deadline-leaders)
22056 diff))
22057 head category tags timestr))))
22058 (setq txt org-agenda-no-heading-message))
22059 (when txt
22060 (setq face (org-agenda-deadline-face dfrac wdays))
22061 (org-add-props txt props
22062 'org-marker (org-agenda-new-marker pos)
22063 'org-hd-marker (org-agenda-new-marker pos1)
22064 'priority (+ (- diff)
22065 (org-get-priority txt))
22066 'org-category category
22067 'type (if upcomingp "upcoming-deadline" "deadline")
22068 'date (if upcomingp date d2)
22069 'face (if donep 'org-done face)
22070 'undone-face face 'done-face 'org-done)
22071 (push txt ee))))))
22072 (nreverse ee)))
22073
22074 (defun org-agenda-deadline-face (fraction &optional wdays)
22075 "Return the face to displaying a deadline item.
22076 FRACTION is what fraction of the head-warning time has passed."
22077 (if (equal wdays 0) (setq fraction 1.))
22078 (let ((faces org-agenda-deadline-faces) f)
22079 (catch 'exit
22080 (while (setq f (pop faces))
22081 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
22082
22083 (defun org-agenda-get-scheduled ()
22084 "Return the scheduled information for agenda display."
22085 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
22086 'org-todo-regexp org-todo-regexp
22087 'done-face 'org-done
22088 'mouse-face 'highlight
22089 'keymap org-agenda-keymap
22090 'help-echo
22091 (format "mouse-2 or RET jump to org file %s"
22092 (abbreviate-file-name buffer-file-name))))
22093 (regexp org-scheduled-time-regexp)
22094 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
22095 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
22096 d2 diff pos pos1 category tags
22097 ee txt head pastschedp donep face timestr s)
22098 (goto-char (point-min))
22099 (while (re-search-forward regexp nil t)
22100 (catch :skip
22101 (org-agenda-skip)
22102 (setq s (match-string 1)
22103 pos (1- (match-beginning 1))
22104 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
22105 ;;; is this right?
22106 ;;; do we need to do this for deadleine too????
22107 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
22108 diff (- d2 d1))
22109 (setq pastschedp (and todayp (< diff 0)))
22110 ;; When to show a scheduled item in the calendar:
22111 ;; If it is on or past the date.
22112 (if (or (and (< diff 0)
22113 (and todayp (not org-agenda-only-exact-dates)))
22114 (= diff 0))
22115 (save-excursion
22116 (setq category (org-get-category))
22117 (if (re-search-backward "^\\*+[ \t]+" nil t)
22118 (progn
22119 (goto-char (match-end 0))
22120 (setq pos1 (match-beginning 0))
22121 (setq tags (org-get-tags-at))
22122 (setq head (buffer-substring-no-properties
22123 (point)
22124 (progn (skip-chars-forward "^\r\n") (point))))
22125 (setq donep (string-match org-looking-at-done-regexp head))
22126 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
22127 (setq timestr
22128 (concat (substring s (match-beginning 1)) " "))
22129 (setq timestr 'time))
22130 (if (and donep
22131 (or org-agenda-skip-scheduled-if-done
22132 (not (= diff 0))))
22133 (setq txt nil)
22134 (setq txt (org-format-agenda-item
22135 (if (= diff 0)
22136 (car org-agenda-scheduled-leaders)
22137 (format (nth 1 org-agenda-scheduled-leaders)
22138 (- 1 diff)))
22139 head category tags timestr))))
22140 (setq txt org-agenda-no-heading-message))
22141 (when txt
22142 (setq face (if pastschedp
22143 'org-scheduled-previously
22144 'org-scheduled-today))
22145 (org-add-props txt props
22146 'undone-face face
22147 'face (if donep 'org-done face)
22148 'org-marker (org-agenda-new-marker pos)
22149 'org-hd-marker (org-agenda-new-marker pos1)
22150 'type (if pastschedp "past-scheduled" "scheduled")
22151 'date (if pastschedp d2 date)
22152 'priority (+ 94 (- 5 diff) (org-get-priority txt))
22153 'org-category category)
22154 (push txt ee))))))
22155 (nreverse ee)))
22156
22157 (defun org-agenda-get-blocks ()
22158 "Return the date-range information for agenda display."
22159 (let* ((props (list 'face nil
22160 'org-not-done-regexp org-not-done-regexp
22161 'org-todo-regexp org-todo-regexp
22162 'mouse-face 'highlight
22163 'keymap org-agenda-keymap
22164 'help-echo
22165 (format "mouse-2 or RET jump to org file %s"
22166 (abbreviate-file-name buffer-file-name))))
22167 (regexp org-tr-regexp)
22168 (d0 (calendar-absolute-from-gregorian date))
22169 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
22170 donep head)
22171 (goto-char (point-min))
22172 (while (re-search-forward regexp nil t)
22173 (catch :skip
22174 (org-agenda-skip)
22175 (setq pos (point))
22176 (setq timestr (match-string 0)
22177 s1 (match-string 1)
22178 s2 (match-string 2)
22179 d1 (time-to-days (org-time-string-to-time s1))
22180 d2 (time-to-days (org-time-string-to-time s2)))
22181 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
22182 ;; Only allow days between the limits, because the normal
22183 ;; date stamps will catch the limits.
22184 (save-excursion
22185 (setq marker (org-agenda-new-marker (point)))
22186 (setq category (org-get-category))
22187 (if (re-search-backward "^\\*+ " nil t)
22188 (progn
22189 (goto-char (match-beginning 0))
22190 (setq hdmarker (org-agenda-new-marker (point)))
22191 (setq tags (org-get-tags-at))
22192 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
22193 (setq head (match-string 1))
22194 (and org-agenda-skip-timestamp-if-done
22195 (org-entry-is-done-p)
22196 (throw :skip t))
22197 (setq txt (org-format-agenda-item
22198 (format (if (= d1 d2) "" "(%d/%d): ")
22199 (1+ (- d0 d1)) (1+ (- d2 d1)))
22200 head category tags
22201 (if (= d0 d1) timestr))))
22202 (setq txt org-agenda-no-heading-message))
22203 (org-add-props txt props
22204 'org-marker marker 'org-hd-marker hdmarker
22205 'type "block" 'date date
22206 'priority (org-get-priority txt) 'org-category category)
22207 (push txt ee)))
22208 (goto-char pos)))
22209 ;; Sort the entries by expiration date.
22210 (nreverse ee)))
22211
22212 ;;; Agenda presentation and sorting
22213
22214 (defconst org-plain-time-of-day-regexp
22215 (concat
22216 "\\(\\<[012]?[0-9]"
22217 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22218 "\\(--?"
22219 "\\(\\<[012]?[0-9]"
22220 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22221 "\\)?")
22222 "Regular expression to match a plain time or time range.
22223 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22224 groups carry important information:
22225 0 the full match
22226 1 the first time, range or not
22227 8 the second time, if it is a range.")
22228
22229 (defconst org-plain-time-extension-regexp
22230 (concat
22231 "\\(\\<[012]?[0-9]"
22232 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22233 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
22234 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
22235 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22236 groups carry important information:
22237 0 the full match
22238 7 hours of duration
22239 9 minutes of duration")
22240
22241 (defconst org-stamp-time-of-day-regexp
22242 (concat
22243 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
22244 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
22245 "\\(--?"
22246 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
22247 "Regular expression to match a timestamp time or time range.
22248 After a match, the following groups carry important information:
22249 0 the full match
22250 1 date plus weekday, for backreferencing to make sure both times on same day
22251 2 the first time, range or not
22252 4 the second time, if it is a range.")
22253
22254 (defvar org-prefix-has-time nil
22255 "A flag, set by `org-compile-prefix-format'.
22256 The flag is set if the currently compiled format contains a `%t'.")
22257 (defvar org-prefix-has-tag nil
22258 "A flag, set by `org-compile-prefix-format'.
22259 The flag is set if the currently compiled format contains a `%T'.")
22260
22261 (defun org-format-agenda-item (extra txt &optional category tags dotime
22262 noprefix remove-re)
22263 "Format TXT to be inserted into the agenda buffer.
22264 In particular, it adds the prefix and corresponding text properties. EXTRA
22265 must be a string and replaces the `%s' specifier in the prefix format.
22266 CATEGORY (string, symbol or nil) may be used to overrule the default
22267 category taken from local variable or file name. It will replace the `%c'
22268 specifier in the format. DOTIME, when non-nil, indicates that a
22269 time-of-day should be extracted from TXT for sorting of this entry, and for
22270 the `%t' specifier in the format. When DOTIME is a string, this string is
22271 searched for a time before TXT is. NOPREFIX is a flag and indicates that
22272 only the correctly processes TXT should be returned - this is used by
22273 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
22274 Any match of REMOVE-RE will be removed from TXT."
22275 (save-match-data
22276 ;; Diary entries sometimes have extra whitespace at the beginning
22277 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
22278 (let* ((category (or category
22279 org-category
22280 (if buffer-file-name
22281 (file-name-sans-extension
22282 (file-name-nondirectory buffer-file-name))
22283 "")))
22284 (tag (if tags (nth (1- (length tags)) tags) ""))
22285 time ; time and tag are needed for the eval of the prefix format
22286 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
22287 (time-of-day (and dotime (org-get-time-of-day ts)))
22288 stamp plain s0 s1 s2 rtn srp)
22289 (when (and dotime time-of-day org-prefix-has-time)
22290 ;; Extract starting and ending time and move them to prefix
22291 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
22292 (setq plain (string-match org-plain-time-of-day-regexp ts)))
22293 (setq s0 (match-string 0 ts)
22294 srp (and stamp (match-end 3))
22295 s1 (match-string (if plain 1 2) ts)
22296 s2 (match-string (if plain 8 (if srp 4 6)) ts))
22297
22298 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
22299 ;; them, we might want to remove them there to avoid duplication.
22300 ;; The user can turn this off with a variable.
22301 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
22302 (string-match (concat (regexp-quote s0) " *") txt)
22303 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
22304 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
22305 (= (match-beginning 0) 0)
22306 t))
22307 (setq txt (replace-match "" nil nil txt))))
22308 ;; Normalize the time(s) to 24 hour
22309 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
22310 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
22311
22312 (when (and s1 (not s2) org-agenda-default-appointment-duration
22313 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
22314 (let ((m (+ (string-to-number (match-string 2 s1))
22315 (* 60 (string-to-number (match-string 1 s1)))
22316 org-agenda-default-appointment-duration))
22317 h)
22318 (setq h (/ m 60) m (- m (* h 60)))
22319 (setq s2 (format "%02d:%02d" h m))))
22320
22321 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22322 txt)
22323 ;; Tags are in the string
22324 (if (or (eq org-agenda-remove-tags t)
22325 (and org-agenda-remove-tags
22326 org-prefix-has-tag))
22327 (setq txt (replace-match "" t t txt))
22328 (setq txt (replace-match
22329 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
22330 (match-string 2 txt))
22331 t t txt))))
22332
22333 (when remove-re
22334 (while (string-match remove-re txt)
22335 (setq txt (replace-match "" t t txt))))
22336
22337 ;; Create the final string
22338 (if noprefix
22339 (setq rtn txt)
22340 ;; Prepare the variables needed in the eval of the compiled format
22341 (setq time (cond (s2 (concat s1 "-" s2))
22342 (s1 (concat s1 "......"))
22343 (t ""))
22344 extra (or extra "")
22345 category (if (symbolp category) (symbol-name category) category))
22346 ;; Evaluate the compiled format
22347 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
22348
22349 ;; And finally add the text properties
22350 (org-add-props rtn nil
22351 'org-category (downcase category) 'tags tags
22352 'org-highest-priority org-highest-priority
22353 'org-lowest-priority org-lowest-priority
22354 'prefix-length (- (length rtn) (length txt))
22355 'time-of-day time-of-day
22356 'txt txt
22357 'time time
22358 'extra extra
22359 'dotime dotime))))
22360
22361 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
22362 (defvar org-agenda-sorting-strategy-selected nil)
22363
22364 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
22365 (catch 'exit
22366 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
22367 ((and todayp (member 'today (car org-agenda-time-grid))))
22368 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
22369 ((member 'weekly (car org-agenda-time-grid)))
22370 (t (throw 'exit list)))
22371 (let* ((have (delq nil (mapcar
22372 (lambda (x) (get-text-property 1 'time-of-day x))
22373 list)))
22374 (string (nth 1 org-agenda-time-grid))
22375 (gridtimes (nth 2 org-agenda-time-grid))
22376 (req (car org-agenda-time-grid))
22377 (remove (member 'remove-match req))
22378 new time)
22379 (if (and (member 'require-timed req) (not have))
22380 ;; don't show empty grid
22381 (throw 'exit list))
22382 (while (setq time (pop gridtimes))
22383 (unless (and remove (member time have))
22384 (setq time (int-to-string time))
22385 (push (org-format-agenda-item
22386 nil string "" nil
22387 (concat (substring time 0 -2) ":" (substring time -2)))
22388 new)
22389 (put-text-property
22390 1 (length (car new)) 'face 'org-time-grid (car new))))
22391 (if (member 'time-up org-agenda-sorting-strategy-selected)
22392 (append new list)
22393 (append list new)))))
22394
22395 (defun org-compile-prefix-format (key)
22396 "Compile the prefix format into a Lisp form that can be evaluated.
22397 The resulting form is returned and stored in the variable
22398 `org-prefix-format-compiled'."
22399 (setq org-prefix-has-time nil org-prefix-has-tag nil)
22400 (let ((s (cond
22401 ((stringp org-agenda-prefix-format)
22402 org-agenda-prefix-format)
22403 ((assq key org-agenda-prefix-format)
22404 (cdr (assq key org-agenda-prefix-format)))
22405 (t " %-12:c%?-12t% s")))
22406 (start 0)
22407 varform vars var e c f opt)
22408 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
22409 s start)
22410 (setq var (cdr (assoc (match-string 4 s)
22411 '(("c" . category) ("t" . time) ("s" . extra)
22412 ("T" . tag))))
22413 c (or (match-string 3 s) "")
22414 opt (match-beginning 1)
22415 start (1+ (match-beginning 0)))
22416 (if (equal var 'time) (setq org-prefix-has-time t))
22417 (if (equal var 'tag) (setq org-prefix-has-tag t))
22418 (setq f (concat "%" (match-string 2 s) "s"))
22419 (if opt
22420 (setq varform
22421 `(if (equal "" ,var)
22422 ""
22423 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22424 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22425 (setq s (replace-match "%s" t nil s))
22426 (push varform vars))
22427 (setq vars (nreverse vars))
22428 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22429
22430 (defun org-set-sorting-strategy (key)
22431 (if (symbolp (car org-agenda-sorting-strategy))
22432 ;; the old format
22433 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22434 (setq org-agenda-sorting-strategy-selected
22435 (or (cdr (assq key org-agenda-sorting-strategy))
22436 (cdr (assq 'agenda org-agenda-sorting-strategy))
22437 '(time-up category-keep priority-down)))))
22438
22439 (defun org-get-time-of-day (s &optional string mod24)
22440 "Check string S for a time of day.
22441 If found, return it as a military time number between 0 and 2400.
22442 If not found, return nil.
22443 The optional STRING argument forces conversion into a 5 character wide string
22444 HH:MM."
22445 (save-match-data
22446 (when
22447 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22448 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22449 (let* ((h (string-to-number (match-string 1 s)))
22450 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22451 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22452 (am-p (equal ampm "am"))
22453 (h1 (cond ((not ampm) h)
22454 ((= h 12) (if am-p 0 12))
22455 (t (+ h (if am-p 0 12)))))
22456 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22457 (mod h1 24) h1))
22458 (t0 (+ (* 100 h2) m))
22459 (t1 (concat (if (>= h1 24) "+" " ")
22460 (if (< t0 100) "0" "")
22461 (if (< t0 10) "0" "")
22462 (int-to-string t0))))
22463 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22464
22465 (defun org-finalize-agenda-entries (list &optional nosort)
22466 "Sort and concatenate the agenda items."
22467 (setq list (mapcar 'org-agenda-highlight-todo list))
22468 (if nosort
22469 list
22470 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22471
22472 (defun org-agenda-highlight-todo (x)
22473 (let (re pl)
22474 (if (eq x 'line)
22475 (save-excursion
22476 (beginning-of-line 1)
22477 (setq re (get-text-property (point) 'org-todo-regexp))
22478 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22479 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22480 (add-text-properties (match-beginning 0) (match-end 0)
22481 (list 'face (org-get-todo-face 0)))
22482 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22483 (delete-region (match-beginning 1) (1- (match-end 0)))
22484 (goto-char (match-beginning 1))
22485 (insert (format org-agenda-todo-keyword-format s)))))
22486 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22487 pl (get-text-property 0 'prefix-length x))
22488 (when (and re
22489 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22490 x (or pl 0)) pl))
22491 (add-text-properties
22492 (or (match-end 1) (match-end 0)) (match-end 0)
22493 (list 'face (org-get-todo-face (match-string 2 x)))
22494 x)
22495 (setq x (concat (substring x 0 (match-end 1))
22496 (format org-agenda-todo-keyword-format
22497 (match-string 2 x))
22498 " "
22499 (substring x (match-end 3)))))
22500 x)))
22501
22502 (defsubst org-cmp-priority (a b)
22503 "Compare the priorities of string A and B."
22504 (let ((pa (or (get-text-property 1 'priority a) 0))
22505 (pb (or (get-text-property 1 'priority b) 0)))
22506 (cond ((> pa pb) +1)
22507 ((< pa pb) -1)
22508 (t nil))))
22509
22510 (defsubst org-cmp-category (a b)
22511 "Compare the string values of categories of strings A and B."
22512 (let ((ca (or (get-text-property 1 'org-category a) ""))
22513 (cb (or (get-text-property 1 'org-category b) "")))
22514 (cond ((string-lessp ca cb) -1)
22515 ((string-lessp cb ca) +1)
22516 (t nil))))
22517
22518 (defsubst org-cmp-tag (a b)
22519 "Compare the string values of categories of strings A and B."
22520 (let ((ta (car (last (get-text-property 1 'tags a))))
22521 (tb (car (last (get-text-property 1 'tags b)))))
22522 (cond ((not ta) +1)
22523 ((not tb) -1)
22524 ((string-lessp ta tb) -1)
22525 ((string-lessp tb ta) +1)
22526 (t nil))))
22527
22528 (defsubst org-cmp-time (a b)
22529 "Compare the time-of-day values of strings A and B."
22530 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22531 (ta (or (get-text-property 1 'time-of-day a) def))
22532 (tb (or (get-text-property 1 'time-of-day b) def)))
22533 (cond ((< ta tb) -1)
22534 ((< tb ta) +1)
22535 (t nil))))
22536
22537 (defun org-entries-lessp (a b)
22538 "Predicate for sorting agenda entries."
22539 ;; The following variables will be used when the form is evaluated.
22540 ;; So even though the compiler complains, keep them.
22541 (let* ((time-up (org-cmp-time a b))
22542 (time-down (if time-up (- time-up) nil))
22543 (priority-up (org-cmp-priority a b))
22544 (priority-down (if priority-up (- priority-up) nil))
22545 (category-up (org-cmp-category a b))
22546 (category-down (if category-up (- category-up) nil))
22547 (category-keep (if category-up +1 nil))
22548 (tag-up (org-cmp-tag a b))
22549 (tag-down (if tag-up (- tag-up) nil)))
22550 (cdr (assoc
22551 (eval (cons 'or org-agenda-sorting-strategy-selected))
22552 '((-1 . t) (1 . nil) (nil . nil))))))
22553
22554 ;;; Agenda restriction lock
22555
22556 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22557 "Overlay to mark the headline to which arenda commands are restricted.")
22558 (org-overlay-put org-agenda-restriction-lock-overlay
22559 'face 'org-agenda-restriction-lock)
22560 (org-overlay-put org-agenda-restriction-lock-overlay
22561 'help-echo "Agendas are currently limited to this subtree.")
22562 (org-detach-overlay org-agenda-restriction-lock-overlay)
22563 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22564 "Overlay marking the agenda restriction line in speedbar.")
22565 (org-overlay-put org-speedbar-restriction-lock-overlay
22566 'face 'org-agenda-restriction-lock)
22567 (org-overlay-put org-speedbar-restriction-lock-overlay
22568 'help-echo "Agendas are currently limited to this item.")
22569 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22570
22571 (defun org-agenda-set-restriction-lock (&optional type)
22572 "Set restriction lock for agenda, to current subtree or file.
22573 Restriction will be the file if TYPE is `file', or if type is the
22574 universal prefix '(4), or if the cursor is before the first headline
22575 in the file. Otherwise, restriction will be to the current subtree."
22576 (interactive "P")
22577 (and (equal type '(4)) (setq type 'file))
22578 (setq type (cond
22579 (type type)
22580 ((org-at-heading-p) 'subtree)
22581 ((condition-case nil (org-back-to-heading t) (error nil))
22582 'subtree)
22583 (t 'file)))
22584 (if (eq type 'subtree)
22585 (progn
22586 (setq org-agenda-restrict t)
22587 (setq org-agenda-overriding-restriction 'subtree)
22588 (put 'org-agenda-files 'org-restrict
22589 (list (buffer-file-name (buffer-base-buffer))))
22590 (org-back-to-heading t)
22591 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22592 (move-marker org-agenda-restrict-begin (point))
22593 (move-marker org-agenda-restrict-end
22594 (save-excursion (org-end-of-subtree t)))
22595 (message "Locking agenda restriction to subtree"))
22596 (put 'org-agenda-files 'org-restrict
22597 (list (buffer-file-name (buffer-base-buffer))))
22598 (setq org-agenda-restrict nil)
22599 (setq org-agenda-overriding-restriction 'file)
22600 (move-marker org-agenda-restrict-begin nil)
22601 (move-marker org-agenda-restrict-end nil)
22602 (message "Locking agenda restriction to file"))
22603 (setq current-prefix-arg nil)
22604 (org-agenda-maybe-redo))
22605
22606 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22607 "Remove the agenda restriction lock."
22608 (interactive "P")
22609 (org-detach-overlay org-agenda-restriction-lock-overlay)
22610 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22611 (setq org-agenda-overriding-restriction nil)
22612 (setq org-agenda-restrict nil)
22613 (put 'org-agenda-files 'org-restrict nil)
22614 (move-marker org-agenda-restrict-begin nil)
22615 (move-marker org-agenda-restrict-end nil)
22616 (setq current-prefix-arg nil)
22617 (message "Agenda restriction lock removed")
22618 (or noupdate (org-agenda-maybe-redo)))
22619
22620 (defun org-agenda-maybe-redo ()
22621 "If there is any window showing the agenda view, update it."
22622 (let ((w (get-buffer-window org-agenda-buffer-name t))
22623 (w0 (selected-window)))
22624 (when w
22625 (select-window w)
22626 (org-agenda-redo)
22627 (select-window w0)
22628 (if org-agenda-overriding-restriction
22629 (message "Agenda view shifted to new %s restriction"
22630 org-agenda-overriding-restriction)
22631 (message "Agenda restriction lock removed")))))
22632
22633 ;;; Agenda commands
22634
22635 (defun org-agenda-check-type (error &rest types)
22636 "Check if agenda buffer is of allowed type.
22637 If ERROR is non-nil, throw an error, otherwise just return nil."
22638 (if (memq org-agenda-type types)
22639 t
22640 (if error
22641 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22642 nil)))
22643
22644 (defun org-agenda-quit ()
22645 "Exit agenda by removing the window or the buffer."
22646 (interactive)
22647 (let ((buf (current-buffer)))
22648 (if (not (one-window-p)) (delete-window))
22649 (kill-buffer buf)
22650 (org-agenda-reset-markers)
22651 (org-columns-remove-overlays))
22652 ;; Maybe restore the pre-agenda window configuration.
22653 (and org-agenda-restore-windows-after-quit
22654 (not (eq org-agenda-window-setup 'other-frame))
22655 org-pre-agenda-window-conf
22656 (set-window-configuration org-pre-agenda-window-conf)))
22657
22658 (defun org-agenda-exit ()
22659 "Exit agenda by removing the window or the buffer.
22660 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22661 Org-mode buffers visited directly by the user will not be touched."
22662 (interactive)
22663 (org-release-buffers org-agenda-new-buffers)
22664 (setq org-agenda-new-buffers nil)
22665 (org-agenda-quit))
22666
22667 (defun org-agenda-execute (arg)
22668 "Execute another agenda command, keeping same window.\\<global-map>
22669 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22670 (interactive "P")
22671 (let ((org-agenda-window-setup 'current-window))
22672 (org-agenda arg)))
22673
22674 (defun org-save-all-org-buffers ()
22675 "Save all Org-mode buffers without user confirmation."
22676 (interactive)
22677 (message "Saving all Org-mode buffers...")
22678 (save-some-buffers t 'org-mode-p)
22679 (message "Saving all Org-mode buffers... done"))
22680
22681 (defun org-agenda-redo ()
22682 "Rebuild Agenda.
22683 When this is the global TODO list, a prefix argument will be interpreted."
22684 (interactive)
22685 (let* ((org-agenda-keep-modes t)
22686 (line (org-current-line))
22687 (window-line (- line (org-current-line (window-start))))
22688 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22689 (message "Rebuilding agenda buffer...")
22690 (org-let lprops '(eval org-agenda-redo-command))
22691 (setq org-agenda-undo-list nil
22692 org-agenda-pending-undo-list nil)
22693 (message "Rebuilding agenda buffer...done")
22694 (goto-line line)
22695 (recenter window-line)))
22696
22697 (defun org-agenda-manipulate-query-add ()
22698 "Manipulate the query by adding a search term with positive selection.
22699 Positive selection means, the term must be matched for selection of an entry."
22700 (interactive)
22701 (org-agenda-manipulate-query ?\[))
22702 (defun org-agenda-manipulate-query-subtract ()
22703 "Manipulate the query by adding a search term with negative selection.
22704 Negative selection means, term must not be matched for selection of an entry."
22705 (interactive)
22706 (org-agenda-manipulate-query ?\]))
22707 (defun org-agenda-manipulate-query-add-re ()
22708 "Manipulate the query by adding a search regexp with positive selection.
22709 Positive selection means, the regexp must match for selection of an entry."
22710 (interactive)
22711 (org-agenda-manipulate-query ?\{))
22712 (defun org-agenda-manipulate-query-subtract-re ()
22713 "Manipulate the query by adding a search regexp with negative selection.
22714 Negative selection means, regexp must not match for selection of an entry."
22715 (interactive)
22716 (org-agenda-manipulate-query ?\}))
22717 (defun org-agenda-manipulate-query (char)
22718 (cond
22719 ((eq org-agenda-type 'search)
22720 (org-add-to-string
22721 'org-agenda-query-string
22722 (cdr (assoc char '((?\[ . " +") (?\] . " -")
22723 (?\{ . " +{}") (?\} . " -{}")))))
22724 (setq org-agenda-redo-command
22725 (list 'org-search-view
22726 (+ (length org-agenda-query-string)
22727 (if (member char '(?\{ ?\})) 0 1))
22728 org-agenda-query-string))
22729 (set-register org-agenda-query-register org-agenda-query-string)
22730 (org-agenda-redo))
22731 (t (error "Canot manipulate query for %s-type agenda buffers"
22732 org-agenda-type))))
22733
22734 (defun org-add-to-string (var string)
22735 (set var (concat (symbol-value var) string)))
22736
22737 (defun org-agenda-goto-date (date)
22738 "Jump to DATE in agenda."
22739 (interactive (list (org-read-date)))
22740 (org-agenda-list nil date))
22741
22742 (defun org-agenda-goto-today ()
22743 "Go to today."
22744 (interactive)
22745 (org-agenda-check-type t 'timeline 'agenda)
22746 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22747 (cond
22748 (tdpos (goto-char tdpos))
22749 ((eq org-agenda-type 'agenda)
22750 (let* ((sd (time-to-days
22751 (time-subtract (current-time)
22752 (list 0 (* 3600 org-extend-today-until) 0))))
22753 (comp (org-agenda-compute-time-span sd org-agenda-span))
22754 (org-agenda-overriding-arguments org-agenda-last-arguments))
22755 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22756 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22757 (org-agenda-redo)
22758 (org-agenda-find-same-or-today-or-agenda)))
22759 (t (error "Cannot find today")))))
22760
22761 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22762 (goto-char
22763 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22764 (text-property-any (point-min) (point-max) 'org-today t)
22765 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22766 (point-min))))
22767
22768 (defun org-agenda-later (arg)
22769 "Go forward in time by thee current span.
22770 With prefix ARG, go forward that many times the current span."
22771 (interactive "p")
22772 (org-agenda-check-type t 'agenda)
22773 (let* ((span org-agenda-span)
22774 (sd org-starting-day)
22775 (greg (calendar-gregorian-from-absolute sd))
22776 (cnt (get-text-property (point) 'org-day-cnt))
22777 greg2 nd)
22778 (cond
22779 ((eq span 'day)
22780 (setq sd (+ arg sd) nd 1))
22781 ((eq span 'week)
22782 (setq sd (+ (* 7 arg) sd) nd 7))
22783 ((eq span 'month)
22784 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22785 sd (calendar-absolute-from-gregorian greg2))
22786 (setcar greg2 (1+ (car greg2)))
22787 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22788 ((eq span 'year)
22789 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22790 sd (calendar-absolute-from-gregorian greg2))
22791 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22792 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22793 (let ((org-agenda-overriding-arguments
22794 (list (car org-agenda-last-arguments) sd nd t)))
22795 (org-agenda-redo)
22796 (org-agenda-find-same-or-today-or-agenda cnt))))
22797
22798 (defun org-agenda-earlier (arg)
22799 "Go backward in time by the current span.
22800 With prefix ARG, go backward that many times the current span."
22801 (interactive "p")
22802 (org-agenda-later (- arg)))
22803
22804 (defun org-agenda-day-view ()
22805 "Switch to daily view for agenda."
22806 (interactive)
22807 (setq org-agenda-ndays 1)
22808 (org-agenda-change-time-span 'day))
22809 (defun org-agenda-week-view ()
22810 "Switch to daily view for agenda."
22811 (interactive)
22812 (setq org-agenda-ndays 7)
22813 (org-agenda-change-time-span 'week))
22814 (defun org-agenda-month-view ()
22815 "Switch to daily view for agenda."
22816 (interactive)
22817 (org-agenda-change-time-span 'month))
22818 (defun org-agenda-year-view ()
22819 "Switch to daily view for agenda."
22820 (interactive)
22821 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22822 (org-agenda-change-time-span 'year)
22823 (error "Abort")))
22824
22825 (defun org-agenda-change-time-span (span)
22826 "Change the agenda view to SPAN.
22827 SPAN may be `day', `week', `month', `year'."
22828 (org-agenda-check-type t 'agenda)
22829 (if (equal org-agenda-span span)
22830 (error "Viewing span is already \"%s\"" span))
22831 (let* ((sd (or (get-text-property (point) 'day)
22832 org-starting-day))
22833 (computed (org-agenda-compute-time-span sd span))
22834 (org-agenda-overriding-arguments
22835 (list (car org-agenda-last-arguments)
22836 (car computed) (cdr computed) t)))
22837 (org-agenda-redo)
22838 (org-agenda-find-same-or-today-or-agenda))
22839 (org-agenda-set-mode-name)
22840 (message "Switched to %s view" span))
22841
22842 (defun org-agenda-compute-time-span (sd span)
22843 "Compute starting date and number of days for agenda.
22844 SPAN may be `day', `week', `month', `year'. The return value
22845 is a cons cell with the starting date and the number of days,
22846 so that the date SD will be in that range."
22847 (let* ((greg (calendar-gregorian-from-absolute sd))
22848 nd)
22849 (cond
22850 ((eq span 'day)
22851 (setq nd 1))
22852 ((eq span 'week)
22853 (let* ((nt (calendar-day-of-week
22854 (calendar-gregorian-from-absolute sd)))
22855 (d (if org-agenda-start-on-weekday
22856 (- nt org-agenda-start-on-weekday)
22857 0)))
22858 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22859 (setq nd 7)))
22860 ((eq span 'month)
22861 (setq sd (calendar-absolute-from-gregorian
22862 (list (car greg) 1 (nth 2 greg)))
22863 nd (- (calendar-absolute-from-gregorian
22864 (list (1+ (car greg)) 1 (nth 2 greg)))
22865 sd)))
22866 ((eq span 'year)
22867 (setq sd (calendar-absolute-from-gregorian
22868 (list 1 1 (nth 2 greg)))
22869 nd (- (calendar-absolute-from-gregorian
22870 (list 1 1 (1+ (nth 2 greg))))
22871 sd))))
22872 (cons sd nd)))
22873
22874 ;; FIXME: does not work if user makes date format that starts with a blank
22875 (defun org-agenda-next-date-line (&optional arg)
22876 "Jump to the next line indicating a date in agenda buffer."
22877 (interactive "p")
22878 (org-agenda-check-type t 'agenda 'timeline)
22879 (beginning-of-line 1)
22880 (if (looking-at "^\\S-") (forward-char 1))
22881 (if (not (re-search-forward "^\\S-" nil t arg))
22882 (progn
22883 (backward-char 1)
22884 (error "No next date after this line in this buffer")))
22885 (goto-char (match-beginning 0)))
22886
22887 (defun org-agenda-previous-date-line (&optional arg)
22888 "Jump to the previous line indicating a date in agenda buffer."
22889 (interactive "p")
22890 (org-agenda-check-type t 'agenda 'timeline)
22891 (beginning-of-line 1)
22892 (if (not (re-search-backward "^\\S-" nil t arg))
22893 (error "No previous date before this line in this buffer")))
22894
22895 ;; Initialize the highlight
22896 (defvar org-hl (org-make-overlay 1 1))
22897 (org-overlay-put org-hl 'face 'highlight)
22898
22899 (defun org-highlight (begin end &optional buffer)
22900 "Highlight a region with overlay."
22901 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22902 org-hl begin end (or buffer (current-buffer))))
22903
22904 (defun org-unhighlight ()
22905 "Detach overlay INDEX."
22906 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22907
22908 ;; FIXME this is currently not used.
22909 (defun org-highlight-until-next-command (beg end &optional buffer)
22910 (org-highlight beg end buffer)
22911 (add-hook 'pre-command-hook 'org-unhighlight-once))
22912 (defun org-unhighlight-once ()
22913 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22914 (org-unhighlight))
22915
22916 (defun org-agenda-follow-mode ()
22917 "Toggle follow mode in an agenda buffer."
22918 (interactive)
22919 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22920 (org-agenda-set-mode-name)
22921 (message "Follow mode is %s"
22922 (if org-agenda-follow-mode "on" "off")))
22923
22924 (defun org-agenda-log-mode ()
22925 "Toggle log mode in an agenda buffer."
22926 (interactive)
22927 (org-agenda-check-type t 'agenda 'timeline)
22928 (setq org-agenda-show-log (not org-agenda-show-log))
22929 (org-agenda-set-mode-name)
22930 (org-agenda-redo)
22931 (message "Log mode is %s"
22932 (if org-agenda-show-log "on" "off")))
22933
22934 (defun org-agenda-toggle-diary ()
22935 "Toggle diary inclusion in an agenda buffer."
22936 (interactive)
22937 (org-agenda-check-type t 'agenda)
22938 (setq org-agenda-include-diary (not org-agenda-include-diary))
22939 (org-agenda-redo)
22940 (org-agenda-set-mode-name)
22941 (message "Diary inclusion turned %s"
22942 (if org-agenda-include-diary "on" "off")))
22943
22944 (defun org-agenda-toggle-time-grid ()
22945 "Toggle time grid in an agenda buffer."
22946 (interactive)
22947 (org-agenda-check-type t 'agenda)
22948 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22949 (org-agenda-redo)
22950 (org-agenda-set-mode-name)
22951 (message "Time-grid turned %s"
22952 (if org-agenda-use-time-grid "on" "off")))
22953
22954 (defun org-agenda-set-mode-name ()
22955 "Set the mode name to indicate all the small mode settings."
22956 (setq mode-name
22957 (concat "Org-Agenda"
22958 (if (equal org-agenda-ndays 1) " Day" "")
22959 (if (equal org-agenda-ndays 7) " Week" "")
22960 (if org-agenda-follow-mode " Follow" "")
22961 (if org-agenda-include-diary " Diary" "")
22962 (if org-agenda-use-time-grid " Grid" "")
22963 (if org-agenda-show-log " Log" "")))
22964 (force-mode-line-update))
22965
22966 (defun org-agenda-post-command-hook ()
22967 (and (eolp) (not (bolp)) (backward-char 1))
22968 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22969 (if (and org-agenda-follow-mode
22970 (get-text-property (point) 'org-marker))
22971 (org-agenda-show)))
22972
22973 (defun org-agenda-show-priority ()
22974 "Show the priority of the current item.
22975 This priority is composed of the main priority given with the [#A] cookies,
22976 and by additional input from the age of a schedules or deadline entry."
22977 (interactive)
22978 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22979 (message "Priority is %d" (if pri pri -1000))))
22980
22981 (defun org-agenda-show-tags ()
22982 "Show the tags applicable to the current item."
22983 (interactive)
22984 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22985 (if tags
22986 (message "Tags are :%s:"
22987 (org-no-properties (mapconcat 'identity tags ":")))
22988 (message "No tags associated with this line"))))
22989
22990 (defun org-agenda-goto (&optional highlight)
22991 "Go to the Org-mode file which contains the item at point."
22992 (interactive)
22993 (let* ((marker (or (get-text-property (point) 'org-marker)
22994 (org-agenda-error)))
22995 (buffer (marker-buffer marker))
22996 (pos (marker-position marker)))
22997 (switch-to-buffer-other-window buffer)
22998 (widen)
22999 (goto-char pos)
23000 (when (org-mode-p)
23001 (org-show-context 'agenda)
23002 (save-excursion
23003 (and (outline-next-heading)
23004 (org-flag-heading nil)))) ; show the next heading
23005 (recenter (/ (window-height) 2))
23006 (run-hooks 'org-agenda-after-show-hook)
23007 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
23008
23009 (defvar org-agenda-after-show-hook nil
23010 "Normal hook run after an item has been shown from the agenda.
23011 Point is in the buffer where the item originated.")
23012
23013 (defun org-agenda-kill ()
23014 "Kill the entry or subtree belonging to the current agenda entry."
23015 (interactive)
23016 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
23017 (let* ((marker (or (get-text-property (point) 'org-marker)
23018 (org-agenda-error)))
23019 (buffer (marker-buffer marker))
23020 (pos (marker-position marker))
23021 (type (get-text-property (point) 'type))
23022 dbeg dend (n 0) conf)
23023 (org-with-remote-undo buffer
23024 (with-current-buffer buffer
23025 (save-excursion
23026 (goto-char pos)
23027 (if (and (org-mode-p) (not (member type '("sexp"))))
23028 (setq dbeg (progn (org-back-to-heading t) (point))
23029 dend (org-end-of-subtree t t))
23030 (setq dbeg (point-at-bol)
23031 dend (min (point-max) (1+ (point-at-eol)))))
23032 (goto-char dbeg)
23033 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
23034 (setq conf (or (eq t org-agenda-confirm-kill)
23035 (and (numberp org-agenda-confirm-kill)
23036 (> n org-agenda-confirm-kill))))
23037 (and conf
23038 (not (y-or-n-p
23039 (format "Delete entry with %d lines in buffer \"%s\"? "
23040 n (buffer-name buffer))))
23041 (error "Abort"))
23042 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
23043 (with-current-buffer buffer (delete-region dbeg dend))
23044 (message "Agenda item and source killed"))))
23045
23046 (defun org-agenda-archive ()
23047 "Kill the entry or subtree belonging to the current agenda entry."
23048 (interactive)
23049 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
23050 (let* ((marker (or (get-text-property (point) 'org-marker)
23051 (org-agenda-error)))
23052 (buffer (marker-buffer marker))
23053 (pos (marker-position marker)))
23054 (org-with-remote-undo buffer
23055 (with-current-buffer buffer
23056 (if (org-mode-p)
23057 (save-excursion
23058 (goto-char pos)
23059 (org-remove-subtree-entries-from-agenda)
23060 (org-back-to-heading t)
23061 (org-archive-subtree))
23062 (error "Archiving works only in Org-mode files"))))))
23063
23064 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
23065 "Remove all lines in the agenda that correspond to a given subtree.
23066 The subtree is the one in buffer BUF, starting at BEG and ending at END.
23067 If this information is not given, the function uses the tree at point."
23068 (let ((buf (or buf (current-buffer))) m p)
23069 (save-excursion
23070 (unless (and beg end)
23071 (org-back-to-heading t)
23072 (setq beg (point))
23073 (org-end-of-subtree t)
23074 (setq end (point)))
23075 (set-buffer (get-buffer org-agenda-buffer-name))
23076 (save-excursion
23077 (goto-char (point-max))
23078 (beginning-of-line 1)
23079 (while (not (bobp))
23080 (when (and (setq m (get-text-property (point) 'org-marker))
23081 (equal buf (marker-buffer m))
23082 (setq p (marker-position m))
23083 (>= p beg)
23084 (<= p end))
23085 (let ((inhibit-read-only t))
23086 (delete-region (point-at-bol) (1+ (point-at-eol)))))
23087 (beginning-of-line 0))))))
23088
23089 (defun org-agenda-open-link ()
23090 "Follow the link in the current line, if any."
23091 (interactive)
23092 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
23093 (save-excursion
23094 (save-restriction
23095 (narrow-to-region (point-at-bol) (point-at-eol))
23096 (org-open-at-point))))
23097
23098 (defun org-agenda-copy-local-variable (var)
23099 "Get a variable from a referenced buffer and install it here."
23100 (let ((m (get-text-property (point) 'org-marker)))
23101 (when (and m (buffer-live-p (marker-buffer m)))
23102 (org-set-local var (with-current-buffer (marker-buffer m)
23103 (symbol-value var))))))
23104
23105 (defun org-agenda-switch-to (&optional delete-other-windows)
23106 "Go to the Org-mode file which contains the item at point."
23107 (interactive)
23108 (let* ((marker (or (get-text-property (point) 'org-marker)
23109 (org-agenda-error)))
23110 (buffer (marker-buffer marker))
23111 (pos (marker-position marker)))
23112 (switch-to-buffer buffer)
23113 (and delete-other-windows (delete-other-windows))
23114 (widen)
23115 (goto-char pos)
23116 (when (org-mode-p)
23117 (org-show-context 'agenda)
23118 (save-excursion
23119 (and (outline-next-heading)
23120 (org-flag-heading nil)))))) ; show the next heading
23121
23122 (defun org-agenda-goto-mouse (ev)
23123 "Go to the Org-mode file which contains the item at the mouse click."
23124 (interactive "e")
23125 (mouse-set-point ev)
23126 (org-agenda-goto))
23127
23128 (defun org-agenda-show ()
23129 "Display the Org-mode file which contains the item at point."
23130 (interactive)
23131 (let ((win (selected-window)))
23132 (org-agenda-goto t)
23133 (select-window win)))
23134
23135 (defun org-agenda-recenter (arg)
23136 "Display the Org-mode file which contains the item at point and recenter."
23137 (interactive "P")
23138 (let ((win (selected-window)))
23139 (org-agenda-goto t)
23140 (recenter arg)
23141 (select-window win)))
23142
23143 (defun org-agenda-show-mouse (ev)
23144 "Display the Org-mode file which contains the item at the mouse click."
23145 (interactive "e")
23146 (mouse-set-point ev)
23147 (org-agenda-show))
23148
23149 (defun org-agenda-check-no-diary ()
23150 "Check if the entry is a diary link and abort if yes."
23151 (if (get-text-property (point) 'org-agenda-diary-link)
23152 (org-agenda-error)))
23153
23154 (defun org-agenda-error ()
23155 (error "Command not allowed in this line"))
23156
23157 (defun org-agenda-tree-to-indirect-buffer ()
23158 "Show the subtree corresponding to the current entry in an indirect buffer.
23159 This calls the command `org-tree-to-indirect-buffer' from the original
23160 Org-mode buffer.
23161 With numerical prefix arg ARG, go up to this level and then take that tree.
23162 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
23163 dedicated frame)."
23164 (interactive)
23165 (org-agenda-check-no-diary)
23166 (let* ((marker (or (get-text-property (point) 'org-marker)
23167 (org-agenda-error)))
23168 (buffer (marker-buffer marker))
23169 (pos (marker-position marker)))
23170 (with-current-buffer buffer
23171 (save-excursion
23172 (goto-char pos)
23173 (call-interactively 'org-tree-to-indirect-buffer)))))
23174
23175 (defvar org-last-heading-marker (make-marker)
23176 "Marker pointing to the headline that last changed its TODO state
23177 by a remote command from the agenda.")
23178
23179 (defun org-agenda-todo-nextset ()
23180 "Switch TODO entry to next sequence."
23181 (interactive)
23182 (org-agenda-todo 'nextset))
23183
23184 (defun org-agenda-todo-previousset ()
23185 "Switch TODO entry to previous sequence."
23186 (interactive)
23187 (org-agenda-todo 'previousset))
23188
23189 (defun org-agenda-todo (&optional arg)
23190 "Cycle TODO state of line at point, also in Org-mode file.
23191 This changes the line at point, all other lines in the agenda referring to
23192 the same tree node, and the headline of the tree node in the Org-mode file."
23193 (interactive "P")
23194 (org-agenda-check-no-diary)
23195 (let* ((col (current-column))
23196 (marker (or (get-text-property (point) 'org-marker)
23197 (org-agenda-error)))
23198 (buffer (marker-buffer marker))
23199 (pos (marker-position marker))
23200 (hdmarker (get-text-property (point) 'org-hd-marker))
23201 (inhibit-read-only t)
23202 newhead)
23203 (org-with-remote-undo buffer
23204 (with-current-buffer buffer
23205 (widen)
23206 (goto-char pos)
23207 (org-show-context 'agenda)
23208 (save-excursion
23209 (and (outline-next-heading)
23210 (org-flag-heading nil))) ; show the next heading
23211 (org-todo arg)
23212 (and (bolp) (forward-char 1))
23213 (setq newhead (org-get-heading))
23214 (save-excursion
23215 (org-back-to-heading)
23216 (move-marker org-last-heading-marker (point))))
23217 (beginning-of-line 1)
23218 (save-excursion
23219 (org-agenda-change-all-lines newhead hdmarker 'fixface))
23220 (move-to-column col))))
23221
23222 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
23223 "Change all lines in the agenda buffer which match HDMARKER.
23224 The new content of the line will be NEWHEAD (as modified by
23225 `org-format-agenda-item'). HDMARKER is checked with
23226 `equal' against all `org-hd-marker' text properties in the file.
23227 If FIXFACE is non-nil, the face of each item is modified acording to
23228 the new TODO state."
23229 (let* ((inhibit-read-only t)
23230 props m pl undone-face done-face finish new dotime cat tags)
23231 (save-excursion
23232 (goto-char (point-max))
23233 (beginning-of-line 1)
23234 (while (not finish)
23235 (setq finish (bobp))
23236 (when (and (setq m (get-text-property (point) 'org-hd-marker))
23237 (equal m hdmarker))
23238 (setq props (text-properties-at (point))
23239 dotime (get-text-property (point) 'dotime)
23240 cat (get-text-property (point) 'org-category)
23241 tags (get-text-property (point) 'tags)
23242 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
23243 pl (get-text-property (point) 'prefix-length)
23244 undone-face (get-text-property (point) 'undone-face)
23245 done-face (get-text-property (point) 'done-face))
23246 (move-to-column pl)
23247 (cond
23248 ((equal new "")
23249 (beginning-of-line 1)
23250 (and (looking-at ".*\n?") (replace-match "")))
23251 ((looking-at ".*")
23252 (replace-match new t t)
23253 (beginning-of-line 1)
23254 (add-text-properties (point-at-bol) (point-at-eol) props)
23255 (when fixface
23256 (add-text-properties
23257 (point-at-bol) (point-at-eol)
23258 (list 'face
23259 (if org-last-todo-state-is-todo
23260 undone-face done-face))))
23261 (org-agenda-highlight-todo 'line)
23262 (beginning-of-line 1))
23263 (t (error "Line update did not work"))))
23264 (beginning-of-line 0)))
23265 (org-finalize-agenda)))
23266
23267 (defun org-agenda-align-tags (&optional line)
23268 "Align all tags in agenda items to `org-agenda-tags-column'."
23269 (let ((inhibit-read-only t) l c)
23270 (save-excursion
23271 (goto-char (if line (point-at-bol) (point-min)))
23272 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
23273 (if line (point-at-eol) nil) t)
23274 (add-text-properties
23275 (match-beginning 2) (match-end 2)
23276 (list 'face (delq nil (list 'org-tag (get-text-property
23277 (match-beginning 2) 'face)))))
23278 (setq l (- (match-end 2) (match-beginning 2))
23279 c (if (< org-agenda-tags-column 0)
23280 (- (abs org-agenda-tags-column) l)
23281 org-agenda-tags-column))
23282 (delete-region (match-beginning 1) (match-end 1))
23283 (goto-char (match-beginning 1))
23284 (insert (org-add-props
23285 (make-string (max 1 (- c (current-column))) ?\ )
23286 (text-properties-at (point))))))))
23287
23288 (defun org-agenda-priority-up ()
23289 "Increase the priority of line at point, also in Org-mode file."
23290 (interactive)
23291 (org-agenda-priority 'up))
23292
23293 (defun org-agenda-priority-down ()
23294 "Decrease the priority of line at point, also in Org-mode file."
23295 (interactive)
23296 (org-agenda-priority 'down))
23297
23298 (defun org-agenda-priority (&optional force-direction)
23299 "Set the priority of line at point, also in Org-mode file.
23300 This changes the line at point, all other lines in the agenda referring to
23301 the same tree node, and the headline of the tree node in the Org-mode file."
23302 (interactive)
23303 (org-agenda-check-no-diary)
23304 (let* ((marker (or (get-text-property (point) 'org-marker)
23305 (org-agenda-error)))
23306 (hdmarker (get-text-property (point) 'org-hd-marker))
23307 (buffer (marker-buffer hdmarker))
23308 (pos (marker-position hdmarker))
23309 (inhibit-read-only t)
23310 newhead)
23311 (org-with-remote-undo buffer
23312 (with-current-buffer buffer
23313 (widen)
23314 (goto-char pos)
23315 (org-show-context 'agenda)
23316 (save-excursion
23317 (and (outline-next-heading)
23318 (org-flag-heading nil))) ; show the next heading
23319 (funcall 'org-priority force-direction)
23320 (end-of-line 1)
23321 (setq newhead (org-get-heading)))
23322 (org-agenda-change-all-lines newhead hdmarker)
23323 (beginning-of-line 1))))
23324
23325 (defun org-get-tags-at (&optional pos)
23326 "Get a list of all headline tags applicable at POS.
23327 POS defaults to point. If tags are inherited, the list contains
23328 the targets in the same sequence as the headlines appear, i.e.
23329 the tags of the current headline come last."
23330 (interactive)
23331 (let (tags lastpos)
23332 (save-excursion
23333 (save-restriction
23334 (widen)
23335 (goto-char (or pos (point)))
23336 (save-match-data
23337 (condition-case nil
23338 (progn
23339 (org-back-to-heading t)
23340 (while (not (equal lastpos (point)))
23341 (setq lastpos (point))
23342 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
23343 (setq tags (append (org-split-string
23344 (org-match-string-no-properties 1) ":")
23345 tags)))
23346 (or org-use-tag-inheritance (error ""))
23347 (org-up-heading-all 1)))
23348 (error nil))))
23349 tags)))
23350
23351 ;; FIXME: should fix the tags property of the agenda line.
23352 (defun org-agenda-set-tags ()
23353 "Set tags for the current headline."
23354 (interactive)
23355 (org-agenda-check-no-diary)
23356 (if (and (org-region-active-p) (interactive-p))
23357 (call-interactively 'org-change-tag-in-region)
23358 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23359 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23360 (org-agenda-error)))
23361 (buffer (marker-buffer hdmarker))
23362 (pos (marker-position hdmarker))
23363 (inhibit-read-only t)
23364 newhead)
23365 (org-with-remote-undo buffer
23366 (with-current-buffer buffer
23367 (widen)
23368 (goto-char pos)
23369 (save-excursion
23370 (org-show-context 'agenda))
23371 (save-excursion
23372 (and (outline-next-heading)
23373 (org-flag-heading nil))) ; show the next heading
23374 (goto-char pos)
23375 (call-interactively 'org-set-tags)
23376 (end-of-line 1)
23377 (setq newhead (org-get-heading)))
23378 (org-agenda-change-all-lines newhead hdmarker)
23379 (beginning-of-line 1)))))
23380
23381 (defun org-agenda-toggle-archive-tag ()
23382 "Toggle the archive tag for the current entry."
23383 (interactive)
23384 (org-agenda-check-no-diary)
23385 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23386 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23387 (org-agenda-error)))
23388 (buffer (marker-buffer hdmarker))
23389 (pos (marker-position hdmarker))
23390 (inhibit-read-only t)
23391 newhead)
23392 (org-with-remote-undo buffer
23393 (with-current-buffer buffer
23394 (widen)
23395 (goto-char pos)
23396 (org-show-context 'agenda)
23397 (save-excursion
23398 (and (outline-next-heading)
23399 (org-flag-heading nil))) ; show the next heading
23400 (call-interactively 'org-toggle-archive-tag)
23401 (end-of-line 1)
23402 (setq newhead (org-get-heading)))
23403 (org-agenda-change-all-lines newhead hdmarker)
23404 (beginning-of-line 1))))
23405
23406 (defun org-agenda-date-later (arg &optional what)
23407 "Change the date of this item to one day later."
23408 (interactive "p")
23409 (org-agenda-check-type t 'agenda 'timeline)
23410 (org-agenda-check-no-diary)
23411 (let* ((marker (or (get-text-property (point) 'org-marker)
23412 (org-agenda-error)))
23413 (buffer (marker-buffer marker))
23414 (pos (marker-position marker)))
23415 (org-with-remote-undo buffer
23416 (with-current-buffer buffer
23417 (widen)
23418 (goto-char pos)
23419 (if (not (org-at-timestamp-p))
23420 (error "Cannot find time stamp"))
23421 (org-timestamp-change arg (or what 'day)))
23422 (org-agenda-show-new-time marker org-last-changed-timestamp))
23423 (message "Time stamp changed to %s" org-last-changed-timestamp)))
23424
23425 (defun org-agenda-date-earlier (arg &optional what)
23426 "Change the date of this item to one day earlier."
23427 (interactive "p")
23428 (org-agenda-date-later (- arg) what))
23429
23430 (defun org-agenda-show-new-time (marker stamp &optional prefix)
23431 "Show new date stamp via text properties."
23432 ;; We use text properties to make this undoable
23433 (let ((inhibit-read-only t))
23434 (setq stamp (concat " " prefix " => " stamp))
23435 (save-excursion
23436 (goto-char (point-max))
23437 (while (not (bobp))
23438 (when (equal marker (get-text-property (point) 'org-marker))
23439 (move-to-column (- (window-width) (length stamp)) t)
23440 (if (featurep 'xemacs)
23441 ;; Use `duplicable' property to trigger undo recording
23442 (let ((ex (make-extent nil nil))
23443 (gl (make-glyph stamp)))
23444 (set-glyph-face gl 'secondary-selection)
23445 (set-extent-properties
23446 ex (list 'invisible t 'end-glyph gl 'duplicable t))
23447 (insert-extent ex (1- (point)) (point-at-eol)))
23448 (add-text-properties
23449 (1- (point)) (point-at-eol)
23450 (list 'display (org-add-props stamp nil
23451 'face 'secondary-selection))))
23452 (beginning-of-line 1))
23453 (beginning-of-line 0)))))
23454
23455 (defun org-agenda-date-prompt (arg)
23456 "Change the date of this item. Date is prompted for, with default today.
23457 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23458 be used to request time specification in the time stamp."
23459 (interactive "P")
23460 (org-agenda-check-type t 'agenda 'timeline)
23461 (org-agenda-check-no-diary)
23462 (let* ((marker (or (get-text-property (point) 'org-marker)
23463 (org-agenda-error)))
23464 (buffer (marker-buffer marker))
23465 (pos (marker-position marker)))
23466 (org-with-remote-undo buffer
23467 (with-current-buffer buffer
23468 (widen)
23469 (goto-char pos)
23470 (if (not (org-at-timestamp-p))
23471 (error "Cannot find time stamp"))
23472 (org-time-stamp arg)
23473 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23474
23475 (defun org-agenda-schedule (arg)
23476 "Schedule the item at point."
23477 (interactive "P")
23478 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23479 (org-agenda-check-no-diary)
23480 (let* ((marker (or (get-text-property (point) 'org-marker)
23481 (org-agenda-error)))
23482 (type (marker-insertion-type marker))
23483 (buffer (marker-buffer marker))
23484 (pos (marker-position marker))
23485 (org-insert-labeled-timestamps-at-point nil)
23486 ts)
23487 (when type (message "%s" type) (sit-for 3))
23488 (set-marker-insertion-type marker t)
23489 (org-with-remote-undo buffer
23490 (with-current-buffer buffer
23491 (widen)
23492 (goto-char pos)
23493 (setq ts (org-schedule arg)))
23494 (org-agenda-show-new-time marker ts "S"))
23495 (message "Item scheduled for %s" ts)))
23496
23497 (defun org-agenda-deadline (arg)
23498 "Schedule the item at point."
23499 (interactive "P")
23500 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23501 (org-agenda-check-no-diary)
23502 (let* ((marker (or (get-text-property (point) 'org-marker)
23503 (org-agenda-error)))
23504 (buffer (marker-buffer marker))
23505 (pos (marker-position marker))
23506 (org-insert-labeled-timestamps-at-point nil)
23507 ts)
23508 (org-with-remote-undo buffer
23509 (with-current-buffer buffer
23510 (widen)
23511 (goto-char pos)
23512 (setq ts (org-deadline arg)))
23513 (org-agenda-show-new-time marker ts "S"))
23514 (message "Deadline for this item set to %s" ts)))
23515
23516 (defun org-get-heading (&optional no-tags)
23517 "Return the heading of the current entry, without the stars."
23518 (save-excursion
23519 (org-back-to-heading t)
23520 (if (looking-at
23521 (if no-tags
23522 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23523 "\\*+[ \t]+\\([^\r\n]*\\)"))
23524 (match-string 1) "")))
23525
23526 (defun org-agenda-clock-in (&optional arg)
23527 "Start the clock on the currently selected item."
23528 (interactive "P")
23529 (org-agenda-check-no-diary)
23530 (let* ((marker (or (get-text-property (point) 'org-marker)
23531 (org-agenda-error)))
23532 (pos (marker-position marker)))
23533 (org-with-remote-undo (marker-buffer marker)
23534 (with-current-buffer (marker-buffer marker)
23535 (widen)
23536 (goto-char pos)
23537 (org-clock-in)))))
23538
23539 (defun org-agenda-clock-out (&optional arg)
23540 "Stop the currently running clock."
23541 (interactive "P")
23542 (unless (marker-buffer org-clock-marker)
23543 (error "No running clock"))
23544 (org-with-remote-undo (marker-buffer org-clock-marker)
23545 (org-clock-out)))
23546
23547 (defun org-agenda-clock-cancel (&optional arg)
23548 "Cancel the currently running clock."
23549 (interactive "P")
23550 (unless (marker-buffer org-clock-marker)
23551 (error "No running clock"))
23552 (org-with-remote-undo (marker-buffer org-clock-marker)
23553 (org-clock-cancel)))
23554
23555 (defun org-agenda-diary-entry ()
23556 "Make a diary entry, like the `i' command from the calendar.
23557 All the standard commands work: block, weekly etc."
23558 (interactive)
23559 (org-agenda-check-type t 'agenda 'timeline)
23560 (require 'diary-lib)
23561 (let* ((char (progn
23562 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23563 (read-char-exclusive)))
23564 (cmd (cdr (assoc char
23565 '((?d . insert-diary-entry)
23566 (?w . insert-weekly-diary-entry)
23567 (?m . insert-monthly-diary-entry)
23568 (?y . insert-yearly-diary-entry)
23569 (?a . insert-anniversary-diary-entry)
23570 (?b . insert-block-diary-entry)
23571 (?c . insert-cyclic-diary-entry)))))
23572 (oldf (symbol-function 'calendar-cursor-to-date))
23573 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23574 (point (point))
23575 (mark (or (mark t) (point))))
23576 (unless cmd
23577 (error "No command associated with <%c>" char))
23578 (unless (and (get-text-property point 'day)
23579 (or (not (equal ?b char))
23580 (get-text-property mark 'day)))
23581 (error "Don't know which date to use for diary entry"))
23582 ;; We implement this by hacking the `calendar-cursor-to-date' function
23583 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23584 (let ((calendar-mark-ring
23585 (list (calendar-gregorian-from-absolute
23586 (or (get-text-property mark 'day)
23587 (get-text-property point 'day))))))
23588 (unwind-protect
23589 (progn
23590 (fset 'calendar-cursor-to-date
23591 (lambda (&optional error)
23592 (calendar-gregorian-from-absolute
23593 (get-text-property point 'day))))
23594 (call-interactively cmd))
23595 (fset 'calendar-cursor-to-date oldf)))))
23596
23597
23598 (defun org-agenda-execute-calendar-command (cmd)
23599 "Execute a calendar command from the agenda, with the date associated to
23600 the cursor position."
23601 (org-agenda-check-type t 'agenda 'timeline)
23602 (require 'diary-lib)
23603 (unless (get-text-property (point) 'day)
23604 (error "Don't know which date to use for calendar command"))
23605 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23606 (point (point))
23607 (date (calendar-gregorian-from-absolute
23608 (get-text-property point 'day)))
23609 ;; the following 2 vars are needed in the calendar
23610 (displayed-month (car date))
23611 (displayed-year (nth 2 date)))
23612 (unwind-protect
23613 (progn
23614 (fset 'calendar-cursor-to-date
23615 (lambda (&optional error)
23616 (calendar-gregorian-from-absolute
23617 (get-text-property point 'day))))
23618 (call-interactively cmd))
23619 (fset 'calendar-cursor-to-date oldf))))
23620
23621 (defun org-agenda-phases-of-moon ()
23622 "Display the phases of the moon for the 3 months around the cursor date."
23623 (interactive)
23624 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23625
23626 (defun org-agenda-holidays ()
23627 "Display the holidays for the 3 months around the cursor date."
23628 (interactive)
23629 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23630
23631 (defvar calendar-longitude)
23632 (defvar calendar-latitude)
23633 (defvar calendar-location-name)
23634
23635 (defun org-agenda-sunrise-sunset (arg)
23636 "Display sunrise and sunset for the cursor date.
23637 Latitude and longitude can be specified with the variables
23638 `calendar-latitude' and `calendar-longitude'. When called with prefix
23639 argument, latitude and longitude will be prompted for."
23640 (interactive "P")
23641 (require 'solar)
23642 (let ((calendar-longitude (if arg nil calendar-longitude))
23643 (calendar-latitude (if arg nil calendar-latitude))
23644 (calendar-location-name
23645 (if arg "the given coordinates" calendar-location-name)))
23646 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23647
23648 (defun org-agenda-goto-calendar ()
23649 "Open the Emacs calendar with the date at the cursor."
23650 (interactive)
23651 (org-agenda-check-type t 'agenda 'timeline)
23652 (let* ((day (or (get-text-property (point) 'day)
23653 (error "Don't know which date to open in calendar")))
23654 (date (calendar-gregorian-from-absolute day))
23655 (calendar-move-hook nil)
23656 (calendar-view-holidays-initially-flag nil)
23657 (view-calendar-holidays-initially nil)
23658 (calendar-view-diary-initially-flag nil)
23659 (view-diary-entries-initially nil))
23660 (calendar)
23661 (calendar-goto-date date)))
23662
23663 (defun org-calendar-goto-agenda ()
23664 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23665 This is a command that has to be installed in `calendar-mode-map'."
23666 (interactive)
23667 (org-agenda-list nil (calendar-absolute-from-gregorian
23668 (calendar-cursor-to-date))
23669 nil))
23670
23671 (defun org-agenda-convert-date ()
23672 (interactive)
23673 (org-agenda-check-type t 'agenda 'timeline)
23674 (let ((day (get-text-property (point) 'day))
23675 date s)
23676 (unless day
23677 (error "Don't know which date to convert"))
23678 (setq date (calendar-gregorian-from-absolute day))
23679 (setq s (concat
23680 "Gregorian: " (calendar-date-string date) "\n"
23681 "ISO: " (calendar-iso-date-string date) "\n"
23682 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23683 "Julian: " (calendar-julian-date-string date) "\n"
23684 "Astron. JD: " (calendar-astro-date-string date)
23685 " (Julian date number at noon UTC)\n"
23686 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23687 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23688 "French: " (calendar-french-date-string date) "\n"
23689 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23690 "Mayan: " (calendar-mayan-date-string date) "\n"
23691 "Coptic: " (calendar-coptic-date-string date) "\n"
23692 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23693 "Persian: " (calendar-persian-date-string date) "\n"
23694 "Chinese: " (calendar-chinese-date-string date) "\n"))
23695 (with-output-to-temp-buffer "*Dates*"
23696 (princ s))
23697 (if (fboundp 'fit-window-to-buffer)
23698 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23699
23700
23701 ;;;; Embedded LaTeX
23702
23703 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23704 "Keymap for the minor `org-cdlatex-mode'.")
23705
23706 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23707 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23708 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23709 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23710 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23711
23712 (defvar org-cdlatex-texmathp-advice-is-done nil
23713 "Flag remembering if we have applied the advice to texmathp already.")
23714
23715 (define-minor-mode org-cdlatex-mode
23716 "Toggle the minor `org-cdlatex-mode'.
23717 This mode supports entering LaTeX environment and math in LaTeX fragments
23718 in Org-mode.
23719 \\{org-cdlatex-mode-map}"
23720 nil " OCDL" nil
23721 (when org-cdlatex-mode (require 'cdlatex))
23722 (unless org-cdlatex-texmathp-advice-is-done
23723 (setq org-cdlatex-texmathp-advice-is-done t)
23724 (defadvice texmathp (around org-math-always-on activate)
23725 "Always return t in org-mode buffers.
23726 This is because we want to insert math symbols without dollars even outside
23727 the LaTeX math segments. If Orgmode thinks that point is actually inside
23728 en embedded LaTeX fragement, let texmathp do its job.
23729 \\[org-cdlatex-mode-map]"
23730 (interactive)
23731 (let (p)
23732 (cond
23733 ((not (org-mode-p)) ad-do-it)
23734 ((eq this-command 'cdlatex-math-symbol)
23735 (setq ad-return-value t
23736 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23737 (t
23738 (let ((p (org-inside-LaTeX-fragment-p)))
23739 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23740 (setq ad-return-value t
23741 texmathp-why '("Org-mode embedded math" . 0))
23742 (if p ad-do-it)))))))))
23743
23744 (defun turn-on-org-cdlatex ()
23745 "Unconditionally turn on `org-cdlatex-mode'."
23746 (org-cdlatex-mode 1))
23747
23748 (defun org-inside-LaTeX-fragment-p ()
23749 "Test if point is inside a LaTeX fragment.
23750 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23751 sequence appearing also before point.
23752 Even though the matchers for math are configurable, this function assumes
23753 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23754 delimiters are skipped when they have been removed by customization.
23755 The return value is nil, or a cons cell with the delimiter and
23756 and the position of this delimiter.
23757
23758 This function does a reasonably good job, but can locally be fooled by
23759 for example currency specifications. For example it will assume being in
23760 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23761 fragments that are properly closed, but during editing, we have to live
23762 with the uncertainty caused by missing closing delimiters. This function
23763 looks only before point, not after."
23764 (catch 'exit
23765 (let ((pos (point))
23766 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23767 (lim (progn
23768 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23769 (point)))
23770 dd-on str (start 0) m re)
23771 (goto-char pos)
23772 (when dodollar
23773 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23774 re (nth 1 (assoc "$" org-latex-regexps)))
23775 (while (string-match re str start)
23776 (cond
23777 ((= (match-end 0) (length str))
23778 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23779 ((= (match-end 0) (- (length str) 5))
23780 (throw 'exit nil))
23781 (t (setq start (match-end 0))))))
23782 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23783 (goto-char pos)
23784 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23785 (and (match-beginning 2) (throw 'exit nil))
23786 ;; count $$
23787 (while (re-search-backward "\\$\\$" lim t)
23788 (setq dd-on (not dd-on)))
23789 (goto-char pos)
23790 (if dd-on (cons "$$" m))))))
23791
23792
23793 (defun org-try-cdlatex-tab ()
23794 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23795 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23796 - inside a LaTeX fragment, or
23797 - after the first word in a line, where an abbreviation expansion could
23798 insert a LaTeX environment."
23799 (when org-cdlatex-mode
23800 (cond
23801 ((save-excursion
23802 (skip-chars-backward "a-zA-Z0-9*")
23803 (skip-chars-backward " \t")
23804 (bolp))
23805 (cdlatex-tab) t)
23806 ((org-inside-LaTeX-fragment-p)
23807 (cdlatex-tab) t)
23808 (t nil))))
23809
23810 (defun org-cdlatex-underscore-caret (&optional arg)
23811 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23812 Revert to the normal definition outside of these fragments."
23813 (interactive "P")
23814 (if (org-inside-LaTeX-fragment-p)
23815 (call-interactively 'cdlatex-sub-superscript)
23816 (let (org-cdlatex-mode)
23817 (call-interactively (key-binding (vector last-input-event))))))
23818
23819 (defun org-cdlatex-math-modify (&optional arg)
23820 "Execute `cdlatex-math-modify' in LaTeX fragments.
23821 Revert to the normal definition outside of these fragments."
23822 (interactive "P")
23823 (if (org-inside-LaTeX-fragment-p)
23824 (call-interactively 'cdlatex-math-modify)
23825 (let (org-cdlatex-mode)
23826 (call-interactively (key-binding (vector last-input-event))))))
23827
23828 (defvar org-latex-fragment-image-overlays nil
23829 "List of overlays carrying the images of latex fragments.")
23830 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23831
23832 (defun org-remove-latex-fragment-image-overlays ()
23833 "Remove all overlays with LaTeX fragment images in current buffer."
23834 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23835 (setq org-latex-fragment-image-overlays nil))
23836
23837 (defun org-preview-latex-fragment (&optional subtree)
23838 "Preview the LaTeX fragment at point, or all locally or globally.
23839 If the cursor is in a LaTeX fragment, create the image and overlay
23840 it over the source code. If there is no fragment at point, display
23841 all fragments in the current text, from one headline to the next. With
23842 prefix SUBTREE, display all fragments in the current subtree. With a
23843 double prefix `C-u C-u', or when the cursor is before the first headline,
23844 display all fragments in the buffer.
23845 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23846 (interactive "P")
23847 (org-remove-latex-fragment-image-overlays)
23848 (save-excursion
23849 (save-restriction
23850 (let (beg end at msg)
23851 (cond
23852 ((or (equal subtree '(16))
23853 (not (save-excursion
23854 (re-search-backward (concat "^" outline-regexp) nil t))))
23855 (setq beg (point-min) end (point-max)
23856 msg "Creating images for buffer...%s"))
23857 ((equal subtree '(4))
23858 (org-back-to-heading)
23859 (setq beg (point) end (org-end-of-subtree t)
23860 msg "Creating images for subtree...%s"))
23861 (t
23862 (if (setq at (org-inside-LaTeX-fragment-p))
23863 (goto-char (max (point-min) (- (cdr at) 2)))
23864 (org-back-to-heading))
23865 (setq beg (point) end (progn (outline-next-heading) (point))
23866 msg (if at "Creating image...%s"
23867 "Creating images for entry...%s"))))
23868 (message msg "")
23869 (narrow-to-region beg end)
23870 (goto-char beg)
23871 (org-format-latex
23872 (concat "ltxpng/" (file-name-sans-extension
23873 (file-name-nondirectory
23874 buffer-file-name)))
23875 default-directory 'overlays msg at 'forbuffer)
23876 (message msg "done. Use `C-c C-c' to remove images.")))))
23877
23878 (defvar org-latex-regexps
23879 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23880 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23881 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23882 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23883 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23884 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23885 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23886 "Regular expressions for matching embedded LaTeX.")
23887
23888 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23889 "Replace LaTeX fragments with links to an image, and produce images."
23890 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23891 (let* ((prefixnodir (file-name-nondirectory prefix))
23892 (absprefix (expand-file-name prefix dir))
23893 (todir (file-name-directory absprefix))
23894 (opt org-format-latex-options)
23895 (matchers (plist-get opt :matchers))
23896 (re-list org-latex-regexps)
23897 (cnt 0) txt link beg end re e checkdir
23898 m n block linkfile movefile ov)
23899 ;; Check if there are old images files with this prefix, and remove them
23900 (when (file-directory-p todir)
23901 (mapc 'delete-file
23902 (directory-files
23903 todir 'full
23904 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23905 ;; Check the different regular expressions
23906 (while (setq e (pop re-list))
23907 (setq m (car e) re (nth 1 e) n (nth 2 e)
23908 block (if (nth 3 e) "\n\n" ""))
23909 (when (member m matchers)
23910 (goto-char (point-min))
23911 (while (re-search-forward re nil t)
23912 (when (or (not at) (equal (cdr at) (match-beginning n)))
23913 (setq txt (match-string n)
23914 beg (match-beginning n) end (match-end n)
23915 cnt (1+ cnt)
23916 linkfile (format "%s_%04d.png" prefix cnt)
23917 movefile (format "%s_%04d.png" absprefix cnt)
23918 link (concat block "[[file:" linkfile "]]" block))
23919 (if msg (message msg cnt))
23920 (goto-char beg)
23921 (unless checkdir ; make sure the directory exists
23922 (setq checkdir t)
23923 (or (file-directory-p todir) (make-directory todir)))
23924 (org-create-formula-image
23925 txt movefile opt forbuffer)
23926 (if overlays
23927 (progn
23928 (setq ov (org-make-overlay beg end))
23929 (if (featurep 'xemacs)
23930 (progn
23931 (org-overlay-put ov 'invisible t)
23932 (org-overlay-put
23933 ov 'end-glyph
23934 (make-glyph (vector 'png :file movefile))))
23935 (org-overlay-put
23936 ov 'display
23937 (list 'image :type 'png :file movefile :ascent 'center)))
23938 (push ov org-latex-fragment-image-overlays)
23939 (goto-char end))
23940 (delete-region beg end)
23941 (insert link))))))))
23942
23943 ;; This function borrows from Ganesh Swami's latex2png.el
23944 (defun org-create-formula-image (string tofile options buffer)
23945 (let* ((tmpdir (if (featurep 'xemacs)
23946 (temp-directory)
23947 temporary-file-directory))
23948 (texfilebase (make-temp-name
23949 (expand-file-name "orgtex" tmpdir)))
23950 (texfile (concat texfilebase ".tex"))
23951 (dvifile (concat texfilebase ".dvi"))
23952 (pngfile (concat texfilebase ".png"))
23953 (fnh (face-attribute 'default :height nil))
23954 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23955 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23956 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23957 "Black"))
23958 (bg (or (plist-get options (if buffer :background :html-background))
23959 "Transparent")))
23960 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23961 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23962 (with-temp-file texfile
23963 (insert org-format-latex-header
23964 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23965 (let ((dir default-directory))
23966 (condition-case nil
23967 (progn
23968 (cd tmpdir)
23969 (call-process "latex" nil nil nil texfile))
23970 (error nil))
23971 (cd dir))
23972 (if (not (file-exists-p dvifile))
23973 (progn (message "Failed to create dvi file from %s" texfile) nil)
23974 (call-process "dvipng" nil nil nil
23975 "-E" "-fg" fg "-bg" bg
23976 "-D" dpi
23977 ;;"-x" scale "-y" scale
23978 "-T" "tight"
23979 "-o" pngfile
23980 dvifile)
23981 (if (not (file-exists-p pngfile))
23982 (progn (message "Failed to create png file from %s" texfile) nil)
23983 ;; Use the requested file name and clean up
23984 (copy-file pngfile tofile 'replace)
23985 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23986 (delete-file (concat texfilebase e)))
23987 pngfile))))
23988
23989 (defun org-dvipng-color (attr)
23990 "Return an rgb color specification for dvipng."
23991 (apply 'format "rgb %s %s %s"
23992 (mapcar 'org-normalize-color
23993 (color-values (face-attribute 'default attr nil)))))
23994
23995 (defun org-normalize-color (value)
23996 "Return string to be used as color value for an RGB component."
23997 (format "%g" (/ value 65535.0)))
23998
23999 ;;;; Exporting
24000
24001 ;;; Variables, constants, and parameter plists
24002
24003 (defconst org-level-max 20)
24004
24005 (defvar org-export-html-preamble nil
24006 "Preamble, to be inserted just after <body>. Set by publishing functions.")
24007 (defvar org-export-html-postamble nil
24008 "Preamble, to be inserted just before </body>. Set by publishing functions.")
24009 (defvar org-export-html-auto-preamble t
24010 "Should default preamble be inserted? Set by publishing functions.")
24011 (defvar org-export-html-auto-postamble t
24012 "Should default postamble be inserted? Set by publishing functions.")
24013 (defvar org-current-export-file nil) ; dynamically scoped parameter
24014 (defvar org-current-export-dir nil) ; dynamically scoped parameter
24015
24016
24017 (defconst org-export-plist-vars
24018 '((:language . org-export-default-language)
24019 (:customtime . org-display-custom-times)
24020 (:headline-levels . org-export-headline-levels)
24021 (:section-numbers . org-export-with-section-numbers)
24022 (:table-of-contents . org-export-with-toc)
24023 (:preserve-breaks . org-export-preserve-breaks)
24024 (:archived-trees . org-export-with-archived-trees)
24025 (:emphasize . org-export-with-emphasize)
24026 (:sub-superscript . org-export-with-sub-superscripts)
24027 (:special-strings . org-export-with-special-strings)
24028 (:footnotes . org-export-with-footnotes)
24029 (:drawers . org-export-with-drawers)
24030 (:tags . org-export-with-tags)
24031 (:TeX-macros . org-export-with-TeX-macros)
24032 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
24033 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
24034 (:fixed-width . org-export-with-fixed-width)
24035 (:timestamps . org-export-with-timestamps)
24036 (:author-info . org-export-author-info)
24037 (:time-stamp-file . org-export-time-stamp-file)
24038 (:tables . org-export-with-tables)
24039 (:table-auto-headline . org-export-highlight-first-table-line)
24040 (:style . org-export-html-style)
24041 (:agenda-style . org-agenda-export-html-style)
24042 (:convert-org-links . org-export-html-link-org-files-as-html)
24043 (:inline-images . org-export-html-inline-images)
24044 (:html-extension . org-export-html-extension)
24045 (:html-table-tag . org-export-html-table-tag)
24046 (:expand-quoted-html . org-export-html-expand)
24047 (:timestamp . org-export-html-with-timestamp)
24048 (:publishing-directory . org-export-publishing-directory)
24049 (:preamble . org-export-html-preamble)
24050 (:postamble . org-export-html-postamble)
24051 (:auto-preamble . org-export-html-auto-preamble)
24052 (:auto-postamble . org-export-html-auto-postamble)
24053 (:author . user-full-name)
24054 (:email . user-mail-address)))
24055
24056 (defun org-default-export-plist ()
24057 "Return the property list with default settings for the export variables."
24058 (let ((l org-export-plist-vars) rtn e)
24059 (while (setq e (pop l))
24060 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
24061 rtn))
24062
24063 (defun org-infile-export-plist ()
24064 "Return the property list with file-local settings for export."
24065 (save-excursion
24066 (save-restriction
24067 (widen)
24068 (goto-char 0)
24069 (let ((re (org-make-options-regexp
24070 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
24071 p key val text options)
24072 (while (re-search-forward re nil t)
24073 (setq key (org-match-string-no-properties 1)
24074 val (org-match-string-no-properties 2))
24075 (cond
24076 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
24077 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
24078 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
24079 ((string-equal key "DATE") (setq p (plist-put p :date val)))
24080 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
24081 ((string-equal key "TEXT")
24082 (setq text (if text (concat text "\n" val) val)))
24083 ((string-equal key "OPTIONS") (setq options val))))
24084 (setq p (plist-put p :text text))
24085 (when options
24086 (let ((op '(("H" . :headline-levels)
24087 ("num" . :section-numbers)
24088 ("toc" . :table-of-contents)
24089 ("\\n" . :preserve-breaks)
24090 ("@" . :expand-quoted-html)
24091 (":" . :fixed-width)
24092 ("|" . :tables)
24093 ("^" . :sub-superscript)
24094 ("-" . :special-strings)
24095 ("f" . :footnotes)
24096 ("d" . :drawers)
24097 ("tags" . :tags)
24098 ("*" . :emphasize)
24099 ("TeX" . :TeX-macros)
24100 ("LaTeX" . :LaTeX-fragments)
24101 ("skip" . :skip-before-1st-heading)
24102 ("author" . :author-info)
24103 ("timestamp" . :time-stamp-file)))
24104 o)
24105 (while (setq o (pop op))
24106 (if (string-match (concat (regexp-quote (car o))
24107 ":\\([^ \t\n\r;,.]*\\)")
24108 options)
24109 (setq p (plist-put p (cdr o)
24110 (car (read-from-string
24111 (match-string 1 options)))))))))
24112 p))))
24113
24114 (defun org-export-directory (type plist)
24115 (let* ((val (plist-get plist :publishing-directory))
24116 (dir (if (listp val)
24117 (or (cdr (assoc type val)) ".")
24118 val)))
24119 dir))
24120
24121 (defun org-skip-comments (lines)
24122 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
24123 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
24124 (re2 "^\\(\\*+\\)[ \t\n\r]")
24125 (case-fold-search nil)
24126 rtn line level)
24127 (while (setq line (pop lines))
24128 (cond
24129 ((and (string-match re1 line)
24130 (setq level (- (match-end 1) (match-beginning 1))))
24131 ;; Beginning of a COMMENT subtree. Skip it.
24132 (while (and (setq line (pop lines))
24133 (or (not (string-match re2 line))
24134 (> (- (match-end 1) (match-beginning 1)) level))))
24135 (setq lines (cons line lines)))
24136 ((string-match "^#" line)
24137 ;; an ordinary comment line
24138 )
24139 ((and org-export-table-remove-special-lines
24140 (string-match "^[ \t]*|" line)
24141 (or (string-match "^[ \t]*| *[!_^] *|" line)
24142 (and (string-match "| *<[0-9]+> *|" line)
24143 (not (string-match "| *[^ <|]" line)))))
24144 ;; a special table line that should be removed
24145 )
24146 (t (setq rtn (cons line rtn)))))
24147 (nreverse rtn)))
24148
24149 (defun org-export (&optional arg)
24150 (interactive)
24151 (let ((help "[t] insert the export option template
24152 \[v] limit export to visible part of outline tree
24153
24154 \[a] export as ASCII
24155
24156 \[h] export as HTML
24157 \[H] export as HTML to temporary buffer
24158 \[R] export region as HTML
24159 \[b] export as HTML and browse immediately
24160 \[x] export as XOXO
24161
24162 \[l] export as LaTeX
24163 \[L] export as LaTeX to temporary buffer
24164
24165 \[i] export current file as iCalendar file
24166 \[I] export all agenda files as iCalendar files
24167 \[c] export agenda files into combined iCalendar file
24168
24169 \[F] publish current file
24170 \[P] publish current project
24171 \[X] publish... (project will be prompted for)
24172 \[A] publish all projects")
24173 (cmds
24174 '((?t . org-insert-export-options-template)
24175 (?v . org-export-visible)
24176 (?a . org-export-as-ascii)
24177 (?h . org-export-as-html)
24178 (?b . org-export-as-html-and-open)
24179 (?H . org-export-as-html-to-buffer)
24180 (?R . org-export-region-as-html)
24181 (?x . org-export-as-xoxo)
24182 (?l . org-export-as-latex)
24183 (?L . org-export-as-latex-to-buffer)
24184 (?i . org-export-icalendar-this-file)
24185 (?I . org-export-icalendar-all-agenda-files)
24186 (?c . org-export-icalendar-combine-agenda-files)
24187 (?F . org-publish-current-file)
24188 (?P . org-publish-current-project)
24189 (?X . org-publish)
24190 (?A . org-publish-all)))
24191 r1 r2 ass)
24192 (save-window-excursion
24193 (delete-other-windows)
24194 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
24195 (princ help))
24196 (message "Select command: ")
24197 (setq r1 (read-char-exclusive)))
24198 (setq r2 (if (< r1 27) (+ r1 96) r1))
24199 (if (setq ass (assq r2 cmds))
24200 (call-interactively (cdr ass))
24201 (error "No command associated with key %c" r1))))
24202
24203 (defconst org-html-entities
24204 '(("nbsp")
24205 ("iexcl")
24206 ("cent")
24207 ("pound")
24208 ("curren")
24209 ("yen")
24210 ("brvbar")
24211 ("vert" . "&#124;")
24212 ("sect")
24213 ("uml")
24214 ("copy")
24215 ("ordf")
24216 ("laquo")
24217 ("not")
24218 ("shy")
24219 ("reg")
24220 ("macr")
24221 ("deg")
24222 ("plusmn")
24223 ("sup2")
24224 ("sup3")
24225 ("acute")
24226 ("micro")
24227 ("para")
24228 ("middot")
24229 ("odot"."o")
24230 ("star"."*")
24231 ("cedil")
24232 ("sup1")
24233 ("ordm")
24234 ("raquo")
24235 ("frac14")
24236 ("frac12")
24237 ("frac34")
24238 ("iquest")
24239 ("Agrave")
24240 ("Aacute")
24241 ("Acirc")
24242 ("Atilde")
24243 ("Auml")
24244 ("Aring") ("AA"."&Aring;")
24245 ("AElig")
24246 ("Ccedil")
24247 ("Egrave")
24248 ("Eacute")
24249 ("Ecirc")
24250 ("Euml")
24251 ("Igrave")
24252 ("Iacute")
24253 ("Icirc")
24254 ("Iuml")
24255 ("ETH")
24256 ("Ntilde")
24257 ("Ograve")
24258 ("Oacute")
24259 ("Ocirc")
24260 ("Otilde")
24261 ("Ouml")
24262 ("times")
24263 ("Oslash")
24264 ("Ugrave")
24265 ("Uacute")
24266 ("Ucirc")
24267 ("Uuml")
24268 ("Yacute")
24269 ("THORN")
24270 ("szlig")
24271 ("agrave")
24272 ("aacute")
24273 ("acirc")
24274 ("atilde")
24275 ("auml")
24276 ("aring")
24277 ("aelig")
24278 ("ccedil")
24279 ("egrave")
24280 ("eacute")
24281 ("ecirc")
24282 ("euml")
24283 ("igrave")
24284 ("iacute")
24285 ("icirc")
24286 ("iuml")
24287 ("eth")
24288 ("ntilde")
24289 ("ograve")
24290 ("oacute")
24291 ("ocirc")
24292 ("otilde")
24293 ("ouml")
24294 ("divide")
24295 ("oslash")
24296 ("ugrave")
24297 ("uacute")
24298 ("ucirc")
24299 ("uuml")
24300 ("yacute")
24301 ("thorn")
24302 ("yuml")
24303 ("fnof")
24304 ("Alpha")
24305 ("Beta")
24306 ("Gamma")
24307 ("Delta")
24308 ("Epsilon")
24309 ("Zeta")
24310 ("Eta")
24311 ("Theta")
24312 ("Iota")
24313 ("Kappa")
24314 ("Lambda")
24315 ("Mu")
24316 ("Nu")
24317 ("Xi")
24318 ("Omicron")
24319 ("Pi")
24320 ("Rho")
24321 ("Sigma")
24322 ("Tau")
24323 ("Upsilon")
24324 ("Phi")
24325 ("Chi")
24326 ("Psi")
24327 ("Omega")
24328 ("alpha")
24329 ("beta")
24330 ("gamma")
24331 ("delta")
24332 ("epsilon")
24333 ("varepsilon"."&epsilon;")
24334 ("zeta")
24335 ("eta")
24336 ("theta")
24337 ("iota")
24338 ("kappa")
24339 ("lambda")
24340 ("mu")
24341 ("nu")
24342 ("xi")
24343 ("omicron")
24344 ("pi")
24345 ("rho")
24346 ("sigmaf") ("varsigma"."&sigmaf;")
24347 ("sigma")
24348 ("tau")
24349 ("upsilon")
24350 ("phi")
24351 ("chi")
24352 ("psi")
24353 ("omega")
24354 ("thetasym") ("vartheta"."&thetasym;")
24355 ("upsih")
24356 ("piv")
24357 ("bull") ("bullet"."&bull;")
24358 ("hellip") ("dots"."&hellip;")
24359 ("prime")
24360 ("Prime")
24361 ("oline")
24362 ("frasl")
24363 ("weierp")
24364 ("image")
24365 ("real")
24366 ("trade")
24367 ("alefsym")
24368 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
24369 ("uarr") ("uparrow"."&uarr;")
24370 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
24371 ("darr")("downarrow"."&darr;")
24372 ("harr") ("leftrightarrow"."&harr;")
24373 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
24374 ("lArr") ("Leftarrow"."&lArr;")
24375 ("uArr") ("Uparrow"."&uArr;")
24376 ("rArr") ("Rightarrow"."&rArr;")
24377 ("dArr") ("Downarrow"."&dArr;")
24378 ("hArr") ("Leftrightarrow"."&hArr;")
24379 ("forall")
24380 ("part") ("partial"."&part;")
24381 ("exist") ("exists"."&exist;")
24382 ("empty") ("emptyset"."&empty;")
24383 ("nabla")
24384 ("isin") ("in"."&isin;")
24385 ("notin")
24386 ("ni")
24387 ("prod")
24388 ("sum")
24389 ("minus")
24390 ("lowast") ("ast"."&lowast;")
24391 ("radic")
24392 ("prop") ("proptp"."&prop;")
24393 ("infin") ("infty"."&infin;")
24394 ("ang") ("angle"."&ang;")
24395 ("and") ("wedge"."&and;")
24396 ("or") ("vee"."&or;")
24397 ("cap")
24398 ("cup")
24399 ("int")
24400 ("there4")
24401 ("sim")
24402 ("cong") ("simeq"."&cong;")
24403 ("asymp")("approx"."&asymp;")
24404 ("ne") ("neq"."&ne;")
24405 ("equiv")
24406 ("le")
24407 ("ge")
24408 ("sub") ("subset"."&sub;")
24409 ("sup") ("supset"."&sup;")
24410 ("nsub")
24411 ("sube")
24412 ("supe")
24413 ("oplus")
24414 ("otimes")
24415 ("perp")
24416 ("sdot") ("cdot"."&sdot;")
24417 ("lceil")
24418 ("rceil")
24419 ("lfloor")
24420 ("rfloor")
24421 ("lang")
24422 ("rang")
24423 ("loz") ("Diamond"."&loz;")
24424 ("spades") ("spadesuit"."&spades;")
24425 ("clubs") ("clubsuit"."&clubs;")
24426 ("hearts") ("diamondsuit"."&hearts;")
24427 ("diams") ("diamondsuit"."&diams;")
24428 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
24429 ("quot")
24430 ("amp")
24431 ("lt")
24432 ("gt")
24433 ("OElig")
24434 ("oelig")
24435 ("Scaron")
24436 ("scaron")
24437 ("Yuml")
24438 ("circ")
24439 ("tilde")
24440 ("ensp")
24441 ("emsp")
24442 ("thinsp")
24443 ("zwnj")
24444 ("zwj")
24445 ("lrm")
24446 ("rlm")
24447 ("ndash")
24448 ("mdash")
24449 ("lsquo")
24450 ("rsquo")
24451 ("sbquo")
24452 ("ldquo")
24453 ("rdquo")
24454 ("bdquo")
24455 ("dagger")
24456 ("Dagger")
24457 ("permil")
24458 ("lsaquo")
24459 ("rsaquo")
24460 ("euro")
24461
24462 ("arccos"."arccos")
24463 ("arcsin"."arcsin")
24464 ("arctan"."arctan")
24465 ("arg"."arg")
24466 ("cos"."cos")
24467 ("cosh"."cosh")
24468 ("cot"."cot")
24469 ("coth"."coth")
24470 ("csc"."csc")
24471 ("deg"."deg")
24472 ("det"."det")
24473 ("dim"."dim")
24474 ("exp"."exp")
24475 ("gcd"."gcd")
24476 ("hom"."hom")
24477 ("inf"."inf")
24478 ("ker"."ker")
24479 ("lg"."lg")
24480 ("lim"."lim")
24481 ("liminf"."liminf")
24482 ("limsup"."limsup")
24483 ("ln"."ln")
24484 ("log"."log")
24485 ("max"."max")
24486 ("min"."min")
24487 ("Pr"."Pr")
24488 ("sec"."sec")
24489 ("sin"."sin")
24490 ("sinh"."sinh")
24491 ("sup"."sup")
24492 ("tan"."tan")
24493 ("tanh"."tanh")
24494 )
24495 "Entities for TeX->HTML translation.
24496 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24497 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24498 In that case, \"\\ent\" will be translated to \"&other;\".
24499 The list contains HTML entities for Latin-1, Greek and other symbols.
24500 It is supplemented by a number of commonly used TeX macros with appropriate
24501 translations. There is currently no way for users to extend this.")
24502
24503 ;;; General functions for all backends
24504
24505 (defun org-cleaned-string-for-export (string &rest parameters)
24506 "Cleanup a buffer STRING so that links can be created safely."
24507 (interactive)
24508 (let* ((re-radio (and org-target-link-regexp
24509 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24510 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24511 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24512 (re-archive (concat ":" org-archive-tag ":"))
24513 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24514 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24515 (htmlp (plist-get parameters :for-html))
24516 (asciip (plist-get parameters :for-ascii))
24517 (latexp (plist-get parameters :for-LaTeX))
24518 (commentsp (plist-get parameters :comments))
24519 (archived-trees (plist-get parameters :archived-trees))
24520 (inhibit-read-only t)
24521 (drawers org-drawers)
24522 (exp-drawers (plist-get parameters :drawers))
24523 (outline-regexp "\\*+ ")
24524 a b xx
24525 rtn p)
24526 (with-current-buffer (get-buffer-create " org-mode-tmp")
24527 (erase-buffer)
24528 (insert string)
24529 ;; Remove license-to-kill stuff
24530 (while (setq p (text-property-any (point-min) (point-max)
24531 :org-license-to-kill t))
24532 (delete-region p (next-single-property-change p :org-license-to-kill)))
24533
24534 (let ((org-inhibit-startup t)) (org-mode))
24535 (untabify (point-min) (point-max))
24536
24537 ;; Get rid of drawers
24538 (unless (eq t exp-drawers)
24539 (goto-char (point-min))
24540 (let ((re (concat "^[ \t]*:\\("
24541 (mapconcat
24542 'identity
24543 (org-delete-all exp-drawers
24544 (copy-sequence drawers))
24545 "\\|")
24546 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24547 (while (re-search-forward re nil t)
24548 (replace-match ""))))
24549
24550 ;; Get the correct stuff before the first headline
24551 (when (plist-get parameters :skip-before-1st-heading)
24552 (goto-char (point-min))
24553 (when (re-search-forward "^\\*+[ \t]" nil t)
24554 (delete-region (point-min) (match-beginning 0))
24555 (goto-char (point-min))
24556 (insert "\n")))
24557 (when (plist-get parameters :add-text)
24558 (goto-char (point-min))
24559 (insert (plist-get parameters :add-text) "\n"))
24560
24561 ;; Get rid of archived trees
24562 (when (not (eq archived-trees t))
24563 (goto-char (point-min))
24564 (while (re-search-forward re-archive nil t)
24565 (if (not (org-on-heading-p t))
24566 (org-end-of-subtree t)
24567 (beginning-of-line 1)
24568 (setq a (if archived-trees
24569 (1+ (point-at-eol)) (point))
24570 b (org-end-of-subtree t))
24571 (if (> b a) (delete-region a b)))))
24572
24573 ;; Find targets in comments and move them out of comments,
24574 ;; but mark them as targets that should be invisible
24575 (goto-char (point-min))
24576 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24577 (replace-match "\\1(INVISIBLE)"))
24578
24579 ;; Protect backend specific stuff, throw away the others.
24580 (let ((formatters
24581 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24582 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24583 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24584 fmt)
24585 (goto-char (point-min))
24586 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24587 (goto-char (match-end 0))
24588 (while (not (looking-at "#\\+END_EXAMPLE"))
24589 (insert ": ")
24590 (beginning-of-line 2)))
24591 (goto-char (point-min))
24592 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24593 (add-text-properties (match-beginning 0) (match-end 0)
24594 '(org-protected t)))
24595 (while formatters
24596 (setq fmt (pop formatters))
24597 (when (car fmt)
24598 (goto-char (point-min))
24599 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24600 ":[ \t]*\\(.*\\)") nil t)
24601 (replace-match "\\1" t)
24602 (add-text-properties
24603 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24604 '(org-protected t))))
24605 (goto-char (point-min))
24606 (while (re-search-forward
24607 (concat "^#\\+"
24608 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24609 (cadddr fmt) "\\>.*\n?") nil t)
24610 (if (car fmt)
24611 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24612 '(org-protected t))
24613 (delete-region (match-beginning 0) (match-end 0))))))
24614
24615 ;; Protect quoted subtrees
24616 (goto-char (point-min))
24617 (while (re-search-forward re-quote nil t)
24618 (goto-char (match-beginning 0))
24619 (end-of-line 1)
24620 (add-text-properties (point) (org-end-of-subtree t)
24621 '(org-protected t)))
24622
24623 ;; Protect verbatim elements
24624 (goto-char (point-min))
24625 (while (re-search-forward org-verbatim-re nil t)
24626 (add-text-properties (match-beginning 4) (match-end 4)
24627 '(org-protected t))
24628 (goto-char (1+ (match-end 4))))
24629
24630 ;; Remove subtrees that are commented
24631 (goto-char (point-min))
24632 (while (re-search-forward re-commented nil t)
24633 (goto-char (match-beginning 0))
24634 (delete-region (point) (org-end-of-subtree t)))
24635
24636 ;; Remove special table lines
24637 (when org-export-table-remove-special-lines
24638 (goto-char (point-min))
24639 (while (re-search-forward "^[ \t]*|" nil t)
24640 (beginning-of-line 1)
24641 (if (or (looking-at "[ \t]*| *[!_^] *|")
24642 (and (looking-at ".*?| *<[0-9]+> *|")
24643 (not (looking-at ".*?| *[^ <|]"))))
24644 (delete-region (max (point-min) (1- (point-at-bol)))
24645 (point-at-eol))
24646 (end-of-line 1))))
24647
24648 ;; Specific LaTeX stuff
24649 (when latexp
24650 (require 'org-export-latex nil)
24651 (org-export-latex-cleaned-string))
24652
24653 (when asciip
24654 (org-export-ascii-clean-string))
24655
24656 ;; Specific HTML stuff
24657 (when htmlp
24658 ;; Convert LaTeX fragments to images
24659 (when (plist-get parameters :LaTeX-fragments)
24660 (org-format-latex
24661 (concat "ltxpng/" (file-name-sans-extension
24662 (file-name-nondirectory
24663 org-current-export-file)))
24664 org-current-export-dir nil "Creating LaTeX image %s"))
24665 (message "Exporting..."))
24666
24667 ;; Remove or replace comments
24668 (goto-char (point-min))
24669 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24670 (if commentsp
24671 (progn (add-text-properties
24672 (match-beginning 0) (match-end 0) '(org-protected t))
24673 (replace-match (format commentsp (match-string 1)) t t))
24674 (replace-match "")))
24675
24676 ;; Find matches for radio targets and turn them into internal links
24677 (goto-char (point-min))
24678 (when re-radio
24679 (while (re-search-forward re-radio nil t)
24680 (org-if-unprotected
24681 (replace-match "\\1[[\\2]]"))))
24682
24683 ;; Find all links that contain a newline and put them into a single line
24684 (goto-char (point-min))
24685 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24686 (org-if-unprotected
24687 (replace-match "\\1 \\3")
24688 (goto-char (match-beginning 0))))
24689
24690
24691 ;; Normalize links: Convert angle and plain links into bracket links
24692 ;; Expand link abbreviations
24693 (goto-char (point-min))
24694 (while (re-search-forward re-plain-link nil t)
24695 (goto-char (1- (match-end 0)))
24696 (org-if-unprotected
24697 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24698 ":" (match-string 3) "]]")))
24699 ;; added 'org-link face to links
24700 (put-text-property 0 (length s) 'face 'org-link s)
24701 (replace-match s t t))))
24702 (goto-char (point-min))
24703 (while (re-search-forward re-angle-link nil t)
24704 (goto-char (1- (match-end 0)))
24705 (org-if-unprotected
24706 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24707 ":" (match-string 3) "]]")))
24708 (put-text-property 0 (length s) 'face 'org-link s)
24709 (replace-match s t t))))
24710 (goto-char (point-min))
24711 (while (re-search-forward org-bracket-link-regexp nil t)
24712 (org-if-unprotected
24713 (let* ((s (concat "[[" (setq xx (save-match-data
24714 (org-link-expand-abbrev (match-string 1))))
24715 "]"
24716 (if (match-end 3)
24717 (match-string 2)
24718 (concat "[" xx "]"))
24719 "]")))
24720 (put-text-property 0 (length s) 'face 'org-link s)
24721 (replace-match s t t))))
24722
24723 ;; Find multiline emphasis and put them into single line
24724 (when (plist-get parameters :emph-multiline)
24725 (goto-char (point-min))
24726 (while (re-search-forward org-emph-re nil t)
24727 (if (not (= (char-after (match-beginning 3))
24728 (char-after (match-beginning 4))))
24729 (org-if-unprotected
24730 (subst-char-in-region (match-beginning 0) (match-end 0)
24731 ?\n ?\ t)
24732 (goto-char (1- (match-end 0))))
24733 (goto-char (1+ (match-beginning 0))))))
24734
24735 (setq rtn (buffer-string)))
24736 (kill-buffer " org-mode-tmp")
24737 rtn))
24738
24739 (defun org-export-grab-title-from-buffer ()
24740 "Get a title for the current document, from looking at the buffer."
24741 (let ((inhibit-read-only t))
24742 (save-excursion
24743 (goto-char (point-min))
24744 (let ((end (save-excursion (outline-next-heading) (point))))
24745 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24746 ;; Mark the line so that it will not be exported as normal text.
24747 (org-unmodified
24748 (add-text-properties (match-beginning 0) (match-end 0)
24749 (list :org-license-to-kill t)))
24750 ;; Return the title string
24751 (org-trim (match-string 0)))))))
24752
24753 (defun org-export-get-title-from-subtree ()
24754 "Return subtree title and exclude it from export."
24755 (let (title (m (mark)))
24756 (save-excursion
24757 (goto-char (region-beginning))
24758 (when (and (org-at-heading-p)
24759 (>= (org-end-of-subtree t t) (region-end)))
24760 ;; This is a subtree, we take the title from the first heading
24761 (goto-char (region-beginning))
24762 (looking-at org-todo-line-regexp)
24763 (setq title (match-string 3))
24764 (org-unmodified
24765 (add-text-properties (point) (1+ (point-at-eol))
24766 (list :org-license-to-kill t)))))
24767 title))
24768
24769 (defun org-solidify-link-text (s &optional alist)
24770 "Take link text and make a safe target out of it."
24771 (save-match-data
24772 (let* ((rtn
24773 (mapconcat
24774 'identity
24775 (org-split-string s "[ \t\r\n]+") "--"))
24776 (a (assoc rtn alist)))
24777 (or (cdr a) rtn))))
24778
24779 (defun org-get-min-level (lines)
24780 "Get the minimum level in LINES."
24781 (let ((re "^\\(\\*+\\) ") l min)
24782 (catch 'exit
24783 (while (setq l (pop lines))
24784 (if (string-match re l)
24785 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24786 1)))
24787
24788 ;; Variable holding the vector with section numbers
24789 (defvar org-section-numbers (make-vector org-level-max 0))
24790
24791 (defun org-init-section-numbers ()
24792 "Initialize the vector for the section numbers."
24793 (let* ((level -1)
24794 (numbers (nreverse (org-split-string "" "\\.")))
24795 (depth (1- (length org-section-numbers)))
24796 (i depth) number-string)
24797 (while (>= i 0)
24798 (if (> i level)
24799 (aset org-section-numbers i 0)
24800 (setq number-string (or (car numbers) "0"))
24801 (if (string-match "\\`[A-Z]\\'" number-string)
24802 (aset org-section-numbers i
24803 (- (string-to-char number-string) ?A -1))
24804 (aset org-section-numbers i (string-to-number number-string)))
24805 (pop numbers))
24806 (setq i (1- i)))))
24807
24808 (defun org-section-number (&optional level)
24809 "Return a string with the current section number.
24810 When LEVEL is non-nil, increase section numbers on that level."
24811 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24812 (when level
24813 (when (> level -1)
24814 (aset org-section-numbers
24815 level (1+ (aref org-section-numbers level))))
24816 (setq idx (1+ level))
24817 (while (<= idx depth)
24818 (if (not (= idx 1))
24819 (aset org-section-numbers idx 0))
24820 (setq idx (1+ idx))))
24821 (setq idx 0)
24822 (while (<= idx depth)
24823 (setq n (aref org-section-numbers idx))
24824 (setq string (concat string (if (not (string= string "")) "." "")
24825 (int-to-string n)))
24826 (setq idx (1+ idx)))
24827 (save-match-data
24828 (if (string-match "\\`\\([@0]\\.\\)+" string)
24829 (setq string (replace-match "" t nil string)))
24830 (if (string-match "\\(\\.0\\)+\\'" string)
24831 (setq string (replace-match "" t nil string))))
24832 string))
24833
24834 ;;; ASCII export
24835
24836 (defvar org-last-level nil) ; dynamically scoped variable
24837 (defvar org-min-level nil) ; dynamically scoped variable
24838 (defvar org-levels-open nil) ; dynamically scoped parameter
24839 (defvar org-ascii-current-indentation nil) ; For communication
24840
24841 (defun org-export-as-ascii (arg)
24842 "Export the outline as a pretty ASCII file.
24843 If there is an active region, export only the region.
24844 The prefix ARG specifies how many levels of the outline should become
24845 underlined headlines. The default is 3."
24846 (interactive "P")
24847 (setq-default org-todo-line-regexp org-todo-line-regexp)
24848 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24849 (org-infile-export-plist)))
24850 (region-p (org-region-active-p))
24851 (subtree-p
24852 (when region-p
24853 (save-excursion
24854 (goto-char (region-beginning))
24855 (and (org-at-heading-p)
24856 (>= (org-end-of-subtree t t) (region-end))))))
24857 (custom-times org-display-custom-times)
24858 (org-ascii-current-indentation '(0 . 0))
24859 (level 0) line txt
24860 (umax nil)
24861 (umax-toc nil)
24862 (case-fold-search nil)
24863 (filename (concat (file-name-as-directory
24864 (org-export-directory :ascii opt-plist))
24865 (file-name-sans-extension
24866 (or (and subtree-p
24867 (org-entry-get (region-beginning)
24868 "EXPORT_FILE_NAME" t))
24869 (file-name-nondirectory buffer-file-name)))
24870 ".txt"))
24871 (filename (if (equal (file-truename filename)
24872 (file-truename buffer-file-name))
24873 (concat filename ".txt")
24874 filename))
24875 (buffer (find-file-noselect filename))
24876 (org-levels-open (make-vector org-level-max nil))
24877 (odd org-odd-levels-only)
24878 (date (plist-get opt-plist :date))
24879 (author (plist-get opt-plist :author))
24880 (title (or (and subtree-p (org-export-get-title-from-subtree))
24881 (plist-get opt-plist :title)
24882 (and (not
24883 (plist-get opt-plist :skip-before-1st-heading))
24884 (org-export-grab-title-from-buffer))
24885 (file-name-sans-extension
24886 (file-name-nondirectory buffer-file-name))))
24887 (email (plist-get opt-plist :email))
24888 (language (plist-get opt-plist :language))
24889 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24890 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24891 (todo nil)
24892 (lang-words nil)
24893 (region
24894 (buffer-substring
24895 (if (org-region-active-p) (region-beginning) (point-min))
24896 (if (org-region-active-p) (region-end) (point-max))))
24897 (lines (org-split-string
24898 (org-cleaned-string-for-export
24899 region
24900 :for-ascii t
24901 :skip-before-1st-heading
24902 (plist-get opt-plist :skip-before-1st-heading)
24903 :drawers (plist-get opt-plist :drawers)
24904 :verbatim-multiline t
24905 :archived-trees
24906 (plist-get opt-plist :archived-trees)
24907 :add-text (plist-get opt-plist :text))
24908 "\n"))
24909 thetoc have-headings first-heading-pos
24910 table-open table-buffer)
24911
24912 (let ((inhibit-read-only t))
24913 (org-unmodified
24914 (remove-text-properties (point-min) (point-max)
24915 '(:org-license-to-kill t))))
24916
24917 (setq org-min-level (org-get-min-level lines))
24918 (setq org-last-level org-min-level)
24919 (org-init-section-numbers)
24920
24921 (find-file-noselect filename)
24922
24923 (setq lang-words (or (assoc language org-export-language-setup)
24924 (assoc "en" org-export-language-setup)))
24925 (switch-to-buffer-other-window buffer)
24926 (erase-buffer)
24927 (fundamental-mode)
24928 ;; create local variables for all options, to make sure all called
24929 ;; functions get the correct information
24930 (mapc (lambda (x)
24931 (set (make-local-variable (cdr x))
24932 (plist-get opt-plist (car x))))
24933 org-export-plist-vars)
24934 (org-set-local 'org-odd-levels-only odd)
24935 (setq umax (if arg (prefix-numeric-value arg)
24936 org-export-headline-levels))
24937 (setq umax-toc (if (integerp org-export-with-toc)
24938 (min org-export-with-toc umax)
24939 umax))
24940
24941 ;; File header
24942 (if title (org-insert-centered title ?=))
24943 (insert "\n")
24944 (if (and (or author email)
24945 org-export-author-info)
24946 (insert (concat (nth 1 lang-words) ": " (or author "")
24947 (if email (concat " <" email ">") "")
24948 "\n")))
24949
24950 (cond
24951 ((and date (string-match "%" date))
24952 (setq date (format-time-string date (current-time))))
24953 (date)
24954 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24955
24956 (if (and date org-export-time-stamp-file)
24957 (insert (concat (nth 2 lang-words) ": " date"\n")))
24958
24959 (insert "\n\n")
24960
24961 (if org-export-with-toc
24962 (progn
24963 (push (concat (nth 3 lang-words) "\n") thetoc)
24964 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24965 (mapc '(lambda (line)
24966 (if (string-match org-todo-line-regexp
24967 line)
24968 ;; This is a headline
24969 (progn
24970 (setq have-headings t)
24971 (setq level (- (match-end 1) (match-beginning 1))
24972 level (org-tr-level level)
24973 txt (match-string 3 line)
24974 todo
24975 (or (and org-export-mark-todo-in-toc
24976 (match-beginning 2)
24977 (not (member (match-string 2 line)
24978 org-done-keywords)))
24979 ; TODO, not DONE
24980 (and org-export-mark-todo-in-toc
24981 (= level umax-toc)
24982 (org-search-todo-below
24983 line lines level))))
24984 (setq txt (org-html-expand-for-ascii txt))
24985
24986 (while (string-match org-bracket-link-regexp txt)
24987 (setq txt
24988 (replace-match
24989 (match-string (if (match-end 2) 3 1) txt)
24990 t t txt)))
24991
24992 (if (and (memq org-export-with-tags '(not-in-toc nil))
24993 (string-match
24994 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24995 txt))
24996 (setq txt (replace-match "" t t txt)))
24997 (if (string-match quote-re0 txt)
24998 (setq txt (replace-match "" t t txt)))
24999
25000 (if org-export-with-section-numbers
25001 (setq txt (concat (org-section-number level)
25002 " " txt)))
25003 (if (<= level umax-toc)
25004 (progn
25005 (push
25006 (concat
25007 (make-string
25008 (* (max 0 (- level org-min-level)) 4) ?\ )
25009 (format (if todo "%s (*)\n" "%s\n") txt))
25010 thetoc)
25011 (setq org-last-level level))
25012 ))))
25013 lines)
25014 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25015
25016 (org-init-section-numbers)
25017 (while (setq line (pop lines))
25018 ;; Remove the quoted HTML tags.
25019 (setq line (org-html-expand-for-ascii line))
25020 ;; Remove targets
25021 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
25022 (setq line (replace-match "" t t line)))
25023 ;; Replace internal links
25024 (while (string-match org-bracket-link-regexp line)
25025 (setq line (replace-match
25026 (if (match-end 3) "[\\3]" "[\\1]")
25027 t nil line)))
25028 (when custom-times
25029 (setq line (org-translate-time line)))
25030 (cond
25031 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25032 ;; a Headline
25033 (setq first-heading-pos (or first-heading-pos (point)))
25034 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25035 txt (match-string 2 line))
25036 (org-ascii-level-start level txt umax lines))
25037
25038 ((and org-export-with-tables
25039 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25040 (if (not table-open)
25041 ;; New table starts
25042 (setq table-open t table-buffer nil))
25043 ;; Accumulate lines
25044 (setq table-buffer (cons line table-buffer))
25045 (when (or (not lines)
25046 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25047 (car lines))))
25048 (setq table-open nil
25049 table-buffer (nreverse table-buffer))
25050 (insert (mapconcat
25051 (lambda (x)
25052 (org-fix-indentation x org-ascii-current-indentation))
25053 (org-format-table-ascii table-buffer)
25054 "\n") "\n")))
25055 (t
25056 (setq line (org-fix-indentation line org-ascii-current-indentation))
25057 (if (and org-export-with-fixed-width
25058 (string-match "^\\([ \t]*\\)\\(:\\)" line))
25059 (setq line (replace-match "\\1" nil nil line)))
25060 (insert line "\n"))))
25061
25062 (normal-mode)
25063
25064 ;; insert the table of contents
25065 (when thetoc
25066 (goto-char (point-min))
25067 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
25068 (progn
25069 (goto-char (match-beginning 0))
25070 (replace-match ""))
25071 (goto-char first-heading-pos))
25072 (mapc 'insert thetoc)
25073 (or (looking-at "[ \t]*\n[ \t]*\n")
25074 (insert "\n\n")))
25075
25076 ;; Convert whitespace place holders
25077 (goto-char (point-min))
25078 (let (beg end)
25079 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25080 (setq end (next-single-property-change beg 'org-whitespace))
25081 (goto-char beg)
25082 (delete-region beg end)
25083 (insert (make-string (- end beg) ?\ ))))
25084
25085 (save-buffer)
25086 ;; remove display and invisible chars
25087 (let (beg end)
25088 (goto-char (point-min))
25089 (while (setq beg (next-single-property-change (point) 'display))
25090 (setq end (next-single-property-change beg 'display))
25091 (delete-region beg end)
25092 (goto-char beg)
25093 (insert "=>"))
25094 (goto-char (point-min))
25095 (while (setq beg (next-single-property-change (point) 'org-cwidth))
25096 (setq end (next-single-property-change beg 'org-cwidth))
25097 (delete-region beg end)
25098 (goto-char beg)))
25099 (goto-char (point-min))))
25100
25101 (defun org-export-ascii-clean-string ()
25102 "Do extra work for ASCII export"
25103 (goto-char (point-min))
25104 (while (re-search-forward org-verbatim-re nil t)
25105 (goto-char (match-end 2))
25106 (backward-delete-char 1) (insert "'")
25107 (goto-char (match-beginning 2))
25108 (delete-char 1) (insert "`")
25109 (goto-char (match-end 2))))
25110
25111 (defun org-search-todo-below (line lines level)
25112 "Search the subtree below LINE for any TODO entries."
25113 (let ((rest (cdr (memq line lines)))
25114 (re org-todo-line-regexp)
25115 line lv todo)
25116 (catch 'exit
25117 (while (setq line (pop rest))
25118 (if (string-match re line)
25119 (progn
25120 (setq lv (- (match-end 1) (match-beginning 1))
25121 todo (and (match-beginning 2)
25122 (not (member (match-string 2 line)
25123 org-done-keywords))))
25124 ; TODO, not DONE
25125 (if (<= lv level) (throw 'exit nil))
25126 (if todo (throw 'exit t))))))))
25127
25128 (defun org-html-expand-for-ascii (line)
25129 "Handle quoted HTML for ASCII export."
25130 (if org-export-html-expand
25131 (while (string-match "@<[^<>\n]*>" line)
25132 ;; We just remove the tags for now.
25133 (setq line (replace-match "" nil nil line))))
25134 line)
25135
25136 (defun org-insert-centered (s &optional underline)
25137 "Insert the string S centered and underline it with character UNDERLINE."
25138 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
25139 (insert (make-string ind ?\ ) s "\n")
25140 (if underline
25141 (insert (make-string ind ?\ )
25142 (make-string (string-width s) underline)
25143 "\n"))))
25144
25145 (defun org-ascii-level-start (level title umax &optional lines)
25146 "Insert a new level in ASCII export."
25147 (let (char (n (- level umax 1)) (ind 0))
25148 (if (> level umax)
25149 (progn
25150 (insert (make-string (* 2 n) ?\ )
25151 (char-to-string (nth (% n (length org-export-ascii-bullets))
25152 org-export-ascii-bullets))
25153 " " title "\n")
25154 ;; find the indentation of the next non-empty line
25155 (catch 'stop
25156 (while lines
25157 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
25158 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
25159 (throw 'stop (setq ind (org-get-indentation (car lines)))))
25160 (pop lines)))
25161 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
25162 (if (or (not (equal (char-before) ?\n))
25163 (not (equal (char-before (1- (point))) ?\n)))
25164 (insert "\n"))
25165 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
25166 (unless org-export-with-tags
25167 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25168 (setq title (replace-match "" t t title))))
25169 (if org-export-with-section-numbers
25170 (setq title (concat (org-section-number level) " " title)))
25171 (insert title "\n" (make-string (string-width title) char) "\n")
25172 (setq org-ascii-current-indentation '(0 . 0)))))
25173
25174 (defun org-export-visible (type arg)
25175 "Create a copy of the visible part of the current buffer, and export it.
25176 The copy is created in a temporary buffer and removed after use.
25177 TYPE is the final key (as a string) that also select the export command in
25178 the `C-c C-e' export dispatcher.
25179 As a special case, if the you type SPC at the prompt, the temporary
25180 org-mode file will not be removed but presented to you so that you can
25181 continue to use it. The prefix arg ARG is passed through to the exporting
25182 command."
25183 (interactive
25184 (list (progn
25185 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
25186 (read-char-exclusive))
25187 current-prefix-arg))
25188 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
25189 (error "Invalid export key"))
25190 (let* ((binding (cdr (assoc type
25191 '((?a . org-export-as-ascii)
25192 (?\C-a . org-export-as-ascii)
25193 (?b . org-export-as-html-and-open)
25194 (?\C-b . org-export-as-html-and-open)
25195 (?h . org-export-as-html)
25196 (?H . org-export-as-html-to-buffer)
25197 (?R . org-export-region-as-html)
25198 (?x . org-export-as-xoxo)))))
25199 (keepp (equal type ?\ ))
25200 (file buffer-file-name)
25201 (buffer (get-buffer-create "*Org Export Visible*"))
25202 s e)
25203 ;; Need to hack the drawers here.
25204 (save-excursion
25205 (goto-char (point-min))
25206 (while (re-search-forward org-drawer-regexp nil t)
25207 (goto-char (match-beginning 1))
25208 (or (org-invisible-p) (org-flag-drawer nil))))
25209 (with-current-buffer buffer (erase-buffer))
25210 (save-excursion
25211 (setq s (goto-char (point-min)))
25212 (while (not (= (point) (point-max)))
25213 (goto-char (org-find-invisible))
25214 (append-to-buffer buffer s (point))
25215 (setq s (goto-char (org-find-visible))))
25216 (org-cycle-hide-drawers 'all)
25217 (goto-char (point-min))
25218 (unless keepp
25219 ;; Copy all comment lines to the end, to make sure #+ settings are
25220 ;; still available for the second export step. Kind of a hack, but
25221 ;; does do the trick.
25222 (if (looking-at "#[^\r\n]*")
25223 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
25224 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
25225 (append-to-buffer buffer (1+ (match-beginning 0))
25226 (min (point-max) (1+ (match-end 0))))))
25227 (set-buffer buffer)
25228 (let ((buffer-file-name file)
25229 (org-inhibit-startup t))
25230 (org-mode)
25231 (show-all)
25232 (unless keepp (funcall binding arg))))
25233 (if (not keepp)
25234 (kill-buffer buffer)
25235 (switch-to-buffer-other-window buffer)
25236 (goto-char (point-min)))))
25237
25238 (defun org-find-visible ()
25239 (let ((s (point)))
25240 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25241 (get-char-property s 'invisible)))
25242 s))
25243 (defun org-find-invisible ()
25244 (let ((s (point)))
25245 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25246 (not (get-char-property s 'invisible))))
25247 s))
25248
25249 ;;; HTML export
25250
25251 (defun org-get-current-options ()
25252 "Return a string with current options as keyword options.
25253 Does include HTML export options as well as TODO and CATEGORY stuff."
25254 (format
25255 "#+TITLE: %s
25256 #+AUTHOR: %s
25257 #+EMAIL: %s
25258 #+LANGUAGE: %s
25259 #+TEXT: Some descriptive text to be emitted. Several lines OK.
25260 #+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
25261 #+CATEGORY: %s
25262 #+SEQ_TODO: %s
25263 #+TYP_TODO: %s
25264 #+PRIORITIES: %c %c %c
25265 #+DRAWERS: %s
25266 #+STARTUP: %s %s %s %s %s
25267 #+TAGS: %s
25268 #+ARCHIVE: %s
25269 #+LINK: %s
25270 "
25271 (buffer-name) (user-full-name) user-mail-address org-export-default-language
25272 org-export-headline-levels
25273 org-export-with-section-numbers
25274 org-export-with-toc
25275 org-export-preserve-breaks
25276 org-export-html-expand
25277 org-export-with-fixed-width
25278 org-export-with-tables
25279 org-export-with-sub-superscripts
25280 org-export-with-special-strings
25281 org-export-with-footnotes
25282 org-export-with-emphasize
25283 org-export-with-TeX-macros
25284 org-export-with-LaTeX-fragments
25285 org-export-skip-text-before-1st-heading
25286 org-export-with-drawers
25287 org-export-with-tags
25288 (file-name-nondirectory buffer-file-name)
25289 "TODO FEEDBACK VERIFY DONE"
25290 "Me Jason Marie DONE"
25291 org-highest-priority org-lowest-priority org-default-priority
25292 (mapconcat 'identity org-drawers " ")
25293 (cdr (assoc org-startup-folded
25294 '((nil . "showall") (t . "overview") (content . "content"))))
25295 (if org-odd-levels-only "odd" "oddeven")
25296 (if org-hide-leading-stars "hidestars" "showstars")
25297 (if org-startup-align-all-tables "align" "noalign")
25298 (cond ((eq org-log-done t) "logdone")
25299 ((equal org-log-done 'note) "lognotedone")
25300 ((not org-log-done) "nologdone"))
25301 (or (mapconcat (lambda (x)
25302 (cond
25303 ((equal '(:startgroup) x) "{")
25304 ((equal '(:endgroup) x) "}")
25305 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
25306 (t (car x))))
25307 (or org-tag-alist (org-get-buffer-tags)) " ") "")
25308 org-archive-location
25309 "org file:~/org/%s.org"
25310 ))
25311
25312 (defun org-insert-export-options-template ()
25313 "Insert into the buffer a template with information for exporting."
25314 (interactive)
25315 (if (not (bolp)) (newline))
25316 (let ((s (org-get-current-options)))
25317 (and (string-match "#\\+CATEGORY" s)
25318 (setq s (substring s 0 (match-beginning 0))))
25319 (insert s)))
25320
25321 (defun org-toggle-fixed-width-section (arg)
25322 "Toggle the fixed-width export.
25323 If there is no active region, the QUOTE keyword at the current headline is
25324 inserted or removed. When present, it causes the text between this headline
25325 and the next to be exported as fixed-width text, and unmodified.
25326 If there is an active region, this command adds or removes a colon as the
25327 first character of this line. If the first character of a line is a colon,
25328 this line is also exported in fixed-width font."
25329 (interactive "P")
25330 (let* ((cc 0)
25331 (regionp (org-region-active-p))
25332 (beg (if regionp (region-beginning) (point)))
25333 (end (if regionp (region-end)))
25334 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
25335 (case-fold-search nil)
25336 (re "[ \t]*\\(:\\)")
25337 off)
25338 (if regionp
25339 (save-excursion
25340 (goto-char beg)
25341 (setq cc (current-column))
25342 (beginning-of-line 1)
25343 (setq off (looking-at re))
25344 (while (> nlines 0)
25345 (setq nlines (1- nlines))
25346 (beginning-of-line 1)
25347 (cond
25348 (arg
25349 (move-to-column cc t)
25350 (insert ":\n")
25351 (forward-line -1))
25352 ((and off (looking-at re))
25353 (replace-match "" t t nil 1))
25354 ((not off) (move-to-column cc t) (insert ":")))
25355 (forward-line 1)))
25356 (save-excursion
25357 (org-back-to-heading)
25358 (if (looking-at (concat outline-regexp
25359 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
25360 (replace-match "" t t nil 1)
25361 (if (looking-at outline-regexp)
25362 (progn
25363 (goto-char (match-end 0))
25364 (insert org-quote-string " "))))))))
25365
25366 (defun org-export-as-html-and-open (arg)
25367 "Export the outline as HTML and immediately open it with a browser.
25368 If there is an active region, export only the region.
25369 The prefix ARG specifies how many levels of the outline should become
25370 headlines. The default is 3. Lower levels will become bulleted lists."
25371 (interactive "P")
25372 (org-export-as-html arg 'hidden)
25373 (org-open-file buffer-file-name))
25374
25375 (defun org-export-as-html-batch ()
25376 "Call `org-export-as-html', may be used in batch processing as
25377 emacs --batch
25378 --load=$HOME/lib/emacs/org.el
25379 --eval \"(setq org-export-headline-levels 2)\"
25380 --visit=MyFile --funcall org-export-as-html-batch"
25381 (org-export-as-html org-export-headline-levels 'hidden))
25382
25383 (defun org-export-as-html-to-buffer (arg)
25384 "Call `org-exort-as-html` with output to a temporary buffer.
25385 No file is created. The prefix ARG is passed through to `org-export-as-html'."
25386 (interactive "P")
25387 (org-export-as-html arg nil nil "*Org HTML Export*")
25388 (switch-to-buffer-other-window "*Org HTML Export*"))
25389
25390 (defun org-replace-region-by-html (beg end)
25391 "Assume the current region has org-mode syntax, and convert it to HTML.
25392 This can be used in any buffer. For example, you could write an
25393 itemized list in org-mode syntax in an HTML buffer and then use this
25394 command to convert it."
25395 (interactive "r")
25396 (let (reg html buf pop-up-frames)
25397 (save-window-excursion
25398 (if (org-mode-p)
25399 (setq html (org-export-region-as-html
25400 beg end t 'string))
25401 (setq reg (buffer-substring beg end)
25402 buf (get-buffer-create "*Org tmp*"))
25403 (with-current-buffer buf
25404 (erase-buffer)
25405 (insert reg)
25406 (org-mode)
25407 (setq html (org-export-region-as-html
25408 (point-min) (point-max) t 'string)))
25409 (kill-buffer buf)))
25410 (delete-region beg end)
25411 (insert html)))
25412
25413 (defun org-export-region-as-html (beg end &optional body-only buffer)
25414 "Convert region from BEG to END in org-mode buffer to HTML.
25415 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
25416 contents, and only produce the region of converted text, useful for
25417 cut-and-paste operations.
25418 If BUFFER is a buffer or a string, use/create that buffer as a target
25419 of the converted HTML. If BUFFER is the symbol `string', return the
25420 produced HTML as a string and leave not buffer behind. For example,
25421 a Lisp program could call this function in the following way:
25422
25423 (setq html (org-export-region-as-html beg end t 'string))
25424
25425 When called interactively, the output buffer is selected, and shown
25426 in a window. A non-interactive call will only retunr the buffer."
25427 (interactive "r\nP")
25428 (when (interactive-p)
25429 (setq buffer "*Org HTML Export*"))
25430 (let ((transient-mark-mode t) (zmacs-regions t)
25431 rtn)
25432 (goto-char end)
25433 (set-mark (point)) ;; to activate the region
25434 (goto-char beg)
25435 (setq rtn (org-export-as-html
25436 nil nil nil
25437 buffer body-only))
25438 (if (fboundp 'deactivate-mark) (deactivate-mark))
25439 (if (and (interactive-p) (bufferp rtn))
25440 (switch-to-buffer-other-window rtn)
25441 rtn)))
25442
25443 (defvar html-table-tag nil) ; dynamically scoped into this.
25444 (defun org-export-as-html (arg &optional hidden ext-plist
25445 to-buffer body-only pub-dir)
25446 "Export the outline as a pretty HTML file.
25447 If there is an active region, export only the region. The prefix
25448 ARG specifies how many levels of the outline should become
25449 headlines. The default is 3. Lower levels will become bulleted
25450 lists. When HIDDEN is non-nil, don't display the HTML buffer.
25451 EXT-PLIST is a property list with external parameters overriding
25452 org-mode's default settings, but still inferior to file-local
25453 settings. When TO-BUFFER is non-nil, create a buffer with that
25454 name and export to that buffer. If TO-BUFFER is the symbol
25455 `string', don't leave any buffer behind but just return the
25456 resulting HTML as a string. When BODY-ONLY is set, don't produce
25457 the file header and footer, simply return the content of
25458 <body>...</body>, without even the body tags themselves. When
25459 PUB-DIR is set, use this as the publishing directory."
25460 (interactive "P")
25461
25462 ;; Make sure we have a file name when we need it.
25463 (when (and (not (or to-buffer body-only))
25464 (not buffer-file-name))
25465 (if (buffer-base-buffer)
25466 (org-set-local 'buffer-file-name
25467 (with-current-buffer (buffer-base-buffer)
25468 buffer-file-name))
25469 (error "Need a file name to be able to export.")))
25470
25471 (message "Exporting...")
25472 (setq-default org-todo-line-regexp org-todo-line-regexp)
25473 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25474 (setq-default org-done-keywords org-done-keywords)
25475 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25476 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25477 ext-plist
25478 (org-infile-export-plist)))
25479
25480 (style (plist-get opt-plist :style))
25481 (html-extension (plist-get opt-plist :html-extension))
25482 (link-validate (plist-get opt-plist :link-validation-function))
25483 valid thetoc have-headings first-heading-pos
25484 (odd org-odd-levels-only)
25485 (region-p (org-region-active-p))
25486 (subtree-p
25487 (when region-p
25488 (save-excursion
25489 (goto-char (region-beginning))
25490 (and (org-at-heading-p)
25491 (>= (org-end-of-subtree t t) (region-end))))))
25492 ;; The following two are dynamically scoped into other
25493 ;; routines below.
25494 (org-current-export-dir
25495 (or pub-dir (org-export-directory :html opt-plist)))
25496 (org-current-export-file buffer-file-name)
25497 (level 0) (line "") (origline "") txt todo
25498 (umax nil)
25499 (umax-toc nil)
25500 (filename (if to-buffer nil
25501 (expand-file-name
25502 (concat
25503 (file-name-sans-extension
25504 (or (and subtree-p
25505 (org-entry-get (region-beginning)
25506 "EXPORT_FILE_NAME" t))
25507 (file-name-nondirectory buffer-file-name)))
25508 "." html-extension)
25509 (file-name-as-directory
25510 (or pub-dir (org-export-directory :html opt-plist))))))
25511 (current-dir (if buffer-file-name
25512 (file-name-directory buffer-file-name)
25513 default-directory))
25514 (buffer (if to-buffer
25515 (cond
25516 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25517 (t (get-buffer-create to-buffer)))
25518 (find-file-noselect filename)))
25519 (org-levels-open (make-vector org-level-max nil))
25520 (date (plist-get opt-plist :date))
25521 (author (plist-get opt-plist :author))
25522 (title (or (and subtree-p (org-export-get-title-from-subtree))
25523 (plist-get opt-plist :title)
25524 (and (not
25525 (plist-get opt-plist :skip-before-1st-heading))
25526 (org-export-grab-title-from-buffer))
25527 (and buffer-file-name
25528 (file-name-sans-extension
25529 (file-name-nondirectory buffer-file-name)))
25530 "UNTITLED"))
25531 (html-table-tag (plist-get opt-plist :html-table-tag))
25532 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25533 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25534 (inquote nil)
25535 (infixed nil)
25536 (in-local-list nil)
25537 (local-list-num nil)
25538 (local-list-indent nil)
25539 (llt org-plain-list-ordered-item-terminator)
25540 (email (plist-get opt-plist :email))
25541 (language (plist-get opt-plist :language))
25542 (lang-words nil)
25543 (target-alist nil) tg
25544 (head-count 0) cnt
25545 (start 0)
25546 (coding-system (and (boundp 'buffer-file-coding-system)
25547 buffer-file-coding-system))
25548 (coding-system-for-write (or org-export-html-coding-system
25549 coding-system))
25550 (save-buffer-coding-system (or org-export-html-coding-system
25551 coding-system))
25552 (charset (and coding-system-for-write
25553 (fboundp 'coding-system-get)
25554 (coding-system-get coding-system-for-write
25555 'mime-charset)))
25556 (region
25557 (buffer-substring
25558 (if region-p (region-beginning) (point-min))
25559 (if region-p (region-end) (point-max))))
25560 (lines
25561 (org-split-string
25562 (org-cleaned-string-for-export
25563 region
25564 :emph-multiline t
25565 :for-html t
25566 :skip-before-1st-heading
25567 (plist-get opt-plist :skip-before-1st-heading)
25568 :drawers (plist-get opt-plist :drawers)
25569 :archived-trees
25570 (plist-get opt-plist :archived-trees)
25571 :add-text
25572 (plist-get opt-plist :text)
25573 :LaTeX-fragments
25574 (plist-get opt-plist :LaTeX-fragments))
25575 "[\r\n]"))
25576 table-open type
25577 table-buffer table-orig-buffer
25578 ind start-is-num starter didclose
25579 rpl path desc descp desc1 desc2 link
25580 )
25581
25582 (let ((inhibit-read-only t))
25583 (org-unmodified
25584 (remove-text-properties (point-min) (point-max)
25585 '(:org-license-to-kill t))))
25586
25587 (message "Exporting...")
25588
25589 (setq org-min-level (org-get-min-level lines))
25590 (setq org-last-level org-min-level)
25591 (org-init-section-numbers)
25592
25593 (cond
25594 ((and date (string-match "%" date))
25595 (setq date (format-time-string date (current-time))))
25596 (date)
25597 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25598
25599 ;; Get the language-dependent settings
25600 (setq lang-words (or (assoc language org-export-language-setup)
25601 (assoc "en" org-export-language-setup)))
25602
25603 ;; Switch to the output buffer
25604 (set-buffer buffer)
25605 (let ((inhibit-read-only t)) (erase-buffer))
25606 (fundamental-mode)
25607
25608 (and (fboundp 'set-buffer-file-coding-system)
25609 (set-buffer-file-coding-system coding-system-for-write))
25610
25611 (let ((case-fold-search nil)
25612 (org-odd-levels-only odd))
25613 ;; create local variables for all options, to make sure all called
25614 ;; functions get the correct information
25615 (mapc (lambda (x)
25616 (set (make-local-variable (cdr x))
25617 (plist-get opt-plist (car x))))
25618 org-export-plist-vars)
25619 (setq umax (if arg (prefix-numeric-value arg)
25620 org-export-headline-levels))
25621 (setq umax-toc (if (integerp org-export-with-toc)
25622 (min org-export-with-toc umax)
25623 umax))
25624 (unless body-only
25625 ;; File header
25626 (insert (format
25627 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25628 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25629 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25630 lang=\"%s\" xml:lang=\"%s\">
25631 <head>
25632 <title>%s</title>
25633 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25634 <meta name=\"generator\" content=\"Org-mode\"/>
25635 <meta name=\"generated\" content=\"%s\"/>
25636 <meta name=\"author\" content=\"%s\"/>
25637 %s
25638 </head><body>
25639 "
25640 language language (org-html-expand title)
25641 (or charset "iso-8859-1") date author style))
25642
25643 (insert (or (plist-get opt-plist :preamble) ""))
25644
25645 (when (plist-get opt-plist :auto-preamble)
25646 (if title (insert (format org-export-html-title-format
25647 (org-html-expand title))))))
25648
25649 (if (and org-export-with-toc (not body-only))
25650 (progn
25651 (push (format "<h%d>%s</h%d>\n"
25652 org-export-html-toplevel-hlevel
25653 (nth 3 lang-words)
25654 org-export-html-toplevel-hlevel)
25655 thetoc)
25656 (push "<ul>\n<li>" thetoc)
25657 (setq lines
25658 (mapcar '(lambda (line)
25659 (if (string-match org-todo-line-regexp line)
25660 ;; This is a headline
25661 (progn
25662 (setq have-headings t)
25663 (setq level (- (match-end 1) (match-beginning 1))
25664 level (org-tr-level level)
25665 txt (save-match-data
25666 (org-html-expand
25667 (org-export-cleanup-toc-line
25668 (match-string 3 line))))
25669 todo
25670 (or (and org-export-mark-todo-in-toc
25671 (match-beginning 2)
25672 (not (member (match-string 2 line)
25673 org-done-keywords)))
25674 ; TODO, not DONE
25675 (and org-export-mark-todo-in-toc
25676 (= level umax-toc)
25677 (org-search-todo-below
25678 line lines level))))
25679 (if (string-match
25680 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25681 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25682 (if (string-match quote-re0 txt)
25683 (setq txt (replace-match "" t t txt)))
25684 (if org-export-with-section-numbers
25685 (setq txt (concat (org-section-number level)
25686 " " txt)))
25687 (if (<= level (max umax umax-toc))
25688 (setq head-count (+ head-count 1)))
25689 (if (<= level umax-toc)
25690 (progn
25691 (if (> level org-last-level)
25692 (progn
25693 (setq cnt (- level org-last-level))
25694 (while (>= (setq cnt (1- cnt)) 0)
25695 (push "\n<ul>\n<li>" thetoc))
25696 (push "\n" thetoc)))
25697 (if (< level org-last-level)
25698 (progn
25699 (setq cnt (- org-last-level level))
25700 (while (>= (setq cnt (1- cnt)) 0)
25701 (push "</li>\n</ul>" thetoc))
25702 (push "\n" thetoc)))
25703 ;; Check for targets
25704 (while (string-match org-target-regexp line)
25705 (setq tg (match-string 1 line)
25706 line (replace-match
25707 (concat "@<span class=\"target\">" tg "@</span> ")
25708 t t line))
25709 (push (cons (org-solidify-link-text tg)
25710 (format "sec-%d" head-count))
25711 target-alist))
25712 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25713 (setq txt (replace-match "" t t txt)))
25714 (push
25715 (format
25716 (if todo
25717 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25718 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25719 head-count txt) thetoc)
25720
25721 (setq org-last-level level))
25722 )))
25723 line)
25724 lines))
25725 (while (> org-last-level (1- org-min-level))
25726 (setq org-last-level (1- org-last-level))
25727 (push "</li>\n</ul>\n" thetoc))
25728 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25729
25730 (setq head-count 0)
25731 (org-init-section-numbers)
25732
25733 (while (setq line (pop lines) origline line)
25734 (catch 'nextline
25735
25736 ;; end of quote section?
25737 (when (and inquote (string-match "^\\*+ " line))
25738 (insert "</pre>\n")
25739 (setq inquote nil))
25740 ;; inside a quote section?
25741 (when inquote
25742 (insert (org-html-protect line) "\n")
25743 (throw 'nextline nil))
25744
25745 ;; verbatim lines
25746 (when (and org-export-with-fixed-width
25747 (string-match "^[ \t]*:\\(.*\\)" line))
25748 (when (not infixed)
25749 (setq infixed t)
25750 (insert "<pre>\n"))
25751 (insert (org-html-protect (match-string 1 line)) "\n")
25752 (when (and lines
25753 (not (string-match "^[ \t]*\\(:.*\\)"
25754 (car lines))))
25755 (setq infixed nil)
25756 (insert "</pre>\n"))
25757 (throw 'nextline nil))
25758
25759 ;; Protected HTML
25760 (when (get-text-property 0 'org-protected line)
25761 (let (par)
25762 (when (re-search-backward
25763 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25764 (setq par (match-string 1))
25765 (replace-match "\\2\n"))
25766 (insert line "\n")
25767 (while (and lines
25768 (or (= (length (car lines)) 0)
25769 (get-text-property 0 'org-protected (car lines))))
25770 (insert (pop lines) "\n"))
25771 (and par (insert "<p>\n")))
25772 (throw 'nextline nil))
25773
25774 ;; Horizontal line
25775 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25776 (insert "\n<hr/>\n")
25777 (throw 'nextline nil))
25778
25779 ;; make targets to anchors
25780 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25781 (cond
25782 ((match-end 2)
25783 (setq line (replace-match
25784 (concat "@<a name=\""
25785 (org-solidify-link-text (match-string 1 line))
25786 "\">\\nbsp@</a>")
25787 t t line)))
25788 ((and org-export-with-toc (equal (string-to-char line) ?*))
25789 (setq line (replace-match
25790 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25791 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25792 t t line)))
25793 (t
25794 (setq line (replace-match
25795 (concat "@<a name=\""
25796 (org-solidify-link-text (match-string 1 line))
25797 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25798 t t line)))))
25799
25800 (setq line (org-html-handle-time-stamps line))
25801
25802 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25803 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25804 ;; Also handle sub_superscripts and checkboxes
25805 (or (string-match org-table-hline-regexp line)
25806 (setq line (org-html-expand line)))
25807
25808 ;; Format the links
25809 (setq start 0)
25810 (while (string-match org-bracket-link-analytic-regexp line start)
25811 (setq start (match-beginning 0))
25812 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25813 (setq path (match-string 3 line))
25814 (setq desc1 (if (match-end 5) (match-string 5 line))
25815 desc2 (if (match-end 2) (concat type ":" path) path)
25816 descp (and desc1 (not (equal desc1 desc2)))
25817 desc (or desc1 desc2))
25818 ;; Make an image out of the description if that is so wanted
25819 (when (and descp (org-file-image-p desc))
25820 (save-match-data
25821 (if (string-match "^file:" desc)
25822 (setq desc (substring desc (match-end 0)))))
25823 (setq desc (concat "<img src=\"" desc "\"/>")))
25824 ;; FIXME: do we need to unescape here somewhere?
25825 (cond
25826 ((equal type "internal")
25827 (setq rpl
25828 (concat
25829 "<a href=\"#"
25830 (org-solidify-link-text
25831 (save-match-data (org-link-unescape path)) target-alist)
25832 "\">" desc "</a>")))
25833 ((member type '("http" "https"))
25834 ;; standard URL, just check if we need to inline an image
25835 (if (and (or (eq t org-export-html-inline-images)
25836 (and org-export-html-inline-images (not descp)))
25837 (org-file-image-p path))
25838 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25839 (setq link (concat type ":" path))
25840 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25841 ((member type '("ftp" "mailto" "news"))
25842 ;; standard URL
25843 (setq link (concat type ":" path))
25844 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25845 ((string= type "file")
25846 ;; FILE link
25847 (let* ((filename path)
25848 (abs-p (file-name-absolute-p filename))
25849 thefile file-is-image-p search)
25850 (save-match-data
25851 (if (string-match "::\\(.*\\)" filename)
25852 (setq search (match-string 1 filename)
25853 filename (replace-match "" t nil filename)))
25854 (setq valid
25855 (if (functionp link-validate)
25856 (funcall link-validate filename current-dir)
25857 t))
25858 (setq file-is-image-p (org-file-image-p filename))
25859 (setq thefile (if abs-p (expand-file-name filename) filename))
25860 (when (and org-export-html-link-org-files-as-html
25861 (string-match "\\.org$" thefile))
25862 (setq thefile (concat (substring thefile 0
25863 (match-beginning 0))
25864 "." html-extension))
25865 (if (and search
25866 ;; make sure this is can be used as target search
25867 (not (string-match "^[0-9]*$" search))
25868 (not (string-match "^\\*" search))
25869 (not (string-match "^/.*/$" search)))
25870 (setq thefile (concat thefile "#"
25871 (org-solidify-link-text
25872 (org-link-unescape search)))))
25873 (when (string-match "^file:" desc)
25874 (setq desc (replace-match "" t t desc))
25875 (if (string-match "\\.org$" desc)
25876 (setq desc (replace-match "" t t desc))))))
25877 (setq rpl (if (and file-is-image-p
25878 (or (eq t org-export-html-inline-images)
25879 (and org-export-html-inline-images
25880 (not descp))))
25881 (concat "<img src=\"" thefile "\"/>")
25882 (concat "<a href=\"" thefile "\">" desc "</a>")))
25883 (if (not valid) (setq rpl desc))))
25884 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25885 (setq rpl (concat "<i>&lt;" type ":"
25886 (save-match-data (org-link-unescape path))
25887 "&gt;</i>"))))
25888 (setq line (replace-match rpl t t line)
25889 start (+ start (length rpl))))
25890
25891 ;; TODO items
25892 (if (and (string-match org-todo-line-regexp line)
25893 (match-beginning 2))
25894
25895 (setq line
25896 (concat (substring line 0 (match-beginning 2))
25897 "<span class=\""
25898 (if (member (match-string 2 line)
25899 org-done-keywords)
25900 "done" "todo")
25901 "\">" (match-string 2 line)
25902 "</span>" (substring line (match-end 2)))))
25903
25904 ;; Does this contain a reference to a footnote?
25905 (when org-export-with-footnotes
25906 (setq start 0)
25907 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25908 (if (get-text-property (match-beginning 2) 'org-protected line)
25909 (setq start (match-end 2))
25910 (let ((n (match-string 2 line)))
25911 (setq line
25912 (replace-match
25913 (format
25914 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25915 (match-string 1 line) n n n)
25916 t t line))))))
25917
25918 (cond
25919 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25920 ;; This is a headline
25921 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25922 txt (match-string 2 line))
25923 (if (string-match quote-re0 txt)
25924 (setq txt (replace-match "" t t txt)))
25925 (if (<= level (max umax umax-toc))
25926 (setq head-count (+ head-count 1)))
25927 (when in-local-list
25928 ;; Close any local lists before inserting a new header line
25929 (while local-list-num
25930 (org-close-li)
25931 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25932 (pop local-list-num))
25933 (setq local-list-indent nil
25934 in-local-list nil))
25935 (setq first-heading-pos (or first-heading-pos (point)))
25936 (org-html-level-start level txt umax
25937 (and org-export-with-toc (<= level umax))
25938 head-count)
25939 ;; QUOTES
25940 (when (string-match quote-re line)
25941 (insert "<pre>")
25942 (setq inquote t)))
25943
25944 ((and org-export-with-tables
25945 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25946 (if (not table-open)
25947 ;; New table starts
25948 (setq table-open t table-buffer nil table-orig-buffer nil))
25949 ;; Accumulate lines
25950 (setq table-buffer (cons line table-buffer)
25951 table-orig-buffer (cons origline table-orig-buffer))
25952 (when (or (not lines)
25953 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25954 (car lines))))
25955 (setq table-open nil
25956 table-buffer (nreverse table-buffer)
25957 table-orig-buffer (nreverse table-orig-buffer))
25958 (org-close-par-maybe)
25959 (insert (org-format-table-html table-buffer table-orig-buffer))))
25960 (t
25961 ;; Normal lines
25962 (when (string-match
25963 (cond
25964 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25965 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25966 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25967 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25968 line)
25969 (setq ind (org-get-string-indentation line)
25970 start-is-num (match-beginning 4)
25971 starter (if (match-beginning 2)
25972 (substring (match-string 2 line) 0 -1))
25973 line (substring line (match-beginning 5)))
25974 (unless (string-match "[^ \t]" line)
25975 ;; empty line. Pretend indentation is large.
25976 (setq ind (if org-empty-line-terminates-plain-lists
25977 0
25978 (1+ (or (car local-list-indent) 1)))))
25979 (setq didclose nil)
25980 (while (and in-local-list
25981 (or (and (= ind (car local-list-indent))
25982 (not starter))
25983 (< ind (car local-list-indent))))
25984 (setq didclose t)
25985 (org-close-li)
25986 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25987 (pop local-list-num) (pop local-list-indent)
25988 (setq in-local-list local-list-indent))
25989 (cond
25990 ((and starter
25991 (or (not in-local-list)
25992 (> ind (car local-list-indent))))
25993 ;; Start new (level of) list
25994 (org-close-par-maybe)
25995 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25996 (push start-is-num local-list-num)
25997 (push ind local-list-indent)
25998 (setq in-local-list t))
25999 (starter
26000 ;; continue current list
26001 (org-close-li)
26002 (insert "<li>\n"))
26003 (didclose
26004 ;; we did close a list, normal text follows: need <p>
26005 (org-open-par)))
26006 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
26007 (setq line
26008 (replace-match
26009 (if (equal (match-string 1 line) "X")
26010 "<b>[X]</b>"
26011 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
26012 t t line))))
26013
26014 ;; Empty lines start a new paragraph. If hand-formatted lists
26015 ;; are not fully interpreted, lines starting with "-", "+", "*"
26016 ;; also start a new paragraph.
26017 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
26018
26019 ;; Is this the start of a footnote?
26020 (when org-export-with-footnotes
26021 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
26022 (org-close-par-maybe)
26023 (let ((n (match-string 1 line)))
26024 (setq line (replace-match
26025 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
26026
26027 ;; Check if the line break needs to be conserved
26028 (cond
26029 ((string-match "\\\\\\\\[ \t]*$" line)
26030 (setq line (replace-match "<br/>" t t line)))
26031 (org-export-preserve-breaks
26032 (setq line (concat line "<br/>"))))
26033
26034 (insert line "\n")))))
26035
26036 ;; Properly close all local lists and other lists
26037 (when inquote (insert "</pre>\n"))
26038 (when in-local-list
26039 ;; Close any local lists before inserting a new header line
26040 (while local-list-num
26041 (org-close-li)
26042 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
26043 (pop local-list-num))
26044 (setq local-list-indent nil
26045 in-local-list nil))
26046 (org-html-level-start 1 nil umax
26047 (and org-export-with-toc (<= level umax))
26048 head-count)
26049
26050 (unless body-only
26051 (when (plist-get opt-plist :auto-postamble)
26052 (insert "<div id=\"postamble\">")
26053 (when (and org-export-author-info author)
26054 (insert "<p class=\"author\"> "
26055 (nth 1 lang-words) ": " author "\n")
26056 (when email
26057 (if (listp (split-string email ",+ *"))
26058 (mapc (lambda(e)
26059 (insert "<a href=\"mailto:" e "\">&lt;"
26060 e "&gt;</a>\n"))
26061 (split-string email ",+ *"))
26062 (insert "<a href=\"mailto:" email "\">&lt;"
26063 email "&gt;</a>\n")))
26064 (insert "</p>\n"))
26065 (when (and date org-export-time-stamp-file)
26066 (insert "<p class=\"date\"> "
26067 (nth 2 lang-words) ": "
26068 date "</p>\n"))
26069 (insert "</div>"))
26070
26071 (if org-export-html-with-timestamp
26072 (insert org-export-html-html-helper-timestamp))
26073 (insert (or (plist-get opt-plist :postamble) ""))
26074 (insert "</body>\n</html>\n"))
26075
26076 (normal-mode)
26077 (if (eq major-mode default-major-mode) (html-mode))
26078
26079 ;; insert the table of contents
26080 (goto-char (point-min))
26081 (when thetoc
26082 (if (or (re-search-forward
26083 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
26084 (re-search-forward
26085 "\\[TABLE-OF-CONTENTS\\]" nil t))
26086 (progn
26087 (goto-char (match-beginning 0))
26088 (replace-match ""))
26089 (goto-char first-heading-pos)
26090 (when (looking-at "\\s-*</p>")
26091 (goto-char (match-end 0))
26092 (insert "\n")))
26093 (insert "<div id=\"table-of-contents\">\n")
26094 (mapc 'insert thetoc)
26095 (insert "</div>\n"))
26096 ;; remove empty paragraphs and lists
26097 (goto-char (point-min))
26098 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
26099 (replace-match ""))
26100 (goto-char (point-min))
26101 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
26102 (replace-match ""))
26103 (goto-char (point-min))
26104 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
26105 (replace-match ""))
26106 ;; Convert whitespace place holders
26107 (goto-char (point-min))
26108 (let (beg end n)
26109 (while (setq beg (next-single-property-change (point) 'org-whitespace))
26110 (setq n (get-text-property beg 'org-whitespace)
26111 end (next-single-property-change beg 'org-whitespace))
26112 (goto-char beg)
26113 (delete-region beg end)
26114 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
26115 (make-string n ?x)))))
26116 (or to-buffer (save-buffer))
26117 (goto-char (point-min))
26118 (message "Exporting... done")
26119 (if (eq to-buffer 'string)
26120 (prog1 (buffer-substring (point-min) (point-max))
26121 (kill-buffer (current-buffer)))
26122 (current-buffer)))))
26123
26124 (defvar org-table-colgroup-info nil)
26125 (defun org-format-table-ascii (lines)
26126 "Format a table for ascii export."
26127 (if (stringp lines)
26128 (setq lines (org-split-string lines "\n")))
26129 (if (not (string-match "^[ \t]*|" (car lines)))
26130 ;; Table made by table.el - test for spanning
26131 lines
26132
26133 ;; A normal org table
26134 ;; Get rid of hlines at beginning and end
26135 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26136 (setq lines (nreverse lines))
26137 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26138 (setq lines (nreverse lines))
26139 (when org-export-table-remove-special-lines
26140 ;; Check if the table has a marking column. If yes remove the
26141 ;; column and the special lines
26142 (setq lines (org-table-clean-before-export lines)))
26143 ;; Get rid of the vertical lines except for grouping
26144 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
26145 rtn line vl1 start)
26146 (while (setq line (pop lines))
26147 (if (string-match org-table-hline-regexp line)
26148 (and (string-match "|\\(.*\\)|" line)
26149 (setq line (replace-match " \\1" t nil line)))
26150 (setq start 0 vl1 vl)
26151 (while (string-match "|" line start)
26152 (setq start (match-end 0))
26153 (or (pop vl1) (setq line (replace-match " " t t line)))))
26154 (push line rtn))
26155 (nreverse rtn))))
26156
26157 (defun org-colgroup-info-to-vline-list (info)
26158 (let (vl new last)
26159 (while info
26160 (setq last new new (pop info))
26161 (if (or (memq last '(:end :startend))
26162 (memq new '(:start :startend)))
26163 (push t vl)
26164 (push nil vl)))
26165 (setq vl (nreverse vl))
26166 (and vl (setcar vl nil))
26167 vl))
26168
26169 (defun org-format-table-html (lines olines)
26170 "Find out which HTML converter to use and return the HTML code."
26171 (if (stringp lines)
26172 (setq lines (org-split-string lines "\n")))
26173 (if (string-match "^[ \t]*|" (car lines))
26174 ;; A normal org table
26175 (org-format-org-table-html lines)
26176 ;; Table made by table.el - test for spanning
26177 (let* ((hlines (delq nil (mapcar
26178 (lambda (x)
26179 (if (string-match "^[ \t]*\\+-" x) x
26180 nil))
26181 lines)))
26182 (first (car hlines))
26183 (ll (and (string-match "\\S-+" first)
26184 (match-string 0 first)))
26185 (re (concat "^[ \t]*" (regexp-quote ll)))
26186 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
26187 hlines))))
26188 (if (and (not spanning)
26189 (not org-export-prefer-native-exporter-for-tables))
26190 ;; We can use my own converter with HTML conversions
26191 (org-format-table-table-html lines)
26192 ;; Need to use the code generator in table.el, with the original text.
26193 (org-format-table-table-html-using-table-generate-source olines)))))
26194
26195 (defun org-format-org-table-html (lines &optional splice)
26196 "Format a table into HTML."
26197 ;; Get rid of hlines at beginning and end
26198 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26199 (setq lines (nreverse lines))
26200 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26201 (setq lines (nreverse lines))
26202 (when org-export-table-remove-special-lines
26203 ;; Check if the table has a marking column. If yes remove the
26204 ;; column and the special lines
26205 (setq lines (org-table-clean-before-export lines)))
26206
26207 (let ((head (and org-export-highlight-first-table-line
26208 (delq nil (mapcar
26209 (lambda (x) (string-match "^[ \t]*|-" x))
26210 (cdr lines)))))
26211 (nlines 0) fnum i
26212 tbopen line fields html gr colgropen)
26213 (if splice (setq head nil))
26214 (unless splice (push (if head "<thead>" "<tbody>") html))
26215 (setq tbopen t)
26216 (while (setq line (pop lines))
26217 (catch 'next-line
26218 (if (string-match "^[ \t]*|-" line)
26219 (progn
26220 (unless splice
26221 (push (if head "</thead>" "</tbody>") html)
26222 (if lines (push "<tbody>" html) (setq tbopen nil)))
26223 (setq head nil) ;; head ends here, first time around
26224 ;; ignore this line
26225 (throw 'next-line t)))
26226 ;; Break the line into fields
26227 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26228 (unless fnum (setq fnum (make-vector (length fields) 0)))
26229 (setq nlines (1+ nlines) i -1)
26230 (push (concat "<tr>"
26231 (mapconcat
26232 (lambda (x)
26233 (setq i (1+ i))
26234 (if (and (< i nlines)
26235 (string-match org-table-number-regexp x))
26236 (incf (aref fnum i)))
26237 (if head
26238 (concat (car org-export-table-header-tags) x
26239 (cdr org-export-table-header-tags))
26240 (concat (car org-export-table-data-tags) x
26241 (cdr org-export-table-data-tags))))
26242 fields "")
26243 "</tr>")
26244 html)))
26245 (unless splice (if tbopen (push "</tbody>" html)))
26246 (unless splice (push "</table>\n" html))
26247 (setq html (nreverse html))
26248 (unless splice
26249 ;; Put in col tags with the alignment (unfortuntely often ignored...)
26250 (push (mapconcat
26251 (lambda (x)
26252 (setq gr (pop org-table-colgroup-info))
26253 (format "%s<col align=\"%s\"></col>%s"
26254 (if (memq gr '(:start :startend))
26255 (prog1
26256 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
26257 (setq colgropen t))
26258 "")
26259 (if (> (/ (float x) nlines) org-table-number-fraction)
26260 "right" "left")
26261 (if (memq gr '(:end :startend))
26262 (progn (setq colgropen nil) "</colgroup>")
26263 "")))
26264 fnum "")
26265 html)
26266 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
26267 (push html-table-tag html))
26268 (concat (mapconcat 'identity html "\n") "\n")))
26269
26270 (defun org-table-clean-before-export (lines)
26271 "Check if the table has a marking column.
26272 If yes remove the column and the special lines."
26273 (setq org-table-colgroup-info nil)
26274 (if (memq nil
26275 (mapcar
26276 (lambda (x) (or (string-match "^[ \t]*|-" x)
26277 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
26278 lines))
26279 (progn
26280 (setq org-table-clean-did-remove-column nil)
26281 (delq nil
26282 (mapcar
26283 (lambda (x)
26284 (cond
26285 ((string-match "^[ \t]*| */ *|" x)
26286 (setq org-table-colgroup-info
26287 (mapcar (lambda (x)
26288 (cond ((member x '("<" "&lt;")) :start)
26289 ((member x '(">" "&gt;")) :end)
26290 ((member x '("<>" "&lt;&gt;")) :startend)
26291 (t nil)))
26292 (org-split-string x "[ \t]*|[ \t]*")))
26293 nil)
26294 (t x)))
26295 lines)))
26296 (setq org-table-clean-did-remove-column t)
26297 (delq nil
26298 (mapcar
26299 (lambda (x)
26300 (cond
26301 ((string-match "^[ \t]*| */ *|" x)
26302 (setq org-table-colgroup-info
26303 (mapcar (lambda (x)
26304 (cond ((member x '("<" "&lt;")) :start)
26305 ((member x '(">" "&gt;")) :end)
26306 ((member x '("<>" "&lt;&gt;")) :startend)
26307 (t nil)))
26308 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
26309 nil)
26310 ((string-match "^[ \t]*| *[!_^/] *|" x)
26311 nil) ; ignore this line
26312 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
26313 (string-match "^\\([ \t]*\\)|[^|]*|" x))
26314 ;; remove the first column
26315 (replace-match "\\1|" t nil x))))
26316 lines))))
26317
26318 (defun org-format-table-table-html (lines)
26319 "Format a table generated by table.el into HTML.
26320 This conversion does *not* use `table-generate-source' from table.el.
26321 This has the advantage that Org-mode's HTML conversions can be used.
26322 But it has the disadvantage, that no cell- or row-spanning is allowed."
26323 (let (line field-buffer
26324 (head org-export-highlight-first-table-line)
26325 fields html empty)
26326 (setq html (concat html-table-tag "\n"))
26327 (while (setq line (pop lines))
26328 (setq empty "&nbsp;")
26329 (catch 'next-line
26330 (if (string-match "^[ \t]*\\+-" line)
26331 (progn
26332 (if field-buffer
26333 (progn
26334 (setq
26335 html
26336 (concat
26337 html
26338 "<tr>"
26339 (mapconcat
26340 (lambda (x)
26341 (if (equal x "") (setq x empty))
26342 (if head
26343 (concat (car org-export-table-header-tags) x
26344 (cdr org-export-table-header-tags))
26345 (concat (car org-export-table-data-tags) x
26346 (cdr org-export-table-data-tags))))
26347 field-buffer "\n")
26348 "</tr>\n"))
26349 (setq head nil)
26350 (setq field-buffer nil)))
26351 ;; Ignore this line
26352 (throw 'next-line t)))
26353 ;; Break the line into fields and store the fields
26354 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26355 (if field-buffer
26356 (setq field-buffer (mapcar
26357 (lambda (x)
26358 (concat x "<br/>" (pop fields)))
26359 field-buffer))
26360 (setq field-buffer fields))))
26361 (setq html (concat html "</table>\n"))
26362 html))
26363
26364 (defun org-format-table-table-html-using-table-generate-source (lines)
26365 "Format a table into html, using `table-generate-source' from table.el.
26366 This has the advantage that cell- or row-spanning is allowed.
26367 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
26368 (require 'table)
26369 (with-current-buffer (get-buffer-create " org-tmp1 ")
26370 (erase-buffer)
26371 (insert (mapconcat 'identity lines "\n"))
26372 (goto-char (point-min))
26373 (if (not (re-search-forward "|[^+]" nil t))
26374 (error "Error processing table"))
26375 (table-recognize-table)
26376 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
26377 (table-generate-source 'html " org-tmp2 ")
26378 (set-buffer " org-tmp2 ")
26379 (buffer-substring (point-min) (point-max))))
26380
26381 (defun org-html-handle-time-stamps (s)
26382 "Format time stamps in string S, or remove them."
26383 (catch 'exit
26384 (let (r b)
26385 (while (string-match org-maybe-keyword-time-regexp s)
26386 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
26387 ;; never export CLOCK
26388 (throw 'exit ""))
26389 (or b (setq b (substring s 0 (match-beginning 0))))
26390 (if (not org-export-with-timestamps)
26391 (setq r (concat r (substring s 0 (match-beginning 0)))
26392 s (substring s (match-end 0)))
26393 (setq r (concat
26394 r (substring s 0 (match-beginning 0))
26395 (if (match-end 1)
26396 (format "@<span class=\"timestamp-kwd\">%s @</span>"
26397 (match-string 1 s)))
26398 (format " @<span class=\"timestamp\">%s@</span>"
26399 (substring
26400 (org-translate-time (match-string 3 s)) 1 -1)))
26401 s (substring s (match-end 0)))))
26402 ;; Line break if line started and ended with time stamp stuff
26403 (if (not r)
26404 s
26405 (setq r (concat r s))
26406 (unless (string-match "\\S-" (concat b s))
26407 (setq r (concat r "@<br/>")))
26408 r))))
26409
26410 (defun org-html-protect (s)
26411 ;; convert & to &amp;, < to &lt; and > to &gt;
26412 (let ((start 0))
26413 (while (string-match "&" s start)
26414 (setq s (replace-match "&amp;" t t s)
26415 start (1+ (match-beginning 0))))
26416 (while (string-match "<" s)
26417 (setq s (replace-match "&lt;" t t s)))
26418 (while (string-match ">" s)
26419 (setq s (replace-match "&gt;" t t s))))
26420 s)
26421
26422 (defun org-export-cleanup-toc-line (s)
26423 "Remove tags and time staps from lines going into the toc."
26424 (when (memq org-export-with-tags '(not-in-toc nil))
26425 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
26426 (setq s (replace-match "" t t s))))
26427 (when org-export-remove-timestamps-from-toc
26428 (while (string-match org-maybe-keyword-time-regexp s)
26429 (setq s (replace-match "" t t s))))
26430 (while (string-match org-bracket-link-regexp s)
26431 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
26432 t t s)))
26433 s)
26434
26435 (defun org-html-expand (string)
26436 "Prepare STRING for HTML export. Applies all active conversions.
26437 If there are links in the string, don't modify these."
26438 (let* ((re (concat org-bracket-link-regexp "\\|"
26439 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
26440 m s l res)
26441 (while (setq m (string-match re string))
26442 (setq s (substring string 0 m)
26443 l (match-string 0 string)
26444 string (substring string (match-end 0)))
26445 (push (org-html-do-expand s) res)
26446 (push l res))
26447 (push (org-html-do-expand string) res)
26448 (apply 'concat (nreverse res))))
26449
26450 (defun org-html-do-expand (s)
26451 "Apply all active conversions to translate special ASCII to HTML."
26452 (setq s (org-html-protect s))
26453 (if org-export-html-expand
26454 (let ((start 0))
26455 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
26456 (setq s (replace-match "<\\1>" t nil s)))))
26457 (if org-export-with-emphasize
26458 (setq s (org-export-html-convert-emphasize s)))
26459 (if org-export-with-special-strings
26460 (setq s (org-export-html-convert-special-strings s)))
26461 (if org-export-with-sub-superscripts
26462 (setq s (org-export-html-convert-sub-super s)))
26463 (if org-export-with-TeX-macros
26464 (let ((start 0) wd ass)
26465 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26466 (if (get-text-property (match-beginning 0) 'org-protected s)
26467 (setq start (match-end 0))
26468 (setq wd (match-string 1 s))
26469 (if (setq ass (assoc wd org-html-entities))
26470 (setq s (replace-match (or (cdr ass)
26471 (concat "&" (car ass) ";"))
26472 t t s))
26473 (setq start (+ start (length wd))))))))
26474 s)
26475
26476 (defun org-create-multibrace-regexp (left right n)
26477 "Create a regular expression which will match a balanced sexp.
26478 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26479 as single character strings.
26480 The regexp returned will match the entire expression including the
26481 delimiters. It will also define a single group which contains the
26482 match except for the outermost delimiters. The maximum depth of
26483 stacked delimiters is N. Escaping delimiters is not possible."
26484 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26485 (or "\\|")
26486 (re nothing)
26487 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26488 (while (> n 1)
26489 (setq n (1- n)
26490 re (concat re or next)
26491 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26492 (concat left "\\(" re "\\)" right)))
26493
26494 (defvar org-match-substring-regexp
26495 (concat
26496 "\\([^\\]\\)\\([_^]\\)\\("
26497 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26498 "\\|"
26499 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26500 "\\|"
26501 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26502 "The regular expression matching a sub- or superscript.")
26503
26504 (defvar org-match-substring-with-braces-regexp
26505 (concat
26506 "\\([^\\]\\)\\([_^]\\)\\("
26507 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26508 "\\)")
26509 "The regular expression matching a sub- or superscript, forcing braces.")
26510
26511 (defconst org-export-html-special-string-regexps
26512 '(("\\\\-" . "&shy;")
26513 ("---\\([^-]\\)" . "&mdash;\\1")
26514 ("--\\([^-]\\)" . "&ndash;\\1")
26515 ("\\.\\.\\." . "&hellip;"))
26516 "Regular expressions for special string conversion.")
26517
26518 (defun org-export-html-convert-special-strings (string)
26519 "Convert special characters in STRING to HTML."
26520 (let ((all org-export-html-special-string-regexps)
26521 e a re rpl start)
26522 (while (setq a (pop all))
26523 (setq re (car a) rpl (cdr a) start 0)
26524 (while (string-match re string start)
26525 (if (get-text-property (match-beginning 0) 'org-protected string)
26526 (setq start (match-end 0))
26527 (setq string (replace-match rpl t nil string)))))
26528 string))
26529
26530 (defun org-export-html-convert-sub-super (string)
26531 "Convert sub- and superscripts in STRING to HTML."
26532 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26533 (while (string-match org-match-substring-regexp string s)
26534 (cond
26535 ((and requireb (match-end 8)) (setq s (match-end 2)))
26536 ((get-text-property (match-beginning 2) 'org-protected string)
26537 (setq s (match-end 2)))
26538 (t
26539 (setq s (match-end 1)
26540 key (if (string= (match-string 2 string) "_") "sub" "sup")
26541 c (or (match-string 8 string)
26542 (match-string 6 string)
26543 (match-string 5 string))
26544 string (replace-match
26545 (concat (match-string 1 string)
26546 "<" key ">" c "</" key ">")
26547 t t string)))))
26548 (while (string-match "\\\\\\([_^]\\)" string)
26549 (setq string (replace-match (match-string 1 string) t t string)))
26550 string))
26551
26552 (defun org-export-html-convert-emphasize (string)
26553 "Apply emphasis."
26554 (let ((s 0) rpl)
26555 (while (string-match org-emph-re string s)
26556 (if (not (equal
26557 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26558 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26559 (setq s (match-beginning 0)
26560 rpl
26561 (concat
26562 (match-string 1 string)
26563 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26564 (match-string 4 string)
26565 (nth 3 (assoc (match-string 3 string)
26566 org-emphasis-alist))
26567 (match-string 5 string))
26568 string (replace-match rpl t t string)
26569 s (+ s (- (length rpl) 2)))
26570 (setq s (1+ s))))
26571 string))
26572
26573 (defvar org-par-open nil)
26574 (defun org-open-par ()
26575 "Insert <p>, but first close previous paragraph if any."
26576 (org-close-par-maybe)
26577 (insert "\n<p>")
26578 (setq org-par-open t))
26579 (defun org-close-par-maybe ()
26580 "Close paragraph if there is one open."
26581 (when org-par-open
26582 (insert "</p>")
26583 (setq org-par-open nil)))
26584 (defun org-close-li ()
26585 "Close <li> if necessary."
26586 (org-close-par-maybe)
26587 (insert "</li>\n"))
26588
26589 (defvar body-only) ; dynamically scoped into this.
26590 (defun org-html-level-start (level title umax with-toc head-count)
26591 "Insert a new level in HTML export.
26592 When TITLE is nil, just close all open levels."
26593 (org-close-par-maybe)
26594 (let ((l org-level-max))
26595 (while (>= l level)
26596 (if (aref org-levels-open (1- l))
26597 (progn
26598 (org-html-level-close l umax)
26599 (aset org-levels-open (1- l) nil)))
26600 (setq l (1- l)))
26601 (when title
26602 ;; If title is nil, this means this function is called to close
26603 ;; all levels, so the rest is done only if title is given
26604 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26605 (setq title (replace-match
26606 (if org-export-with-tags
26607 (save-match-data
26608 (concat
26609 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26610 (mapconcat 'identity (org-split-string
26611 (match-string 1 title) ":")
26612 "&nbsp;")
26613 "</span>"))
26614 "")
26615 t t title)))
26616 (if (> level umax)
26617 (progn
26618 (if (aref org-levels-open (1- level))
26619 (progn
26620 (org-close-li)
26621 (insert "<li>" title "<br/>\n"))
26622 (aset org-levels-open (1- level) t)
26623 (org-close-par-maybe)
26624 (insert "<ul>\n<li>" title "<br/>\n")))
26625 (aset org-levels-open (1- level) t)
26626 (if (and org-export-with-section-numbers (not body-only))
26627 (setq title (concat (org-section-number level) " " title)))
26628 (setq level (+ level org-export-html-toplevel-hlevel -1))
26629 (if with-toc
26630 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26631 level level head-count title level))
26632 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26633 (org-open-par)))))
26634
26635 (defun org-html-level-close (level max-outline-level)
26636 "Terminate one level in HTML export."
26637 (if (<= level max-outline-level)
26638 (insert "</div>\n")
26639 (org-close-li)
26640 (insert "</ul>\n")))
26641
26642 ;;; iCalendar export
26643
26644 ;;;###autoload
26645 (defun org-export-icalendar-this-file ()
26646 "Export current file as an iCalendar file.
26647 The iCalendar file will be located in the same directory as the Org-mode
26648 file, but with extension `.ics'."
26649 (interactive)
26650 (org-export-icalendar nil buffer-file-name))
26651
26652 ;;;###autoload
26653 (defun org-export-icalendar-all-agenda-files ()
26654 "Export all files in `org-agenda-files' to iCalendar .ics files.
26655 Each iCalendar file will be located in the same directory as the Org-mode
26656 file, but with extension `.ics'."
26657 (interactive)
26658 (apply 'org-export-icalendar nil (org-agenda-files t)))
26659
26660 ;;;###autoload
26661 (defun org-export-icalendar-combine-agenda-files ()
26662 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26663 The file is stored under the name `org-combined-agenda-icalendar-file'."
26664 (interactive)
26665 (apply 'org-export-icalendar t (org-agenda-files t)))
26666
26667 (defun org-export-icalendar (combine &rest files)
26668 "Create iCalendar files for all elements of FILES.
26669 If COMBINE is non-nil, combine all calendar entries into a single large
26670 file and store it under the name `org-combined-agenda-icalendar-file'."
26671 (save-excursion
26672 (org-prepare-agenda-buffers files)
26673 (let* ((dir (org-export-directory
26674 :ical (list :publishing-directory
26675 org-export-publishing-directory)))
26676 file ical-file ical-buffer category started org-agenda-new-buffers)
26677 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26678 (when combine
26679 (setq ical-file
26680 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26681 org-combined-agenda-icalendar-file
26682 (expand-file-name org-combined-agenda-icalendar-file dir))
26683 ical-buffer (org-get-agenda-file-buffer ical-file))
26684 (set-buffer ical-buffer) (erase-buffer))
26685 (while (setq file (pop files))
26686 (catch 'nextfile
26687 (org-check-agenda-file file)
26688 (set-buffer (org-get-agenda-file-buffer file))
26689 (unless combine
26690 (setq ical-file (concat (file-name-as-directory dir)
26691 (file-name-sans-extension
26692 (file-name-nondirectory buffer-file-name))
26693 ".ics"))
26694 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26695 (with-current-buffer ical-buffer (erase-buffer)))
26696 (setq category (or org-category
26697 (file-name-sans-extension
26698 (file-name-nondirectory buffer-file-name))))
26699 (if (symbolp category) (setq category (symbol-name category)))
26700 (let ((standard-output ical-buffer))
26701 (if combine
26702 (and (not started) (setq started t)
26703 (org-start-icalendar-file org-icalendar-combined-name))
26704 (org-start-icalendar-file category))
26705 (org-print-icalendar-entries combine)
26706 (when (or (and combine (not files)) (not combine))
26707 (org-finish-icalendar-file)
26708 (set-buffer ical-buffer)
26709 (save-buffer)
26710 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26711 (org-release-buffers org-agenda-new-buffers))))
26712
26713 (defvar org-after-save-iCalendar-file-hook nil
26714 "Hook run after an iCalendar file has been saved.
26715 The iCalendar buffer is still current when this hook is run.
26716 A good way to use this is to tell a desktop calenndar application to re-read
26717 the iCalendar file.")
26718
26719 (defun org-print-icalendar-entries (&optional combine)
26720 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26721 When COMBINE is non nil, add the category to each line."
26722 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26723 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26724 (dts (org-ical-ts-to-string
26725 (format-time-string (cdr org-time-stamp-formats) (current-time))
26726 "DTSTART"))
26727 hd ts ts2 state status (inc t) pos b sexp rrule
26728 scheduledp deadlinep tmp pri category entry location summary desc
26729 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26730 (org-refresh-category-properties)
26731 (save-excursion
26732 (goto-char (point-min))
26733 (while (re-search-forward re1 nil t)
26734 (catch :skip
26735 (org-agenda-skip)
26736 (when (boundp 'org-icalendar-verify-function)
26737 (unless (funcall org-icalendar-verify-function)
26738 (outline-next-heading)
26739 (backward-char 1)
26740 (throw :skip nil)))
26741 (setq pos (match-beginning 0)
26742 ts (match-string 0)
26743 inc t
26744 hd (org-get-heading)
26745 summary (org-icalendar-cleanup-string
26746 (org-entry-get nil "SUMMARY"))
26747 desc (org-icalendar-cleanup-string
26748 (or (org-entry-get nil "DESCRIPTION")
26749 (and org-icalendar-include-body (org-get-entry)))
26750 t org-icalendar-include-body)
26751 location (org-icalendar-cleanup-string
26752 (org-entry-get nil "LOCATION"))
26753 category (org-get-category))
26754 (if (looking-at re2)
26755 (progn
26756 (goto-char (match-end 0))
26757 (setq ts2 (match-string 1) inc nil))
26758 (setq tmp (buffer-substring (max (point-min)
26759 (- pos org-ds-keyword-length))
26760 pos)
26761 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26762 (progn
26763 (setq inc nil)
26764 (replace-match "\\1" t nil ts))
26765 ts)
26766 deadlinep (string-match org-deadline-regexp tmp)
26767 scheduledp (string-match org-scheduled-regexp tmp)
26768 ;; donep (org-entry-is-done-p)
26769 ))
26770 (if (or (string-match org-tr-regexp hd)
26771 (string-match org-ts-regexp hd))
26772 (setq hd (replace-match "" t t hd)))
26773 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26774 (setq rrule
26775 (concat "\nRRULE:FREQ="
26776 (cdr (assoc
26777 (match-string 2 ts)
26778 '(("d" . "DAILY")("w" . "WEEKLY")
26779 ("m" . "MONTHLY")("y" . "YEARLY"))))
26780 ";INTERVAL=" (match-string 1 ts)))
26781 (setq rrule ""))
26782 (setq summary (or summary hd))
26783 (if (string-match org-bracket-link-regexp summary)
26784 (setq summary
26785 (replace-match (if (match-end 3)
26786 (match-string 3 summary)
26787 (match-string 1 summary))
26788 t t summary)))
26789 (if deadlinep (setq summary (concat "DL: " summary)))
26790 (if scheduledp (setq summary (concat "S: " summary)))
26791 (if (string-match "\\`<%%" ts)
26792 (with-current-buffer sexp-buffer
26793 (insert (substring ts 1 -1) " " summary "\n"))
26794 (princ (format "BEGIN:VEVENT
26795 %s
26796 %s%s
26797 SUMMARY:%s%s%s
26798 CATEGORIES:%s
26799 END:VEVENT\n"
26800 (org-ical-ts-to-string ts "DTSTART")
26801 (org-ical-ts-to-string ts2 "DTEND" inc)
26802 rrule summary
26803 (if (and desc (string-match "\\S-" desc))
26804 (concat "\nDESCRIPTION: " desc) "")
26805 (if (and location (string-match "\\S-" location))
26806 (concat "\nLOCATION: " location) "")
26807 category)))))
26808
26809 (when (and org-icalendar-include-sexps
26810 (condition-case nil (require 'icalendar) (error nil))
26811 (fboundp 'icalendar-export-region))
26812 ;; Get all the literal sexps
26813 (goto-char (point-min))
26814 (while (re-search-forward "^&?%%(" nil t)
26815 (catch :skip
26816 (org-agenda-skip)
26817 (setq b (match-beginning 0))
26818 (goto-char (1- (match-end 0)))
26819 (forward-sexp 1)
26820 (end-of-line 1)
26821 (setq sexp (buffer-substring b (point)))
26822 (with-current-buffer sexp-buffer
26823 (insert sexp "\n"))
26824 (princ (org-diary-to-ical-string sexp-buffer)))))
26825
26826 (when org-icalendar-include-todo
26827 (goto-char (point-min))
26828 (while (re-search-forward org-todo-line-regexp nil t)
26829 (catch :skip
26830 (org-agenda-skip)
26831 (when (boundp 'org-icalendar-verify-function)
26832 (unless (funcall org-icalendar-verify-function)
26833 (outline-next-heading)
26834 (backward-char 1)
26835 (throw :skip nil)))
26836 (setq state (match-string 2))
26837 (setq status (if (member state org-done-keywords)
26838 "COMPLETED" "NEEDS-ACTION"))
26839 (when (and state
26840 (or (not (member state org-done-keywords))
26841 (eq org-icalendar-include-todo 'all))
26842 (not (member org-archive-tag (org-get-tags-at)))
26843 )
26844 (setq hd (match-string 3)
26845 summary (org-icalendar-cleanup-string
26846 (org-entry-get nil "SUMMARY"))
26847 desc (org-icalendar-cleanup-string
26848 (or (org-entry-get nil "DESCRIPTION")
26849 (and org-icalendar-include-body (org-get-entry)))
26850 t org-icalendar-include-body)
26851 location (org-icalendar-cleanup-string
26852 (org-entry-get nil "LOCATION")))
26853 (if (string-match org-bracket-link-regexp hd)
26854 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26855 (match-string 1 hd))
26856 t t hd)))
26857 (if (string-match org-priority-regexp hd)
26858 (setq pri (string-to-char (match-string 2 hd))
26859 hd (concat (substring hd 0 (match-beginning 1))
26860 (substring hd (match-end 1))))
26861 (setq pri org-default-priority))
26862 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26863 (- org-lowest-priority org-highest-priority))))))
26864
26865 (princ (format "BEGIN:VTODO
26866 %s
26867 SUMMARY:%s%s%s
26868 CATEGORIES:%s
26869 SEQUENCE:1
26870 PRIORITY:%d
26871 STATUS:%s
26872 END:VTODO\n"
26873 dts
26874 (or summary hd)
26875 (if (and location (string-match "\\S-" location))
26876 (concat "\nLOCATION: " location) "")
26877 (if (and desc (string-match "\\S-" desc))
26878 (concat "\nDESCRIPTION: " desc) "")
26879 category pri status)))))))))
26880
26881 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26882 "Take out stuff and quote what needs to be quoted.
26883 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26884 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26885 characters."
26886 (if (not s)
26887 nil
26888 (when is-body
26889 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26890 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26891 (while (string-match re s) (setq s (replace-match "" t t s)))
26892 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26893 (let ((start 0))
26894 (while (string-match "\\([,;\\]\\)" s start)
26895 (setq start (+ (match-beginning 0) 2)
26896 s (replace-match "\\\\\\1" nil nil s))))
26897 (when is-body
26898 (while (string-match "[ \t]*\n[ \t]*" s)
26899 (setq s (replace-match "\\n" t t s))))
26900 (setq s (org-trim s))
26901 (if is-body
26902 (if maxlength
26903 (if (and (numberp maxlength)
26904 (> (length s) maxlength))
26905 (setq s (substring s 0 maxlength)))))
26906 s))
26907
26908 (defun org-get-entry ()
26909 "Clean-up description string."
26910 (save-excursion
26911 (org-back-to-heading t)
26912 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26913
26914 (defun org-start-icalendar-file (name)
26915 "Start an iCalendar file by inserting the header."
26916 (let ((user user-full-name)
26917 (name (or name "unknown"))
26918 (timezone (cadr (current-time-zone))))
26919 (princ
26920 (format "BEGIN:VCALENDAR
26921 VERSION:2.0
26922 X-WR-CALNAME:%s
26923 PRODID:-//%s//Emacs with Org-mode//EN
26924 X-WR-TIMEZONE:%s
26925 CALSCALE:GREGORIAN\n" name user timezone))))
26926
26927 (defun org-finish-icalendar-file ()
26928 "Finish an iCalendar file by inserting the END statement."
26929 (princ "END:VCALENDAR\n"))
26930
26931 (defun org-ical-ts-to-string (s keyword &optional inc)
26932 "Take a time string S and convert it to iCalendar format.
26933 KEYWORD is added in front, to make a complete line like DTSTART....
26934 When INC is non-nil, increase the hour by two (if time string contains
26935 a time), or the day by one (if it does not contain a time)."
26936 (let ((t1 (org-parse-time-string s 'nodefault))
26937 t2 fmt have-time time)
26938 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26939 (setq t2 t1 have-time t)
26940 (setq t2 (org-parse-time-string s)))
26941 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26942 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26943 (when inc
26944 (if have-time
26945 (if org-agenda-default-appointment-duration
26946 (setq mi (+ org-agenda-default-appointment-duration mi))
26947 (setq h (+ 2 h)))
26948 (setq d (1+ d))))
26949 (setq time (encode-time s mi h d m y)))
26950 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26951 (concat keyword (format-time-string fmt time))))
26952
26953 ;;; XOXO export
26954
26955 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26956 (with-current-buffer buffer
26957 (apply 'insert output)))
26958 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26959
26960 (defun org-export-as-xoxo (&optional buffer)
26961 "Export the org buffer as XOXO.
26962 The XOXO buffer is named *xoxo-<source buffer name>*"
26963 (interactive (list (current-buffer)))
26964 ;; A quickie abstraction
26965
26966 ;; Output everything as XOXO
26967 (with-current-buffer (get-buffer buffer)
26968 (let* ((pos (point))
26969 (opt-plist (org-combine-plists (org-default-export-plist)
26970 (org-infile-export-plist)))
26971 (filename (concat (file-name-as-directory
26972 (org-export-directory :xoxo opt-plist))
26973 (file-name-sans-extension
26974 (file-name-nondirectory buffer-file-name))
26975 ".html"))
26976 (out (find-file-noselect filename))
26977 (last-level 1)
26978 (hanging-li nil))
26979 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26980 ;; Check the output buffer is empty.
26981 (with-current-buffer out (erase-buffer))
26982 ;; Kick off the output
26983 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26984 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26985 (let* ((hd (match-string-no-properties 1))
26986 (level (length hd))
26987 (text (concat
26988 (match-string-no-properties 2)
26989 (save-excursion
26990 (goto-char (match-end 0))
26991 (let ((str ""))
26992 (catch 'loop
26993 (while 't
26994 (forward-line)
26995 (if (looking-at "^[ \t]\\(.*\\)")
26996 (setq str (concat str (match-string-no-properties 1)))
26997 (throw 'loop str)))))))))
26998
26999 ;; Handle level rendering
27000 (cond
27001 ((> level last-level)
27002 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
27003
27004 ((< level last-level)
27005 (dotimes (- (- last-level level) 1)
27006 (if hanging-li
27007 (org-export-as-xoxo-insert-into out "</li>\n"))
27008 (org-export-as-xoxo-insert-into out "</ol>\n"))
27009 (when hanging-li
27010 (org-export-as-xoxo-insert-into out "</li>\n")
27011 (setq hanging-li nil)))
27012
27013 ((equal level last-level)
27014 (if hanging-li
27015 (org-export-as-xoxo-insert-into out "</li>\n")))
27016 )
27017
27018 (setq last-level level)
27019
27020 ;; And output the new li
27021 (setq hanging-li 't)
27022 (if (equal ?+ (elt text 0))
27023 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
27024 (org-export-as-xoxo-insert-into out "<li>" text))))
27025
27026 ;; Finally finish off the ol
27027 (dotimes (- last-level 1)
27028 (if hanging-li
27029 (org-export-as-xoxo-insert-into out "</li>\n"))
27030 (org-export-as-xoxo-insert-into out "</ol>\n"))
27031
27032 (goto-char pos)
27033 ;; Finish the buffer off and clean it up.
27034 (switch-to-buffer-other-window out)
27035 (indent-region (point-min) (point-max) nil)
27036 (save-buffer)
27037 (goto-char (point-min))
27038 )))
27039
27040
27041 ;;;; Key bindings
27042
27043 ;; Make `C-c C-x' a prefix key
27044 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
27045
27046 ;; TAB key with modifiers
27047 (org-defkey org-mode-map "\C-i" 'org-cycle)
27048 (org-defkey org-mode-map [(tab)] 'org-cycle)
27049 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
27050 (org-defkey org-mode-map [(meta tab)] 'org-complete)
27051 (org-defkey org-mode-map "\M-\t" 'org-complete)
27052 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
27053 ;; The following line is necessary under Suse GNU/Linux
27054 (unless (featurep 'xemacs)
27055 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
27056 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
27057 (define-key org-mode-map [backtab] 'org-shifttab)
27058
27059 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
27060 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
27061 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
27062
27063 ;; Cursor keys with modifiers
27064 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
27065 (org-defkey org-mode-map [(meta right)] 'org-metaright)
27066 (org-defkey org-mode-map [(meta up)] 'org-metaup)
27067 (org-defkey org-mode-map [(meta down)] 'org-metadown)
27068
27069 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
27070 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
27071 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
27072 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
27073
27074 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
27075 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
27076 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
27077 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
27078
27079 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
27080 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
27081
27082 ;;; Extra keys for tty access.
27083 ;; We only set them when really needed because otherwise the
27084 ;; menus don't show the simple keys
27085
27086 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
27087 (not window-system))
27088 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
27089 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
27090 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
27091 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
27092 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
27093 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
27094 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
27095 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
27096 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
27097 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
27098 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
27099 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
27100 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
27101 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
27102 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
27103 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
27104 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
27105 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
27106 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
27107 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
27108 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
27109 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
27110
27111 ;; All the other keys
27112
27113 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
27114 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
27115 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
27116 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
27117 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
27118 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
27119 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
27120 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
27121 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
27122 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
27123 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
27124 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
27125 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
27126 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
27127 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
27128 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
27129 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
27130 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
27131 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
27132 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
27133 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
27134 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
27135 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
27136 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
27137 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
27138 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
27139 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
27140 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
27141 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
27142 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
27143 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
27144 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
27145 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
27146 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
27147 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
27148 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
27149 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
27150 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
27151 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
27152 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
27153 (org-defkey org-mode-map "\C-c^" 'org-sort)
27154 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
27155 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
27156 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
27157 (org-defkey org-mode-map "\C-m" 'org-return)
27158 (org-defkey org-mode-map "\C-j" 'org-return-indent)
27159 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
27160 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
27161 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
27162 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
27163 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
27164 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
27165 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
27166 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
27167 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
27168 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
27169 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
27170 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
27171 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
27172 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
27173 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
27174
27175 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
27176 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
27177 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
27178 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
27179
27180 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
27181 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
27182 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
27183 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
27184 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
27185 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
27186 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
27187 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
27188 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
27189 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
27190 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
27191 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
27192
27193 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
27194
27195 (when (featurep 'xemacs)
27196 (org-defkey org-mode-map 'button3 'popup-mode-menu))
27197
27198 (defsubst org-table-p () (org-at-table-p))
27199
27200 (defun org-self-insert-command (N)
27201 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
27202 If the cursor is in a table looking at whitespace, the whitespace is
27203 overwritten, and the table is not marked as requiring realignment."
27204 (interactive "p")
27205 (if (and (org-table-p)
27206 (progn
27207 ;; check if we blank the field, and if that triggers align
27208 (and org-table-auto-blank-field
27209 (member last-command
27210 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
27211 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
27212 ;; got extra space, this field does not determine column width
27213 (let (org-table-may-need-update) (org-table-blank-field))
27214 ;; no extra space, this field may determine column width
27215 (org-table-blank-field)))
27216 t)
27217 (eq N 1)
27218 (looking-at "[^|\n]* |"))
27219 (let (org-table-may-need-update)
27220 (goto-char (1- (match-end 0)))
27221 (delete-backward-char 1)
27222 (goto-char (match-beginning 0))
27223 (self-insert-command N))
27224 (setq org-table-may-need-update t)
27225 (self-insert-command N)
27226 (org-fix-tags-on-the-fly)))
27227
27228 (defun org-fix-tags-on-the-fly ()
27229 (when (and (equal (char-after (point-at-bol)) ?*)
27230 (org-on-heading-p))
27231 (org-align-tags-here org-tags-column)))
27232
27233 (defun org-delete-backward-char (N)
27234 "Like `delete-backward-char', insert whitespace at field end in tables.
27235 When deleting backwards, in tables this function will insert whitespace in
27236 front of the next \"|\" separator, to keep the table aligned. The table will
27237 still be marked for re-alignment if the field did fill the entire column,
27238 because, in this case the deletion might narrow the column."
27239 (interactive "p")
27240 (if (and (org-table-p)
27241 (eq N 1)
27242 (string-match "|" (buffer-substring (point-at-bol) (point)))
27243 (looking-at ".*?|"))
27244 (let ((pos (point))
27245 (noalign (looking-at "[^|\n\r]* |"))
27246 (c org-table-may-need-update))
27247 (backward-delete-char N)
27248 (skip-chars-forward "^|")
27249 (insert " ")
27250 (goto-char (1- pos))
27251 ;; noalign: if there were two spaces at the end, this field
27252 ;; does not determine the width of the column.
27253 (if noalign (setq org-table-may-need-update c)))
27254 (backward-delete-char N)
27255 (org-fix-tags-on-the-fly)))
27256
27257 (defun org-delete-char (N)
27258 "Like `delete-char', but insert whitespace at field end in tables.
27259 When deleting characters, in tables this function will insert whitespace in
27260 front of the next \"|\" separator, to keep the table aligned. The table will
27261 still be marked for re-alignment if the field did fill the entire column,
27262 because, in this case the deletion might narrow the column."
27263 (interactive "p")
27264 (if (and (org-table-p)
27265 (not (bolp))
27266 (not (= (char-after) ?|))
27267 (eq N 1))
27268 (if (looking-at ".*?|")
27269 (let ((pos (point))
27270 (noalign (looking-at "[^|\n\r]* |"))
27271 (c org-table-may-need-update))
27272 (replace-match (concat
27273 (substring (match-string 0) 1 -1)
27274 " |"))
27275 (goto-char pos)
27276 ;; noalign: if there were two spaces at the end, this field
27277 ;; does not determine the width of the column.
27278 (if noalign (setq org-table-may-need-update c)))
27279 (delete-char N))
27280 (delete-char N)
27281 (org-fix-tags-on-the-fly)))
27282
27283 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
27284 (put 'org-self-insert-command 'delete-selection t)
27285 (put 'orgtbl-self-insert-command 'delete-selection t)
27286 (put 'org-delete-char 'delete-selection 'supersede)
27287 (put 'org-delete-backward-char 'delete-selection 'supersede)
27288
27289 ;; Make `flyspell-mode' delay after some commands
27290 (put 'org-self-insert-command 'flyspell-delayed t)
27291 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
27292 (put 'org-delete-char 'flyspell-delayed t)
27293 (put 'org-delete-backward-char 'flyspell-delayed t)
27294
27295 ;; Make pabbrev-mode expand after org-mode commands
27296 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
27297 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
27298
27299 ;; How to do this: Measure non-white length of current string
27300 ;; If equal to column width, we should realign.
27301
27302 (defun org-remap (map &rest commands)
27303 "In MAP, remap the functions given in COMMANDS.
27304 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
27305 (let (new old)
27306 (while commands
27307 (setq old (pop commands) new (pop commands))
27308 (if (fboundp 'command-remapping)
27309 (org-defkey map (vector 'remap old) new)
27310 (substitute-key-definition old new map global-map)))))
27311
27312 (when (eq org-enable-table-editor 'optimized)
27313 ;; If the user wants maximum table support, we need to hijack
27314 ;; some standard editing functions
27315 (org-remap org-mode-map
27316 'self-insert-command 'org-self-insert-command
27317 'delete-char 'org-delete-char
27318 'delete-backward-char 'org-delete-backward-char)
27319 (org-defkey org-mode-map "|" 'org-force-self-insert))
27320
27321 (defun org-shiftcursor-error ()
27322 "Throw an error because Shift-Cursor command was applied in wrong context."
27323 (error "This command is active in special context like tables, headlines or timestamps"))
27324
27325 (defun org-shifttab (&optional arg)
27326 "Global visibility cycling or move to previous table field.
27327 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
27328 on context.
27329 See the individual commands for more information."
27330 (interactive "P")
27331 (cond
27332 ((org-at-table-p) (call-interactively 'org-table-previous-field))
27333 (arg (message "Content view to level: ")
27334 (org-content (prefix-numeric-value arg))
27335 (setq org-cycle-global-status 'overview))
27336 (t (call-interactively 'org-global-cycle))))
27337
27338 (defun org-shiftmetaleft ()
27339 "Promote subtree or delete table column.
27340 Calls `org-promote-subtree', `org-outdent-item',
27341 or `org-table-delete-column', depending on context.
27342 See the individual commands for more information."
27343 (interactive)
27344 (cond
27345 ((org-at-table-p) (call-interactively 'org-table-delete-column))
27346 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
27347 ((org-at-item-p) (call-interactively 'org-outdent-item))
27348 (t (org-shiftcursor-error))))
27349
27350 (defun org-shiftmetaright ()
27351 "Demote subtree or insert table column.
27352 Calls `org-demote-subtree', `org-indent-item',
27353 or `org-table-insert-column', depending on context.
27354 See the individual commands for more information."
27355 (interactive)
27356 (cond
27357 ((org-at-table-p) (call-interactively 'org-table-insert-column))
27358 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
27359 ((org-at-item-p) (call-interactively 'org-indent-item))
27360 (t (org-shiftcursor-error))))
27361
27362 (defun org-shiftmetaup (&optional arg)
27363 "Move subtree up or kill table row.
27364 Calls `org-move-subtree-up' or `org-table-kill-row' or
27365 `org-move-item-up' depending on context. See the individual commands
27366 for more information."
27367 (interactive "P")
27368 (cond
27369 ((org-at-table-p) (call-interactively 'org-table-kill-row))
27370 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27371 ((org-at-item-p) (call-interactively 'org-move-item-up))
27372 (t (org-shiftcursor-error))))
27373 (defun org-shiftmetadown (&optional arg)
27374 "Move subtree down or insert table row.
27375 Calls `org-move-subtree-down' or `org-table-insert-row' or
27376 `org-move-item-down', depending on context. See the individual
27377 commands for more information."
27378 (interactive "P")
27379 (cond
27380 ((org-at-table-p) (call-interactively 'org-table-insert-row))
27381 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27382 ((org-at-item-p) (call-interactively 'org-move-item-down))
27383 (t (org-shiftcursor-error))))
27384
27385 (defun org-metaleft (&optional arg)
27386 "Promote heading or move table column to left.
27387 Calls `org-do-promote' or `org-table-move-column', depending on context.
27388 With no specific context, calls the Emacs default `backward-word'.
27389 See the individual commands for more information."
27390 (interactive "P")
27391 (cond
27392 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
27393 ((or (org-on-heading-p) (org-region-active-p))
27394 (call-interactively 'org-do-promote))
27395 ((org-at-item-p) (call-interactively 'org-outdent-item))
27396 (t (call-interactively 'backward-word))))
27397
27398 (defun org-metaright (&optional arg)
27399 "Demote subtree or move table column to right.
27400 Calls `org-do-demote' or `org-table-move-column', depending on context.
27401 With no specific context, calls the Emacs default `forward-word'.
27402 See the individual commands for more information."
27403 (interactive "P")
27404 (cond
27405 ((org-at-table-p) (call-interactively 'org-table-move-column))
27406 ((or (org-on-heading-p) (org-region-active-p))
27407 (call-interactively 'org-do-demote))
27408 ((org-at-item-p) (call-interactively 'org-indent-item))
27409 (t (call-interactively 'forward-word))))
27410
27411 (defun org-metaup (&optional arg)
27412 "Move subtree up or move table row up.
27413 Calls `org-move-subtree-up' or `org-table-move-row' or
27414 `org-move-item-up', depending on context. See the individual commands
27415 for more information."
27416 (interactive "P")
27417 (cond
27418 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
27419 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27420 ((org-at-item-p) (call-interactively 'org-move-item-up))
27421 (t (transpose-lines 1) (beginning-of-line -1))))
27422
27423 (defun org-metadown (&optional arg)
27424 "Move subtree down or move table row down.
27425 Calls `org-move-subtree-down' or `org-table-move-row' or
27426 `org-move-item-down', depending on context. See the individual
27427 commands for more information."
27428 (interactive "P")
27429 (cond
27430 ((org-at-table-p) (call-interactively 'org-table-move-row))
27431 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27432 ((org-at-item-p) (call-interactively 'org-move-item-down))
27433 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
27434
27435 (defun org-shiftup (&optional arg)
27436 "Increase item in timestamp or increase priority of current headline.
27437 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
27438 depending on context. See the individual commands for more information."
27439 (interactive "P")
27440 (cond
27441 ((org-at-timestamp-p t)
27442 (call-interactively (if org-edit-timestamp-down-means-later
27443 'org-timestamp-down 'org-timestamp-up)))
27444 ((org-on-heading-p) (call-interactively 'org-priority-up))
27445 ((org-at-item-p) (call-interactively 'org-previous-item))
27446 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
27447
27448 (defun org-shiftdown (&optional arg)
27449 "Decrease item in timestamp or decrease priority of current headline.
27450 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
27451 depending on context. See the individual commands for more information."
27452 (interactive "P")
27453 (cond
27454 ((org-at-timestamp-p t)
27455 (call-interactively (if org-edit-timestamp-down-means-later
27456 'org-timestamp-up 'org-timestamp-down)))
27457 ((org-on-heading-p) (call-interactively 'org-priority-down))
27458 (t (call-interactively 'org-next-item))))
27459
27460 (defun org-shiftright ()
27461 "Next TODO keyword or timestamp one day later, depending on context."
27462 (interactive)
27463 (cond
27464 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
27465 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
27466 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
27467 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
27468 (t (org-shiftcursor-error))))
27469
27470 (defun org-shiftleft ()
27471 "Previous TODO keyword or timestamp one day earlier, depending on context."
27472 (interactive)
27473 (cond
27474 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27475 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27476 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27477 ((org-at-property-p)
27478 (call-interactively 'org-property-previous-allowed-value))
27479 (t (org-shiftcursor-error))))
27480
27481 (defun org-shiftcontrolright ()
27482 "Switch to next TODO set."
27483 (interactive)
27484 (cond
27485 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27486 (t (org-shiftcursor-error))))
27487
27488 (defun org-shiftcontrolleft ()
27489 "Switch to previous TODO set."
27490 (interactive)
27491 (cond
27492 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27493 (t (org-shiftcursor-error))))
27494
27495 (defun org-ctrl-c-ret ()
27496 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27497 (interactive)
27498 (cond
27499 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27500 (t (call-interactively 'org-insert-heading))))
27501
27502 (defun org-copy-special ()
27503 "Copy region in table or copy current subtree.
27504 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27505 See the individual commands for more information."
27506 (interactive)
27507 (call-interactively
27508 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27509
27510 (defun org-cut-special ()
27511 "Cut region in table or cut current subtree.
27512 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27513 See the individual commands for more information."
27514 (interactive)
27515 (call-interactively
27516 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27517
27518 (defun org-paste-special (arg)
27519 "Paste rectangular region into table, or past subtree relative to level.
27520 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27521 See the individual commands for more information."
27522 (interactive "P")
27523 (if (org-at-table-p)
27524 (org-table-paste-rectangle)
27525 (org-paste-subtree arg)))
27526
27527 (defun org-ctrl-c-ctrl-c (&optional arg)
27528 "Set tags in headline, or update according to changed information at point.
27529
27530 This command does many different things, depending on context:
27531
27532 - If the cursor is in a headline, prompt for tags and insert them
27533 into the current line, aligned to `org-tags-column'. When called
27534 with prefix arg, realign all tags in the current buffer.
27535
27536 - If the cursor is in one of the special #+KEYWORD lines, this
27537 triggers scanning the buffer for these lines and updating the
27538 information.
27539
27540 - If the cursor is inside a table, realign the table. This command
27541 works even if the automatic table editor has been turned off.
27542
27543 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27544 the entire table.
27545
27546 - If the cursor is a the beginning of a dynamic block, update it.
27547
27548 - If the cursor is inside a table created by the table.el package,
27549 activate that table.
27550
27551 - If the current buffer is a remember buffer, close note and file it.
27552 with a prefix argument, file it without further interaction to the default
27553 location.
27554
27555 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27556 links in this buffer.
27557
27558 - If the cursor is on a numbered item in a plain list, renumber the
27559 ordered list.
27560
27561 - If the cursor is on a checkbox, toggle it."
27562 (interactive "P")
27563 (let ((org-enable-table-editor t))
27564 (cond
27565 ((or org-clock-overlays
27566 org-occur-highlights
27567 org-latex-fragment-image-overlays)
27568 (org-remove-clock-overlays)
27569 (org-remove-occur-highlights)
27570 (org-remove-latex-fragment-image-overlays)
27571 (message "Temporary highlights/overlays removed from current buffer"))
27572 ((and (local-variable-p 'org-finish-function (current-buffer))
27573 (fboundp org-finish-function))
27574 (funcall org-finish-function))
27575 ((org-at-property-p)
27576 (call-interactively 'org-property-action))
27577 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27578 ((org-on-heading-p) (call-interactively 'org-set-tags))
27579 ((org-at-table.el-p)
27580 (require 'table)
27581 (beginning-of-line 1)
27582 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27583 (call-interactively 'table-recognize-table))
27584 ((org-at-table-p)
27585 (org-table-maybe-eval-formula)
27586 (if arg
27587 (call-interactively 'org-table-recalculate)
27588 (org-table-maybe-recalculate-line))
27589 (call-interactively 'org-table-align))
27590 ((org-at-item-checkbox-p)
27591 (call-interactively 'org-toggle-checkbox))
27592 ((org-at-item-p)
27593 (call-interactively 'org-maybe-renumber-ordered-list))
27594 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27595 ;; Dynamic block
27596 (beginning-of-line 1)
27597 (org-update-dblock))
27598 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27599 (cond
27600 ((equal (match-string 1) "TBLFM")
27601 ;; Recalculate the table before this line
27602 (save-excursion
27603 (beginning-of-line 1)
27604 (skip-chars-backward " \r\n\t")
27605 (if (org-at-table-p)
27606 (org-call-with-arg 'org-table-recalculate t))))
27607 (t
27608 (call-interactively 'org-mode-restart))))
27609 (t (error "C-c C-c can do nothing useful at this location.")))))
27610
27611 (defun org-mode-restart ()
27612 "Restart Org-mode, to scan again for special lines.
27613 Also updates the keyword regular expressions."
27614 (interactive)
27615 (let ((org-inhibit-startup t)) (org-mode))
27616 (message "Org-mode restarted to refresh keyword and special line setup"))
27617
27618 (defun org-kill-note-or-show-branches ()
27619 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27620 (interactive)
27621 (if (not org-finish-function)
27622 (call-interactively 'show-branches)
27623 (let ((org-note-abort t))
27624 (funcall org-finish-function))))
27625
27626 (defun org-return (&optional indent)
27627 "Goto next table row or insert a newline.
27628 Calls `org-table-next-row' or `newline', depending on context.
27629 See the individual commands for more information."
27630 (interactive)
27631 (cond
27632 ((bobp) (if indent (newline-and-indent) (newline)))
27633 ((and (org-at-heading-p)
27634 (looking-at
27635 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27636 (org-show-entry)
27637 (end-of-line 1)
27638 (newline))
27639 ((org-at-table-p)
27640 (org-table-justify-field-maybe)
27641 (call-interactively 'org-table-next-row))
27642 (t (if indent (newline-and-indent) (newline)))))
27643
27644 (defun org-return-indent ()
27645 "Goto next table row or insert a newline and indent.
27646 Calls `org-table-next-row' or `newline-and-indent', depending on
27647 context. See the individual commands for more information."
27648 (interactive)
27649 (org-return t))
27650
27651 (defun org-ctrl-c-star ()
27652 "Compute table, or change heading status of lines.
27653 Calls `org-table-recalculate' or `org-toggle-region-headlines',
27654 depending on context. This will also turn a plain list item or a normal
27655 line into a subheading."
27656 (interactive)
27657 (cond
27658 ((org-at-table-p)
27659 (call-interactively 'org-table-recalculate))
27660 ((org-region-active-p)
27661 ;; Convert all lines in region to list items
27662 (call-interactively 'org-toggle-region-headings))
27663 ((org-on-heading-p)
27664 (org-toggle-region-headings (point-at-bol)
27665 (min (1+ (point-at-eol)) (point-max))))
27666 ((org-at-item-p)
27667 ;; Convert to heading
27668 (let ((level (save-match-data
27669 (save-excursion
27670 (condition-case nil
27671 (progn
27672 (org-back-to-heading t)
27673 (funcall outline-level))
27674 (error 0))))))
27675 (replace-match
27676 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
27677 (t (org-toggle-region-headings (point-at-bol)
27678 (min (1+ (point-at-eol)) (point-max))))))
27679
27680 (defun org-ctrl-c-minus ()
27681 "Insert separator line in table or modify bullet status of line.
27682 Also turns a plain line or a region of lines into list items.
27683 Calls `org-table-insert-hline', `org-toggle-region-items', or
27684 `org-cycle-list-bullet', depending on context."
27685 (interactive)
27686 (cond
27687 ((org-at-table-p)
27688 (call-interactively 'org-table-insert-hline))
27689 ((org-on-heading-p)
27690 ;; Convert to item
27691 (save-excursion
27692 (beginning-of-line 1)
27693 (if (looking-at "\\*+ ")
27694 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
27695 ((org-region-active-p)
27696 ;; Convert all lines in region to list items
27697 (call-interactively 'org-toggle-region-items))
27698 ((org-in-item-p)
27699 (call-interactively 'org-cycle-list-bullet))
27700 (t (org-toggle-region-items (point-at-bol)
27701 (min (1+ (point-at-eol)) (point-max))))))
27702
27703 (defun org-toggle-region-items (beg end)
27704 "Convert all lines in region to list items.
27705 If the first line is already an item, convert all list items in the region
27706 to normal lines."
27707 (interactive "r")
27708 (let (l2 l)
27709 (save-excursion
27710 (goto-char end)
27711 (setq l2 (org-current-line))
27712 (goto-char beg)
27713 (beginning-of-line 1)
27714 (setq l (1- (org-current-line)))
27715 (if (org-at-item-p)
27716 ;; We already have items, de-itemize
27717 (while (< (setq l (1+ l)) l2)
27718 (when (org-at-item-p)
27719 (goto-char (match-beginning 2))
27720 (delete-region (match-beginning 2) (match-end 2))
27721 (and (looking-at "[ \t]+") (replace-match "")))
27722 (beginning-of-line 2))
27723 (while (< (setq l (1+ l)) l2)
27724 (unless (org-at-item-p)
27725 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27726 (replace-match "\\1- \\2")))
27727 (beginning-of-line 2))))))
27728
27729 (defun org-toggle-region-headings (beg end)
27730 "Convert all lines in region to list items.
27731 If the first line is already an item, convert all list items in the region
27732 to normal lines."
27733 (interactive "r")
27734 (let (l2 l)
27735 (save-excursion
27736 (goto-char end)
27737 (setq l2 (org-current-line))
27738 (goto-char beg)
27739 (beginning-of-line 1)
27740 (setq l (1- (org-current-line)))
27741 (if (org-on-heading-p)
27742 ;; We already have headlines, de-star them
27743 (while (< (setq l (1+ l)) l2)
27744 (when (org-on-heading-p t)
27745 (and (looking-at outline-regexp) (replace-match "")))
27746 (beginning-of-line 2))
27747 (let* ((stars (save-excursion
27748 (re-search-backward org-complex-heading-regexp nil t)
27749 (or (match-string 1) "*")))
27750 (add-stars (if org-odd-levels-only "**" "*"))
27751 (rpl (concat stars add-stars " \\2")))
27752 (while (< (setq l (1+ l)) l2)
27753 (unless (org-on-heading-p)
27754 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27755 (replace-match rpl)))
27756 (beginning-of-line 2)))))))
27757
27758 (defun org-meta-return (&optional arg)
27759 "Insert a new heading or wrap a region in a table.
27760 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27761 See the individual commands for more information."
27762 (interactive "P")
27763 (cond
27764 ((org-at-table-p)
27765 (call-interactively 'org-table-wrap-region))
27766 (t (call-interactively 'org-insert-heading))))
27767
27768 ;;; Menu entries
27769
27770 ;; Define the Org-mode menus
27771 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27772 '("Tbl"
27773 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27774 ["Next Field" org-cycle (org-at-table-p)]
27775 ["Previous Field" org-shifttab (org-at-table-p)]
27776 ["Next Row" org-return (org-at-table-p)]
27777 "--"
27778 ["Blank Field" org-table-blank-field (org-at-table-p)]
27779 ["Edit Field" org-table-edit-field (org-at-table-p)]
27780 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27781 "--"
27782 ("Column"
27783 ["Move Column Left" org-metaleft (org-at-table-p)]
27784 ["Move Column Right" org-metaright (org-at-table-p)]
27785 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27786 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27787 ("Row"
27788 ["Move Row Up" org-metaup (org-at-table-p)]
27789 ["Move Row Down" org-metadown (org-at-table-p)]
27790 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27791 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27792 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27793 "--"
27794 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27795 ("Rectangle"
27796 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27797 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27798 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27799 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27800 "--"
27801 ("Calculate"
27802 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27803 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27804 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27805 "--"
27806 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27807 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27808 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27809 "--"
27810 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27811 "--"
27812 ["Sum Column/Rectangle" org-table-sum
27813 (or (org-at-table-p) (org-region-active-p))]
27814 ["Which Column?" org-table-current-column (org-at-table-p)])
27815 ["Debug Formulas"
27816 org-table-toggle-formula-debugger
27817 :style toggle :selected org-table-formula-debug]
27818 ["Show Col/Row Numbers"
27819 org-table-toggle-coordinate-overlays
27820 :style toggle :selected org-table-overlay-coordinates]
27821 "--"
27822 ["Create" org-table-create (and (not (org-at-table-p))
27823 org-enable-table-editor)]
27824 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27825 ["Import from File" org-table-import (not (org-at-table-p))]
27826 ["Export to File" org-table-export (org-at-table-p)]
27827 "--"
27828 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27829
27830 (easy-menu-define org-org-menu org-mode-map "Org menu"
27831 '("Org"
27832 ("Show/Hide"
27833 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27834 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27835 ["Sparse Tree" org-occur t]
27836 ["Reveal Context" org-reveal t]
27837 ["Show All" show-all t]
27838 "--"
27839 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27840 "--"
27841 ["New Heading" org-insert-heading t]
27842 ("Navigate Headings"
27843 ["Up" outline-up-heading t]
27844 ["Next" outline-next-visible-heading t]
27845 ["Previous" outline-previous-visible-heading t]
27846 ["Next Same Level" outline-forward-same-level t]
27847 ["Previous Same Level" outline-backward-same-level t]
27848 "--"
27849 ["Jump" org-goto t])
27850 ("Edit Structure"
27851 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27852 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27853 "--"
27854 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27855 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27856 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27857 "--"
27858 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27859 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27860 ["Demote Heading" org-metaright (not (org-at-table-p))]
27861 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27862 "--"
27863 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27864 "--"
27865 ["Convert to odd levels" org-convert-to-odd-levels t]
27866 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27867 ("Editing"
27868 ["Emphasis..." org-emphasize t])
27869 ("Archive"
27870 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27871 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27872 ; :active t :keys "C-u C-c C-x C-a"]
27873 ["Sparse trees open ARCHIVE trees"
27874 (setq org-sparse-tree-open-archived-trees
27875 (not org-sparse-tree-open-archived-trees))
27876 :style toggle :selected org-sparse-tree-open-archived-trees]
27877 ["Cycling opens ARCHIVE trees"
27878 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27879 :style toggle :selected org-cycle-open-archived-trees]
27880 ["Agenda includes ARCHIVE trees"
27881 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27882 :style toggle :selected (not org-agenda-skip-archived-trees)]
27883 "--"
27884 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27885 ; ["Check and Move Children" (org-archive-subtree '(4))
27886 ; :active t :keys "C-u C-c C-x C-s"]
27887 )
27888 "--"
27889 ("TODO Lists"
27890 ["TODO/DONE/-" org-todo t]
27891 ("Select keyword"
27892 ["Next keyword" org-shiftright (org-on-heading-p)]
27893 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27894 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27895 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27896 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27897 ["Show TODO Tree" org-show-todo-tree t]
27898 ["Global TODO list" org-todo-list t]
27899 "--"
27900 ["Set Priority" org-priority t]
27901 ["Priority Up" org-shiftup t]
27902 ["Priority Down" org-shiftdown t])
27903 ("TAGS and Properties"
27904 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27905 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27906 "--"
27907 ["Set property" 'org-set-property t]
27908 ["Column view of properties" org-columns t]
27909 ["Insert Column View DBlock" org-insert-columns-dblock t])
27910 ("Dates and Scheduling"
27911 ["Timestamp" org-time-stamp t]
27912 ["Timestamp (inactive)" org-time-stamp-inactive t]
27913 ("Change Date"
27914 ["1 Day Later" org-shiftright t]
27915 ["1 Day Earlier" org-shiftleft t]
27916 ["1 ... Later" org-shiftup t]
27917 ["1 ... Earlier" org-shiftdown t])
27918 ["Compute Time Range" org-evaluate-time-range t]
27919 ["Schedule Item" org-schedule t]
27920 ["Deadline" org-deadline t]
27921 "--"
27922 ["Custom time format" org-toggle-time-stamp-overlays
27923 :style radio :selected org-display-custom-times]
27924 "--"
27925 ["Goto Calendar" org-goto-calendar t]
27926 ["Date from Calendar" org-date-from-calendar t])
27927 ("Logging work"
27928 ["Clock in" org-clock-in t]
27929 ["Clock out" org-clock-out t]
27930 ["Clock cancel" org-clock-cancel t]
27931 ["Goto running clock" org-clock-goto t]
27932 ["Display times" org-clock-display t]
27933 ["Create clock table" org-clock-report t]
27934 "--"
27935 ["Record DONE time"
27936 (progn (setq org-log-done (not org-log-done))
27937 (message "Switching to %s will %s record a timestamp"
27938 (car org-done-keywords)
27939 (if org-log-done "automatically" "not")))
27940 :style toggle :selected org-log-done])
27941 "--"
27942 ["Agenda Command..." org-agenda t]
27943 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27944 ("File List for Agenda")
27945 ("Special views current file"
27946 ["TODO Tree" org-show-todo-tree t]
27947 ["Check Deadlines" org-check-deadlines t]
27948 ["Timeline" org-timeline t]
27949 ["Tags Tree" org-tags-sparse-tree t])
27950 "--"
27951 ("Hyperlinks"
27952 ["Store Link (Global)" org-store-link t]
27953 ["Insert Link" org-insert-link t]
27954 ["Follow Link" org-open-at-point t]
27955 "--"
27956 ["Next link" org-next-link t]
27957 ["Previous link" org-previous-link t]
27958 "--"
27959 ["Descriptive Links"
27960 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27961 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27962 ["Literal Links"
27963 (progn
27964 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27965 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27966 "--"
27967 ["Export/Publish..." org-export t]
27968 ("LaTeX"
27969 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27970 :selected org-cdlatex-mode]
27971 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27972 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27973 ["Modify math symbol" org-cdlatex-math-modify
27974 (org-inside-LaTeX-fragment-p)]
27975 ["Export LaTeX fragments as images"
27976 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27977 :style toggle :selected org-export-with-LaTeX-fragments])
27978 "--"
27979 ("Documentation"
27980 ["Show Version" org-version t]
27981 ["Info Documentation" org-info t])
27982 ("Customize"
27983 ["Browse Org Group" org-customize t]
27984 "--"
27985 ["Expand This Menu" org-create-customize-menu
27986 (fboundp 'customize-menu-create)])
27987 "--"
27988 ["Refresh setup" org-mode-restart t]
27989 ))
27990
27991 (defun org-info (&optional node)
27992 "Read documentation for Org-mode in the info system.
27993 With optional NODE, go directly to that node."
27994 (interactive)
27995 (info (format "(org)%s" (or node ""))))
27996
27997 (defun org-install-agenda-files-menu ()
27998 (let ((bl (buffer-list)))
27999 (save-excursion
28000 (while bl
28001 (set-buffer (pop bl))
28002 (if (org-mode-p) (setq bl nil)))
28003 (when (org-mode-p)
28004 (easy-menu-change
28005 '("Org") "File List for Agenda"
28006 (append
28007 (list
28008 ["Edit File List" (org-edit-agenda-file-list) t]
28009 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
28010 ["Remove Current File from List" org-remove-file t]
28011 ["Cycle through agenda files" org-cycle-agenda-files t]
28012 ["Occur in all agenda files" org-occur-in-agenda-files t]
28013 "--")
28014 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
28015
28016 ;;;; Documentation
28017
28018 (defun org-customize ()
28019 "Call the customize function with org as argument."
28020 (interactive)
28021 (customize-browse 'org))
28022
28023 (defun org-create-customize-menu ()
28024 "Create a full customization menu for Org-mode, insert it into the menu."
28025 (interactive)
28026 (if (fboundp 'customize-menu-create)
28027 (progn
28028 (easy-menu-change
28029 '("Org") "Customize"
28030 `(["Browse Org group" org-customize t]
28031 "--"
28032 ,(customize-menu-create 'org)
28033 ["Set" Custom-set t]
28034 ["Save" Custom-save t]
28035 ["Reset to Current" Custom-reset-current t]
28036 ["Reset to Saved" Custom-reset-saved t]
28037 ["Reset to Standard Settings" Custom-reset-standard t]))
28038 (message "\"Org\"-menu now contains full customization menu"))
28039 (error "Cannot expand menu (outdated version of cus-edit.el)")))
28040
28041 ;;;; Miscellaneous stuff
28042
28043
28044 ;;; Generally useful functions
28045
28046 (defun org-context ()
28047 "Return a list of contexts of the current cursor position.
28048 If several contexts apply, all are returned.
28049 Each context entry is a list with a symbol naming the context, and
28050 two positions indicating start and end of the context. Possible
28051 contexts are:
28052
28053 :headline anywhere in a headline
28054 :headline-stars on the leading stars in a headline
28055 :todo-keyword on a TODO keyword (including DONE) in a headline
28056 :tags on the TAGS in a headline
28057 :priority on the priority cookie in a headline
28058 :item on the first line of a plain list item
28059 :item-bullet on the bullet/number of a plain list item
28060 :checkbox on the checkbox in a plain list item
28061 :table in an org-mode table
28062 :table-special on a special filed in a table
28063 :table-table in a table.el table
28064 :link on a hyperlink
28065 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
28066 :target on a <<target>>
28067 :radio-target on a <<<radio-target>>>
28068 :latex-fragment on a LaTeX fragment
28069 :latex-preview on a LaTeX fragment with overlayed preview image
28070
28071 This function expects the position to be visible because it uses font-lock
28072 faces as a help to recognize the following contexts: :table-special, :link,
28073 and :keyword."
28074 (let* ((f (get-text-property (point) 'face))
28075 (faces (if (listp f) f (list f)))
28076 (p (point)) clist o)
28077 ;; First the large context
28078 (cond
28079 ((org-on-heading-p t)
28080 (push (list :headline (point-at-bol) (point-at-eol)) clist)
28081 (when (progn
28082 (beginning-of-line 1)
28083 (looking-at org-todo-line-tags-regexp))
28084 (push (org-point-in-group p 1 :headline-stars) clist)
28085 (push (org-point-in-group p 2 :todo-keyword) clist)
28086 (push (org-point-in-group p 4 :tags) clist))
28087 (goto-char p)
28088 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
28089 (if (looking-at "\\[#[A-Z0-9]\\]")
28090 (push (org-point-in-group p 0 :priority) clist)))
28091
28092 ((org-at-item-p)
28093 (push (org-point-in-group p 2 :item-bullet) clist)
28094 (push (list :item (point-at-bol)
28095 (save-excursion (org-end-of-item) (point)))
28096 clist)
28097 (and (org-at-item-checkbox-p)
28098 (push (org-point-in-group p 0 :checkbox) clist)))
28099
28100 ((org-at-table-p)
28101 (push (list :table (org-table-begin) (org-table-end)) clist)
28102 (if (memq 'org-formula faces)
28103 (push (list :table-special
28104 (previous-single-property-change p 'face)
28105 (next-single-property-change p 'face)) clist)))
28106 ((org-at-table-p 'any)
28107 (push (list :table-table) clist)))
28108 (goto-char p)
28109
28110 ;; Now the small context
28111 (cond
28112 ((org-at-timestamp-p)
28113 (push (org-point-in-group p 0 :timestamp) clist))
28114 ((memq 'org-link faces)
28115 (push (list :link
28116 (previous-single-property-change p 'face)
28117 (next-single-property-change p 'face)) clist))
28118 ((memq 'org-special-keyword faces)
28119 (push (list :keyword
28120 (previous-single-property-change p 'face)
28121 (next-single-property-change p 'face)) clist))
28122 ((org-on-target-p)
28123 (push (org-point-in-group p 0 :target) clist)
28124 (goto-char (1- (match-beginning 0)))
28125 (if (looking-at org-radio-target-regexp)
28126 (push (org-point-in-group p 0 :radio-target) clist))
28127 (goto-char p))
28128 ((setq o (car (delq nil
28129 (mapcar
28130 (lambda (x)
28131 (if (memq x org-latex-fragment-image-overlays) x))
28132 (org-overlays-at (point))))))
28133 (push (list :latex-fragment
28134 (org-overlay-start o) (org-overlay-end o)) clist)
28135 (push (list :latex-preview
28136 (org-overlay-start o) (org-overlay-end o)) clist))
28137 ((org-inside-LaTeX-fragment-p)
28138 ;; FIXME: positions wrong.
28139 (push (list :latex-fragment (point) (point)) clist)))
28140
28141 (setq clist (nreverse (delq nil clist)))
28142 clist))
28143
28144 ;; FIXME: Compare with at-regexp-p Do we need both?
28145 (defun org-in-regexp (re &optional nlines visually)
28146 "Check if point is inside a match of regexp.
28147 Normally only the current line is checked, but you can include NLINES extra
28148 lines both before and after point into the search.
28149 If VISUALLY is set, require that the cursor is not after the match but
28150 really on, so that the block visually is on the match."
28151 (catch 'exit
28152 (let ((pos (point))
28153 (eol (point-at-eol (+ 1 (or nlines 0))))
28154 (inc (if visually 1 0)))
28155 (save-excursion
28156 (beginning-of-line (- 1 (or nlines 0)))
28157 (while (re-search-forward re eol t)
28158 (if (and (<= (match-beginning 0) pos)
28159 (>= (+ inc (match-end 0)) pos))
28160 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
28161
28162 (defun org-at-regexp-p (regexp)
28163 "Is point inside a match of REGEXP in the current line?"
28164 (catch 'exit
28165 (save-excursion
28166 (let ((pos (point)) (end (point-at-eol)))
28167 (beginning-of-line 1)
28168 (while (re-search-forward regexp end t)
28169 (if (and (<= (match-beginning 0) pos)
28170 (>= (match-end 0) pos))
28171 (throw 'exit t)))
28172 nil))))
28173
28174 (defun org-occur-in-agenda-files (regexp &optional nlines)
28175 "Call `multi-occur' with buffers for all agenda files."
28176 (interactive "sOrg-files matching: \np")
28177 (let* ((files (org-agenda-files))
28178 (tnames (mapcar 'file-truename files))
28179 (extra org-agenda-text-search-extra-files)
28180 f)
28181 (while (setq f (pop extra))
28182 (unless (member (file-truename f) tnames)
28183 (add-to-list 'files f 'append)
28184 (add-to-list 'tnames (file-truename f) 'append)))
28185 (multi-occur
28186 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
28187 regexp)))
28188
28189 (if (boundp 'occur-mode-find-occurrence-hook)
28190 ;; Emacs 23
28191 (add-hook 'occur-mode-find-occurrence-hook
28192 (lambda ()
28193 (when (org-mode-p)
28194 (org-reveal))))
28195 ;; Emacs 22
28196 (defadvice occur-mode-goto-occurrence
28197 (after org-occur-reveal activate)
28198 (and (org-mode-p) (org-reveal)))
28199 (defadvice occur-mode-goto-occurrence-other-window
28200 (after org-occur-reveal activate)
28201 (and (org-mode-p) (org-reveal)))
28202 (defadvice occur-mode-display-occurrence
28203 (after org-occur-reveal activate)
28204 (when (org-mode-p)
28205 (let ((pos (occur-mode-find-occurrence)))
28206 (with-current-buffer (marker-buffer pos)
28207 (save-excursion
28208 (goto-char pos)
28209 (org-reveal)))))))
28210
28211 (defun org-uniquify (list)
28212 "Remove duplicate elements from LIST."
28213 (let (res)
28214 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
28215 res))
28216
28217 (defun org-delete-all (elts list)
28218 "Remove all elements in ELTS from LIST."
28219 (while elts
28220 (setq list (delete (pop elts) list)))
28221 list)
28222
28223 (defun org-back-over-empty-lines ()
28224 "Move backwards over witespace, to the beginning of the first empty line.
28225 Returns the number of empty lines passed."
28226 (let ((pos (point)))
28227 (skip-chars-backward " \t\n\r")
28228 (beginning-of-line 2)
28229 (goto-char (min (point) pos))
28230 (count-lines (point) pos)))
28231
28232 (defun org-skip-whitespace ()
28233 (skip-chars-forward " \t\n\r"))
28234
28235 (defun org-point-in-group (point group &optional context)
28236 "Check if POINT is in match-group GROUP.
28237 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
28238 match. If the match group does ot exist or point is not inside it,
28239 return nil."
28240 (and (match-beginning group)
28241 (>= point (match-beginning group))
28242 (<= point (match-end group))
28243 (if context
28244 (list context (match-beginning group) (match-end group))
28245 t)))
28246
28247 (defun org-switch-to-buffer-other-window (&rest args)
28248 "Switch to buffer in a second window on the current frame.
28249 In particular, do not allow pop-up frames."
28250 (let (pop-up-frames special-display-buffer-names special-display-regexps
28251 special-display-function)
28252 (apply 'switch-to-buffer-other-window args)))
28253
28254 (defun org-combine-plists (&rest plists)
28255 "Create a single property list from all plists in PLISTS.
28256 The process starts by copying the first list, and then setting properties
28257 from the other lists. Settings in the last list are the most significant
28258 ones and overrule settings in the other lists."
28259 (let ((rtn (copy-sequence (pop plists)))
28260 p v ls)
28261 (while plists
28262 (setq ls (pop plists))
28263 (while ls
28264 (setq p (pop ls) v (pop ls))
28265 (setq rtn (plist-put rtn p v))))
28266 rtn))
28267
28268 (defun org-move-line-down (arg)
28269 "Move the current line down. With prefix argument, move it past ARG lines."
28270 (interactive "p")
28271 (let ((col (current-column))
28272 beg end pos)
28273 (beginning-of-line 1) (setq beg (point))
28274 (beginning-of-line 2) (setq end (point))
28275 (beginning-of-line (+ 1 arg))
28276 (setq pos (move-marker (make-marker) (point)))
28277 (insert (delete-and-extract-region beg end))
28278 (goto-char pos)
28279 (move-to-column col)))
28280
28281 (defun org-move-line-up (arg)
28282 "Move the current line up. With prefix argument, move it past ARG lines."
28283 (interactive "p")
28284 (let ((col (current-column))
28285 beg end pos)
28286 (beginning-of-line 1) (setq beg (point))
28287 (beginning-of-line 2) (setq end (point))
28288 (beginning-of-line (- arg))
28289 (setq pos (move-marker (make-marker) (point)))
28290 (insert (delete-and-extract-region beg end))
28291 (goto-char pos)
28292 (move-to-column col)))
28293
28294 (defun org-replace-escapes (string table)
28295 "Replace %-escapes in STRING with values in TABLE.
28296 TABLE is an association list with keys like \"%a\" and string values.
28297 The sequences in STRING may contain normal field width and padding information,
28298 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
28299 so values can contain further %-escapes if they are define later in TABLE."
28300 (let ((case-fold-search nil)
28301 e re rpl)
28302 (while (setq e (pop table))
28303 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
28304 (while (string-match re string)
28305 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
28306 (cdr e)))
28307 (setq string (replace-match rpl t t string))))
28308 string))
28309
28310
28311 (defun org-sublist (list start end)
28312 "Return a section of LIST, from START to END.
28313 Counting starts at 1."
28314 (let (rtn (c start))
28315 (setq list (nthcdr (1- start) list))
28316 (while (and list (<= c end))
28317 (push (pop list) rtn)
28318 (setq c (1+ c)))
28319 (nreverse rtn)))
28320
28321 (defun org-find-base-buffer-visiting (file)
28322 "Like `find-buffer-visiting' but alway return the base buffer and
28323 not an indirect buffer."
28324 (let ((buf (find-buffer-visiting file)))
28325 (if buf
28326 (or (buffer-base-buffer buf) buf)
28327 nil)))
28328
28329 (defun org-image-file-name-regexp ()
28330 "Return regexp matching the file names of images."
28331 (if (fboundp 'image-file-name-regexp)
28332 (image-file-name-regexp)
28333 (let ((image-file-name-extensions
28334 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
28335 "xbm" "xpm" "pbm" "pgm" "ppm")))
28336 (concat "\\."
28337 (regexp-opt (nconc (mapcar 'upcase
28338 image-file-name-extensions)
28339 image-file-name-extensions)
28340 t)
28341 "\\'"))))
28342
28343 (defun org-file-image-p (file)
28344 "Return non-nil if FILE is an image."
28345 (save-match-data
28346 (string-match (org-image-file-name-regexp) file)))
28347
28348 ;;; Paragraph filling stuff.
28349 ;; We want this to be just right, so use the full arsenal.
28350
28351 (defun org-indent-line-function ()
28352 "Indent line like previous, but further if previous was headline or item."
28353 (interactive)
28354 (let* ((pos (point))
28355 (itemp (org-at-item-p))
28356 column bpos bcol tpos tcol bullet btype bullet-type)
28357 ;; Find the previous relevant line
28358 (beginning-of-line 1)
28359 (cond
28360 ((looking-at "#") (setq column 0))
28361 ((looking-at "\\*+ ") (setq column 0))
28362 (t
28363 (beginning-of-line 0)
28364 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
28365 (beginning-of-line 0))
28366 (cond
28367 ((looking-at "\\*+[ \t]+")
28368 (goto-char (match-end 0))
28369 (setq column (current-column)))
28370 ((org-in-item-p)
28371 (org-beginning-of-item)
28372 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28373 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
28374 (setq bpos (match-beginning 1) tpos (match-end 0)
28375 bcol (progn (goto-char bpos) (current-column))
28376 tcol (progn (goto-char tpos) (current-column))
28377 bullet (match-string 1)
28378 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
28379 (if (not itemp)
28380 (setq column tcol)
28381 (goto-char pos)
28382 (beginning-of-line 1)
28383 (if (looking-at "\\S-")
28384 (progn
28385 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28386 (setq bullet (match-string 1)
28387 btype (if (string-match "[0-9]" bullet) "n" bullet))
28388 (setq column (if (equal btype bullet-type) bcol tcol)))
28389 (setq column (org-get-indentation)))))
28390 (t (setq column (org-get-indentation))))))
28391 (goto-char pos)
28392 (if (<= (current-column) (current-indentation))
28393 (indent-line-to column)
28394 (save-excursion (indent-line-to column)))
28395 (setq column (current-column))
28396 (beginning-of-line 1)
28397 (if (looking-at
28398 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
28399 (replace-match (concat "\\1" (format org-property-format
28400 (match-string 2) (match-string 3)))
28401 t nil))
28402 (move-to-column column)))
28403
28404 (defun org-set-autofill-regexps ()
28405 (interactive)
28406 ;; In the paragraph separator we include headlines, because filling
28407 ;; text in a line directly attached to a headline would otherwise
28408 ;; fill the headline as well.
28409 (org-set-local 'comment-start-skip "^#+[ \t]*")
28410 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
28411 ;; The paragraph starter includes hand-formatted lists.
28412 (org-set-local 'paragraph-start
28413 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
28414 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
28415 ;; But only if the user has not turned off tables or fixed-width regions
28416 (org-set-local
28417 'auto-fill-inhibit-regexp
28418 (concat "\\*+ \\|#\\+"
28419 "\\|[ \t]*" org-keyword-time-regexp
28420 (if (or org-enable-table-editor org-enable-fixed-width-editor)
28421 (concat
28422 "\\|[ \t]*["
28423 (if org-enable-table-editor "|" "")
28424 (if org-enable-fixed-width-editor ":" "")
28425 "]"))))
28426 ;; We use our own fill-paragraph function, to make sure that tables
28427 ;; and fixed-width regions are not wrapped. That function will pass
28428 ;; through to `fill-paragraph' when appropriate.
28429 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
28430 ; Adaptive filling: To get full control, first make sure that
28431 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
28432 (org-set-local 'adaptive-fill-regexp "\000")
28433 (org-set-local 'adaptive-fill-function
28434 'org-adaptive-fill-function)
28435 (org-set-local
28436 'align-mode-rules-list
28437 '((org-in-buffer-settings
28438 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
28439 (modes . '(org-mode))))))
28440
28441 (defun org-fill-paragraph (&optional justify)
28442 "Re-align a table, pass through to fill-paragraph if no table."
28443 (let ((table-p (org-at-table-p))
28444 (table.el-p (org-at-table.el-p)))
28445 (cond ((and (equal (char-after (point-at-bol)) ?*)
28446 (save-excursion (goto-char (point-at-bol))
28447 (looking-at outline-regexp)))
28448 t) ; skip headlines
28449 (table.el-p t) ; skip table.el tables
28450 (table-p (org-table-align) t) ; align org-mode tables
28451 (t nil)))) ; call paragraph-fill
28452
28453 ;; For reference, this is the default value of adaptive-fill-regexp
28454 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
28455
28456 (defun org-adaptive-fill-function ()
28457 "Return a fill prefix for org-mode files.
28458 In particular, this makes sure hanging paragraphs for hand-formatted lists
28459 work correctly."
28460 (cond ((looking-at "#[ \t]+")
28461 (match-string 0))
28462 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
28463 (save-excursion
28464 (goto-char (match-end 0))
28465 (make-string (current-column) ?\ )))
28466 (t nil)))
28467
28468 ;;;; Functions extending outline functionality
28469
28470
28471 (defun org-beginning-of-line (&optional arg)
28472 "Go to the beginning of the current line. If that is invisible, continue
28473 to a visible line beginning. This makes the function of C-a more intuitive.
28474 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28475 first attempt, and only move to after the tags when the cursor is already
28476 beyond the end of the headline."
28477 (interactive "P")
28478 (let ((pos (point)))
28479 (beginning-of-line 1)
28480 (if (bobp)
28481 nil
28482 (backward-char 1)
28483 (if (org-invisible-p)
28484 (while (and (not (bobp)) (org-invisible-p))
28485 (backward-char 1)
28486 (beginning-of-line 1))
28487 (forward-char 1)))
28488 (when org-special-ctrl-a/e
28489 (cond
28490 ((and (looking-at org-todo-line-regexp)
28491 (= (char-after (match-end 1)) ?\ ))
28492 (goto-char
28493 (if (eq org-special-ctrl-a/e t)
28494 (cond ((> pos (match-beginning 3)) (match-beginning 3))
28495 ((= pos (point)) (match-beginning 3))
28496 (t (point)))
28497 (cond ((> pos (point)) (point))
28498 ((not (eq last-command this-command)) (point))
28499 (t (match-beginning 3))))))
28500 ((org-at-item-p)
28501 (goto-char
28502 (if (eq org-special-ctrl-a/e t)
28503 (cond ((> pos (match-end 4)) (match-end 4))
28504 ((= pos (point)) (match-end 4))
28505 (t (point)))
28506 (cond ((> pos (point)) (point))
28507 ((not (eq last-command this-command)) (point))
28508 (t (match-end 4))))))))))
28509
28510 (defun org-end-of-line (&optional arg)
28511 "Go to the end of the line.
28512 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28513 first attempt, and only move to after the tags when the cursor is already
28514 beyond the end of the headline."
28515 (interactive "P")
28516 (if (or (not org-special-ctrl-a/e)
28517 (not (org-on-heading-p)))
28518 (end-of-line arg)
28519 (let ((pos (point)))
28520 (beginning-of-line 1)
28521 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
28522 (if (eq org-special-ctrl-a/e t)
28523 (if (or (< pos (match-beginning 1))
28524 (= pos (match-end 0)))
28525 (goto-char (match-beginning 1))
28526 (goto-char (match-end 0)))
28527 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
28528 (goto-char (match-end 0))
28529 (goto-char (match-beginning 1))))
28530 (end-of-line arg)))))
28531
28532 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
28533 (define-key org-mode-map "\C-e" 'org-end-of-line)
28534
28535 (defun org-kill-line (&optional arg)
28536 "Kill line, to tags or end of line."
28537 (interactive "P")
28538 (cond
28539 ((or (not org-special-ctrl-k)
28540 (bolp)
28541 (not (org-on-heading-p)))
28542 (call-interactively 'kill-line))
28543 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
28544 (kill-region (point) (match-beginning 1))
28545 (org-set-tags nil t))
28546 (t (kill-region (point) (point-at-eol)))))
28547
28548 (define-key org-mode-map "\C-k" 'org-kill-line)
28549
28550 (defun org-invisible-p ()
28551 "Check if point is at a character currently not visible."
28552 ;; Early versions of noutline don't have `outline-invisible-p'.
28553 (if (fboundp 'outline-invisible-p)
28554 (outline-invisible-p)
28555 (get-char-property (point) 'invisible)))
28556
28557 (defun org-invisible-p2 ()
28558 "Check if point is at a character currently not visible."
28559 (save-excursion
28560 (if (and (eolp) (not (bobp))) (backward-char 1))
28561 ;; Early versions of noutline don't have `outline-invisible-p'.
28562 (if (fboundp 'outline-invisible-p)
28563 (outline-invisible-p)
28564 (get-char-property (point) 'invisible))))
28565
28566 (defalias 'org-back-to-heading 'outline-back-to-heading)
28567 (defalias 'org-on-heading-p 'outline-on-heading-p)
28568 (defalias 'org-at-heading-p 'outline-on-heading-p)
28569 (defun org-at-heading-or-item-p ()
28570 (or (org-on-heading-p) (org-at-item-p)))
28571
28572 (defun org-on-target-p ()
28573 (or (org-in-regexp org-radio-target-regexp)
28574 (org-in-regexp org-target-regexp)))
28575
28576 (defun org-up-heading-all (arg)
28577 "Move to the heading line of which the present line is a subheading.
28578 This function considers both visible and invisible heading lines.
28579 With argument, move up ARG levels."
28580 (if (fboundp 'outline-up-heading-all)
28581 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28582 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28583
28584 (defun org-up-heading-safe ()
28585 "Move to the heading line of which the present line is a subheading.
28586 This version will not throw an error. It will return the level of the
28587 headline found, or nil if no higher level is found."
28588 (let ((pos (point)) start-level level
28589 (re (concat "^" outline-regexp)))
28590 (catch 'exit
28591 (outline-back-to-heading t)
28592 (setq start-level (funcall outline-level))
28593 (if (equal start-level 1) (throw 'exit nil))
28594 (while (re-search-backward re nil t)
28595 (setq level (funcall outline-level))
28596 (if (< level start-level) (throw 'exit level)))
28597 nil)))
28598
28599 (defun org-first-sibling-p ()
28600 "Is this heading the first child of its parents?"
28601 (interactive)
28602 (let ((re (concat "^" outline-regexp))
28603 level l)
28604 (unless (org-at-heading-p t)
28605 (error "Not at a heading"))
28606 (setq level (funcall outline-level))
28607 (save-excursion
28608 (if (not (re-search-backward re nil t))
28609 t
28610 (setq l (funcall outline-level))
28611 (< l level)))))
28612
28613 (defun org-goto-sibling (&optional previous)
28614 "Goto the next sibling, even if it is invisible.
28615 When PREVIOUS is set, go to the previous sibling instead. Returns t
28616 when a sibling was found. When none is found, return nil and don't
28617 move point."
28618 (let ((fun (if previous 're-search-backward 're-search-forward))
28619 (pos (point))
28620 (re (concat "^" outline-regexp))
28621 level l)
28622 (when (condition-case nil (org-back-to-heading t) (error nil))
28623 (setq level (funcall outline-level))
28624 (catch 'exit
28625 (or previous (forward-char 1))
28626 (while (funcall fun re nil t)
28627 (setq l (funcall outline-level))
28628 (when (< l level) (goto-char pos) (throw 'exit nil))
28629 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28630 (goto-char pos)
28631 nil))))
28632
28633 (defun org-show-siblings ()
28634 "Show all siblings of the current headline."
28635 (save-excursion
28636 (while (org-goto-sibling) (org-flag-heading nil)))
28637 (save-excursion
28638 (while (org-goto-sibling 'previous)
28639 (org-flag-heading nil))))
28640
28641 (defun org-show-hidden-entry ()
28642 "Show an entry where even the heading is hidden."
28643 (save-excursion
28644 (org-show-entry)))
28645
28646 (defun org-flag-heading (flag &optional entry)
28647 "Flag the current heading. FLAG non-nil means make invisible.
28648 When ENTRY is non-nil, show the entire entry."
28649 (save-excursion
28650 (org-back-to-heading t)
28651 ;; Check if we should show the entire entry
28652 (if entry
28653 (progn
28654 (org-show-entry)
28655 (save-excursion
28656 (and (outline-next-heading)
28657 (org-flag-heading nil))))
28658 (outline-flag-region (max (point-min) (1- (point)))
28659 (save-excursion (outline-end-of-heading) (point))
28660 flag))))
28661
28662 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28663 ;; This is an exact copy of the original function, but it uses
28664 ;; `org-back-to-heading', to make it work also in invisible
28665 ;; trees. And is uses an invisible-OK argument.
28666 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28667 (org-back-to-heading invisible-OK)
28668 (let ((first t)
28669 (level (funcall outline-level)))
28670 (while (and (not (eobp))
28671 (or first (> (funcall outline-level) level)))
28672 (setq first nil)
28673 (outline-next-heading))
28674 (unless to-heading
28675 (if (memq (preceding-char) '(?\n ?\^M))
28676 (progn
28677 ;; Go to end of line before heading
28678 (forward-char -1)
28679 (if (memq (preceding-char) '(?\n ?\^M))
28680 ;; leave blank line before heading
28681 (forward-char -1))))))
28682 (point))
28683
28684 (defun org-show-subtree ()
28685 "Show everything after this heading at deeper levels."
28686 (outline-flag-region
28687 (point)
28688 (save-excursion
28689 (outline-end-of-subtree) (outline-next-heading) (point))
28690 nil))
28691
28692 (defun org-show-entry ()
28693 "Show the body directly following this heading.
28694 Show the heading too, if it is currently invisible."
28695 (interactive)
28696 (save-excursion
28697 (condition-case nil
28698 (progn
28699 (org-back-to-heading t)
28700 (outline-flag-region
28701 (max (point-min) (1- (point)))
28702 (save-excursion
28703 (re-search-forward
28704 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28705 (or (match-beginning 1) (point-max)))
28706 nil))
28707 (error nil))))
28708
28709 (defun org-make-options-regexp (kwds)
28710 "Make a regular expression for keyword lines."
28711 (concat
28712 "^"
28713 "#?[ \t]*\\+\\("
28714 (mapconcat 'regexp-quote kwds "\\|")
28715 "\\):[ \t]*"
28716 "\\(.+\\)"))
28717
28718 ;; Make isearch reveal the necessary context
28719 (defun org-isearch-end ()
28720 "Reveal context after isearch exits."
28721 (when isearch-success ; only if search was successful
28722 (if (featurep 'xemacs)
28723 ;; Under XEmacs, the hook is run in the correct place,
28724 ;; we directly show the context.
28725 (org-show-context 'isearch)
28726 ;; In Emacs the hook runs *before* restoring the overlays.
28727 ;; So we have to use a one-time post-command-hook to do this.
28728 ;; (Emacs 22 has a special variable, see function `org-mode')
28729 (unless (and (boundp 'isearch-mode-end-hook-quit)
28730 isearch-mode-end-hook-quit)
28731 ;; Only when the isearch was not quitted.
28732 (org-add-hook 'post-command-hook 'org-isearch-post-command
28733 'append 'local)))))
28734
28735 (defun org-isearch-post-command ()
28736 "Remove self from hook, and show context."
28737 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28738 (org-show-context 'isearch))
28739
28740
28741 ;;;; Integration with and fixes for other packages
28742
28743 ;;; Imenu support
28744
28745 (defvar org-imenu-markers nil
28746 "All markers currently used by Imenu.")
28747 (make-variable-buffer-local 'org-imenu-markers)
28748
28749 (defun org-imenu-new-marker (&optional pos)
28750 "Return a new marker for use by Imenu, and remember the marker."
28751 (let ((m (make-marker)))
28752 (move-marker m (or pos (point)))
28753 (push m org-imenu-markers)
28754 m))
28755
28756 (defun org-imenu-get-tree ()
28757 "Produce the index for Imenu."
28758 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28759 (setq org-imenu-markers nil)
28760 (let* ((n org-imenu-depth)
28761 (re (concat "^" outline-regexp))
28762 (subs (make-vector (1+ n) nil))
28763 (last-level 0)
28764 m tree level head)
28765 (save-excursion
28766 (save-restriction
28767 (widen)
28768 (goto-char (point-max))
28769 (while (re-search-backward re nil t)
28770 (setq level (org-reduced-level (funcall outline-level)))
28771 (when (<= level n)
28772 (looking-at org-complex-heading-regexp)
28773 (setq head (org-match-string-no-properties 4)
28774 m (org-imenu-new-marker))
28775 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28776 (if (>= level last-level)
28777 (push (cons head m) (aref subs level))
28778 (push (cons head (aref subs (1+ level))) (aref subs level))
28779 (loop for i from (1+ level) to n do (aset subs i nil)))
28780 (setq last-level level)))))
28781 (aref subs 1)))
28782
28783 (eval-after-load "imenu"
28784 '(progn
28785 (add-hook 'imenu-after-jump-hook
28786 (lambda () (org-show-context 'org-goto)))))
28787
28788 ;; Speedbar support
28789
28790 (defun org-speedbar-set-agenda-restriction ()
28791 "Restrict future agenda commands to the location at point in speedbar.
28792 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28793 (interactive)
28794 (let (p m tp np dir txt w)
28795 (cond
28796 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28797 'org-imenu t))
28798 (setq m (get-text-property p 'org-imenu-marker))
28799 (save-excursion
28800 (save-restriction
28801 (set-buffer (marker-buffer m))
28802 (goto-char m)
28803 (org-agenda-set-restriction-lock 'subtree))))
28804 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28805 'speedbar-function 'speedbar-find-file))
28806 (setq tp (previous-single-property-change
28807 (1+ p) 'speedbar-function)
28808 np (next-single-property-change
28809 tp 'speedbar-function)
28810 dir (speedbar-line-directory)
28811 txt (buffer-substring-no-properties (or tp (point-min))
28812 (or np (point-max))))
28813 (save-excursion
28814 (save-restriction
28815 (set-buffer (find-file-noselect
28816 (let ((default-directory dir))
28817 (expand-file-name txt))))
28818 (unless (org-mode-p)
28819 (error "Cannot restrict to non-Org-mode file"))
28820 (org-agenda-set-restriction-lock 'file))))
28821 (t (error "Don't know how to restrict Org-mode's agenda")))
28822 (org-move-overlay org-speedbar-restriction-lock-overlay
28823 (point-at-bol) (point-at-eol))
28824 (setq current-prefix-arg nil)
28825 (org-agenda-maybe-redo)))
28826
28827 (eval-after-load "speedbar"
28828 '(progn
28829 (speedbar-add-supported-extension ".org")
28830 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28831 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28832 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28833 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28834 (add-hook 'speedbar-visiting-tag-hook
28835 (lambda () (org-show-context 'org-goto)))))
28836
28837
28838 ;;; Fixes and Hacks
28839
28840 ;; Make flyspell not check words in links, to not mess up our keymap
28841 (defun org-mode-flyspell-verify ()
28842 "Don't let flyspell put overlays at active buttons."
28843 (not (get-text-property (point) 'keymap)))
28844
28845 ;; Make `bookmark-jump' show the jump location if it was hidden.
28846 (eval-after-load "bookmark"
28847 '(if (boundp 'bookmark-after-jump-hook)
28848 ;; We can use the hook
28849 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28850 ;; Hook not available, use advice
28851 (defadvice bookmark-jump (after org-make-visible activate)
28852 "Make the position visible."
28853 (org-bookmark-jump-unhide))))
28854
28855 (defun org-bookmark-jump-unhide ()
28856 "Unhide the current position, to show the bookmark location."
28857 (and (org-mode-p)
28858 (or (org-invisible-p)
28859 (save-excursion (goto-char (max (point-min) (1- (point))))
28860 (org-invisible-p)))
28861 (org-show-context 'bookmark-jump)))
28862
28863 ;; Make session.el ignore our circular variable
28864 (eval-after-load "session"
28865 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28866
28867 ;;;; Experimental code
28868
28869 (defun org-closed-in-range ()
28870 "Sparse tree of items closed in a certain time range.
28871 Still experimental, may disappear in the future."
28872 (interactive)
28873 ;; Get the time interval from the user.
28874 (let* ((time1 (time-to-seconds
28875 (org-read-date nil 'to-time nil "Starting date: ")))
28876 (time2 (time-to-seconds
28877 (org-read-date nil 'to-time nil "End date:")))
28878 ;; callback function
28879 (callback (lambda ()
28880 (let ((time
28881 (time-to-seconds
28882 (apply 'encode-time
28883 (org-parse-time-string
28884 (match-string 1))))))
28885 ;; check if time in interval
28886 (and (>= time time1) (<= time time2))))))
28887 ;; make tree, check each match with the callback
28888 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28889
28890
28891 ;;;; Finish up
28892
28893 (provide 'org)
28894
28895 (run-hooks 'org-load-hook)
28896
28897 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28898 ;;; org.el ends here
28899